auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void init() throws ConfigurationResourceException { final ServiceConfiguration config = serviceConfiguration.get(); for (Service service : config.getServices()) { final String name = service.getName().split("=")[1]; // OpenNMS:Name=Manager => Manager this.daemonList.add(new DaemonInfo(name, ignoreList.contains(name), service.isEnabled(), service.isReloadable() /* Internal daemons are not reloadable by default */)); } }

Target:
public void init() throws ConfigurationResourceException { final ServiceConfiguration config = serviceConfiguration.get(); for (Service service : config.getServices()) { final String name = service.getName().split("=")[1]; // OpenNMS:Name=Manager => Manager daemonList.add(new DaemonInfo(name, ignoreList.contains(name), service.isEnabled(), service.isReloadable() /* Internal daemons are not reloadable by default */)); } }
Source:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType())) { if (providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); // Force a check on the next get forceReload = true; } } }

Target:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType()) && providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); // Force a check on the next get forceReload = true; } }
Source:
public void expand() { try { ui.testCase.setImplicitWait(1, TimeUnit.SECONDS); getElement().findElement(By.xpath("//a[@class='gwt-Anchor icon-plus']")).click(); } catch (NoSuchElementException e) { } finally { ui.testCase.setImplicitWait(); } waitForTransition(); }

Target:
public void expand() throws NoSuchElementException { try { ui.testCase.setImplicitWait(1, TimeUnit.SECONDS); getElement().findElement(By.xpath("//a[@class='gwt-Anchor icon-plus']")).click(); waitForTransition(); } finally { ui.testCase.setImplicitWait(); } }
Source:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }

Target:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { throw new RuntimeException(e); } }
Source:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) // Filter out excluded addresses .filter(item -> { return !isExcluded(item.getAddress());}) .iterator(); }

Target:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) // Filter out excluded addresses .filter(item -> !isExcluded(item.getAddress())) .iterator(); }
Source:
public void execute(List<VertexRef> targets, OperationContext operationContext) { if (operationContext != null && operationContext.getGraphContainer() != null) { operationContext.getGraphContainer().getBaseTopology().refresh(); operationContext.getGraphContainer().setDirty(true); operationContext.getGraphContainer().redoLayout(); TopologyUI.getCurrent().markAsDirtyRecursive(); } }

Target:
public void execute(List<VertexRef> targets, OperationContext operationContext) { if (operationContext != null && operationContext.getGraphContainer() != null) { execute(operationContext.getGraphContainer()); } }
Source:
public BsmAdminPageEditWindow openNewDialog(String businessServiceName) throws InterruptedException { findElementById("createButton").click(); wait.until(pageContainsText("Business Service Edit")); // we wait until the edit dialog appears return new BsmAdminPageEditWindow(businessServiceName).name(businessServiceName); }

Target:
public BsmAdminPageEditWindow openNewDialog(String businessServiceName) throws InterruptedException { findElementById("createButton").click(); wait.until(pageContainsText("Business Service Edit")); // we wait until the edit dialog appears return new BsmAdminPageEditWindow().name(businessServiceName); }
Source:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder != null) { throw new IllegalStateException("Cannot configure both SSLContextBuilder and TrustSelfSignCert"); } // trust any self signed certificate sslBuilder = SSLContexts.custom().loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); }

Target:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder == null) { sslBuilder = SSLContexts.custom(); } // trust any self signed certificate sslBuilder.loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); }
Source:
public synchronized int getPendingConfirmsCount() { return this.pendingConfirms.values().stream() .map(Map::size) .mapToInt(Integer::valueOf) .sum(); }

Target:
public synchronized int getPendingConfirmsCount() { return this.pendingConfirms.values().stream() .mapToInt(Map::size) .sum(); }
Source:
public AsyncRabbitTemplate(RabbitTemplate template) { Assert.notNull(template, "'template' cannot be null"); this.template = template; this.container = null; this.replyAddress = null; this.directReplyToContainer = new DirectReplyToMessageListenerContainer(this.template.getConnectionFactory()); this.directReplyToContainer.setQueueNames(Address.AMQ_RABBITMQ_REPLY_TO); this.directReplyToContainer.setChannelAwareMessageListener(this); }

Target:
public AsyncRabbitTemplate(RabbitTemplate template) { Assert.notNull(template, "'template' cannot be null"); this.template = template; this.container = null; this.replyAddress = null; this.directReplyToContainer = new DirectReplyToMessageListenerContainer(this.template.getConnectionFactory()); this.directReplyToContainer.setChannelAwareMessageListener(this); }
Source:
public void addQueues(Queue... queues) { try { addQueues(Arrays.stream(queues) .map(Queue::getName)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + queues, e.getCause()); } super.addQueues(queues); }

Target:
public void addQueues(Queue... queues) { try { addQueues(Arrays.stream(queues) .map(Queue::getName)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + Arrays.asList(queues), e.getCause()); } super.addQueues(queues); }
Source:
public void setAdminsThatShouldDeclare(AmqpAdmin... admins) { Assert.notNull(admins, "'admins' cannot be null"); if (admins.length > 1) { Assert.noNullElements(admins, "'admins' cannot contain null elements"); } Collection<AmqpAdmin> declaringAdmins = new ArrayList<AmqpAdmin>(); if (admins.length > 0 && !(admins.length == 1 && admins[0] == null)) { declaringAdmins.addAll(Arrays.asList(admins)); } this.declaringAdmins = declaringAdmins; }

