auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public PluginLoader(SitePaths sitePaths, PluginGuiceEnvironment pe, ServerInformationImpl sii, PluginUser.Factory puf, Provider<PluginCleanerTask> pct, @GerritServerConfig Config cfg, @CanonicalWebUrl Provider<String> provider) { pluginsDir = sitePaths.plugins_dir; dataDir = sitePaths.data_dir; tmpDir = sitePaths.tmp_dir; env = pe; srvInfoImpl = sii; pluginUserFactory = puf; running = Maps.newConcurrentMap(); disabled = Maps.newConcurrentMap(); broken = Maps.newHashMap(); toCleanup = Queues.newArrayDeque(); cleanupHandles = Maps.newConcurrentMap(); cleaner = pct; urlProvider = provider; <START> remoteInstall = <END> cfg.getBoolean("plugins", null, "allowRemoteAdmin", false); long checkFrequency = ConfigUtil.getTimeUnit(cfg, "plugins", null, "checkFrequency", TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); if (checkFrequency > 0) { scanner = new PluginScannerThread(this, checkFrequency); } else { scanner = null; } }</code><technical_language>Nit: name of variable longer matches name of config parameter, I this is a blocker</technical_language>

Target:
public PluginLoader(SitePaths sitePaths, PluginGuiceEnvironment pe, ServerInformationImpl sii, PluginUser.Factory puf, Provider<PluginCleanerTask> pct, @GerritServerConfig Config cfg, @CanonicalWebUrl Provider<String> provider) { pluginsDir = sitePaths.plugins_dir; dataDir = sitePaths.data_dir; tmpDir = sitePaths.tmp_dir; env = pe; srvInfoImpl = sii; pluginUserFactory = puf; running = Maps.newConcurrentMap(); disabled = Maps.newConcurrentMap(); broken = Maps.newHashMap(); toCleanup = Queues.newArrayDeque(); cleanupHandles = Maps.newConcurrentMap(); cleaner = pct; urlProvider = provider; remoteAdmin = cfg.getBoolean("plugins", null, "allowRemoteAdmin", false); long checkFrequency = ConfigUtil.getTimeUnit(cfg, "plugins", null, "checkFrequency", TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS); if (checkFrequency > 0) { scanner = new PluginScannerThread(this, checkFrequency); } else { scanner = null; } }
Source:
<code>private static Retry createRetry(AmqpRetryOptions options) { if (options.getDelay() == null || options.getDelay().equals(Duration.ZERO)) { <START> return Retry.max(0L); <END> } final Duration delay = options.getDelay().plus(SERVER_BUSY_WAIT_TIME); final RetryBackoffSpec retrySpec; switch (options.getMode()) { case FIXED: retrySpec = Retry.fixedDelay(options.getMaxRetries(), delay); break; case EXPONENTIAL: retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; default: LOGGER.warning("Unknown: '{}'. Using exponential delay. Delay: {}. Max Delay: {}. Max Retries: {}.", options.getMode(), options.getDelay(), options.getMaxDelay(), options.getMaxRetries()); retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; } return retrySpec.jitter(JITTER_FACTOR) .maxBackoff(options.getMaxDelay()) .filter(error -> error instanceof TimeoutException || error instanceof AmqpException && ((AmqpException) error).isTransient()); }</code><technical_language>is delay attempt retries? want this instead? java return Retry.max(options.getMaxRetries());</technical_language>

Target:
private static Retry createRetry(AmqpRetryOptions options) { if (options.getDelay() == null || options.getDelay().equals(Duration.ZERO)) { return Retry.max(0L); } final Duration delay = options.getDelay().plus(SERVER_BUSY_WAIT_TIME); final RetryBackoffSpec retrySpec; switch (options.getMode()) { case FIXED: retrySpec = Retry.fixedDelay(options.getMaxRetries(), delay); break; case EXPONENTIAL: retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; default: LOGGER.warning("Unknown: '{}'. Using exponential delay. Delay: {}. Max Delay: {}. Max Retries: {}.", options.getMode(), options.getDelay(), options.getMaxDelay(), options.getMaxRetries()); retrySpec = Retry.backoff(options.getMaxRetries(), delay); break; } return retrySpec.jitter(JITTER_FACTOR) .maxBackoff(options.getMaxDelay()) .filter(error -> error instanceof TimeoutException || (error instanceof AmqpException && ((AmqpException) error).isTransient())); }
Source:
<code>public String convert(Sort sort) { if (sort == null || sort.getSort() == null) { return ""; } List<SortField> fields = Arrays.asList(sort.getSort()); String sortString = fields.stream() .filter(sortField -> sortField.getField() != null) .map(sortField -> { String key = this.converterImpl.convertKey(sortField.getField()); <START> String value = ASC; <END> if (sortField.getReverse()) { value = DESC; } return key + " " + value; }).collect(Collectors.joining(",")); return sortString; }</code><technical_language>If I understand right, this variable named sortOrder is confusing,</technical_language>

Target:
public String convert(Sort sort) { if (sort == null || sort.getSort() == null) { return ""; } List<SortField> fields = Arrays.asList(sort.getSort()); String sortString = fields.stream() .filter(sortField -> sortField.getField() != null) .map(sortField -> { String key = this.converterImpl.convertKey(sortField.getField()); String sortDirection = ASC; if (sortField.getReverse()) { sortDirection = DESC; } return key + " " + sortDirection; }).collect(Collectors.joining(",")); return sortString; }
Source:
<code>private ShadowDOM.Update createShadowDOMUpdate() { mDOMProvider.verifyThreadAccess(); if (mDOMProvider.getRootElement() != mShadowDOM.getRootElement()) { throw new IllegalStateException(); } ShadowDOM.UpdateBuilder updateBuilder = mShadowDOM.beginUpdate(); ListAccumulator<Object> childrenAccumulator = acquireChildrenAccumulator(); Queue<Object> queue = new ArrayDeque<>(); queue.add(mDOMProvider.getRootElement()); while (!queue.isEmpty()) { final Object element = queue.remove(); NodeDescriptor descriptor = mDOMProvider.getNodeDescriptor(element); mObjectIdMapper.putObject(element); descriptor.getChildren(element, childrenAccumulator); updateBuilder.setElementChildren(element, childrenAccumulator); <START> for (int i = 0, N = childrenAccumulator.size(); i < N; ++i) { <END> queue.add(childrenAccumulator.get(i)); } childrenAccumulator.clear(); } releaseChildrenAccumulator(childrenAccumulator); return updateBuilder.build(); }</code><technical_language>a neat pattern :)</technical_language>

