auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static boolean binaryIdentical(IStorage left, IStorage right) { <START> BufferedInputStream leftStream = null; <END> BufferedInputStream rightStream = null; try { final int maxBufferSize = 8192; final byte[] leftBuff = new byte[maxBufferSize]; final byte[] rightBuff = new byte[maxBufferSize]; leftStream = new BufferedInputStream(left.getContents(), maxBufferSize); rightStream = new BufferedInputStream(right.getContents(), maxBufferSize); int readMin; do { leftStream.mark(maxBufferSize); rightStream.mark(maxBufferSize); int readLeft = leftStream.read(leftBuff, 0, leftBuff.length); int readRight = rightStream.read(rightBuff, 0, rightBuff.length); readMin = Math.min(readLeft, readRight); if ((readLeft == -1) != (readRight == -1) || !equalArrays(readMin, leftBuff, rightBuff)) { return false; } if (readMin > 0) { resetAndSkip(leftStream, readMin); resetAndSkip(rightStream, readMin); } } while (readMin > 0); return true; } catch (CoreException e) { logError(e); } catch (IOException e) { logError(e); } finally { Closeables.closeQuietly(leftStream); Closeables.closeQuietly(rightStream); } return false; }</code><technical_language>Good point, I mistakenly thinking mark/reset solution. Thank for solution! I freedom of splitting some code a sub-method building 3-array-compare solution a lot of code reused, readability improved -- upcoming change set</technical_language>

Target:
public static boolean binaryIdentical(IStorage left, IStorage right) { BufferedInputStream leftStream = null; BufferedInputStream rightStream = null; try { final int maxBufferSize = 8192; final byte[] buffer = new byte[maxBufferSize]; leftStream = new BufferedInputStream(left.getContents(), maxBufferSize); rightStream = new BufferedInputStream(right.getContents(), maxBufferSize); int readLeft; do { readLeft = leftStream.read(buffer, 0, buffer.length); if (readLeft == -1) { return rightStream.read() == -1; } if (!verifyNextBytes(rightStream, buffer, 0, readLeft)) { return false; } } while (readLeft > 0); return true; } catch (CoreException e) { logError(e); } catch (IOException e) { logError(e); } finally { Closeables.closeQuietly(leftStream); Closeables.closeQuietly(rightStream); } return false; }
Source:
<code>public List<Node> getDatanodesInRack(String loc) { netlock.readLock().lock(); try { loc = NodeBase.normalize(loc); if (!NodeBase.ROOT.equals(loc)) { loc = loc.substring(1); } InnerNode rack = (InnerNode) clusterMap.getLoc(loc); <START> return (rack == null) ? Collections.emptyList() <END> : Collections.unmodifiableList(new ArrayList<>(rack.getChildren())); } finally { netlock.readLock().unlock(); } }</code><technical_language>unmodifiable here</technical_language>

Target:
public List<Node> getDatanodesInRack(String loc) { netlock.readLock().lock(); try { loc = NodeBase.normalize(loc); if (!NodeBase.ROOT.equals(loc)) { loc = loc.substring(1); } InnerNode rack = (InnerNode) clusterMap.getLoc(loc); return (rack == null) ? new ArrayList<>(0) : new ArrayList<>(rack.getChildren()); } finally { netlock.readLock().unlock(); } }
Source:
<code>public static File createTemporaryIndexedVcfFromInput(final File vcfFile, final String tempFilePrefix) throws IOException { final String extension; if (vcfFile.getAbsolutePath().endsWith(IOUtil.VCF_FILE_EXTENSION) ) extension = IOUtil.VCF_FILE_EXTENSION; else if (vcfFile.getAbsolutePath().endsWith(IOUtil.COMPRESSED_VCF_FILE_EXTENSION) ) extension = IOUtil.COMPRESSED_VCF_FILE_EXTENSION; else throw new IllegalArgumentException("couldn't find a " + IOUtil.VCF_FILE_EXTENSION + " or " + IOUtil.COMPRESSED_VCF_FILE_EXTENSION + " ending for input file " + vcfFile.getAbsolutePath()); File output = createTemporaryIndexedVcfFile(tempFilePrefix, extension); <START> final VCFFileReader in = new VCFFileReader(vcfFile, false); <END> final VCFHeader header = in.getFileHeader(); final VariantContextWriter out = new VariantContextWriterBuilder(). setReferenceDictionary(header.getSequenceDictionary()). setOptions(EnumSet.of(Options.INDEX_ON_THE_FLY)). setOutputFile(output).build(); out.writeHeader(header); for (final VariantContext ctx : in) { out.add(ctx); } out.close(); in.close(); return output; }</code><technical_language>I prefer try-with-resources handle this sort of closing</technical_language>

Target:
public static File createTemporaryIndexedVcfFromInput(final File vcfFile, final String tempFilePrefix) throws IOException { final String extension; if (vcfFile.getAbsolutePath().endsWith(IOUtil.VCF_FILE_EXTENSION)) extension = IOUtil.VCF_FILE_EXTENSION; else if (vcfFile.getAbsolutePath().endsWith(IOUtil.COMPRESSED_VCF_FILE_EXTENSION)) extension = IOUtil.COMPRESSED_VCF_FILE_EXTENSION; else throw new IllegalArgumentException("couldn't find a " + IOUtil.VCF_FILE_EXTENSION + " or " + IOUtil.COMPRESSED_VCF_FILE_EXTENSION + " ending for input file " + vcfFile.getAbsolutePath()); File output = createTemporaryIndexedVcfFile(tempFilePrefix, extension); try (final VCFFileReader in = new VCFFileReader(vcfFile, false); final VariantContextWriter out = new VariantContextWriterBuilder(). setReferenceDictionary(in.getFileHeader().getSequenceDictionary()). setOptions(EnumSet.of(Options.INDEX_ON_THE_FLY)). setOutputFile(output).build()) { out.writeHeader(in.getFileHeader()); for (final VariantContext ctx : in) { out.add(ctx); } } return output; }
Source:
<code>public synchronized void setDDFUUID(DDF ddf, UUID uuid) throws DDFException { if(this.containsDDF(uuid)) { throw new DDFException(String.format("DDF with uuid %s already exists", uuid)); } else { UUID prevUUID = ddf.getUUID(); ddf.setUUID(uuid); if(prevUUID != null) { mDDFCache.invalidate(prevUUID); mDDFCache.put(uuid, ddf); if(ddf.getUri() != null) { <START> mUris.remove(ddf.getUri()); <END> mUris.put(ddf.getUri(), ddf.getUUID()); } } } }</code><technical_language>this necessary put replace/remove current</technical_language>