Target:
public void setAdminsThatShouldDeclare(AmqpAdmin... admins) { Collection<AmqpAdmin> declaringAdmins = new ArrayList<AmqpAdmin>(); if (admins != null) { if (admins.length > 1) { Assert.noNullElements(admins, "'admins' cannot contain null elements"); } if (admins.length > 0 && !(admins.length == 1 && admins[0] == null)) { declaringAdmins.addAll(Arrays.asList(admins)); } } this.declaringAdmins = declaringAdmins; }
Source:
protected void invokeErrorHandler(Throwable ex) { if (this.errorHandler != null) { this.errorHandler.handleError(ex); } else if (logger.isWarnEnabled()) { logger.warn("Execution of Rabbit message listener failed, and no ErrorHandler has been set.", ex); } else if (logger.isWarnEnabled()) { logger.warn("Execution of Rabbit message listener failed, and no ErrorHandler has been set: " + ex.getClass() + ": " + ex.getMessage()); } }

Target:
protected void invokeErrorHandler(Throwable ex) { if (this.errorHandler != null) { this.errorHandler.handleError(ex); } else if (logger.isWarnEnabled()) { logger.warn("Execution of Rabbit message listener failed, and no ErrorHandler has been set.", ex); } }
Source:
public String treatRequest(String helpRequesterInformations) { System.out.println("police called!"); EmergencyServer.policeWasCalled = true; return RESPONSE_TO_POST_REQUEST; }