Target:
private ShadowDOM.Update createShadowDOMUpdate() { mDOMProvider.verifyThreadAccess(); if (mDOMProvider.getRootElement() != mShadowDOM.getRootElement()) { throw new IllegalStateException(); } ArrayListAccumulator<Object> childrenAccumulator = acquireChildrenAccumulator(); ShadowDOM.UpdateBuilder updateBuilder = mShadowDOM.beginUpdate(); Queue<Object> queue = new ArrayDeque<>(); queue.add(mDOMProvider.getRootElement()); while (!queue.isEmpty()) { final Object element = queue.remove(); NodeDescriptor descriptor = mDOMProvider.getNodeDescriptor(element); mObjectIdMapper.putObject(element); descriptor.getChildren(element, childrenAccumulator); updateBuilder.setElementChildren(element, childrenAccumulator); for (int i = 0, N = childrenAccumulator.size(); i < N; ++i) { queue.add(childrenAccumulator.get(i)); } childrenAccumulator.clear(); } releaseChildrenAccumulator(childrenAccumulator); return updateBuilder.build(); }
Source:
<code>public abstract void append(Event event) throws EventDeliveryException; @Override public abstract void appendBatch(List<Event> events) throws EventDeliveryException; @Override public abstract boolean isActive(); @Override public abstract void close() throws FlumeException; protected abstract void configure(Properties properties) throws FlumeException; <START> public static int parseBatchSize(Properties properties) { <END> String strBatchSize = properties.getProperty( RpcClientConfigurationConstants.CONFIG_BATCH_SIZE); logger.debug("Batch size string = " + strBatchSize); int _batchSize = RpcClientConfigurationConstants.DEFAULT_BATCH_SIZE; if (strBatchSize != null && !strBatchSize.isEmpty()) { try { int parsedBatch = Integer.parseInt(strBatchSize); if (parsedBatch < 1) { logger.warn("Invalid value for batchSize: {}; Using default value.", parsedBatch); } else { _batchSize = parsedBatch; } } catch (NumberFormatException e) { logger.warn("Batchsize is not valid for RpcClient: " + strBatchSize + ". Default value assigned.", e); } } return _batchSize; }</code><technical_language>AbstractRpcClient place for this static method. _batchSize a bit strange in java. AbstractRpcClient.parseBatchSize(clientProps) call in AbstractRpcSink too. I consider move method a utility class (or RpcClient)</technical_language>

Target:
public abstract void append(Event event) throws EventDeliveryException; @Override public abstract void appendBatch(List<Event> events) throws EventDeliveryException; @Override public abstract boolean isActive(); @Override public abstract void close() throws FlumeException; protected abstract void configure(Properties properties) throws FlumeException; public static int parseBatchSize(Properties properties) { String strBatchSize = properties.getProperty( RpcClientConfigurationConstants.CONFIG_BATCH_SIZE); logger.debug("Batch size string = " + strBatchSize); int batchSize = RpcClientConfigurationConstants.DEFAULT_BATCH_SIZE; if (strBatchSize != null && !strBatchSize.isEmpty()) { try { int parsedBatch = Integer.parseInt(strBatchSize); if (parsedBatch < 1) { logger.warn("Invalid value for batchSize: {}; Using default value.", parsedBatch); } else { batchSize = parsedBatch; } } catch (NumberFormatException e) { logger.warn("Batchsize is not valid for RpcClient: " + strBatchSize + ". Default value assigned.", e); } } return batchSize; }
Source:
<code>public void visit(LambdaExpr n, Object arg) { printJavaComment(n.getComment(), arg); List<Parameter> parameters = n.getParameters(); <START> boolean printPar = n.isParametersEnclosed(); <END> if (printPar) { printer.print("("); } if (parameters != null) { for (Iterator<Parameter> i = parameters.iterator(); i.hasNext();) { Parameter p = i.next(); p.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } } if (printPar) { printer.print(")"); } printer.print(" -> "); Statement body = n.getBody(); if (body instanceof ExpressionStmt) { ((ExpressionStmt) body).getExpression().accept(this, arg); } else { body.accept(this, arg); } }</code><technical_language>printPar final</technical_language>

Target:
public void visit(LambdaExpr n, Object arg) { printJavaComment(n.getComment(), arg); final List<Parameter> parameters = n.getParameters(); final boolean printPar = n.isParametersEnclosed(); if (printPar) { printer.print("("); } if (parameters != null) { for (Iterator<Parameter> i = parameters.iterator(); i.hasNext();) { Parameter p = i.next(); p.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } } if (printPar) { printer.print(")"); } printer.print(" -> "); final Statement body = n.getBody(); if (body instanceof ExpressionStmt) { ((ExpressionStmt) body).getExpression().accept(this, arg); } else { body.accept(this, arg); } }
Source:
<code>private Set<MpackInstance> copyAndEnrichMpackInstances(ClusterTopology topology) { Set<MpackInstance> mpacks = topology.getMpacks().stream().map(MpackInstance::copy).collect(toSet()); Map<StackId, Set<String>> mpackServices = topology.getComponents().collect(toMap( ResolvedComponent::stackId, comp -> ImmutableSet.of(comp.serviceInfo().getName()), <START> (set1, set2) -> ImmutableSet.copyOf(Sets.union(set1, set2)) <END> )); for (MpackInstance mpack: mpacks) { if (!mpackServices.containsKey(mpack.getStackId())) { LOG.warn("No services declared for mpack {}.", mpack.getStackId()); } else { Set<String> existingMpackServices = mpack.getServiceInstances().stream().map(ServiceInstance::getType).collect(toSet()); for(String service: mpackServices.get(mpack.getStackId())) { if (existingMpackServices.contains(service)) { LOG.debug("Mpack instance already contains service {}", mpack.getStackId(), service); } else { LOG.debug("Adding service to mpack instance {}", service, mpack.getStackId()); mpack.getServiceInstances().add(new ServiceInstance(service, service, null, mpack)); } } } } return mpacks; }</code><technical_language>done expensively (and more simply) built-ins: Map<StackId, Set<String>> mpackServices = topology.getComponents().collect( groupingBy(ResolvedComponent::stackId, mapping(comp -> comp.serviceInfo().getName(), toSet())));</technical_language>