Target:
public synchronized void setDDFUUID(DDF ddf, UUID uuid) throws DDFException { if (this.containsDDF(uuid)) { throw new DDFException(String.format("DDF with uuid %s already exists", uuid)); } else { UUID prevUUID = ddf.getUUID(); ddf.setUUID(uuid); if (prevUUID != null) { if (ddf.getName() == null) { mDDFCache.invalidate(prevUUID); mDDFCache.put(uuid, ddf); } else { mDDFwithNameCache.invalidate(prevUUID); mDDFCache.put(uuid, ddf); } if (ddf.getUri() != null) { mUris.put(ddf.getUri(), ddf.getUUID()); } } } }
Source:
<code>private boolean accept() { if (request instanceof BendpointRequest) { <START> ConnectionEditPart connectionEditPart = ((BendpointRequest) request).getSource(); <END> Iterable<ConnectionEditPart> selectedConnectionEditPartsIterable = Iterables.filter(connectionEditPart.getViewer().getSelectedEditParts(), ConnectionEditPart.class); Iterator<ConnectionEditPart> selectedConnectionEditParts = selectedConnectionEditPartsIterable.iterator(); boolean result = Iterables.size(selectedConnectionEditPartsIterable) == connectionEditPart.getViewer().getSelectedEditParts().size(); Set<Integer> edgeDirections = Sets.newLinkedHashSet(); while (selectedConnectionEditParts.hasNext() && result) { ConnectionEditPart selectedConnectionEditPart = selectedConnectionEditParts.next(); result = result && accept(selectedConnectionEditPart, edgeDirections); } return result && edgeDirections.size() == 1; } return false; }</code><technical_language>in previous patch set 8: Iterables.any() a predicate checks instanceof ConnectionEditPart "accept(selectedConnectionEditPart, edgeDirections)"</technical_language>

Target:
private boolean accept() { if (request instanceof BendpointRequest) { ConnectionEditPart connectionEditPart = ((BendpointRequest) request).getSource(); boolean result = Iterables.any(Iterables.filter(connectionEditPart.getViewer().getSelectedEditParts(), EditPart.class), new Predicate<EditPart>() { @Override public boolean apply(EditPart input) { return input instanceof ConnectionEditPart; } }); Iterator<ConnectionEditPart> selectedConnectionEditParts = Iterables.filter(connectionEditPart.getViewer().getSelectedEditParts(), ConnectionEditPart.class).iterator(); Set<Integer> edgeDirections = Sets.newLinkedHashSet(); while (selectedConnectionEditParts.hasNext() && result) { ConnectionEditPart selectedConnectionEditPart = selectedConnectionEditParts.next(); result = result && accept(selectedConnectionEditPart, edgeDirections); } return result && edgeDirections.size() == 1; } return false; }
Source:
<code>public Optional<FieldProjectionExpectations<ZonedDateTime>> getFieldProjectionExpectations() { return Optional.of( new FieldProjectionExpectations<>( LocalDateTime.of( 2018, 2, 1, 0, 0, 0, 1 ).atZone( ZoneId.of( "Europe/Paris" ) ), LocalDateTime.of( 2018, 3, 1, 0, 0 ).atZone( ZoneId.of( "Europe/Paris" ) ), <START> LocalDateTime.of( 2018, 4, 1, 0, 0 ).atZone( ZoneId.of( "Europe/Paris" ) ) <END> ) ); }</code><technical_language>too, timezones nice, check timezone is retrieved "Europe/Paris" chance, JVM default time zone</technical_language>

Target:
public Optional<FieldProjectionExpectations<ZonedDateTime>> getFieldProjectionExpectations() { return Optional.of( new FieldProjectionExpectations<>( LocalDateTime.of( 2018, 2, 1, 0, 0, 0, 1 ).atZone( ZoneId.of( "Europe/Paris" ) ), LocalDateTime.of( 2018, 3, 1, 0, 0 ).atZone( ZoneId.of( "Europe/Paris" ) ), LocalDateTime.of( 2018, 3, 1, 0, 0 ).atZone( ZoneId.of( "UTC" ) ) ) ); }
Source:
<code>protected void ExecuteVmCommand() { if (getParameters().getVmStaticData() != null) { mOldVmStatic = getVm().getStaticData(); getParameters().getVmStaticData().setcreation_date(mOldVmStatic.getcreation_date()); if (getParameters().getVmStaticData().getcreation_date().equals(DateTime.getMinValue()) || getParameters().getVmStaticData().getcreation_date().equals(DateTime.getMinValue())) { getParameters().getVmStaticData().setcreation_date(new Date()); } if (mOldVmStatic != null) { UpdateVmNetworks(); UpdateVmData(); <START> VmDeviceUtils.updateVmDevices(getVm().getStaticData(), (VmBase) mOldVmStatic); <END> if (((Boolean) Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(getVm().getstorage_pool_id())).getReturnValue()) .booleanValue()) { setVm(null); UpdateVmInSpm(getVm().getstorage_pool_id(), new java.util.ArrayList<VM>(java.util.Arrays.asList(new VM[] { getVm() }))); } setSucceeded(true); } } }</code><technical_language>downcast is redundant</technical_language>