Target:
public String treatRequest(String helpRequesterInformations) { EmergencyServer.policeWasCalled = true; return RESPONSE_TO_POST_REQUEST; }
Source:
public String treatRequest(@PathParam("path") String path) { String emergencyAnswer = null; try { emergencyAnswer = sendingPostResquest(EMERGENCY_URL, A_POST_REQUEST); } catch (Exception e) { // TODO the emergency server is probably no started e.printStackTrace(); } return RESPONSE_TO_POST_REQUEST + emergencyAnswer; }

Target:
public String treatRequest(@PathParam("path") String path) { String emergencyAnswer = null; try { emergencyAnswer = sendingPostResquest(EMERGENCY_URL, A_POST_REQUEST); } catch (IOException e) { e.printStackTrace(); } return RESPONSE_TO_POST_REQUEST + emergencyAnswer; }
Source:
public boolean equals(Object o) { return o == this; }

Target:
public boolean equals(Object o) { return o != null && o.getClass() == this.getClass(); }
Source:
public void run() { try { // IntegrationTestSuite is run when -Dit.test is not specify in maven command. // IntegrationTestSuite uses the configuration from integration-tests/src/test/resources/testng.xml // which already handle suite onStart and onFinish automatically if (!"IntegrationTestSuite".equals(getSuite().getName())) { SUITE_LISTENER.onStart(getSuite()); } runTests(); } catch (Exception e) { LOG.error(e, ""); throw new RuntimeException(e); } finally { // IntegrationTestSuite uses the configuration from integration-tests/src/test/resources/testng.xml // which already handle suite onStart and onFinish automatically if (!"IntegrationTestSuite".equals(getSuite().getName())) { SUITE_LISTENER.onFinish(getSuite()); } } }

Target:
public void run() { try { // IntegrationTestSuite is run when -Dit.test is not specify in maven command. // IntegrationTestSuite uses the configuration from integration-tests/src/test/resources/testng.xml // which already handle suite onStart and onFinish automatically if (!"IntegrationTestSuite".equals(getSuite().getName())) { SUITE_LISTENER.onStart(getSuite()); } runTests(); } finally { // IntegrationTestSuite uses the configuration from integration-tests/src/test/resources/testng.xml // which already handle suite onStart and onFinish automatically if (!"IntegrationTestSuite".equals(getSuite().getName())) { SUITE_LISTENER.onFinish(getSuite()); } } }
Source:
public void matchRemainder() { matchingRemainder = true; if (condition.isAlwaysFalse()) { currentIterator = extractor.iterable().iterator(); } else if (condition.isAlwaysTrue()) { currentIterator = Collections.emptyIterator(); } else { currentIterator = Iterators.filter( extractor.iterable().iterator(), entry -> entry != null && !matchedKeys.contains(entry.getKey()) ); } nextMatch(); }

Target:
public void matchRemainder() { matchingRemainder = true; if (condition.isAlwaysFalse()) { currentIterator = extractor.iterable().iterator(); } else if (condition.isAlwaysTrue()) { currentIterator = Collections.emptyIterator(); } else { //noinspection ConstantConditions - entry can not be null because extractor.iterable() prevents this currentIterator = Iterators.filter( extractor.iterable().iterator(), entry -> !matchedKeys.contains(entry.getKey()) ); } nextMatch(); }
Source:
public long size() throws IOException { flushIfNeeded(0); // To avoid check the declared IOException never thrown error return writeOutBytes; }

Target:
public long size() { return writeOutBytes; }
Source:
public Sequence<T> run(QueryPlus<T> queryPlus, ResponseContext responseContext) { //noinspection ObjectEquality if (queryPlus.getQuery() != query) { throw new ISE("Unexpected query received"); } Sequence<T> result = baseRunner.run(queryPlus.withQuery(newQuery), responseContext); return result; }

Target:
public Sequence<T> run(QueryPlus<T> queryPlus, ResponseContext responseContext) { //noinspection ObjectEquality if (queryPlus.getQuery() != query) { throw new ISE("Unexpected query received"); } return baseRunner.run(queryPlus.withQuery(newQuery), responseContext); }
Source:
public ResultSegment<ListBlobItem> listBlobsWithPrefixInContainerSegmented( final String containerName, final String prefix, ResultContinuation continuationToken, int maxResults ) throws StorageException, URISyntaxException { CloudBlobContainer cloudBlobContainer = cloudBlobClient.getContainerReference(containerName); return cloudBlobContainer .listBlobsSegmented( prefix, /* Use flat blob listing here so that we get only blob types and not directories.*/ USE_FLAT_BLOB_LISTING, EnumSet .noneOf(BlobListingDetails.class), maxResults, continuationToken, null, null ); }

Target:
ResultSegment<ListBlobItem> listBlobsWithPrefixInContainerSegmented( final String containerName, final String prefix, ResultContinuation continuationToken, int maxResults ) throws StorageException, URISyntaxException { CloudBlobContainer cloudBlobContainer = cloudBlobClient.getContainerReference(containerName); return cloudBlobContainer .listBlobsSegmented( prefix, /* Use flat blob listing here so that we get only blob types and not directories.*/ USE_FLAT_BLOB_LISTING, EnumSet .noneOf(BlobListingDetails.class), maxResults, continuationToken, null, null ); }
Source:
public void forEach(BiConsumer<Interval, PartitionBoundaries> consumer) { intervalToPartitionBoundaries.forEach(consumer); }

Target:
private void forEach(BiConsumer<Interval, PartitionBoundaries> consumer) { intervalToPartitionBoundaries.forEach(consumer); }
Source:
public InputStream open() throws IOException { // Get data of the given object and open an input stream final String bucket = uri.getAuthority(); final String key = GoogleUtils.extractGoogleCloudStorageObjectKey(uri); final GoogleByteSource byteSource = new GoogleByteSource(storage, bucket, key); return CompressionUtils.decompress(byteSource.openStream(), uri.toString()); }

Target:
public InputStream open() throws IOException { // Get data of the given object and open an input stream final String bucket = uri.getAuthority(); final String key = GoogleUtils.extractGoogleCloudStorageObjectKey(uri); final GoogleByteSource byteSource = new GoogleByteSource(storage, bucket, key); return CompressionUtils.decompress(byteSource.openStream(), uri.getPath()); }
Source:
protected InputSourceReader formattableReader( InputRowSchema inputRowSchema, InputFormat inputFormat, @Nullable File temporaryDirectory ) throws IOException { return new InputEntityIteratingReader( inputRowSchema, inputFormat, // formattableReader() is supposed to be called in each task that actually creates segments. // The task should already have only one split in parallel indexing, // while there's no need to make splits using splitHintSpec in sequential indexing. createSplits(inputFormat, null).map(split -> new S3Entity(s3Client, split.get())), temporaryDirectory ); }

Target:
protected InputSourceReader formattableReader( InputRowSchema inputRowSchema, InputFormat inputFormat, @Nullable File temporaryDirectory ) { return new InputEntityIteratingReader( inputRowSchema, inputFormat, // formattableReader() is supposed to be called in each task that actually creates segments. // The task should already have only one split in parallel indexing, // while there's no need to make splits using splitHintSpec in sequential indexing. createSplits(inputFormat, null).map(split -> new S3Entity(s3Client, split.get())), temporaryDirectory ); }
Source:
public Map<String, ImmutableWorkerInfo> getWorkersEligibleToRunTasks() { return Maps.transformEntries( Maps.filterEntries( workers, input -> !lazyWorkers.containsKey(input.getKey()) && !workersWithUnacknowledgedTask.containsKey(input.getKey()) && !blackListedWorkers.containsKey(input.getKey()) && input.getValue().isInitialized() && input.getValue().isEnabled() ), (String key, WorkerHolder value) -> value.toImmutable() ); }

Target:
Map<String, ImmutableWorkerInfo> getWorkersEligibleToRunTasks() { // In this class, this method is called with statusLock held. // writes to workersWithUnacknowledgedTask are always guarded by statusLock. // however writes to lazyWorker/blacklistedWorkers aren't necessarily guarded by same lock, so technically there // could be races in that a task could get assigned to a worker which in another thread is concurrently being // marked lazy/blacklisted , but that is ok because that is equivalent to this worker being picked for task and // being assigned lazy/blacklisted right after even when the two threads hold a mutually exclusive lock. return Maps.transformEntries( Maps.filterEntries( workers, input -> !lazyWorkers.containsKey(input.getKey()) && !workersWithUnacknowledgedTask.containsKey(input.getKey()) && !blackListedWorkers.containsKey(input.getKey()) && input.getValue().isInitialized() && input.getValue().isEnabled() ), (String key, WorkerHolder value) -> value.toImmutable() ); }
Source:
private void shutdown(Lifecycle lifecycle) { //noinspection finally (not completing the 'finally' block normally is intentional) try { lifecycle.stop(); } catch (Throwable t) { log.warn(t, "Exception when stopping druid lifecycle"); } finally { System.exit(1); } }

Target:
private void shutdown(Lifecycle lifecycle) { //noinspection finally (not completing the 'finally' block normally is intentional) try { lifecycle.stop(); } catch (Throwable t) { log.error(t, "Exception when stopping druid lifecycle"); } finally { System.exit(1); } }
Source:
public Comparator getComparator() { if (errorBoundsStdDev == null) { return Ordering.natural(); } else { return (o1, o2) -> Doubles.compare( ((SketchEstimateWithErrorBounds) o1).getEstimate(), ((SketchEstimateWithErrorBounds) o2).getEstimate() ); } }

Target:
public Comparator getComparator() { if (errorBoundsStdDev == null) { return Ordering.natural(); } else { return new Comparator() { @Override public int compare(Object o1, Object o2) { return Doubles.compare( ((SketchEstimateWithErrorBounds) o1).getEstimate(), ((SketchEstimateWithErrorBounds) o2).getEstimate() ); } }; } }
Source:
public byte[] getCacheKey() { return new CacheKeyBuilder(HavingSpecUtil.CACHE_TYPE_ID_GREATER_THAN) .appendString(aggregationName) .appendByteArray(StringUtils.toUtf8(String.valueOf(value))) .appendStrings(aggregators.keySet()) .appendCacheables(aggregators.values()) .build(); }

Target:
public byte[] getCacheKey() { return new CacheKeyBuilder(HavingSpecUtil.CACHE_TYPE_ID_GREATER_THAN) .appendString(aggregationName) .appendByteArray(StringUtils.toUtf8(String.valueOf(value))) .build(); }
Source:
public void printStuff() { System.out.println(); for (Map<Object, Integer> valueMap : dimensionMap.values()) { System.out.println("DIMENSION " + valueMap + "\n============"); new TreeMap<>(valueMap).forEach((val, cnt) -> System.out.println(" VAL: " + val + " CNT: " + cnt)); } }

Target:
public void printStuff() { System.out.println(); dimensionMap.forEach((key, valueMap) -> new TreeMap<>(valueMap).forEach((val, cnt) -> System.out.println(" VAL: " + val + " CNT: " + cnt))); }
Source:
public synchronized void close() { if (closed) { return; } closed = true; log.info("Firehose closing."); // Critical to add the poison pill to the queue, don't allow interruption. Uninterruptibles.putUninterruptibly(buffer, FIREHOSE_CLOSED); eventReceiverFirehoseRegister.unregister(serviceName); if (chatHandlerProvider != null) { chatHandlerProvider.unregister(serviceName); } Thread delayedCloseExecutor = this.delayedCloseExecutor; if (delayedCloseExecutor != null && !delayedCloseExecutor.equals(Thread.currentThread())) { // Interrupt delayedCloseExecutor to let it discover that closed flag is already set and exit. delayedCloseExecutor.interrupt(); } }

Target:
public synchronized void close() { if (closed) { return; } closed = true; log.info("Firehose closing."); // Critical to add the poison pill to the queue, don't allow interruption. Uninterruptibles.putUninterruptibly(buffer, FIREHOSE_CLOSED); eventReceiverFirehoseRegister.unregister(serviceName); if (chatHandlerProvider != null) { chatHandlerProvider.unregister(serviceName); } if (delayedCloseExecutor != null && !delayedCloseExecutor.equals(Thread.currentThread())) { // Interrupt delayedCloseExecutor to let it discover that closed flag is already set and exit. delayedCloseExecutor.interrupt(); } }
Source:
public static DateTime of(String instant) { try { Integer seconds = Integer.valueOf(instant); return new DateTime(seconds * 1000L, ISOChronology.getInstanceUTC()); } catch (NumberFormatException ex) { try { return new DateTime(Long.valueOf(instant), ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex2) { try { return new DateTime(instant, ISOChronology.getInstanceUTC()); } catch (Exception ex3) { throw ex; } } } }

Target:
public static DateTime of(String instant) { try { return new DateTime(instant, ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex) { try { return new DateTime(Long.valueOf(instant), ISOChronology.getInstanceUTC()); } catch (IllegalArgumentException ex2) { throw ex; } } }
Source:
public void close() { if (this.closed) { return; } assign(ImmutableSet.of()); scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.warn(e, "InterruptedException while shutting down"); } this.closed = true; }

Target:
public void close() { if (this.closed) { return; } assign(ImmutableSet.of()); scheduledExec.shutdown(); try { if (!scheduledExec.awaitTermination(EXCEPTION_RETRY_DELAY_MS, TimeUnit.MILLISECONDS)) { scheduledExec.shutdownNow(); } } catch (InterruptedException e) { log.warn(e, "InterruptedException while shutting down"); throw new RuntimeException(e); } this.closed = true; }
Source:
private void rescheduleRunnable(long delayMillis) { if (started && !stopRequested) { try { scheduledExec.schedule(getRecordRunnable(), delayMillis, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { log.warn( "Caught RejectedExecutionException, KinesisRecordSupplier for partition[%s] has likely temporarily shutdown the ExecutorService." + "This is expected behavior after calling seek(), seekToEarliest() and seekToLatest()", streamPartition.getPartitionId() ); } } else { log.info("Worker for partition[%s] has been stopped", streamPartition.getPartitionId()); } }

Target:
private void rescheduleRunnable(long delayMillis) { if (started && !stopRequested) { try { scheduledExec.schedule(getRecordRunnable(), delayMillis, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { log.warn( e, "Caught RejectedExecutionException, KinesisRecordSupplier for partition[%s] has likely temporarily shutdown the ExecutorService." + "This is expected behavior after calling seek(), seekToEarliest() and seekToLatest()", streamPartition.getPartitionId() ); } } else { log.info("Worker for partition[%s] has been stopped", streamPartition.getPartitionId()); } }
Source:
public String getStream() { return id; }

Target:
public String getStream() { return stream; }
Source:
public Object finalizeComputation(Object object) { try { if (object instanceof ByteBuffer) { return BloomKFilter.deserialize((ByteBuffer) object); } else if (object instanceof byte[]) { return BloomKFilter.deserialize(ByteBuffer.wrap((byte[]) object)); } else { return object; } } catch (IOException ioe) { throw new RuntimeException("Failed to deserialize BloomKFilter"); } }

Target:
public Object finalizeComputation(Object object) { try { if (object instanceof ByteBuffer) { return BloomKFilter.deserialize((ByteBuffer) object); } else if (object instanceof byte[]) { return BloomKFilter.deserialize(ByteBuffer.wrap((byte[]) object)); } else { return object; } } catch (IOException ioe) { throw new RuntimeException("Failed to deserialize BloomKFilter", ioe); } }
Source:
public Parser getFlatParser() { JSONParseSpec spec = new JSONParseSpec( new TimestampSpec("ts", "iso", null, null), new DimensionsSpec(null, null, null), null, null ); return spec.makeParser(); }

Target:
public Parser getFlatParser() { JSONParseSpec spec = new JSONParseSpec( new TimestampSpec("ts", "iso", null), new DimensionsSpec(null, null, null), null, null ); return spec.makeParser(); }
Source:
public static long getMaxBytesInMemoryOrDefault(final long maxBytesInMemory) { // In the main tuningConfig class constructor, we set the maxBytes to 0 if null to avoid setting // maxBytes to max jvm memory of the process that starts first. Instead we set the default based on // the actual task node's jvm memory. long newMaxBytesInMemory = maxBytesInMemory; if (maxBytesInMemory == 0) { newMaxBytesInMemory = TuningConfig.DEFAULT_MAX_BYTES_IN_MEMORY; } else if (maxBytesInMemory == -1) { newMaxBytesInMemory = Long.MAX_VALUE; } return newMaxBytesInMemory; }

Target:
public static long getMaxBytesInMemoryOrDefault(final long maxBytesInMemory) { // In the main tuningConfig class constructor, we set the maxBytes to 0 if null to avoid setting // maxBytes to max jvm memory of the process that starts first. Instead we set the default based on // the actual task node's jvm memory. long newMaxBytesInMemory = maxBytesInMemory; if (maxBytesInMemory == 0) { newMaxBytesInMemory = TuningConfig.DEFAULT_MAX_BYTES_IN_MEMORY; } else if (maxBytesInMemory < 0) { newMaxBytesInMemory = Long.MAX_VALUE; } return newMaxBytesInMemory; }
Source:
public Map<String, Object> getStats() { try { return getCurrentTotalStats(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("getStats() interrupted."); throw new RuntimeException(ie); } catch (ExecutionException | TimeoutException eete) { throw new RuntimeException(eete); } }

Target:
public Map<String, Map<String, Object>> getStats() { try { return getCurrentTotalStats(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error(ie, "getStats() interrupted."); throw new RuntimeException(ie); } catch (ExecutionException | TimeoutException eete) { throw new RuntimeException(eete); } }
Source:
public AuthenticationResult createEscalatedAuthenticationResult() { return new AuthenticationResult(internalClientUsername, authorizerName, BASIC, null); }

Target:
public AuthenticationResult createEscalatedAuthenticationResult() { // if you found your self asking why the authenticatedBy field is set to null please read this: // https://github.com/druid-io/druid/pull/5706#discussion_r185940889 return new AuthenticationResult(internalClientUsername, authorizerName, null, null); }
Source:
public List<ReferenceCountingResourceHolder<T>> takeBatch(final int elementNum) { checkInitialized(); try { return takeObjects(elementNum).stream().map(this::wrapObject).collect(Collectors.toList()); } catch (InterruptedException e) { throw Throwables.propagate(e); } }

Target:
public List<ReferenceCountingResourceHolder<T>> takeBatch(final int elementNum) { checkInitialized(); try { return takeObjects(elementNum).stream().map(this::wrapObject).collect(Collectors.toList()); } catch (InterruptedException e) { throw new RuntimeException(e); } }
Source:
OnheapIncrementalIndex( IncrementalIndexSchema incrementalIndexSchema, boolean deserializeComplexMetrics, boolean reportParseExceptions, boolean concurrentEventAdd, boolean sortFacts, int maxRowCount, long maxBytesInMemory ) { super(incrementalIndexSchema, deserializeComplexMetrics, reportParseExceptions, concurrentEventAdd); this.maxRowCount = maxRowCount; this.maxBytesInMemory = maxBytesInMemory == 0 ? defaultMaxBytesInMemory : maxBytesInMemory; this.facts = incrementalIndexSchema.isRollup() ? new RollupFactsHolder(sortFacts, dimsComparator(), getDimensions()) : new PlainFactsHolder(sortFacts); maxBytesPerRowForAggregators = getMaxBytesPerRowForAggregators(incrementalIndexSchema); }

Target:
OnheapIncrementalIndex( IncrementalIndexSchema incrementalIndexSchema, boolean deserializeComplexMetrics, boolean reportParseExceptions, boolean concurrentEventAdd, boolean sortFacts, int maxRowCount, long maxBytesInMemory ) { super(incrementalIndexSchema, deserializeComplexMetrics, reportParseExceptions, concurrentEventAdd); this.maxRowCount = maxRowCount; this.maxBytesInMemory = maxBytesInMemory == 0 ? -1 : maxBytesInMemory; this.facts = incrementalIndexSchema.isRollup() ? new RollupFactsHolder(sortFacts, dimsComparator(), getDimensions()) : new PlainFactsHolder(sortFacts); maxBytesPerRowForAggregators = getMaxBytesPerRowForAggregators(incrementalIndexSchema); }
Source:
public int getPartition(LongWritable interval, BytesWritable text, int numPartitions) { final String jobTrackerString = config.get("mapred.job.tracker"); if ((jobTrackerString != null && jobTrackerString.equals("local")) || determineIntervals) { return 0; } else { return reducerLookup.get(interval); } }

Target:
public int getPartition(LongWritable interval, BytesWritable text, int numPartitions) { if ("local".equals(config.get("mapred.job.tracker")) || determineIntervals) { return 0; } else { return reducerLookup.get(interval); } }
Source:
public boolean equals(final Object o) { if (!super.equals(o)) { return false; } final ArrayOfDoublesSketchMultiPostAggregator that = (ArrayOfDoublesSketchMultiPostAggregator) o; return fields.equals(that.fields); }

Target:
public boolean equals(final Object o) { if (!super.equals(o)) { return false; } // this check is used here instead of instanceof because this is an abstract class // and subclasses not overriding equals should not be equal to each other if (o == null || getClass() != o.getClass()) { return false; } final ArrayOfDoublesSketchMultiPostAggregator that = (ArrayOfDoublesSketchMultiPostAggregator) o; return fields.equals(that.fields); }
Source:
public ArrayOfDoublesSketchBuildAggregator( final DimensionSelector keySelector, final List<BaseDoubleColumnValueSelector> valueSelectors, final int nominalEntries ) { this.keySelector = keySelector; this.valueSelectors = valueSelectors.toArray(new BaseDoubleColumnValueSelector[valueSelectors.size()]); values = new double[valueSelectors.size()]; sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(nominalEntries) .setNumberOfValues(valueSelectors.size()).build(); }

Target:
public ArrayOfDoublesSketchBuildAggregator( final DimensionSelector keySelector, final List<BaseDoubleColumnValueSelector> valueSelectors, final int nominalEntries ) { this.keySelector = keySelector; this.valueSelectors = valueSelectors.toArray(new BaseDoubleColumnValueSelector[0]); values = new double[valueSelectors.size()]; sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(nominalEntries) .setNumberOfValues(valueSelectors.size()).build(); }
Source:
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { if (other.getName().equals(this.getName()) && other instanceof DoublesSketchAggregatorFactory) { return new DoublesSketchMergeAggregatorFactory(name, k); } else { throw new AggregatorFactoryNotMergeableException(this, other); } }

Target:
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { if (other.getName().equals(this.getName()) && other instanceof DoublesSketchAggregatorFactory) { // DoublesUnion supports inputs with different k. // The result will have effective k between the specified k and the minimum k from all input sketches // to achieve higher accuracy as much as possible. return new DoublesSketchMergeAggregatorFactory(name, Math.max(k, ((DoublesSketchAggregatorFactory) other).k)); } else { throw new AggregatorFactoryNotMergeableException(this, other); } }
Source:
public void replaceInput(int ordinalInParent, RelNode p) { if (ordinalInParent == 0) { Preconditions.checkArgument( p instanceof DruidRel, "RelNode[%s] is not a DruidRel", p.getClass().getCanonicalName() ); this.left = (DruidRel<?>) p; } else if (ordinalInParent == 1) { this.right = p; } else { throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent)); } }

Target:
public void replaceInput(int ordinalInParent, RelNode p) { if (ordinalInParent != 0) { throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent)); } // 'right' is the only one Calcite concerns. See getInputs(). this.right = p; }
Source:
public boolean isNUllRow(int[] row, Indexed<String> encodings) { if (row == null) { return true; } for (int i : row) { if (encodings.get(i) != null) { // Non-Null value return false; } } return true; }

Target:
private boolean isNUllRow(int[] row, Indexed<String> encodings) { if (row == null) { return true; } for (int i : row) { if (encodings.get(i) != null) { // Non-Null value return false; } } return true; }
Source:
static int requiredBufferCapacity( int cardinality, AggregatorFactory[] aggregatorFactories ) { final int cardinalityWithMissingValue = cardinality + 1; final int recordSize = Arrays.stream(aggregatorFactories) .mapToInt(AggregatorFactory::getMaxIntermediateSize) .sum(); return Integer.BYTES + // grouping key size getUsedFlagBufferCapacity(cardinalityWithMissingValue) + // total used flags size cardinalityWithMissingValue * recordSize; // total values size }

Target:
static int requiredBufferCapacity( int cardinality, AggregatorFactory[] aggregatorFactories ) { final int cardinalityWithMissingValue = cardinality + 1; final int recordSize = Arrays.stream(aggregatorFactories) .mapToInt(AggregatorFactory::getMaxIntermediateSize) .sum(); return getUsedFlagBufferCapacity(cardinalityWithMissingValue) + // total used flags size cardinalityWithMissingValue * recordSize; // total values size }
Source:
private static ImmutableWorkerInfo selectFromEligibleWorkers(final Map<String, ImmutableWorkerInfo> eligibleWorkers) { return eligibleWorkers.values().stream().min( Comparator.comparing(ImmutableWorkerInfo::getAvailableCapacity).reversed() ).orElse(null); }

Target:
private static ImmutableWorkerInfo selectFromEligibleWorkers(final Map<String, ImmutableWorkerInfo> eligibleWorkers) { return eligibleWorkers.values().stream().max( Comparator.comparing(ImmutableWorkerInfo::getAvailableCapacity) ).orElse(null); }
Source:
private LogicalType determineTimestampSpecLogicalType(Schema schema, String timestampSpecField) { for (Schema.Field field : schema.getFields()) { if (field.name().equals(timestampSpecField)) { this.timestampSpecLogicalType = field.schema().getLogicalType(); return this.timestampSpecLogicalType; } } // The timestamp field does not exist in the provided schema return null; }

Target:
private LogicalType determineTimestampSpecLogicalType(Schema schema, String timestampSpecField) { for (Schema.Field field : schema.getFields()) { if (field.name().equals(timestampSpecField)) { return field.schema().getLogicalType(); } } return null; }
Source:
public int compare(String s, String s2) { // Avoid conversion to bytes for equal references if(Objects.equals(s, s2)){ return 0; } return ORDERING.compare(s, s2); }

Target:
public int compare(String s, String s2) { // Avoid conversion to bytes for equal references // Assuming we mostly compare different strings, checking s.equals(s2) will only make the comparison slower. if (s == s2) { return 0; } return ORDERING.compare(s, s2); }
Source:
public LocalFirehoseFactory( @JsonProperty("baseDir") File baseDir, @JsonProperty("filter") String filter, // Backwards compatible @JsonProperty("parser") StringInputRowParser parser ) { super( FileUtils.listFiles( Preconditions.checkNotNull(baseDir).getAbsoluteFile(), new WildcardFileFilter(filter), TrueFileFilter.INSTANCE ) ); this.baseDir = baseDir; this.filter = filter; this.parser = parser; log.info("Initialized with " + getObjects() + " files"); }

Target:
public LocalFirehoseFactory( @JsonProperty("baseDir") File baseDir, @JsonProperty("filter") String filter, // Backwards compatible @JsonProperty("parser") StringInputRowParser parser ) { this.baseDir = baseDir; this.filter = filter; this.parser = parser; }
Source:
public ValueMatcher makeValueMatcher(final LongColumnSelector selector, final String value) { Long matchVal = DimensionHandlerUtils.convertObjectToLong(value); if (matchVal == null) { return BooleanValueMatcher.of(false); } final long matchValLong = matchVal; return new ValueMatcher() { @Override public boolean matches() { return selector.get() == matchValLong; } }; }

Target:
public ValueMatcher makeValueMatcher(final LongColumnSelector selector, final String value) { final Long matchVal = DimensionHandlerUtils.convertObjectToLong(value); if (matchVal == null) { return BooleanValueMatcher.of(false); } final long matchValLong = matchVal; return new ValueMatcher() { @Override public boolean matches() { return selector.get() == matchValLong; } }; }
Source:
public boolean determineApplyLimitPushDown() { final boolean forceLimitPushDown = validateAndGetForceLimitPushDown(); if (limitSpec instanceof DefaultLimitSpec) { DefaultLimitSpec defaultLimitSpec = (DefaultLimitSpec) limitSpec; // If only applying an orderby without a limit, don't try to push down if (defaultLimitSpec.getLimit() == Integer.MAX_VALUE) { return false; } if (forceLimitPushDown) { return true; } // If the sorting order only uses columns in the grouping key, we can always push the limit down // to the buffer grouper without affecting result accuracy boolean sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields( limitSpec, getDimensions() ); return !sortHasNonGroupingFields; } return false; }

Target:
public boolean determineApplyLimitPushDown() { final boolean forceLimitPushDown = validateAndGetForceLimitPushDown(); if (limitSpec instanceof DefaultLimitSpec) { DefaultLimitSpec defaultLimitSpec = (DefaultLimitSpec) limitSpec; // If only applying an orderby without a limit, don't try to push down if (defaultLimitSpec.getLimit() == Integer.MAX_VALUE) { return false; } if (forceLimitPushDown) { return true; } // If the sorting order only uses columns in the grouping key, we can always push the limit down // to the buffer grouper without affecting result accuracy boolean sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields( (DefaultLimitSpec) limitSpec, getDimensions() ); return !sortHasNonGroupingFields; } return false; }
Source:
public void reset() { size = 0; growthCount = 0; // clear the used bits of both buffers for (int i = 0; i < maxBuckets; i++) { subHashTableBuffers[0].put(i * bucketSizeWithHash, (byte) 0); subHashTableBuffers[1].put(i * bucketSizeWithHash, (byte) 0); } tableBuffer = subHashTableBuffers[0]; }

Target:
public void reset() { size = 0; growthCount = 0; // clear the used bits of the first buffer for (int i = 0; i < maxBuckets; i++) { subHashTableBuffers[0].put(i * bucketSizeWithHash, (byte) 0); } tableBuffer = subHashTableBuffers[0]; }
Source:
private void sendToKafka(final String topic, MemoryBoundLinkedBlockingQueue<String> recordQueue) { ObjectContainer<String> objectToSend; try { while((objectToSend = recordQueue.take()) != null) { producer.send(new ProducerRecord<String, String>(topic, objectToSend.getData()), producerCallback); } } catch (InterruptedException e) { log.warn(e, "Failed to take record from queue!"); } }

Target:
private void sendToKafka(final String topic, MemoryBoundLinkedBlockingQueue<String> recordQueue) { ObjectContainer<String> objectToSend; try { while (true) { objectToSend = recordQueue.take(); producer.send(new ProducerRecord<>(topic, objectToSend.getData()), producerCallback); } } catch (InterruptedException e) { log.warn(e, "Failed to take record from queue!"); } }
Source:
public int get(int index) { return 0; }

Target:
public int get(int index) { // Skip range check in production, assume "index" was 0 like it really should have been. assert index == 0; return 0; }
Source:
public Callable<String> getCachePopulator( final String id, final StaticMapExtractionNamespace extractionNamespace, final String lastVersion, final Map<String, String> swap ) { return new Callable<String>() { @Override public String call() throws Exception { if (lastVersion != null) { // Throwing AssertionError, because NamespaceExtractionCacheManager doesn't suppress Errors and will stop // trying to update the cache periodically. throw new AssertionError( "StaticMapExtractionNamespaceCacheFactory could only be configured for a namespace which is scheduled " + "to be updated once, not periodically. Last version: `" + lastVersion + "`"); } else { swap.putAll(extractionNamespace.getMap()); return version; } } }; }

Target:
public Callable<String> getCachePopulator( final String id, final StaticMapExtractionNamespace extractionNamespace, final String lastVersion, final Map<String, String> swap ) { if (lastVersion != null) { // Throwing AssertionError, because NamespaceExtractionCacheManager doesn't suppress Errors and will stop trying // to update the cache periodically. throw new AssertionError( "StaticMapExtractionNamespaceCacheFactory could only be configured for a namespace which is scheduled " + "to be updated once, not periodically. Last version: `" + lastVersion + "`"); } return new Callable<String>() { @Override public String call() throws Exception { swap.putAll(extractionNamespace.getMap()); return version; } }; }
Source:
public Map<String, String> parse(String input) { final Map<String, Object> inner = delegate.parse(input); final String k = Preconditions.checkNotNull( inner.get(key), "Key column [%s] missing data in line [%s]", key, input ).toString(); // Just in case is long final Object val = inner.get(value); if (val == null) { // Skip nulls return null; } return ImmutableMap.of(k, val.toString()); }

Target:
public Map<String, String> parse(String input) { final Map<String, Object> inner = delegate.parse(input); final String k = Preconditions.checkNotNull( inner.get(key), "Key column [%s] missing data in line [%s]", key, input ).toString(); // Just in case is long final Object val = inner.get(value); if (val == null) { // Skip null or missing values, treat them as if there were no row at all. return ImmutableMap.of(); } return ImmutableMap.of(k, val.toString()); }
Source:
public void testThrowParseExceptions(){ InputRow in = new MapBasedInputRow( timestamp, dims, event ); AggregatorFactory[] aggregatorFactories = new AggregatorFactory[] { new DoubleSumAggregatorFactory("agg_non_existing", "agg_non_existing_in"), new DoubleSumAggregatorFactory("m1out", "m1"), new LongSumAggregatorFactory("m2out", "m2"), new HyperUniquesAggregatorFactory("m3out", "m3"), new LongSumAggregatorFactory("unparseable", "m3") // Unparseable from String to Long }; try { InputRowSerde.toBytes(in, aggregatorFactories, true); Assert.fail("Should have thrown parseException"); } catch (ParseException e){ // expected } }

Target:
public void testThrowParseExceptions() { InputRow in = new MapBasedInputRow( timestamp, dims, event ); AggregatorFactory[] aggregatorFactories = new AggregatorFactory[]{ new DoubleSumAggregatorFactory("agg_non_existing", "agg_non_existing_in"), new DoubleSumAggregatorFactory("m1out", "m1"), new LongSumAggregatorFactory("m2out", "m2"), new HyperUniquesAggregatorFactory("m3out", "m3"), new LongSumAggregatorFactory("unparseable", "m3") // Unparseable from String to Long }; InputRowSerde.toBytes(in, aggregatorFactories, true); }
Source:
public static Expr binaryOp(BinaryOpExprBase binary, Expr left, Expr right) { try { return binary.getClass() .getDeclaredConstructor(String.class, Expr.class, Expr.class) .newInstance(binary.op, left, right); } catch (Exception e) { log.info(e, "failed to rewrite expression " + binary); return binary; // best effort.. keep it working } }

Target:
public static Expr binaryOp(BinaryOpExprBase binary, Expr left, Expr right) { try { return binary.getClass() .getDeclaredConstructor(String.class, Expr.class, Expr.class) .newInstance(binary.op, left, right); } catch (Exception e) { log.warn(e, "failed to rewrite expression " + binary); return binary; // best effort.. keep it working } }
Source:
private boolean possiblyStopAndRemoveSupervisorInternal(String id, boolean writeTombstone) { Pair<Supervisor, SupervisorSpec> pair = supervisors.get(id); if (pair != null) { if (writeTombstone) { metadataSupervisorManager.insert(id, new NoopSupervisorSpec()); // where NoopSupervisorSpec is a tombstone } pair.lhs.stop(true); supervisors.remove(id); return true; } return false; }

Target:
private boolean possiblyStopAndRemoveSupervisorInternal(String id, boolean writeTombstone) { Pair<Supervisor, SupervisorSpec> pair = supervisors.get(id); if (pair == null) { return false; } if (writeTombstone) { metadataSupervisorManager.insert(id, new NoopSupervisorSpec()); // where NoopSupervisorSpec is a tombstone } pair.lhs.stop(true); supervisors.remove(id); return true; }
Source:
public boolean stopAndRemoveSupervisor(String id) { Preconditions.checkState(started, "SupervisorManager not started"); Preconditions.checkNotNull(id, "id"); synchronized (lock) { return possiblyStopAndRemoveSupervisorInternal(id, true); } }

Target:
public boolean stopAndRemoveSupervisor(String id) { Preconditions.checkState(started, "SupervisorManager not started"); Preconditions.checkNotNull(id, "id"); synchronized (lock) { Preconditions.checkState(started, "SupervisorManager not started"); return possiblyStopAndRemoveSupervisorInternal(id, true); } }
Source:
public OffheapIncrementalIndex( long minTimestamp, QueryGranularity gran, final AggregatorFactory[] metrics, boolean deserializeComplexMetrics, boolean reportParseExceptions, boolean sortFacts, int maxRowCount, StupidPool<ByteBuffer> bufferPool ) { this( new IncrementalIndexSchema.Builder().withMinTimestamp(minTimestamp) .withQueryGranularity(gran) .withMetrics(metrics) .withRollup(DEFAULT_ROLLUP) .build(), deserializeComplexMetrics, reportParseExceptions, sortFacts, maxRowCount, bufferPool ); }

Target:
public OffheapIncrementalIndex( long minTimestamp, QueryGranularity gran, final AggregatorFactory[] metrics, boolean deserializeComplexMetrics, boolean reportParseExceptions, boolean sortFacts, int maxRowCount, StupidPool<ByteBuffer> bufferPool ) { this( new IncrementalIndexSchema.Builder().withMinTimestamp(minTimestamp) .withQueryGranularity(gran) .withMetrics(metrics) .withRollup(IncrementalIndexSchema.DEFAULT_ROLLUP) .build(), deserializeComplexMetrics, reportParseExceptions, sortFacts, maxRowCount, bufferPool ); }
Source:
RetryPolicyFactory createRetryPolicyFactory() { return new RetryPolicyFactory(new RetryPolicyConfig() .setMinWait(Period.seconds(2)) .setMaxWait(Period.seconds(8)) .setMaxRetryCount(5) ); }

Target:
RetryPolicyFactory createRetryPolicyFactory() { // Retries for about a minute before giving up; this should be long enough to handle any temporary unresponsiveness // such as network issues, if a task is still in the process of starting up, or if the task is in the middle of // persisting to disk and doesn't respond immediately. return new RetryPolicyFactory( new RetryPolicyConfig() .setMinWait(Period.seconds(2)) .setMaxWait(Period.seconds(8)) .setMaxRetryCount(8) ); }
Source:
private LookupExtractionFn ensureDelegate() { LookupExtractionFn delegate = this.delegate; if (null == delegate) { // http://www.javamex.com/tutorials/double_checked_locking.shtml synchronized (delegateLock) { delegate = this.delegate; if (null == delegate) { delegate = new LookupExtractionFn( Preconditions.checkNotNull(manager.get(getLookup()), "Lookup [%s] not found", getLookup()).get(), isRetainMissingValue(), getReplaceMissingValueWith(), isInjective(), isOptimize() ); this.delegate = delegate; } } } return delegate; }

Target:
private LookupExtractionFn ensureDelegate() { if (null == delegate) { // http://www.javamex.com/tutorials/double_checked_locking.shtml synchronized (delegateLock) { if (null == delegate) { delegate = new LookupExtractionFn( Preconditions.checkNotNull(manager.get(getLookup()), "Lookup [%s] not found", getLookup()).get(), isRetainMissingValue(), getReplaceMissingValueWith(), isInjective(), isOptimize() ); } } } return delegate; }