Target:
private Set<MpackInstance> copyAndEnrichMpackInstances(ClusterTopology topology) { Set<MpackInstance> mpacks = topology.getMpacks().stream().map(MpackInstance::copy).collect(toSet()); Map<StackId, Set<String>> mpackServices = topology.getComponents().collect( groupingBy(ResolvedComponent::stackId, mapping(comp -> comp.serviceInfo().getName(), toSet()))); for (MpackInstance mpack: mpacks) { if (!mpackServices.containsKey(mpack.getStackId())) { LOG.warn("No services declared for mpack {}.", mpack.getStackId()); } else { Set<String> existingMpackServices = mpack.getServiceInstances().stream().map(ServiceInstance::getType).collect(toSet()); for(String service: mpackServices.get(mpack.getStackId())) { if (existingMpackServices.contains(service)) { LOG.debug("Mpack instance already contains service {}", mpack.getStackId(), service); } else { LOG.debug("Adding service to mpack instance {}", service, mpack.getStackId()); mpack.getServiceInstances().add(new ServiceInstance(service, service, null, mpack)); } } } } return mpacks; }
Source:
<code>public Thread newThread(Runnable r) { Thread t = new Thread(group, r, "junit-timeout-thread-" + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) <START> t.setPriority(Thread.NORM_PRIORITY); <END> return t; }</code><technical_language>I need ifs shut executor afterwards</technical_language>

Target:
public Thread newThread(Runnable r) { return new Thread(r, "junit-timeout-thread-" + threadNumber.getAndIncrement()); }
Source:
<code>public Set<String> keySet() { Set<String> keys = new HashSet<>(); <START> keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, new Object[]{this.region}, String.class)); <END> return Collections.unmodifiableSet(keys); }</code><technical_language>is this variant simplify code here: queryForList(String sql, Class<T> elementType, @Nullable Object... args)</technical_language>

Target:
public Set<String> keySet() { Set<String> keys = new HashSet<>(); keys.addAll(this.jdbcTemplate.queryForList(this.getAllKeysQuery, String.class, this.region)); return Collections.unmodifiableSet(keys); }
Source:
<code>public void testLatestVersion() { APIVersion expectedLatest = APIVersion.VALID_VERSIONS.values() <START> .stream() <END> .max(Comparator.comparingInt(v -> v.version)) .orElseThrow(); assertEquals(expectedLatest, APIVersion.latest()); }</code><technical_language>Formatting</technical_language>

Target:
public void testLatestVersion() { APIVersion expectedLatest = APIVersion.VALID_VERSIONS.values() .stream() .max(APIVersion.COMPARATOR) .orElseThrow(); assertEquals(expectedLatest, APIVersion.latest()); }
Source:
<code>public HttpResponseException(final int statusCode, final String s) { <START> super(s == null || s.isEmpty() ? Integer.toString(statusCode) : s); <END> this.statusCode = statusCode; }</code><technical_language>@panchenko good. mind TextUtils#isBlank instead, please</technical_language>

Target:
public HttpResponseException(final int statusCode, final String s) { super(TextUtils.isBlank(s) ? Integer.toString(statusCode) : s); this.statusCode = statusCode; }
Source:
<code>public List<DiffEntry> call() throws GitAPIException, IOException { final DiffFormatter diffFmt = new DiffFormatter(null); diffFmt.setRepository(repo); try { if (cached) { if (oldTree == null) { ObjectId head = repo.resolve(HEAD + "^{tree}"); if (head == null) throw new NoHeadException(JGitText.get().cannotReadTree); CanonicalTreeParser p = new CanonicalTreeParser(); ObjectReader reader = repo.newObjectReader(); try { p.reset(reader, head); } finally { reader.release(); } oldTree = p; } newTree = new DirCacheIterator(repo.readDirCache()); } else if (oldTree == null) { oldTree = new DirCacheIterator(repo.readDirCache()); <START> newTree = new FileTreeIterator(repo); <END> } else if (newTree == null) newTree = new FileTreeIterator(repo); diffFmt.setPathFilter(pathFilter); if (showNameAndStatusOnly) { return diffFmt.scan(oldTree, newTree); } else { throw new UnsupportedOperationException(); } } finally { diffFmt.release(); } }</code><technical_language>overwrite newtree checked is explicitly set? If sets newTree oldTree ignore newTree</technical_language>