Target:
protected void ExecuteVmCommand() { if (getParameters().getVmStaticData() != null) { mOldVmStatic = getVm().getStaticData(); getParameters().getVmStaticData().setcreation_date(mOldVmStatic.getcreation_date()); if (getParameters().getVmStaticData().getcreation_date().equals(DateTime.getMinValue()) || getParameters().getVmStaticData().getcreation_date().equals(DateTime.getMinValue())) { getParameters().getVmStaticData().setcreation_date(new Date()); } if (mOldVmStatic != null) { UpdateVmNetworks(); UpdateVmData(); VmDeviceUtils.updateVmDevices(getVm().getStaticData(), mOldVmStatic); if (((Boolean) Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(getVm().getstorage_pool_id())).getReturnValue()) .booleanValue()) { setVm(null); UpdateVmInSpm(getVm().getstorage_pool_id(), new java.util.ArrayList<VM>(java.util.Arrays.asList(new VM[] { getVm() }))); } setSucceeded(true); } } }
Source:
<code>private MimeBodyPart getContent(final EmailType type, final AbstractBuild<?, ?> build, MimeMessage msg, BuildListener listener, String charset) throws MessagingException { final String text = new ContentBuilder().transformText(type.getBody(), this, type, build, listener); String messageContentType = contentType; if (messageContentType == null || "default".equals(messageContentType)) { messageContentType = DESCRIPTOR.getDefaultContentType(); if (messageContentType == null) { messageContentType = "text/plain"; } } messageContentType += "; charset=" + charset; MimeBodyPart msgPart = new MimeBodyPart(); debug(listener.getLogger(), "messageContentType = %s", messageContentType); <START> if (messageContentType.equals("text/html")) { <END> String inlinedCssHtml = new CssInliner().process(text); msgPart.setContent(inlinedCssHtml, messageContentType); } else { msgPart.setContent(text, messageContentType); } return msgPart; }</code><technical_language>I this option do for HTML emails</technical_language>

Target:
private MimeBodyPart getContent(final EmailType type, final AbstractBuild<?, ?> build, MimeMessage msg, BuildListener listener, String charset) throws MessagingException { final String text = new ContentBuilder().transformText(type.getBody(), this, type, build, listener); String messageContentType = contentType; if (messageContentType == null || "default".equals(messageContentType)) { messageContentType = DESCRIPTOR.getDefaultContentType(); if (messageContentType == null) { messageContentType = "text/plain"; } } messageContentType += "; charset=" + charset; MimeBodyPart msgPart = new MimeBodyPart(); debug(listener.getLogger(), "messageContentType = %s", messageContentType); if (messageContentType.startsWith("text/html")) { String inlinedCssHtml = new CssInliner().process(text); msgPart.setContent(inlinedCssHtml, messageContentType); } else { msgPart.setContent(text, messageContentType); } return msgPart; }
Source:
<code>public FragmentedPlanStatsCalculator(StatsCalculator delegate, FragmentedPlanSourceProvider sourceProvider) { <START> this.delegate = delegate; <END> this.sourceProvider = sourceProvider; }</code><technical_language>null check</technical_language>

Target:
public FragmentedPlanStatsCalculator(StatsCalculator delegate, FragmentedPlanSourceProvider sourceProvider) { this.delegate = requireNonNull(delegate, "delegate is null"); this.sourceProvider = requireNonNull(sourceProvider, "source provider is null"); }
Source:
<code>public final static byte[] decode(byte[] sArr, int sOff, int sLen) throws DecodeException { try { return doDecode(sArr, sOff, sLen); <START> } catch (Exception e) { <END> throw new DecodeException(e); } }</code><technical_language>is RuntimeException enough</technical_language>

Target:
public final static byte[] decode(byte[] sArr, int sOff, int sLen) throws DecodeException { try { return doDecode(sArr, sOff, sLen); } catch (RuntimeException e) { throw new DecodeException(e); } }
Source:
<code>void buildPackageList(String property, PackageManager pm) { String searchPath = property; Log.d(LOG_TAG, <START> String.format("Search <END> path from property: <%s>", property)); if (searchPath == null) { searchPath = ""; } searchPath = searchPath.replaceAll("(?:^|:)" + DEFAULT_HELPERS + "(:|$)", "$1"); searchPath += ":" + DEFAULT_HELPERS; mLoadPackages.clear(); mSourceDirs.clear(); mPrefixes.clear(); for (String pkg : searchPath.split(":")) { if (pkg.isEmpty()) { continue; } ApplicationInfo info = null; try { info = pm.getApplicationInfo(pkg, PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { Log.w(LOG_TAG, String.format("Unable to find helper package %s", pkg)); continue; } mLoadPackages.add(pkg); mSourceDirs.add(info.publicSourceDir); if (info.metaData == null) { Log.w(LOG_TAG, String.format("Helper apk %s is missing meta-data.", pkg)); continue; } String prefix = info.metaData.getString("interaction-helpers-prefix"); if (prefix == null || prefix.isEmpty()) { Log.w(LOG_TAG, String.format("Helper apk %s does not set a class prefix", pkg)); } else if (!mPrefixes.contains(prefix)) { mPrefixes.add(prefix); } } }</code><technical_language>Canonical java use: "Search path property: < " + property + ">"</technical_language>

Target:
void buildPackageList(String property, PackageManager pm) { String searchPath = property; Log.d(LOG_TAG, "Search path from property: <" + property + ">"); if (searchPath == null) { searchPath = ""; } searchPath = searchPath.replaceAll("(?:^|:)" + DEFAULT_HELPERS + "(:|$)", "$1"); searchPath += ":" + DEFAULT_HELPERS; mLoadPackages.clear(); mSourceDirs.clear(); mPrefixes.clear(); for (String pkg : searchPath.split(":")) { if (pkg.isEmpty()) { continue; } ApplicationInfo info = null; try { info = pm.getApplicationInfo(pkg, PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { Log.w(LOG_TAG, String.format("Unable to find helper package %s", pkg)); continue; } mLoadPackages.add(pkg); mSourceDirs.add(info.publicSourceDir); if (info.metaData == null) { Log.w(LOG_TAG, String.format("Helper apk %s is missing meta-data.", pkg)); continue; } String prefix = info.metaData.getString("interaction-helpers-prefix"); if (prefix == null || prefix.isEmpty()) { Log.w(LOG_TAG, String.format("Helper apk %s does not set a class prefix", pkg)); } else if (!mPrefixes.contains(prefix)) { mPrefixes.add(prefix); } } }
Source:
<code><START> synchronized public static OrderManager getInstance() { <END> return sInstance; }</code><technical_language>need synchonized</technical_language>

Target:
public static OrderManager getInstance() { return sInstance; }
Source:
<code>private Future<Void> dispatchAssignmentChangeIfNeeded(String connectorType, List<DatastreamTask> assignment) { ConnectorWrapper connector = _connectors.get(connectorType); List<DatastreamTask> addedTasks = new ArrayList<>(assignment); List<DatastreamTask> removedTasks; List<DatastreamTask> oldAssignment = _assignedDatastreamTasks.values() .stream() .filter(t -> t.getConnectorType().equals(connectorType)) .collect(Collectors.toList()); addedTasks.removeAll(oldAssignment); oldAssignment.removeAll(assignment); removedTasks = oldAssignment; if (!addedTasks.isEmpty() || !removedTasks.isEmpty()) { _eventProducerPool.assignEventProducers(connectorType, addedTasks, removedTasks, _customCheckpointingConnectorTypes.contains(connectorType)); _assignmentChangeThreadPool.submit(() -> { try { connector.onAssignmentChange(assignment); } catch (Exception ex) { _log.warn( <START> "connector.onAssignmentChange threw an exception, Queuing up a new onAssignmentChange event for retry.", <END> ex); _eventQueue.put(CoordinatorEvent.createHandleInstanceErrorEvent(ExceptionUtils.getRootCauseMessage(ex))); _eventQueue.put(CoordinatorEvent.createHandleAssignmentChangeEvent()); } }); } return null; }</code><technical_language>nit: include connectorType in log message clearer</technical_language>

Target:
private Future<Void> dispatchAssignmentChangeIfNeeded(String connectorType, List<DatastreamTask> assignment) { ConnectorWrapper connector = _connectors.get(connectorType); List<DatastreamTask> addedTasks = new ArrayList<>(assignment); List<DatastreamTask> removedTasks; List<DatastreamTask> oldAssignment = _assignedDatastreamTasks.values() .stream() .filter(t -> t.getConnectorType().equals(connectorType)) .collect(Collectors.toList()); addedTasks.removeAll(oldAssignment); oldAssignment.removeAll(assignment); removedTasks = oldAssignment; if (!addedTasks.isEmpty() || !removedTasks.isEmpty()) { _eventProducerPool.assignEventProducers(connectorType, addedTasks, removedTasks, _customCheckpointingConnectorTypes.contains(connectorType)); _assignmentChangeThreadPool.submit(() -> { try { connector.onAssignmentChange(assignment); } catch (Exception ex) { _log.warn(String.format("connector.onAssignmentChange for connector %s threw an exception, " + "Queuing up a new onAssignmentChange event for retry.", connectorType), ex); _eventQueue.put(CoordinatorEvent.createHandleInstanceErrorEvent(ExceptionUtils.getRootCauseMessage(ex))); _eventQueue.put(CoordinatorEvent.createHandleAssignmentChangeEvent()); } }); } return null; }
Source:
<code>public void testCompositeBlobNotChunkSizeMultipleGetSuccess() throws Exception { <START> <END> maxChunkSize = random.nextInt(1024 * 1024) + 1; for (int i = 0; i < 10; i++) { blobSize = maxChunkSize * i + random.nextInt(maxChunkSize - 1) + 1; doPut(); getAndAssertSuccess(); } }</code><technical_language>extra line</technical_language>

Target:
public void testCompositeBlobNotChunkSizeMultipleGetSuccess() throws Exception { for (int i = 0; i < 10; i++) { blobSize = maxChunkSize * i + random.nextInt(maxChunkSize - 1) + 1; doPut(); getAndAssertSuccess(); } }
Source:
<code>public void stateChanged(CuratorFramework client, ConnectionState newState) { switch (newState) { case CONNECTED: case LOST: setState(State.SECONDARY); break; <START> case SUSPENDED: <END> case RECONNECTED: if (mConnectionErrorPolicy == ZookeeperConnectionErrorPolicy.STANDARD) { setState(State.SECONDARY); } else { if (newState == ConnectionState.SUSPENDED) { LOG.warn("Session suspended for primary selector at state: {}", getState()); } else { if (getState() == State.PRIMARY) { try { long reconnectSessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); if (mLeaderZkSessionId != reconnectSessionId) { LOG.warn(String.format( "Curator reconnected under a different session. " + "Old sessionId: %x, New sessionId: %x", mLeaderZkSessionId, reconnectSessionId)); setState(State.SECONDARY); } else { LOG.info(String.format( "Retaining leader state after zookeeper reconnected with sessionId: %x.", reconnectSessionId)); } } catch (Exception e) { LOG.warn(String .format("Cannot query session Id after session is reconnected with Id: %x", e)); setState(State.SECONDARY); } } } } break; default: throw new IllegalStateException(String.format("Unexpected state: %s", newState)); } if ((newState != ConnectionState.LOST) && (newState != ConnectionState.SUSPENDED)) { try { String leaderId = mLeaderSelector.getLeader().getId(); if (!leaderId.isEmpty()) { LOG.info("The current leader is {}", leaderId); } } catch (Exception e) { LOG.error(e.getMessage(), e); } } }</code><technical_language>if want fall check state</technical_language>

Target:
public void stateChanged(CuratorFramework client, ConnectionState newState) { if (mConnectionErrorPolicy == ZookeeperConnectionErrorPolicy.SESSION) { handleStateChangeSession(client, newState); } else { handleStateChangeStandard(client, newState); } if ((newState != ConnectionState.LOST) && (newState != ConnectionState.SUSPENDED)) { try { String leaderId = mLeaderSelector.getLeader().getId(); if (!leaderId.isEmpty()) { LOG.info("The current leader is {}", leaderId); } } catch (Exception e) { LOG.error(e.getMessage(), e); } } }
Source:
<code><START> protected void onPostExecute(AppInstallStatus result) { <END> super.onPostExecute(result); boolean inIncompleteState = !(result == AppInstallStatus.UpdateStaged || result == AppInstallStatus.UpToDate); if (inIncompleteState) { resourceManager.processUpdateFailure(result, ctx); } if (pinnedNotificationProgress != null) { pinnedNotificationProgress.handleTaskCompletion(result); } if (taskListener != null) { taskListener.handleTaskCompletion(result); } synchronized (lock) { singletonRunningInstance = null; } }</code><technical_language>want clear UpdateStats talked</technical_language>

Target:
protected void onPostExecute(AppInstallStatus result) { super.onPostExecute(result); if (!result.isUpdateInCompletedState()) { resourceManager.processUpdateFailure(result, ctx, wasTriggeredByAutoUpdate); } else if (wasTriggeredByAutoUpdate) { ResourceInstallUtils.recordAutoUpdateCompletion(app); } if (pinnedNotificationProgress != null) { pinnedNotificationProgress.handleTaskCompletion(result); } if (taskListener != null) { taskListener.handleTaskCompletion(result); } clearTaskInstance(); }
Source:
<code>public void deserializeParagraphFromDifferentDateFormat() { Paragraph paragraph = Note.GSON .fromJson("{\"dateUpdated\":\"2017-09-01 00:01:02.345\"}", Paragraph.class); <START> System.out.println(paragraph.dateUpdated); <END> }</code><technical_language>a unit test for that? i dont System.out.println is enough. assert</technical_language>

Target:
public void deserializeParagraphFromDifferentDateFormat() throws ParseException { String dateString = "2017-09-01 00:01:02.345"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(dateString); Paragraph paragraph = Note.GSON .fromJson("{\"dateUpdated\":\"" + dateString + "\"}", Paragraph.class); assertEquals(date, paragraph.dateUpdated); }
Source:
<code>private void loadDefaultProperties(String fileName) { try { Properties fileProps = new Properties(); InputStream fileStream; if(OSUtils.IS_ANDROID) { fileStream = getClass().getClassLoader() .getResourceAsStream(fileName); } else if(isLaunchedByWebStart()) { logger.info("WebStart classloader"); fileStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(fileName); } else { logger.info("Normal classloader"); fileStream = ClassLoader.getSystemResourceAsStream(fileName); } if(fileStream == null) { <START> logger.info("failed to find " + fileName + " with class loader, will continue without it."); <END> return; } fileProps.load(fileStream); fileStream.close(); for (Map.Entry<Object, Object> entry : fileProps.entrySet()) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); if ( name == null || value == null || name.trim().length() == 0) { continue; } if (name.startsWith("*")) { name = name.substring(1); if(name.trim().length() == 0) { continue; } immutableDefaultProperties.put(name, value); defaultProperties.remove(name); } else { defaultProperties.put(name, value); immutableDefaultProperties.remove(name); } } } catch (Exception ex) { logger.info("No defaults property file loaded: " + fileName + ". Not a problem."); if(logger.isDebugEnabled()) logger.debug("load exception", ex); } }</code><technical_language>This line is long, please wrap 80 chars</technical_language>

Target:
private void loadDefaultProperties(String fileName) { try { Properties fileProps = new Properties(); InputStream fileStream; if(OSUtils.IS_ANDROID) { fileStream = getClass().getClassLoader() .getResourceAsStream(fileName); } else if(isLaunchedByWebStart()) { logger.info("WebStart classloader"); fileStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(fileName); } else { logger.info("Normal classloader"); fileStream = ClassLoader.getSystemResourceAsStream(fileName); } if(fileStream == null) { logger.info("failed to find " + fileName + " with class " + "loader, will continue without it."); return; } fileProps.load(fileStream); fileStream.close(); for (Map.Entry<Object, Object> entry : fileProps.entrySet()) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); if ( name == null || value == null || name.trim().length() == 0) { continue; } if (name.startsWith("*")) { name = name.substring(1); if(name.trim().length() == 0) { continue; } immutableDefaultProperties.put(name, value); defaultProperties.remove(name); } else { defaultProperties.put(name, value); immutableDefaultProperties.remove(name); } } } catch (Exception ex) { logger.info("No defaults property file loaded: " + fileName + ". Not a problem."); if(logger.isDebugEnabled()) logger.debug("load exception", ex); } }
Source:
<code>void readsFromSingleClasspathResourceWithMoreHeadersThanLines() { CsvFileSource annotation = annotation("ISO-8859-1", "\n", ',', 10, "/single-column.csv"); Stream<Object[]> arguments = provide(new CsvFileArgumentsProvider(), annotation); <START> assertThat(arguments).containsExactly(); <END> }</code><technical_language>isEmpty()</technical_language>