Target:
public List<DiffEntry> call() throws GitAPIException, IOException { final DiffFormatter diffFmt = new DiffFormatter(null); diffFmt.setRepository(repo); try { if (cached) { if (oldTree == null) { ObjectId head = repo.resolve(HEAD + "^{tree}"); if (head == null) throw new NoHeadException(JGitText.get().cannotReadTree); CanonicalTreeParser p = new CanonicalTreeParser(); ObjectReader reader = repo.newObjectReader(); try { p.reset(reader, head); } finally { reader.release(); } oldTree = p; } newTree = new DirCacheIterator(repo.readDirCache()); } else { if (oldTree == null) oldTree = new DirCacheIterator(repo.readDirCache()); if (newTree == null) newTree = new FileTreeIterator(repo); } diffFmt.setPathFilter(pathFilter); if (showNameAndStatusOnly) { return diffFmt.scan(oldTree, newTree); } else { throw new UnsupportedOperationException(); } } finally { diffFmt.release(); } }
Source:
<code>public void setTypeMap(Map<String, Class<?>> map) throws SQLException { Map<String, Class<?>> newMap = new HashMap<>(map); Map<Class<?>, Set<String>> newDirectMap = new HashMap<>(); Map<Class<?>, Set<String>> newInheritedMap = new HashMap<>(); for (Map.Entry<String, Class<?>> entry : newMap.entrySet()) { String type = entry.getKey(); Class<?> directClass = entry.getValue(); addInference(newDirectMap, directClass, type); for (Class<?> clazz : getAllClasses(directClass)) { addInference(newInheritedMap, clazz, type); } } makeValuesUnmodifiable(newDirectMap); makeValuesUnmodifiable(newInheritedMap); <START> synchronized (typemapLock) { <END> typemap = Collections.unmodifiableMap(newMap); inferenceMapDirect = Collections.unmodifiableMap(newDirectMap); inferenceMapInherited = Collections.unmodifiableMap(newInheritedMap); } LOGGER.log(Level.FINE, " setTypeMap = {0}", map); }</code><technical_language>is purpose of this synchronization? reads (from get methods) synchronized. Is concern handle concurrent calls setTypeMap PgConnection</technical_language>

Target:
public void setTypeMap(Map<String, Class<?>> map) throws SQLException { checkClosed(); if (map == null || map.isEmpty()) { udtMap = UdtMap.EMPTY; } else { udtMap = new UdtMap(new LinkedHashMap<String, Class<?>>(map)); } LOGGER.log(Level.FINE, " setTypeMap = {0}", map); }
Source:
<code>private String getCurrentSuitePrefix(ITestResult iTestResult){ <START> return "{" + getCurrentSuiteName(iTestResult.getTestContext()) +"}"; <END> }</code><technical_language>space +</technical_language>

Target:
private String getCurrentSuitePrefix(ITestResult iTestResult){ return "{" + getCurrentSuiteTitle(iTestResult.getTestContext()) + "}"; }
Source:
<code>public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; <START> synchronized (sActiveDelegatesLock) { <END> applyDayNightToActiveDelegates(); } } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } }</code><technical_language>Push synchronization block method</technical_language>

Target:
public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; applyDayNightToActiveDelegates(); } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } }
Source:
<code>public void testZeroLengthPutHasContentLengthHeader() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().addHeader(ETAG, "ABCDEF")); server.play(); S3Client client = getS3Client(server.getUrl("/")); S3Object nada = client.newS3Object(); nada.getMetadata().setKey("object"); nada.setPayload(new byte[] {}); assertEquals(client.putObject("bucket", nada), "ABCDEF"); RecordedRequest request = server.takeRequest(); assertEquals(request.getRequestLine(), "PUT /bucket/object HTTP/1.1"); assertEquals(request.getHeaders(CONTENT_LENGTH), ImmutableList.of("0")); <START> assert request.getHeaders(EXPECT).isEmpty(); <END> server.shutdown(); }</code><technical_language>Call assertThat(request.getHeaders(EXPECT).isEmpty())</technical_language>

Target:
public void testZeroLengthPutHasContentLengthHeader() throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().addHeader(ETAG, "ABCDEF")); server.play(); S3Client client = getS3Client(server.getUrl("/")); S3Object nada = client.newS3Object(); nada.getMetadata().setKey("object"); nada.setPayload(new byte[] {}); assertEquals(client.putObject("bucket", nada), "ABCDEF"); RecordedRequest request = server.takeRequest(); assertEquals(request.getRequestLine(), "PUT /bucket/object HTTP/1.1"); assertEquals(request.getHeaders(CONTENT_LENGTH), ImmutableList.of("0")); assertThat(request.getHeaders(EXPECT)).isEmpty(); server.shutdown(); }
Source:
<code>public Subscription subscribe() { return storIOSQLite .get() .listOfObjects(User.class) .withQuery(UserTableMeta.QUERY_ALL) .prepare() .createObservableStream() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) <START> .subscribe(new Observer<List<User>>() { <END> @Override public void onError(Throwable e) { fail("Error occurred: " + e); } @Override public void onNext(List<User> users) { onNextObtained(users); } @Override public void onCompleted() { } }); }</code><technical_language>java .subscribe(new Action1<ResultType> { });</technical_language>

Target:
public Subscription subscribe() { return storIOSQLite .get() .listOfObjects(User.class) .withQuery(UserTableMeta.QUERY_ALL) .prepare() .createObservable() .subscribeOn(Schedulers.io()) .subscribe(new Action1<List<User>>() { @Override public void call(List<User> users) { onNextObtained(users); } }); }
Source:
<code>public void query( IndexProgressor.NodeValueClient cursor, IndexOrder indexOrder, IndexQuery... predicates ) throws IndexNotApplicableKernelException { if ( predicates.length > 1 ) { luceneReader.query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof ExactPredicate ) { ExactPredicate exactPredicate = (ExactPredicate) predicates[0]; selector.select( nativeReader, luceneReader, exactPredicate.value() ).query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof NumberRangePredicate ) { nativeReader.query( cursor, indexOrder, predicates[0] ); return; } if ( predicates[0] instanceof ExistsPredicate ) { <START> MultiProgressorNodeValueCursor multiProgressor = new MultiProgressorNodeValueCursor( cursor, propertyKeys ); <END> cursor.initialize( multiProgressor, propertyKeys ); nativeReader.query( multiProgressor, indexOrder, predicates[0] ); luceneReader.query( multiProgressor, indexOrder, predicates[0] ); return; } luceneReader.query( cursor, indexOrder, predicates ); }</code><technical_language>If provide ExistsPredicate a IndexOrder need fail if serve it</technical_language>