Target:
void readsFromSingleClasspathResourceWithMoreHeadersThanLines() { CsvFileSource annotation = annotation("ISO-8859-1", "\n", ',', 10, "/single-column.csv"); Stream<Object[]> arguments = provide(new CsvFileArgumentsProvider(), annotation); assertThat(arguments).isEmpty(); }
Source:
<code>protected void onResume() { super.onResume(); try { checkForCrashes(); }catch (NoClassDefFoundError e){ <START> Log.w(TAG, "Busgnag is unsupported when building from Eclipse", e); <END> } }</code><technical_language>a error message "Failed checkForChrashes call" dump stack a line "e.printStackTrace();"</technical_language>

Target:
protected void onResume() { super.onResume(); try { checkForCrashes(); }catch (NoClassDefFoundError e){ Log.w(TAG, "Failed checkForChrashes call"); e.printStackTrace(); } }
Source:
<code><START> protected boolean isEmailProviderDisabled() { <END> return selectedProvider.equals(PROVIDER_DISABLED); }</code><technical_language>This method meant stay internal. I perspective author of this class. re-used part of other computations, is intended UI</technical_language>

Target:
private boolean isEmailProviderDisabled() { return selectedProvider.equals(PROVIDER_DISABLED); }
Source:
<code>NativeAllocation(int bytes, boolean testingDeadlock) throws Exception { this.bytes = bytes; register_native_allocation.invoke(runtime, bytes); synchronized (nativeLock) { if (!testingDeadlock) { nativeBytes += bytes; <START> if (nativeBytes > 2 * maxMem) { throw new OutOfMemoryError(); } <END> } } }</code><technical_language>Try running in gcstress mode</technical_language>

Target:
NativeAllocation(int bytes, boolean testingDeadlock) throws Exception { this.bytes = bytes; register_native_allocation.invoke(runtime, bytes); if (!testingDeadlock) { VMRuntime.runFinalization(0); } synchronized (nativeLock) { if (!testingDeadlock) { nativeBytes += bytes; if (nativeBytes > 2 * maxMem) { throw new OutOfMemoryError(); } } } }
Source:
<code><START> private void getAllCollapsedElements(@NonNull ITimeGraphEntry entry, @NonNull Set<@NonNull ITimeGraphEntry> collapsedEntries) { <END> if (!fTimeGraphCtrl.getExpandedState(entry)) { collapsedEntries.add(entry); } for (ITimeGraphEntry child : entry.getChildren()) { getAllCollapsedElements(child, collapsedEntries); } }</code><technical_language>more efficient collect collapsed entries children. In TimeGraphControl, expanded flag for items do children set true false API effect. a refresh() items leafs flag set false (collapsed)</technical_language>