Target:
public void query( IndexProgressor.NodeValueClient cursor, IndexOrder indexOrder, IndexQuery... predicates ) throws IndexNotApplicableKernelException { if ( predicates.length > 1 ) { luceneReader.query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof ExactPredicate ) { ExactPredicate exactPredicate = (ExactPredicate) predicates[0]; selector.select( nativeReader, luceneReader, exactPredicate.value() ).query( cursor, indexOrder, predicates ); return; } if ( predicates[0] instanceof NumberRangePredicate ) { nativeReader.query( cursor, indexOrder, predicates[0] ); return; } if ( predicates[0] instanceof ExistsPredicate ) { if ( indexOrder != IndexOrder.NONE ) { throw new UnsupportedOperationException( format( "Tried to query index with unsupported order %s. Supported orders for query %s are %s.", indexOrder, Arrays.toString( predicates ), IndexOrder.NONE ) ); } BridgingIndexProgressor multiProgressor = new BridgingIndexProgressor( cursor, propertyKeys ); cursor.initialize( multiProgressor, propertyKeys ); nativeReader.query( multiProgressor, indexOrder, predicates[0] ); luceneReader.query( multiProgressor, indexOrder, predicates[0] ); return; } luceneReader.query( cursor, indexOrder, predicates ); }
Source:
<code>default Gen<T> intersperse(Gen<T> other) { AtomicReference<Tuple2<Gen<T>, Gen<T>>> interspersedReference = new AtomicReference<>(Tuple.of(other, this)); return random -> interspersedReference.updateAndGet(generators -> Tuple.of(generators._2, generators._1))._1.apply(random); <START> } <END></code><technical_language>questions of prev PR: - do in-place swap. This is for Tuple2 of generic types T1 != T2 (wlog) - Lets implement iterator a boolean switch = !switch state avoid new Tuple instances: java Iterator<Gen<T>> iter = new Java.util.Iterator<>() { boolean switch = false; hasNext() = true next() = { gen = switch ? ... : ...; seitch = !switch; return gen; } } return rnd -> iter.next().apply(rnd);</technical_language>

Target:
default Gen<T> intersperse(Gen<T> other) { java.util.Iterator<Gen<T>> iter = new java.util.Iterator<Gen<T>>() { boolean genSwitch = false; @Override public boolean hasNext() { return true; } @Override public Gen<T> next() { return (genSwitch = !genSwitch) ? Gen.this : other; } }; return random -> iter.next().apply(random); }
Source:
<code>public void mockEventManager() throws Exception { this.manager = mock(PluginManager.class); this.testPluginContainer = mock(PluginContainer.class); when(this.testPluginContainer.getId()).thenReturn("TestPlugin"); when(this.manager.fromInstance(testPlugin)).thenReturn(Optional.of(this.testPluginContainer)); Game game = mock(Game.class); when(game.getEventManager()).thenReturn(mock(EventManager.class)); CauseStackManager csm = mock(CauseStackManager.class); <START> Mockito.when(game.getCauseStackManager()).thenReturn(csm); <END> Mockito.when(csm.pushCause(null)).thenReturn(csm); Mockito.when(csm.popCause()).thenReturn(null); Mockito.when(csm.getCurrentCause()).thenReturn(Cause.of(EventContext.empty(), this)); TestHooks.setGame(game); }</code><technical_language>static import for Mockito.when here</technical_language>

Target:
public void mockEventManager() throws Exception { this.manager = mock(PluginManager.class); this.testPluginContainer = mock(PluginContainer.class); when(this.testPluginContainer.getId()).thenReturn("TestPlugin"); when(this.manager.fromInstance(this.testPlugin)).thenReturn(Optional.of(this.testPluginContainer)); Game game = mock(Game.class); TestHooks.setInstance("eventManager", mock(EventManager.class)); when(game.getEventManager()).thenReturn(mock(EventManager.class)); CauseStackManager csm = mock(CauseStackManager.class); when(game.getCauseStackManager()).thenReturn(csm); when(csm.pushCause(null)).thenReturn(csm); when(csm.popCause()).thenReturn(null); when(csm.getCurrentCause()).thenReturn(Cause.of(EventContext.empty(), this)); TestHooks.setGame(game); TestHooks.setInstance("causeStackManager", csm); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BoundDimFilter)) { return false; } BoundDimFilter that = (BoundDimFilter) o; if (isLowerStrict() != that.isLowerStrict()) { return false; } if (isUpperStrict() != that.isUpperStrict()) { return false; } if (isAlphaNumeric() != that.isAlphaNumeric()) { return false; } if (!getDimension().equals(that.getDimension())) { return false; } if (!getUpper().equals(that.getUpper())) { return false; } <START> return getLower().equals(that.getLower()); <END> }</code><technical_language>this is asuuming upper non-null</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BoundDimFilter)) { return false; } BoundDimFilter that = (BoundDimFilter) o; if (isLowerStrict() != that.isLowerStrict()) { return false; } if (isUpperStrict() != that.isUpperStrict()) { return false; } if (isAlphaNumeric() != that.isAlphaNumeric()) { return false; } if (!getDimension().equals(that.getDimension())) { return false; } if (getUpper() != null ? !getUpper().equals(that.getUpper()) : that.getUpper() != null) { return false; } return !(getLower() != null ? !getLower().equals(that.getLower()) : that.getLower() != null); }
Source:
<code><START> public Boolean aggregateJobDetails(JobDetails jobDetails, <END> AggregationConstants.AGGREGATION_TYPE aggType) { HTable aggTable = aggDailyTable; switch (aggType) { case DAILY: aggTable = aggDailyTable; break; case WEEKLY: aggTable = aggWeeklyTable; break; default: LOG.error("Unknown aggregation type : " + aggType); return false; } try { JobKey jobKey = jobDetails.getJobKey(); AppAggregationKey appAggKey = new AppAggregationKey(jobKey.getCluster(), jobKey.getUserName(), jobKey.getAppId(), getTimestamp(jobKey.getRunId(), aggType)); LOG.info("Aggregating " + aggType + " stats for " + jobKey.toString()); Increment aggIncrement = incrementAppSummary(appAggKey, jobDetails); aggTable.increment(aggIncrement); boolean status = updateMoreAggInfo(aggTable, appAggKey, jobDetails); return status; } catch (Exception e) { LOG.error("Caught exception while attempting to aggregate for " + aggType + " table " + e); e.printStackTrace(); return Boolean.FALSE; } }</code><technical_language>Is returning object type Boolean necessary? I is fine primitive type (boolean). object unnecessarily boxing unboxing subtle bugs</technical_language>

Target:
public boolean aggregateJobDetails(JobDetails jobDetails, AggregationConstants.AGGREGATION_TYPE aggType) { HTable aggTable = aggDailyTable; switch (aggType) { case DAILY: aggTable = aggDailyTable; break; case WEEKLY: aggTable = aggWeeklyTable; break; default: LOG.error("Unknown aggregation type : " + aggType); return false; } try { JobKey jobKey = jobDetails.getJobKey(); AppAggregationKey appAggKey = new AppAggregationKey(jobKey.getCluster(), jobKey.getUserName(), jobKey.getAppId(), getTimestamp(jobKey.getRunId(), aggType)); LOG.info("Aggregating " + aggType + " stats for " + jobKey.toString()); Increment aggIncrement = incrementAppSummary(appAggKey, jobDetails); aggTable.increment(aggIncrement); boolean status = updateMoreAggInfo(aggTable, appAggKey, jobDetails); return status; } catch (Exception e) { LOG.error("Caught exception while attempting to aggregate for " + aggType + " table ", e); return false; } }
Source:
<code>public String getTccConfigInstrumentOrigin() { InstGmosCommon inst = (InstGmosCommon) _oe.getInstrument(); switch (_oe.getAoAspect()) { case ngs : return "ngs2gmos"; <START> case lgs : return _oe.getAltairConfig().getMode().equals(AltairParams.Mode.LGS_P1) ? "lgs2gmos_p1" : "lgs2gmos"; <END> default: return ((GmosCommonType.FPUnit) inst.getFPUnit()).isIFU() ? "gmos_ifu" : "gmos"; } }</code><technical_language>reverse equals avoid a NPE, safe side. AlatirParams.Mode.LGS_P1.equals(_oe.blah blah blah)</technical_language>

Target:
public String getTccConfigInstrumentOrigin() { InstGmosCommon inst = (InstGmosCommon) _oe.getInstrument(); switch (_oe.getAoAspect()) { case ngs : return "ngs2gmos"; case lgs : return _oe.adjustInstrumentOriginForLGS_P1("lgs2gmos"); default: return ((GmosCommonType.FPUnit) inst.getFPUnit()).isIFU() ? "gmos_ifu" : "gmos"; } }
Source:
<code>public void beginTree(DetailAST rootAST) { context = new Context(null); <START> } <END></code><technical_language>@Nimfadora , is a nuance. checks clear internal non-property fields in beginTree method context is shared files validation. For files create instance of Check object, beginTree reset initial state. reproduce a problem, please launch Check files. Yes, test Check file in UT, in real life instance of Check is for files of execution. need UT executes Check files</technical_language>

Target:
public void beginTree(DetailAST rootAST) { context = new Context(null); contextStack.clear(); }
Source:
<code>private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners, boolean pathExists) { try { final ZkPathStatRecord pathStatRecord = new ZkPathStatRecord(path); for (final IZkChildListener listener : childListeners) { _eventThread.send(new ZkEventThread.ZkEvent("Children of " + path + " changed sent to " + listener) { @Override public void run() throws Exception { if (!pathStatRecord.pathChecked()) { if (!pathExists) { pathStatRecord.recordPathStat(getStat(path, hasListeners(path) && pathExists), OptionalLong.empty()); } else { <START> pathStatRecord.recordPathStat(getStat(path, true, true), OptionalLong.empty()); <END> } } List<String> children = null; if (pathStatRecord.pathExists()) { try { children = getChildren(path); } catch (ZkNoNodeException e) { LOG.warn("Get children under path: failed.", path, e); } } listener.handleChildChange(path, children); } }); } } catch (Exception e) { LOG.error("Failed to fire child changed event. Unable to getChildren.", e); } }</code><technical_language>If listener, need watch? Why</technical_language>

Target:
private void fireChildChangedEvents(final String path, Set<IZkChildListener> childListeners, boolean pathExists) { try { final ZkPathStatRecord pathStatRecord = new ZkPathStatRecord(path); for (final IZkChildListener listener : childListeners) { _eventThread.send(new ZkEventThread.ZkEvent("Children of " + path + " changed sent to " + listener) { @Override public void run() throws Exception { if (!pathStatRecord.pathChecked()) { Stat stat = null; if (!pathExists || !hasListeners(path)) { stat = getStat(path, false); } else { stat = installWatchOnlyPathExist(path); } pathStatRecord.recordPathStat(stat, OptionalLong.empty()); } List<String> children = null; if (pathStatRecord.pathExists()) { try { children = getChildren(path); } catch (ZkNoNodeException e) { LOG.warn("Get children under path: failed.", path, e); } } listener.handleChildChange(path, children); } }); } } catch (Exception e) { LOG.error("Failed to fire child changed event. Unable to getChildren.", e); } }
Source:
<code>private boolean findAssignments() { try { return assignmentsExport.getAssignmentsInSite(siteId); } catch (TypeException te) { <START> log.error("export-common-cartridge type error outputting assignments" + te); <END> setErrMessage("Error outputting forum attachments: " + te.getMessage()); return false; } catch (PermissionException pe) { log.error("export-common-cartridge permission error outputting assignments" + pe); setErrMessage("Error outputting forum attachments: " + pe.getMessage()); return false; } catch (IdUnusedException ide) { log.error("export-common-cartridge ID unuse error outputting assignments" + ide); setErrMessage("Error outputting forum attachments: " + ide.getMessage()); return false; } catch (ServerOverloadException soe) { log.error("export-common-cartridge server overload error outputting assignments" + soe); setErrMessage("Error outputting selected files: " + soe.getMessage()); return false; } }</code><technical_language>switch + a , get a stack trace in logs</technical_language>