Target:
private void getAllCollapsedElements(@NonNull ITimeGraphEntry entry, @NonNull Set<@NonNull ITimeGraphEntry> collapsedEntries) { if (entry.hasChildren() && !fTimeGraphCtrl.getExpandedState(entry)) { collapsedEntries.add(entry); } for (ITimeGraphEntry child : entry.getChildren()) { getAllCollapsedElements(child, collapsedEntries); } }
Source:
<code>public void nested_try_return_catch_finally() { ControlFlowGraph actualCfg = cfgForBlock("" + "try { " + " try {" + " tryBody(succ = [_empty], syntSucc = _empty);" + " return;" + " } catch (Exception $e) {" + " catchBody(succ=[finallyBody], pred = [_empty]);" + " } finally {" + " finallyBody(succ=[outerFinallyBody], pred = [catchBody,_empty]);" + <START> " }" + <END> "} finally {" + " outerFinallyBody(succ=[END], pred = [finallyBody]);" + "}"); ExpectedCfgStructure expectedCfgStructure = ExpectedCfgStructure.parse(actualCfg.blocks(), expected -> { expected.createEmptyBlockExpectation() .withPredecessorIds("tryBody") .withSuccessorsIds("catchBody", "finallyBody"); return expected; }); new Validator(expectedCfgStructure).assertCfg(actualCfg); }</code><technical_language>I this test more interesting if a statement</technical_language>

Target:
public void nested_try_return_catch_finally() { ControlFlowGraph actualCfg = cfgForBlock("" + "try { " + " try {" + " tryBody(succ = [_empty], syntSucc = _empty);" + " return;" + " } catch (Exception $e) {" + " catchBody(succ=[finallyBody], pred = [_empty]);" + " } finally {" + " finallyBody(succ=[afterInnerTry, outerFinallyBody], pred = [catchBody,_empty]);" + " }" + " afterInnerTry(succ = [outerFinallyBody], pred = [finallyBody]);" + "} finally {" + " outerFinallyBody(succ=[END], pred = [afterInnerTry, finallyBody]);" + "}"); ExpectedCfgStructure expectedCfgStructure = ExpectedCfgStructure.parse(actualCfg.blocks(), expected -> { expected.createEmptyBlockExpectation() .withPredecessorIds("tryBody") .withSuccessorsIds("catchBody", "finallyBody"); return expected; }); new Validator(expectedCfgStructure).assertCfg(actualCfg); }
Source:
<code>public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { if (!(hoverRegion.equals(this.lastRegion) && textViewer.equals(this.textViewer) && this.hoverRequest != null)) { initiateHoverRequest(textViewer, hoverRegion.getOffset()); } if (this.hoverRequest == null) { return null; } Hover hoverResult = null; try { hoverResult = this.hoverRequest.get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); } if (hoverResult == null) { return null; } StringBuilder res = new StringBuilder(); for (String string : hoverResult.getContents()) { res.append(string); <START> res.append('\n'); <END> } MarkdownLanguage markdownLanguage = new MarkdownLanguage(); StringWriter writer = new StringWriter(); MarkupParser parser = new MarkupParser(markdownLanguage, new HtmlDocumentBuilder(writer)); parser.parse(res.toString()); return writer.toString(); }</code><technical_language>markdown, this "\n\n" create a new paragraph. avoid 2 ones. I suggest hoverResuld.getContents().stream().collect(Collectors.joining("\n\n") in line</technical_language>

Target:
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { if (!(hoverRegion.equals(this.lastRegion) && textViewer.equals(this.textViewer) && this.hoverRequest != null)) { initiateHoverRequest(textViewer, hoverRegion.getOffset()); } if (this.hoverRequest == null) { return null; } Hover hoverResult = null; try { hoverResult = this.hoverRequest.get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); } if (hoverResult == null) { return null; } String result = hoverResult.getContents().stream().collect(Collectors.joining("\n\n")); return MARKDOWN_PARSER.parseToHtml(result); }
Source:
<code>public ValidationResult validate(Object value) { assert value == null || value instanceof String : "This validation must be run on a String!"; String mask = (String) value; <START> if (isPrefixAllowed) { <END> if (!(MaskValidator.getInstance().isPrefixValid(mask) || (MaskValidator.getInstance() .isValidNetmaskFormat(mask) && MaskValidator.getInstance().isNetmaskValid( mask)))) { return failWith(getBadPrefixFormatMessage()); } } else { if (!MaskValidator.getInstance().isValidNetmaskFormat(mask)) { return failWith(getBadNetmaskFormatMessage()); } else if (!MaskValidator.getInstance().isNetmaskValid(mask)) { return failWith(getInvalidMask()); } } return new ValidationResult(); }</code><technical_language>This flow simplified: if (isValidNetmaskFormat()) { if (!isNetmaskValid) { return failWith(getInvalidMask()); } } else { if (isPrefixAllowed) { if (!isPrefixValid()) { failWith(getBadPrefixFormatMessage()); } else { failWith(getBadNetmaskFormatMessage()); } } } This repeat method call</technical_language>

Target:
public ValidationResult validate(Object value) { assert value == null || value instanceof String : "This validation must be run on a String!"; String mask = (String) value; if (getMaskValidator().isValidNetmaskFormat(mask)) { if (!getMaskValidator().isNetmaskValid(mask)) { return failWith(getInvalidMask()); } } else { if (isPrefixAllowed) { if (!getMaskValidator().isPrefixValid(mask)) { return failWith(getBadPrefixOrNetmaskFormatMessage()); } } else { return failWith(getBadNetmaskFormatMessage()); } } return new ValidationResult(); }
Source:
<code>public PyCallExpressionTree callExpression(AstNode astNode) { PyExpressionTree callee = expression(astNode.getFirstChild()); AstNode argListNode = astNode.getFirstChild(PythonGrammar.ARGLIST); PyArgListTree argListTree = null; if (argListNode != null) { argListTree = new PyArgListTreeImpl(argListNode, argList(argListNode)); <START> } <END> return new PyCallExpressionTreeImpl(astNode, callee, argListTree, astNode.getFirstChild(PythonPunctuator.LPARENTHESIS), astNode.getFirstChild(PythonPunctuator.RPARENTHESIS)); }</code><technical_language>factorize code in a "argList" method return null</technical_language>