Target:
private boolean findAssignments() { return assignmentsExport.getAssignmentsInSite(siteId); }
Source:
<code>public ResponseEntity<Void> beginValidation( @ApiParam(value="Validation parameters") @RequestBody final ValidationRestInput validationInput) { final String uniqueJobId = ValidationRequests.createUniqueValidationJobKey(validationInput.getCodeSystemURI()); final String jobId = ValidationRequests .prepareValidate() .setRuleParameters(ImmutableMap.of( ValidationConfiguration.IS_UNPUBLISHED_ONLY, validationInput.isUnpublishedOnly() )) .setRuleIds(validationInput.getRuleIds()) <START> .build(new CodeSystemURI(validationInput.getCodeSystemURI())) <END> .runAsJobWithRestart(uniqueJobId, String.format("Validating '%s'", validationInput.getCodeSystemURI())) .execute(getBus()) .getSync(1, TimeUnit.MINUTES); return ResponseEntity.created(getResourceLocationURI(jobId)).build(); }</code><technical_language>need wrap CodeSystemURI here</technical_language>

Target:
public ResponseEntity<Void> beginValidation( @ApiParam(value="Validation parameters") @RequestBody final ValidationRestInput validationInput) { final String uniqueJobId = ValidationRequests.createUniqueValidationJobKey(validationInput.getPath()); final String jobId = ValidationRequests .prepareValidate() .setRuleParameters(ImmutableMap.of( ValidationConfiguration.IS_UNPUBLISHED_ONLY, validationInput.isUnpublishedOnly() )) .setRuleIds(validationInput.getRuleIds()) .build(repositoryId, validationInput.getPath()) .runAsJobWithRestart(uniqueJobId, String.format("Validating '%s'", validationInput.getPath())) .execute(getBus()) .getSync(1, TimeUnit.MINUTES); return ResponseEntity.created(getResourceLocationURI(jobId)).build(); }
Source:
<code>private static void setLogStreamLevel(int level) { <START> LogStream.level = 6; <END> }</code><technical_language>hardcoded instead of argument? :)</technical_language>

Target:
private static void setLogStreamLevel(int level) { LogStream.level = level; }
Source:
<code>MediaControllerImplBase(Context context, MediaController instance, SessionToken token, Executor executor, ControllerCallback callback) { mInstance = instance; if (context == null) { throw new IllegalArgumentException("context shouldn't be null"); } if (token == null) { throw new IllegalArgumentException("token shouldn't be null"); } if (callback == null) { throw new IllegalArgumentException("callback shouldn't be null"); } if (executor == null) { throw new IllegalArgumentException("executor shouldn't be null"); } mContext = context; mSequencedFutureManager = new SequencedFutureManager(); mControllerStub = new MediaControllerStub(this, mSequencedFutureManager); mToken = token; mCallback = callback; mCallbackExecutor = executor; mDeathRecipient = new IBinder.DeathRecipient() { @Override public void binderDied() { mInstance.close(); } }; boolean connectCalled; if (mToken.getType() == SessionToken.TYPE_SESSION) { mServiceConnection = null; <START> connectCalled = connectToSession(); <END> } else { mServiceConnection = new SessionServiceConnection(); connectCalled = connectToService(); } if (!connectCalled) { close(); } }</code><technical_language>agree change follows? requestSent = sendConnectionRequestToSession();</technical_language>

Target:
MediaControllerImplBase(Context context, MediaController instance, SessionToken token, Executor executor, ControllerCallback callback) { mInstance = instance; if (context == null) { throw new IllegalArgumentException("context shouldn't be null"); } if (token == null) { throw new IllegalArgumentException("token shouldn't be null"); } if (callback == null) { throw new IllegalArgumentException("callback shouldn't be null"); } if (executor == null) { throw new IllegalArgumentException("executor shouldn't be null"); } mContext = context; mSequencedFutureManager = new SequencedFutureManager(); mControllerStub = new MediaControllerStub(this, mSequencedFutureManager); mToken = token; mCallback = callback; mCallbackExecutor = executor; mDeathRecipient = new IBinder.DeathRecipient() { @Override public void binderDied() { mInstance.close(); } }; IMediaSession iSession = IMediaSession.Stub.asInterface((IBinder) mToken.getBinder()); if (mToken.getType() == SessionToken.TYPE_SESSION) { mServiceConnection = null; connectToSession(); } else { mServiceConnection = new SessionServiceConnection(); connectToService(); } }
Source:
<code>@Override Bitmap decode(Request data) throws IOException { boolean loadFromLocalCacheOnly = retryCount == 0; Response response = downloader.load(data.uri, loadFromLocalCacheOnly); if (response == null) { return null; } loadedFrom = response.isCached() ? DISK : NETWORK; Bitmap result = response.getBitmap(); if (result != null) { return result; } InputStream is = response.getInputStream(); if (is == null) { return null; } if (loadedFrom == NETWORK) { <START> stats.dispatchDownloadFinished(is.available()); <END> } try { return decodeStream(is, data); } finally { Utils.closeQuietly(is); } }</code><technical_language>is.available() is reliable. want Content-Length header (if present) if present wrap InputStream count bytes</technical_language>

Target:
@Override Bitmap decode(Request data) throws IOException { boolean loadFromLocalCacheOnly = retryCount == 0; Response response = downloader.load(data.uri, loadFromLocalCacheOnly); if (response == null) { return null; } loadedFrom = response.cached ? DISK : NETWORK; Bitmap result = response.getBitmap(); if (result != null) { return result; } InputStream is = response.getInputStream(); if (is == null) { return null; } if (loadedFrom == NETWORK && response.getContentLength() > 0) { stats.dispatchDownloadFinished(response.getContentLength()); } try { return decodeStream(is, data); } finally { Utils.closeQuietly(is); } }
Source:
<code>public void addValue(String value) { <START> Objects.requireNonNull(value, "'value' cannot be null."); <END> this.value += "," + value; }</code><technical_language>ctor check for null addValue does. consistently do null check</technical_language>

Target:
public void addValue(String value) { if (this.value != null) { this.value += "," + value; } else { this.value = value; } }
Source:
<code>public String toString() { <START> return String.join(", ", value); <END> }</code><technical_language>suggestion return Arrays.toString(value);</technical_language>

Target:
public String toString() { return Arrays.toString(value); }
Source:
<code>protected void runTest(@Nonnull String testName, @Nonnull baksmaliOptions options) throws IOException, RecognitionException { String smaliFile = String.format("%s%s%s.smali", testDir, File.separatorChar, testName); InputStream smaliStream = <START> LambdaTest.class.getClassLoader(). <END> getResourceAsStream(smaliFile); if (smaliStream == null) { Assert.fail("Could not load " + smaliFile); } String source = readFully(smaliStream); BaksmaliTestUtils.assertSmaliCompiledEquals(source, source, options, true); }</code><technical_language>want a dependency LambdaTest here</technical_language>

Target:
protected void runTest(@Nonnull String testName, @Nonnull baksmaliOptions options) throws IOException, RecognitionException { String inputFilename = getInputFilename(testName); String input = readResourceFully(getInputFilename(testName)); String output; if (getOutputFilename(testName).equals(inputFilename)) { output = input; } else { output = readResourceFully(getOutputFilename(testName)); } BaksmaliTestUtils.assertSmaliCompiledEquals(input, output, options, true); }
Source:
<code>public int compareTo(ImmutableHideData o) { return ComparisonChain.start() <START> .compare(enchantments, o.hideEnchantments().get()) <END> .compare(attributes, o.hideAttributes().get()) .compare(unbreakable, o.hideUnbreakable().get()) .compare(canDestroy, o.hideCanDestroy().get()) .compare(canPlace, o.hideCanPlace().get()) .compare(miscellaneous, o.hideMiscellaneous().get()) .result(); }</code><technical_language>this. for of</technical_language>

Target:
public int compareTo(ImmutableHideData o) { return ComparisonChain.start() .compare(this.enchantments, o.hideEnchantments().get()) .compare(this.attributes, o.hideAttributes().get()) .compare(this.unbreakable, o.hideUnbreakable().get()) .compare(this.canDestroy, o.hideCanDestroy().get()) .compare(this.canPlace, o.hideCanPlace().get()) .compare(this.miscellaneous, o.hideMiscellaneous().get()) .result(); }
Source:
<code>private void buildForm() { generateIds(); boolean virtSupported = ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly); boolean glusterSupported = ApplicationModeHelper.isModeSupported(ApplicationMode.GlusterOnly); formBuilder = new FormBuilder(formPanel, 1, 8); formBuilder.setRelativeColumnWidth(0, 3); formBuilder.addFormItem(new FormItem(constants.osVersionHostGeneral(), oS, 0).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.kernelVersionHostGeneral(), kernelVersion, 0).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.kvmVersionHostGeneral(), kvmVersion, 0, virtSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.libvirtVersionHostGeneral(), libvirtVersion, 0, virtSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.vdsmVersionHostGeneral(), vdsmVersion, 0).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.spiceVersionHostGeneral(), spiceVersion, 0, virtSupported).withAutoPlacement()); <START> formBuilder.addFormItem(new FormItem(constants.glusterVersionHostGeneral(), glusterVersion, 0, glusterSupported).withAutoPlacement()); <END> formBuilder.addFormItem(new FormItem(constants.rhsVersionHostGeneral(), rhsVersion, 0, glusterSupported).withAutoPlacement()); }</code><technical_language>this field is added always. if rhs-version is</technical_language>

Target:
private void buildForm() { generateIds(); boolean virtSupported = ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly); boolean glusterSupported = ApplicationModeHelper.isModeSupported(ApplicationMode.GlusterOnly); formBuilder = new FormBuilder(formPanel, 1, 9); formBuilder.setRelativeColumnWidth(0, 3); formBuilder.addFormItem(new FormItem(constants.osVersionHostGeneral(), oS, 0).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.kernelVersionHostGeneral(), kernelVersion, 0).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.kvmVersionHostGeneral(), kvmVersion, 0, virtSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.libvirtVersionHostGeneral(), libvirtVersion, 0, virtSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.vdsmVersionHostGeneral(), vdsmVersion, 0).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.spiceVersionHostGeneral(), spiceVersion, 0, virtSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.glusterVersionHostGeneral(), glusterVersion, 0, glusterSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.cephVersionHostGeneral(), librbdVersion, 0, virtSupported).withAutoPlacement()); formBuilder.addFormItem(new FormItem(constants.rhsVersionHostGeneral(), rhsVersion, 0, glusterSupported).withAutoPlacement()); }
Source:
<code>public void testNormalizedUrl() throws IOException { <START> int port = 8000 + new Random().nextInt(1000); <END> HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext( "/", new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { byte[] response = httpExchange.getRequestURI().toString().getBytes(); httpExchange.sendResponseHeaders(200, response.length); OutputStream os = httpExchange.getResponseBody(); os.write(response); os.close(); } }); server.start(); ApacheHttpTransport transport = new ApacheHttpTransport(); com.google.api.client.http.HttpResponse response = transport .createRequestFactory() .buildGetRequest(new GenericUrl("http://localhost:" + port + "/foo .execute(); assertEquals(200, response.getStatusCode()); assertEquals("/foo }</code><technical_language>find unused port? This hit 8080 is occupied</technical_language>

Target:
public void testNormalizedUrl() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext( "/", new HttpHandler() { @Override public void handle(HttpExchange httpExchange) throws IOException { byte[] response = httpExchange.getRequestURI().toString().getBytes(); httpExchange.sendResponseHeaders(200, response.length); try (OutputStream out = httpExchange.getResponseBody()) { out.write(response); } } }); server.start(); ApacheHttpTransport transport = new ApacheHttpTransport(); GenericUrl testUrl = new GenericUrl("http://localhost/foo testUrl.setPort(server.getAddress().getPort()); com.google.api.client.http.HttpResponse response = transport .createRequestFactory() .buildGetRequest(testUrl) .execute(); assertEquals(200, response.getStatusCode()); assertEquals("/foo }