Target:
public PyCallExpressionTree callExpression(AstNode astNode) { PyExpressionTree callee = expression(astNode.getFirstChild()); AstNode argListNode = astNode.getFirstChild(PythonGrammar.ARGLIST); return new PyCallExpressionTreeImpl(astNode, callee, argList(argListNode), astNode.getFirstChild(PythonPunctuator.LPARENTHESIS), astNode.getFirstChild(PythonPunctuator.RPARENTHESIS)); }
Source:
<code><START> private List<GlusterServerHook> getMissingServerHooks() { <END> List<GlusterServerHook> serverHooks = new ArrayList<GlusterServerHook>(); for (GlusterServerHook serverHook: getGlusterHook().getServerHooks()) { if (serverHook.getStatus().equals(GlusterHookStatus.MISSING)) { serverHooks.add(serverHook); } } return serverHooks; }</code><technical_language>wouldnt cache this list in command? instead of calculating time (i more 1 call this method)</technical_language>

Target:
private List<GlusterServerHook> getMissingServerHooks() { if (missingServerHooks == null) { missingServerHooks = new ArrayList<GlusterServerHook>(); for (GlusterServerHook serverHook: getGlusterHook().getServerHooks()) { if (serverHook.getStatus().equals(GlusterHookStatus.MISSING)) { missingServerHooks.add(serverHook); } } } return missingServerHooks; }
Source:
<code>private void addEventListener(ClientDescriptor clientDescriptor, ServerSideServerStore cacheStore) { synchronized (eventListeners) { boolean wasEmpty = eventListeners.isEmpty(); <START> eventListeners.add(clientDescriptor); <END> if (wasEmpty) { cacheStore.enableEvents(true); } } }</code><technical_language>get with: java if (eventListeners.add(clientDescriptor) { cacheStore.enableEvents(true); }</technical_language>

Target:
private void addEventListener(ClientDescriptor clientDescriptor, ServerSideServerStore cacheStore) { synchronized (eventListeners) { if (eventListeners.add(clientDescriptor)) { cacheStore.enableEvents(true); } } }
Source:
<code>protected SecurityRealm[] getSecurityRealms() throws Exception { setUpKeyStores(); URL keystoreResource = Thread.currentThread().getContextClassLoader().getResource("security/server.keystore"); URL truststoreResource = Thread.currentThread().getContextClassLoader().getResource("security/jsse.keystore"); <START> ClassLoader clloader = Thread.currentThread().getContextClassLoader(); <END> RealmKeystore keystore = new RealmKeystore.Builder() .keystorePassword("changeit") .keystorePath(keystoreResource.getPath()) .build(); RealmKeystore truststore = new RealmKeystore.Builder() .keystorePassword("changeit") .keystorePath(truststoreResource.getPath()) .build(); return new SecurityRealm[]{new SecurityRealm.Builder() .name("ssl-realm") .serverIdentity( new ServerIdentity.Builder() .ssl(keystore) .build()) .authentication( new Authentication.Builder() .truststore(truststore) .build() ) .build()}; }</code><technical_language>Is this needed? referenced anywhere</technical_language>

Target:
protected SecurityRealm[] getSecurityRealms() throws Exception { setUpKeyStores(); URL keystoreResource = Thread.currentThread().getContextClassLoader().getResource("security/server.keystore"); URL truststoreResource = Thread.currentThread().getContextClassLoader().getResource("security/jsse.keystore"); RealmKeystore keystore = new RealmKeystore.Builder() .keystorePassword("changeit") .keystorePath(keystoreResource.getPath()) .build(); RealmKeystore truststore = new RealmKeystore.Builder() .keystorePassword("changeit") .keystorePath(truststoreResource.getPath()) .build(); return new SecurityRealm[]{new SecurityRealm.Builder() .name("ssl-realm") .serverIdentity( new ServerIdentity.Builder() .ssl(keystore) .build()) .authentication( new Authentication.Builder() .truststore(truststore) .build() ) .build()}; }
Source:
<code>public static boolean hasGitFolder(InputStream inputStream) throws IOException { TarArchiveInputStream tarInputStream = null; try { boolean gitFolderPresent = false; tarInputStream = new TarArchiveInputStream(new GzipCompressorInputStream(inputStream)); <START> for (TarArchiveEntry entry; (entry = tarInputStream.getNextTarEntry()) != null;) { <END> if (GIT_FOLDER_NAME.equals(entry.getName()) && entry.isDirectory()) { gitFolderPresent = true; break; } } return gitFolderPresent; } finally { StreamUtils.close(tarInputStream); } }</code><technical_language>this is a bad change: removig initialization, in this better</technical_language>

Target:
public static boolean hasGitFolder(InputStream inputStream) throws IOException { TarArchiveInputStream tarInputStream = null; try { boolean gitFolderPresent = false; tarInputStream = new TarArchiveInputStream(new GzipCompressorInputStream(inputStream)); for (TarArchiveEntry entry = null; (entry = tarInputStream.getNextTarEntry()) != null;) { if (GIT_FOLDER_NAME.equals(entry.getName()) && entry.isDirectory()) { gitFolderPresent = true; break; } } return gitFolderPresent; } finally { StreamUtils.close(tarInputStream); } }
Source:
<code><START> public void setTime(Time t) <END> { time = t; }</code><technical_language>this a valid spot package private level access instead of public? test is in package engine-tests? recall if works way</technical_language>

Target:
void setTime(Time t) { time = t; }
Source:
<code>public void shouldCapture() throws Exception { when(response.getStatus()).thenReturn(HttpStatus.SC_OK); Either<GatewayError, GatewayClient.Response> response = right(new TestResponse(this.response)); when(client.postRequestFor(anyString(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); Either<GatewayError, EpdqCaptureResponse> unmarshalledResponse = right(XMLUnmarshaller.unmarshall(load(EPDQ_CAPTURE_SUCCESS_RESPONSE), EpdqCaptureResponse.class)); when(client.unmarshallResponse(any(TestResponse.class), any(Class.class))).thenReturn(unmarshalledResponse); CaptureResponse gatewayResponse = epdqCaptureHandler.capture(buildTestCaptureRequest()); assertTrue(gatewayResponse.isSuccessful()); assertThat(gatewayResponse.getTransactionId().isPresent(), is(true)); assertThat(gatewayResponse.getTransactionId().get(), is("3014644340")); <START> } <END></code><technical_language>assert state well, CaptureResponse contains state</technical_language>

Target:
public void shouldCapture() throws Exception { when(response.getStatus()).thenReturn(HttpStatus.SC_OK); Either<GatewayError, GatewayClient.Response> response = right(new TestResponse(this.response)); when(client.postRequestFor(anyString(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); Either<GatewayError, EpdqCaptureResponse> unmarshalledResponse = right(XMLUnmarshaller.unmarshall(load(EPDQ_CAPTURE_SUCCESS_RESPONSE), EpdqCaptureResponse.class)); when(client.unmarshallResponse(any(TestResponse.class), any(Class.class))).thenReturn(unmarshalledResponse); CaptureResponse gatewayResponse = epdqCaptureHandler.capture(buildTestCaptureRequest()); assertTrue(gatewayResponse.isSuccessful()); assertThat(gatewayResponse.state(), is(CaptureResponse.ChargeState.PENDING)); assertThat(gatewayResponse.getTransactionId().isPresent(), is(true)); assertThat(gatewayResponse.getTransactionId().get(), is("3014644340")); }
Source:
<code>public void testInit() { when(safeUri.asString()).thenReturn("someUri"); Metadata metadata = mock(Metadata.class); Command callback = mock(Command.class); tested.init(metadata, callback); ArgumentCaptor<com.ait.lienzo.client.core.image.ImageStrip[]> stripsCaptor = ArgumentCaptor.forClass(com.ait.lienzo.client.core.image.ImageStrip[].class); verify(lienzoStripRegistration, times(1)).accept(stripsCaptor.capture(), any(Runnable.class)); final com.ait.lienzo.client.core.image.ImageStrip[] strips = stripsCaptor.getValue(); assertNotNull(strips); <START> assertTrue(strips.length == 1); <END> assertEquals("someUri", strips[0].getUrl()); assertEquals(16, strips[0].getWide()); assertEquals(16, strips[0].getHigh()); assertEquals(5, strips[0].getPadding()); assertEquals(com.ait.lienzo.client.core.image.ImageStrip.Orientation.HORIZONTAL, strips[0].getOrientation()); assertFalse(tested.getRegistered().isEmpty()); }</code><technical_language>assertEquals(1, strips.length); instead</technical_language>

Target:
public void testInit() { when(safeUri.asString()).thenReturn("someUri"); Metadata metadata = mock(Metadata.class); Command callback = mock(Command.class); tested.init(metadata, callback); ArgumentCaptor<com.ait.lienzo.client.core.image.ImageStrip[]> stripsCaptor = ArgumentCaptor.forClass(com.ait.lienzo.client.core.image.ImageStrip[].class); verify(lienzoStripRegistration, times(1)).accept(stripsCaptor.capture(), any(Runnable.class)); final com.ait.lienzo.client.core.image.ImageStrip[] strips = stripsCaptor.getValue(); assertNotNull(strips); assertEquals(1, strips.length); assertEquals("someUri", strips[0].getUrl()); assertEquals(16, strips[0].getWide()); assertEquals(16, strips[0].getHigh()); assertEquals(5, strips[0].getPadding()); assertEquals(com.ait.lienzo.client.core.image.ImageStrip.Orientation.HORIZONTAL, strips[0].getOrientation()); assertFalse(tested.getRegistered().isEmpty()); }
Source:
<code>Builder addClientCapabilities(Collection<String> clientCapabilities) { for (String cap: clientCapabilities) { if (cap.startsWith("agent=")) { setAgent(cap.substring("agent=".length())); } else { clientCaps.add(cap); } } <START> clientCaps.addAll(clientCapabilities); <END> return this; }</code><technical_language>This adds caps a time</technical_language>

Target:
Builder addClientCapabilities(Collection<String> clientCapabilities) { for (String cap: clientCapabilities) { if (cap.startsWith("agent=")) { setAgent(cap.substring("agent=".length())); } else { clientCaps.add(cap); } } return this; }
Source:
<code>protected static Imports getImports(JSIImportsType source) { Imports toReturn = new Imports(); <START> if (source != null) { final JSIWrappedImportsType imports = source.getImports(); if (imports != null) { imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } } <END> return toReturn; }</code><technical_language>This variant is a bit shorter readable, do think? java if (source != null && source.getImports() != null) { final JSIWrappedImportsType imports = source.getImports(); imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); }</technical_language>

Target:
protected static Imports getImports(JSIImportsType source) { Imports toReturn = new Imports(); if (source != null && source.getImports() != null) { final JSIWrappedImportsType imports = source.getImports(); imports.getImport().forEach(importsType -> toReturn.addImport(getImport(importsType))); } return toReturn; }
Source:
<code>public static void setUpClass() throws Exception { repository = new TestRepository(); repository.create(SearchControllerTest.class.getResourceAsStream("/org/opengrok/indexer/index/source.zip")); env.setHistoryEnabled(false); env.setProjectsEnabled(true); Indexer.getInstance().prepareIndexer(env, true, true, false, null, null); env.setDefaultProjectsFromNames(Collections.singleton("__all__")); <START> Indexer.getInstance().doIndexerExecution(true, null, null); <END> env.getSuggesterConfig().setRebuildCronConfig(null); }</code><technical_language>is necessary run indexer test simple cors header in response</technical_language>

Target:
public static void setUpClass() throws Exception { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); repository = new TestRepository(); repository.create(SearchControllerTest.class.getResourceAsStream("/org/opengrok/indexer/index/source.zip")); env.setHistoryEnabled(false); env.setProjectsEnabled(true); env.setDefaultProjectsFromNames(Collections.singleton("__all__")); env.getSuggesterConfig().setRebuildCronConfig(null); }
Source:
<code>protected void callRebindHooks() { <START> long delay = (long) (Math.random() * MAX_REBIND_SENSOR_CONNECT_DELAY); <END> log.info("Scheduled reconnection of sensors on in {}ms", this, delay); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { connectSensors(); } }, delay); }</code><technical_language>Check if rebind delay is enabled, configured delay, set delay zero</technical_language>

Target:
protected void callRebindHooks() { Duration configuredMaxDelay = getConfig(MAXIMUM_REBIND_SENSOR_CONNECT_DELAY); if (configuredMaxDelay == null || Duration.ZERO.equals(configuredMaxDelay)) { connectSensors(); } else { long delay = (long) (Math.random() * configuredMaxDelay.toMilliseconds()); log.debug("Scheduled reconnection of sensors on in {}ms", this, delay); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { connectSensors(); } }, delay); } }