auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Request toRequest() { return new RequestTemplate() .method(request.method()) .appendDirectly(getUri().toASCIIString()) .headers(request.headers()) .body(request.body(), request.charset()) .request(); }

Target:
Request toRequest() { final byte[] body = request.body(); final int bodyLength = body != null ? body.length : 0; Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>(); headers.putAll(request.headers()); headers.put(Util.CONTENT_LENGTH, Arrays.asList(String.valueOf(bodyLength))); return Request.create(request.method(), getUri().toASCIIString(), headers, body, request.charset()); }
Source:
private void setItemToCache(final AuthenticationRequest request, AuthenticationResult result, boolean afterPrompt) throws AuthenticationException { if (mTokenCacheStore != null) { Logger.v(TAG, "Setting item to cache" + getCorrelationLogInfo()); logReturnedToken(request, result); if (afterPrompt) { if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getDisplayableId())) { Logger.v(TAG, "Updating cache for username:" + result.getUserInfo().getDisplayableId() + getCorrelationLogInfo()); setItemToCacheForUser(request, result, result.getUserInfo().getDisplayableId()); } } else { String userKey = request.getUserId(); if (StringExtensions.IsNullOrBlank(userKey)) { userKey = request.getLoginHint(); } setItemToCacheForUser(request, result, userKey); } if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getUserId())) { Logger.v(TAG, "Updating userId:" + result.getUserInfo().getUserId() + getCorrelationLogInfo()); setItemToCacheForUser(request, result, result.getUserInfo().getUserId()); } } }

Target:
private void setItemToCache(final AuthenticationRequest request, AuthenticationResult result, boolean afterPrompt) throws AuthenticationException { if (mTokenCacheStore != null) { Logger.v(TAG, "Setting item to cache" + getCorrelationLogInfo()); logReturnedToken(request, result); String userKey = request.getUserId(); if (afterPrompt) { if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getDisplayableId())) { Logger.v(TAG, "Updating cache for username:" + result.getUserInfo().getDisplayableId() + getCorrelationLogInfo()); userKey = result.getUserInfo().getDisplayableId(); } } else if (StringExtensions.IsNullOrBlank(userKey)) { userKey = request.getLoginHint(); } setItemToCacheForUser(request, result, userKey); if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getUserId())) { Logger.v(TAG, "Updating userId:" + result.getUserInfo().getUserId() + getCorrelationLogInfo()); setItemToCacheForUser(request, result, result.getUserInfo().getUserId()); } } }
Source:
private void flushRedo(IUndoContext context) { if (DEBUG_OPERATION_HISTORY_DISPOSE) { Tracing.printTrace("OPERATIONHISTORY", "Flushing redo history for " + context); } synchronized (undoRedoHistoryLock) { Object[] filtered = filter(redoList, context); for (Object element : filtered) { IUndoableOperation operation = (IUndoableOperation) element; if (context == GLOBAL_UNDO_CONTEXT || operation.getContexts().length == 1) { redoList.remove(operation); internalRemove(operation); } else { IUndoContext[] contexts = operation.getContexts(); for (IUndoContext context2 : contexts) { if (context2.matches(context)) { operation.removeContext(context2); } } if (operation.getContexts().length == 0) { redoList.remove(operation); internalRemove(operation); } } } } }

Target:
private void flushRedo(IUndoContext context) { if (DEBUG_OPERATION_HISTORY_DISPOSE) { Tracing.printTrace("OPERATIONHISTORY", "Flushing redo history for " + context); } synchronized (undoRedoHistoryLock) { Object[] filtered = filter(redoList, context); for (Object element : filtered) { IUndoableOperation operation = (IUndoableOperation) element; if (context == GLOBAL_UNDO_CONTEXT || operation.getContexts().length == 1) { redoList.remove(operation); internalRemove(operation); } else { for (IUndoContext undoContext : operation.getContexts()) { if (undoContext.matches(context)) { operation.removeContext(undoContext); } } if (operation.getContexts().length == 0) { redoList.remove(operation); internalRemove(operation); } } } } }
Source:
private void addRoundResetStep(final List<IExecutable> steps) { final IExecutable loop = new IExecutable() { private static final long serialVersionUID = 3118458517320468680L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { pushFightLoopOnStack(); } }; steps.add( new IExecutable() { private static final long serialVersionUID = -3993599528368570254L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { if (!isOver) { round++; if (round > MAX_INFINITE_ROUNDS) { throw new IllegalStateException( "Round 10,000 reached in a battle. Something must be wrong." + " Attacking unit types: " + attackingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(",")) + ", Defending unit types: " + defendingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(","))); } updateOffensiveAaUnits(); updateDefendingAaUnits(); stepStrings = determineStepStrings(); final IDisplay display = bridge.getDisplayChannelBroadcaster(); display.listBattleSteps(battleId, stepStrings); if (!MustFightBattle.this.stack.isEmpty()) { throw new IllegalStateException("Stack not empty:" + MustFightBattle.this.stack); } MustFightBattle.this.stack.push(loop); } } }); }

Target:
private void addRoundResetStep(final List<IExecutable> steps) { final IExecutable loop = new IExecutable() { private static final long serialVersionUID = 3118458517320468680L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { pushFightLoopOnStack(); } }; steps.add( new IExecutable() { private static final long serialVersionUID = -3993599528368570254L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { if (!isOver) { round++; if (round > MAX_ROUNDS) { throw new IllegalStateException( "Round 10,000 reached in a battle. Something must be wrong." + " Please report this to TripleA.\n" + " Attacking unit types: " + attackingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(",")) + ", Defending unit types: " + defendingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(","))); } updateOffensiveAaUnits(); updateDefendingAaUnits(); stepStrings = determineStepStrings(); final IDisplay display = bridge.getDisplayChannelBroadcaster(); display.listBattleSteps(battleId, stepStrings); if (!MustFightBattle.this.stack.isEmpty()) { throw new IllegalStateException("Stack not empty:" + MustFightBattle.this.stack); } MustFightBattle.this.stack.push(loop); } } }); }
Source:
public int getStreamIndex() { return streamIndex; }

Target:
private int getStreamIndex() { return streamIndex; }
Source:
public void close() { if (context != null) { try { context.dispose(); } catch (GSSException e) { throw new AuthenticationException(e); } } }

Target:
public void close() { try { try { context.dispose(); } finally { loginContext.logout(); } } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } }
Source:
public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); mUnwantedNetworkCapabilities &= ~(mNetworkCapabilities & mUnwantedNetworkCapabilities); }

Target:
public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); mUnwantedNetworkCapabilities &= ~mNetworkCapabilities; }
Source:
protected Backup snapshotTable(String snapshotId, TableName tableName) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(snapshotId)); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableName.getNameAsString())); CreateBackupRequest request = CreateBackupRequest.of(getBackupClusterName().getClusterId(), snapshotId) .setSourceTableId(tableName.getNameAsString()); int ttlSecs = configuration.getInt( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY, BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_VALUE); if (ttlSecs > 0) { Instant expireTime = Instant.now().plus(ttlSecs, ChronoUnit.SECONDS); request.setExpireTime(expireTime); } return Futures.getChecked( tableAdminClientWrapper.createBackupAsync(request), IOException.class); }

Target:
protected Backup snapshotTable(String snapshotId, TableName tableName) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(snapshotId)); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableName.getNameAsString())); CreateBackupRequest request = CreateBackupRequest.of(getBackupClusterName().getClusterId(), snapshotId) .setSourceTableId(tableName.getNameAsString()); int ttlSecs = configuration.getInt( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY, BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_VALUE); if (ttlSecs <= 0) { throw new IllegalArgumentException( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY + " must be > 0"); } Instant expireTime = Instant.now().plus(ttlSecs, ChronoUnit.SECONDS); request.setExpireTime(expireTime); return Futures.getChecked( tableAdminClientWrapper.createBackupAsync(request), IOException.class); }
Source:
void testWithCsvSource(String first, int second) { assertNotNull(Objects.toString(first, "<null>")); assertNotEquals(0, second); }

Target:
void testWithCsvSource(String first, int second) { assertNotNull(first); assertNotEquals(0, second); }
Source:
private boolean createConfigDriveIso(VirtualMachineProfile profile, DeployDestination dest, DiskTO disk) throws ResourceUnavailableException { DataStore dataStore = null; if (disk != null) { String dId = disk.getData().getDataStore().getUuid(); if (VirtualMachineManager.VmConfigDriveOnPrimaryPool.value()) { dataStore = _dataStoreMgr.getDataStore(dId, DataStoreRole.Primary); } else { List<DataStore> dataStores = _dataStoreMgr.listImageStores(); String url = disk.getData().getDataStore().getUrl(); for(DataStore ds : dataStores) { if (url.equals(ds.getUri()) && DataStoreRole.Image.equals(ds.getRole())) { dataStore = ds; break; } } } } else { dataStore = findDataStore(profile, dest); } final Long agentId = findAgentId(profile, dest, dataStore); if (agentId == null || dataStore == null) { throw new ResourceUnavailableException("Config drive iso creation failed, agent or datastore not available", ConfigDriveNetworkElement.class, 0L); } LOG.debug("Creating config drive ISO for vm: " + profile.getInstanceName()); final String isoFileName = ConfigDrive.configIsoFileName(profile.getInstanceName()); final String isoPath = ConfigDrive.createConfigDrivePath(profile.getInstanceName()); final String isoData = ConfigDriveBuilder.buildConfigDrive(profile.getVmData(), isoFileName, profile.getConfigDriveLabel()); final HandleConfigDriveIsoCommand configDriveIsoCommand = new HandleConfigDriveIsoCommand(isoPath, isoData, dataStore.getTO(), true); final Answer answer = agentManager.easySend(agentId, configDriveIsoCommand); if (!answer.getResult()) { throw new ResourceUnavailableException(String.format("Config drive iso creation failed, details: %s", answer.getDetails()), ConfigDriveNetworkElement.class, 0L); } addConfigDriveDisk(profile, dataStore); return true; }

Target:
private boolean createConfigDriveIso(VirtualMachineProfile profile, DeployDestination dest, DiskTO disk) throws ResourceUnavailableException { DataStore dataStore = getDatastoreForConfigDriveIso(disk, profile, dest); final Long agentId = findAgentId(profile, dest, dataStore); if (agentId == null || dataStore == null) { throw new ResourceUnavailableException("Config drive iso creation failed, agent or datastore not available", ConfigDriveNetworkElement.class, 0L); } LOG.debug("Creating config drive ISO for vm: " + profile.getInstanceName()); final String isoFileName = ConfigDrive.configIsoFileName(profile.getInstanceName()); final String isoPath = ConfigDrive.createConfigDrivePath(profile.getInstanceName()); final String isoData = ConfigDriveBuilder.buildConfigDrive(profile.getVmData(), isoFileName, profile.getConfigDriveLabel()); final HandleConfigDriveIsoCommand configDriveIsoCommand = new HandleConfigDriveIsoCommand(isoPath, isoData, dataStore.getTO(), true); final Answer answer = agentManager.easySend(agentId, configDriveIsoCommand); if (!answer.getResult()) { throw new ResourceUnavailableException(String.format("Config drive iso creation failed, details: %s", answer.getDetails()), ConfigDriveNetworkElement.class, 0L); } addConfigDriveDisk(profile, dataStore); return true; }
Source:
public SubTabHostInterfacePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, HostMainSelectedItems selectedItems, HostInterfaceActionPanelPresenterWidget actionPanel, ExpandAllButtonPresenterWidget expandAll, SearchableDetailModelProvider<HostInterfaceLineModel, HostListModel<Void>, HostInterfaceListModel> modelProvider) { super(eventBus, view, proxy, placeManager, modelProvider, selectedItems, actionPanel, HostSubTabPanelPresenter.TYPE_SetTabContent); expandAll.setTarget(this); actionPanel.addSearchPanel(expandAll); actionPanel.addSearchPanel(new ToggleActionButtonView(constants.showVfLabel(), constants.hideVfLabel()) { @Override public void handleOnClick(ClickEvent event, boolean isDefault) { getModelProvider().getModel().onShowHideVirtualFunction(isDefault); } }); }

Target:
public SubTabHostInterfacePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, HostMainSelectedItems selectedItems, HostInterfaceActionPanelPresenterWidget actionPanel, ExpandAllButtonPresenterWidget expandAll, SearchableDetailModelProvider<HostInterfaceLineModel, HostListModel<Void>, HostInterfaceListModel> modelProvider) { super(eventBus, view, proxy, placeManager, modelProvider, selectedItems, actionPanel, HostSubTabPanelPresenter.TYPE_SetTabContent); expandAll.setTarget(this); actionPanel.addSearchPanel(expandAll); actionPanel.addSearchPanel(ToggleActionButtonView.of(constants.showVfLabel(), constants.hideVfLabel(), (event, isHidden) -> getModelProvider().getModel().onShowHideVirtualFunction(!isHidden))); }
Source:
boolean verify() throws Exception { byte[] data = UUID.randomUUID().toString().getBytes(); byte[] digitalSignature = signData(data); return verifySig(data, digitalSignature); }

Target:
boolean verify() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] data = new byte[16]; SecureRandom.getInstanceStrong().nextBytes(data); byte[] digitalSignature = signData(data); Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM_NAME); signer.initVerify(publicKey); signer.update(data); return signer.verify(digitalSignature); }
Source:
private String createContentString() { return "distanceInfluence=" + distanceInfluence + ", speedFactor=" + speedFactorMap + ", maxSpeed=" + maxSpeedMap + ", maxSpeedFallback=" + maxSpeedFallback + ", priorityMap=" + priorityMap + ", areas=" + areas; }

Target:
private String createContentString() { return "distanceInfluence=" + distanceInfluence + "|speedFactor=" + speedFactorMap + "|maxSpeed=" + maxSpeedMap + "|maxSpeedFallback=" + maxSpeedFallback + "|priorityMap=" + priorityMap + "|areas=" + areas; }
Source:
public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { if (header.getName().equals(MantaHttpHeaders.REQUEST_ID)) { continue; } httpMessage.addHeader(header); } }

Target:
public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { if (MantaHttpHeaders.REQUEST_ID.equals(header.getName())) { continue; } httpMessage.addHeader(header); } }
Source:
private Collection<EObject> getFeatureExtensionsData(final EObject associatedInstance, Collection<Resource> resources) { final Collection<EObject> datas = new ArrayList<>(); Collection<Resource> allResources = new HashSet<>(); allResources.addAll(resources); if (associatedInstance != null) { Resource associatedInstanceResource = associatedInstance.eResource(); if (associatedInstanceResource != null) { allResources.add(associatedInstanceResource); } } else { for (Resource resource : resources) { if (resource instanceof AirdResource) { AirdResource aird = (AirdResource) resource; for (Resource res : aird.getResourceSet().getResources()) { if (res instanceof SiriusRepresentationXMIResourceImpl) { allResources.add(res); } } } allResources.addAll(session.getAllSessionResources()); } } for (final Resource res : allResources) { for (final EObject object : res.getContents()) { if (object instanceof DFeatureExtension) { datas.add(object); } } } return datas; }

Target:
private Collection<EObject> getFeatureExtensionsData(final EObject associatedInstance, Collection<Resource> resources) { final Collection<EObject> datas = new ArrayList<>(); Collection<Resource> allResources = new HashSet<>(); allResources.addAll(resources); if (associatedInstance != null) { Resource associatedInstanceResource = associatedInstance.eResource(); if (associatedInstanceResource != null) { allResources.add(associatedInstanceResource); } } else { for (Resource resource : resources) { List<Resource> srms = resource.getResourceSet().getResources().stream().filter(res -> new ResourceQuery(res).isSrmResource()).collect(Collectors.toList()); allResources.addAll(srms); break; } allResources.addAll(session.getAllSessionResources()); } for (final Resource res : allResources) { for (final EObject object : res.getContents()) { if (object instanceof DFeatureExtension) { datas.add(object); } } } return datas; }
Source:
private boolean isValidCwl(String content, Yaml yaml) { try { Map<String, Object> mapping = yaml.loadAs(content, Map.class); final Object cwlVersion = mapping.get("cwlVersion"); if (cwlVersion != null) { final boolean equals = cwlVersion.toString().startsWith(CWLHandler.CWL_VERSION_PREFIX); if (!equals) { LOG.error("detected invalid version: " + cwlVersion.toString()); } return equals; } } catch (ClassCastException | YAMLException e) { return false; } return false; }

Target:
private boolean isValidCwl(String content, Yaml yaml) { try { Map<String, Object> mapping = yaml.loadAs(content, Map.class); final Object cwlVersion = mapping.get("cwlVersion"); if (cwlVersion != null) { final boolean startsWith = cwlVersion.toString().startsWith(CWLHandler.CWL_VERSION_PREFIX); if (!startsWith) { LOG.error("detected invalid version: " + cwlVersion.toString()); } return startsWith; } } catch (ClassCastException | YAMLException e) { return false; } return false; }
Source:
public void testWatchForCommitForRetryfailure() throws Exception { OzoneConfiguration conf = new OzoneConfiguration(); conf.setTimeDuration(OzoneConfigKeys.OZONE_CLIENT_WATCH_REQUEST_TIMEOUT, 100, TimeUnit.SECONDS); conf.setInt(OzoneConfigKeys.DFS_RATIS_CLIENT_REQUEST_MAX_RETRIES_KEY, 10); startCluster(conf); XceiverClientManager clientManager = new XceiverClientManager(conf); ContainerWithPipeline container1 = storageContainerLocationClient .allocateContainer(HddsProtos.ReplicationType.RATIS, HddsProtos.ReplicationFactor.THREE, containerOwner); XceiverClientSpi xceiverClient = clientManager .acquireClient(container1.getPipeline()); Assert.assertEquals(1, xceiverClient.getRefcount()); Assert.assertEquals(container1.getPipeline(), xceiverClient.getPipeline()); Pipeline pipeline = xceiverClient.getPipeline(); XceiverClientReply reply = xceiverClient.sendCommandAsync( ContainerTestHelper.getCreateContainerRequest( container1.getContainerInfo().getContainerID(), xceiverClient.getPipeline())); reply.getResponse().get(); long index = reply.getLogIndex(); cluster.shutdownHddsDatanode(pipeline.getNodes().get(0)); cluster.shutdownHddsDatanode(pipeline.getNodes().get(1)); try { xceiverClient .watchForCommit(index + new Random().nextInt(100) + 10, 20000); Assert.fail("expected exception not thrown"); } catch (Exception e) { Assert.assertTrue(e instanceof ExecutionException); Assert.assertFalse(HddsClientUtils .checkForException(e) instanceof TimeoutException); } clientManager.releaseClient(xceiverClient, false); shutdown(); }

Target:
public void testWatchForCommitForRetryfailure() throws Exception { OzoneConfiguration conf = new OzoneConfiguration(); conf.setTimeDuration(OzoneConfigKeys.OZONE_CLIENT_WATCH_REQUEST_TIMEOUT, 100, TimeUnit.SECONDS); conf.setInt(OzoneConfigKeys.DFS_RATIS_CLIENT_REQUEST_MAX_RETRIES_KEY, 20); startCluster(conf); XceiverClientManager clientManager = new XceiverClientManager(conf); ContainerWithPipeline container1 = storageContainerLocationClient .allocateContainer(HddsProtos.ReplicationType.RATIS, HddsProtos.ReplicationFactor.THREE, containerOwner); XceiverClientSpi xceiverClient = clientManager .acquireClient(container1.getPipeline()); Assert.assertEquals(1, xceiverClient.getRefcount()); Assert.assertEquals(container1.getPipeline(), xceiverClient.getPipeline()); Pipeline pipeline = xceiverClient.getPipeline(); XceiverClientReply reply = xceiverClient.sendCommandAsync( ContainerTestHelper.getCreateContainerRequest( container1.getContainerInfo().getContainerID(), xceiverClient.getPipeline())); reply.getResponse().get(); long index = reply.getLogIndex(); cluster.shutdownHddsDatanode(pipeline.getNodes().get(0)); cluster.shutdownHddsDatanode(pipeline.getNodes().get(1)); try { xceiverClient .watchForCommit(index + new Random().nextInt(100) + 10, 20000); Assert.fail("expected exception not thrown"); } catch (Exception e) { Assert.assertTrue(e instanceof ExecutionException); Assert.assertFalse(HddsClientUtils .checkForException(e) instanceof TimeoutException); } clientManager.releaseClient(xceiverClient, false); shutdown(); }
Source:
private RevCommit tryFastForward(String headName, RevCommit oldCommit, RevCommit newCommit) throws IOException, JGitInternalException, GitAPIException { boolean tryRebase = false; for (RevCommit parentCommit : newCommit.getParents()) if (parentCommit.equals(oldCommit)) tryRebase = true; if (!tryRebase) return null; CheckoutCommand co = new CheckoutCommand(repo); try { co.setName(newCommit.name()).call(); if (headName.startsWith(Constants.R_HEADS)) { RefUpdate rup = repo.updateRef(headName); rup.setExpectedOldObjectId(oldCommit); rup.setNewObjectId(newCommit); rup.setRefLogMessage("Fast-foward from " + oldCommit.name() + " to " + newCommit.name(), false); Result res = rup.update(walk); switch (res) { case FAST_FORWARD: case NO_CHANGE: case FORCED: break; default: throw new IOException("Could not fast-forward"); } } return newCommit; } catch (RefAlreadyExistsException e) { throw new JGitInternalException(e.getMessage(), e); } catch (RefNotFoundException e) { throw new JGitInternalException(e.getMessage(), e); } catch (InvalidRefNameException e) { throw new JGitInternalException(e.getMessage(), e); } catch (CheckoutConflictException e) { throw new JGitInternalException(e.getMessage(), e); } }

Target:
private RevCommit tryFastForward(String headName, RevCommit oldCommit, RevCommit newCommit) throws IOException, GitAPIException { boolean tryRebase = false; for (RevCommit parentCommit : newCommit.getParents()) if (parentCommit.equals(oldCommit)) tryRebase = true; if (!tryRebase) return null; CheckoutCommand co = new CheckoutCommand(repo); try { co.setName(newCommit.name()).call(); if (headName.startsWith(Constants.R_HEADS)) { RefUpdate rup = repo.updateRef(headName); rup.setExpectedOldObjectId(oldCommit); rup.setNewObjectId(newCommit); rup.setRefLogMessage("Fast-foward from " + oldCommit.name() + " to " + newCommit.name(), false); Result res = rup.update(walk); switch (res) { case FAST_FORWARD: case NO_CHANGE: case FORCED: break; default: throw new IOException("Could not fast-forward"); } } return newCommit; } catch (RefAlreadyExistsException e) { throw new JGitInternalException(e.getMessage(), e); } catch (RefNotFoundException e) { throw new JGitInternalException(e.getMessage(), e); } catch (InvalidRefNameException e) { throw new JGitInternalException(e.getMessage(), e); } catch (CheckoutConflictException e) { throw new JGitInternalException(e.getMessage(), e); } }
Source:
public void resolveSuppressedMuleExceptionLoggingCause() { ErrorType expected = DISPATCH; Throwable exception = new DispatchException(createStaticMessage("DISPATCH PROBLEM"), new ValidateResponse(), suppressIfPresent(CONNECTION_EXCEPTION, CONNECTION_EXCEPTION.getClass(), true)); MessagingException me = newMessagingException(exception, event, processor); MessagingExceptionResolver anotherResolver = new MessagingExceptionResolver(new TestProcessor()); MessagingException resolved = anotherResolver.resolve(me, locator, emptyList()); assertExceptionErrorType(resolved, expected); assertExceptionMessage(resolved.getMessage(), "DISPATCH PROBLEM"); assertExceptionMessage(resolved.getInfo().get(MuleExceptionInfo.INFO_CAUSED_BY_KEY).toString(), "CONNECTION PROBLEM"); }

Target:
public void resolveSuppressedMuleExceptionLoggingCause() { ErrorType expected = DISPATCH; Throwable exception = new DispatchException(createStaticMessage("DISPATCH PROBLEM"), new ValidateResponse(), suppressIfPresent(CONNECTION_EXCEPTION, CONNECTION_EXCEPTION.getClass())); MessagingException me = newMessagingException(exception, event, processor); MessagingExceptionResolver anotherResolver = new MessagingExceptionResolver(new TestProcessor()); MessagingException resolved = anotherResolver.resolve(me, locator, emptyList()); assertExceptionErrorType(resolved, expected); assertExceptionMessage(resolved.getMessage(), "DISPATCH PROBLEM"); assertExceptionMessage(resolved.getInfo().get(INFO_CAUSED_BY_KEY).toString(), "CONNECTION PROBLEM"); }
Source:
public void testScheduledPoolGC() throws Exception { ActiveMQServer server = new ActiveMQServerImpl(); server.start(); WeakReference<Runnable> scheduledRunnableRef; { Runnable scheduledRunnable = new Runnable() { @Override public void run() { } }; scheduledRunnableRef = new WeakReference<>(scheduledRunnable); ScheduledFuture scheduledFuture = server.getScheduledPool().schedule(scheduledRunnable, 5000, TimeUnit.MILLISECONDS); scheduledFuture.cancel(true); } Assert.assertNotEquals(null, scheduledRunnableRef.get()); long timeout = System.currentTimeMillis() + 3000; while (timeout > System.currentTimeMillis() && scheduledRunnableRef.get() != null) { ThreadLeakCheckRule.forceGC(); } Assert.assertEquals(null, scheduledRunnableRef.get()); }

Target:
public void testScheduledPoolGC() throws Exception { ActiveMQServer server = createServer(false); server.start(); Runnable scheduledRunnable = new Runnable() { @Override public void run() { Assert.fail(); } }; WeakReference<Runnable> scheduledRunnableRef = new WeakReference<>(scheduledRunnable); ScheduledExecutorService scheduledPool = server.getScheduledPool(); ScheduledFuture scheduledFuture = scheduledPool.schedule(scheduledRunnable, 5000, TimeUnit.MILLISECONDS); Assert.assertFalse(scheduledFuture.isCancelled()); Assert.assertTrue(scheduledFuture.cancel(true)); Assert.assertTrue(scheduledFuture.isCancelled()); Assert.assertNotEquals(null, scheduledRunnableRef.get()); scheduledRunnable = null; forceGC(); Assert.assertEquals(null, scheduledRunnableRef.get()); server.stop(); }
Source:
protected double scoreForNullFormat(Object planData, RegisteredType type, RegisteredTypeLoadingContext context) { return 0; }

Target:
protected double scoreForNullFormat(Object planData, RegisteredType type, RegisteredTypeLoadingContext context) { Maybe<Map<?, ?>> yamlMap = RegisteredTypes.getAsYamlMap(planData); if (yamlMap.isAbsent() || !yamlMap.get().containsKey("tosca_definitions_version")) { return 0; } return 1; }
Source:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = Collections.singletonList(event); } else { if (fEvents.equals(Collections.EMPTY_LIST)) { fEvents = new ArrayList<>(); } if (fEvents.size() > id && fEvents.get(id) != null) { throw new ParseException("Event id already exists"); } while (fEvents.size() <= id) { fEvents.add(null); } fEvents.set(id, event); } }

Target:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = Collections.singletonList(event); } else { if (fEvents.equals(Collections.EMPTY_LIST)) { fEvents = new ArrayList<>(); } if (fEvents.size() > id && fEvents.get(id) != null) { throw new ParseException("Event id already exists"); } ensureSize(id); fEvents.set(id, event); } }
Source:
protected void executeCommand() { addCustomValue(AUDIT_LOG_VAR_VM_NAME, getVmName()); addCustomValue(AUDIT_LOG_VAR_MEMORY_SIZE_MB, String.valueOf(getUnpluggedDeviceSize())); addCustomValue(AUDIT_LOG_VAR_DEVICE_ID, getParameters().getDeviceId().toString()); final VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.HotUnplugMemory, new HotUnplugMemoryVDSCommand.Params(getVm().getRunOnVds(), getDeviceToHotUnplug(), getVm().getMinAllocatedMem())); if (!vdsReturnValue.getSucceeded()) { addCustomValue(AUDIT_LOG_VAR_ERROR_MESSAGE, vdsReturnValue.getVdsError().getMessage()); setReturnValueFailure(vdsReturnValue); return; } if (getVm().getMemSizeMb() - getUnpluggedDeviceSize() >= getVm().getMinAllocatedMem()) { updateVm(); } setSucceeded(true); }

Target:
protected void executeCommand() { addCustomValue(AUDIT_LOG_VAR_VM_NAME, getVmName()); addCustomValue(AUDIT_LOG_VAR_MEMORY_SIZE_MB, String.valueOf(getUnpluggedDeviceSize())); addCustomValue(AUDIT_LOG_VAR_DEVICE_ID, getParameters().getDeviceId().toString()); final VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.HotUnplugMemory, new HotUnplugMemoryVDSCommand.Params(getVm().getRunOnVds(), getDeviceToHotUnplug())); if (!vdsReturnValue.getSucceeded()) { addCustomValue(AUDIT_LOG_VAR_ERROR_MESSAGE, vdsReturnValue.getVdsError().getMessage()); setReturnValueFailure(vdsReturnValue); return; } if (getVm().getMemSizeMb() - getUnpluggedDeviceSize() >= getVm().getMinAllocatedMem()) { updateVm(); } setSucceeded(true); }
Source:
public int indexOf(byte[] bytes) { int i = 0; for (byte[] label : labels) { if (Arrays.equals(label, bytes)) { return i; } i++; } return -1; }

Target:
public int indexOf(byte[] bytes) { return indexOf(bytes, 0, bytes.length); }
Source:
public void indexSync() { linker.linkTo(this).execute(); final HttpPost httpPost = new HttpPost(linker.get()); final Cookie[] cookies = user.getRequest().getCookies(); LOGGER.info("Running thread to sync solr indexes"); new Thread(new Runnable() { @Override public void run() { LOGGER.info("Solr indexes thread started!"); CookieStore cookieStore = new BasicCookieStore(); for (Cookie c : cookies) { BasicClientCookie bc = new BasicClientCookie(c.getName(), c.getValue()); bc.setDomain("localhost"); cookieStore.addCookie(bc); } try ( CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .build() ) { CloseableHttpResponse response = httpClient.execute(httpPost); LOGGER.info("Index sync received " + response.getStatusLine().getStatusCode()); } catch (IOException e) { LOGGER.info("Couldn't execute post " + httpPost); } } }).start(); result.nothing(); }

Target:
public void indexSync() { linker.linkTo(this).execute(); final HttpPost httpPost = new HttpPost(linker.get()); final Cookie[] cookies = request.getCookies(); LOGGER.info("Running thread to sync solr indexes"); new Thread(new Runnable() { @Override public void run() { LOGGER.info("Solr indexes thread started!"); CookieStore cookieStore = new BasicCookieStore(); for (Cookie c : cookies) { BasicClientCookie bc = new BasicClientCookie(c.getName(), c.getValue()); bc.setDomain("localhost"); cookieStore.addCookie(bc); } try ( CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .build() ) { CloseableHttpResponse response = httpClient.execute(httpPost); LOGGER.info("Index sync received " + response.getStatusLine().getStatusCode()); } catch (IOException e) { LOGGER.info("Couldn't execute post " + httpPost); } } }).start(); result.nothing(); }
Source:
public void onUnityAdsPlacementStateChanged(String placementId, UnityAds.PlacementState oldState, UnityAds.PlacementState newState) { if (newState == UnityAds.PlacementState.WAITING || newState == UnityAds.PlacementState.READY) { for (Listener listener : mListeners) { listener.onInitializeSuccess(); } mListeners.clear(); UnityAds.removeListener(getInstance().getUnitySingletonListenerInstance()); } }

Target:
public void onUnityAdsPlacementStateChanged(String placementId, UnityAds.PlacementState oldState, UnityAds.PlacementState newState) { if (mPlacementsInUse.containsKey(placementId) && mPlacementsInUse.get(placementId).get() != null) { mPlacementsInUse.get(placementId).get().onUnityAdsPlacementStateChanged(placementId, oldState, newState); } }
Source:
private void processCurrentStates(BaseControllerDataProvider cache, Map<String, Resource> resourceMap, Map<String, Resource> resourceToRebalance, Map<String, IdealState> idealStates, boolean isTaskCache) throws StageException { Map<String, LiveInstance> availableInstances = cache.getLiveInstances(); if (availableInstances != null && availableInstances.size() > 0) { for (LiveInstance instance : availableInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getEphemeralOwner(); processCurrentStateMap(cache.getCurrentState(instanceName, clientSessionId), resourceMap, resourceToRebalance, idealStates, isTaskCache); if (isTaskCache) { Map<String, CurrentState> taskCurrentStateMap = ((WorkflowControllerDataProvider) cache) .getTaskCurrentState(instanceName, clientSessionId); processCurrentStateMap(taskCurrentStateMap, resourceMap, resourceToRebalance, idealStates, true); } } } }

Target:
private void processCurrentStates(BaseControllerDataProvider cache, Map<String, Resource> resourceMap, Map<String, Resource> resourceToRebalance, Map<String, IdealState> idealStates, boolean isTaskCache) throws StageException { Map<String, LiveInstance> availableInstances = cache.getLiveInstances(); if (availableInstances != null && availableInstances.size() > 0) { for (LiveInstance instance : availableInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getEphemeralOwner(); Map<String, CurrentState> currentStateMap = cache.getCurrentState(instanceName, clientSessionId, isTaskCache); for (CurrentState currentState : currentStateMap.values()) { String resourceName = currentState.getResourceName(); Map<String, String> resourceStateMap = currentState.getPartitionStateMap(); if (resourceStateMap.keySet().isEmpty()) { continue; } if (!resourceMap.containsKey(resourceName)) { Resource resource = new Resource(resourceName); resource.setStateModelDefRef(currentState.getStateModelDefRef()); resource.setStateModelFactoryName(currentState.getStateModelFactoryName()); resource.setBucketSize(currentState.getBucketSize()); resource.setBatchMessageMode(currentState.getBatchMessageMode()); if (isTaskCache == TaskConstants.STATE_MODEL_NAME .equals(resource.getStateModelDefRef())) { resourceToRebalance.put(resourceName, resource); } IdealState idealState = idealStates.get(resourceName); if (idealState != null) { resource.setResourceGroupName(idealState.getResourceGroupName()); resource.setResourceTag(idealState.getInstanceGroupTag()); } resourceMap.put(resourceName, resource); } if (currentState.getStateModelDefRef() == null) { LogUtil.logError(LOG, _eventId, "state model def is null." + "resource:" + currentState.getResourceName() + ", partitions: " + currentState.getPartitionStateMap().keySet() + ", states: " + currentState.getPartitionStateMap().values()); throw new StageException( "State model def is null for resource:" + currentState.getResourceName()); } for (String partition : resourceStateMap.keySet()) { addPartition(partition, resourceName, resourceMap); } } } } }
Source:
private static Class<Map> getMapClass(String className) { return Util.<Map>loadClass(className, Map.class.getClassLoader()); }

Target:
private static Class<? extends Map> getMapClass(String className) { return Util.<Map>loadClass(className, Map.class.getClassLoader()); }
Source:
public void test() { final CatalogDescriptor catalogDescriptor = new JDBCCatalogDescriptor(PostgresCatalog.DEFAULT_DATABASE, TEST_USERNAME, TEST_PWD, baseUrl); final Map<String, String> properties = catalogDescriptor.toProperties(); final Catalog actualCatalog = TableFactoryService.find(CatalogFactory.class, properties) .createCatalog(TEST_CATALOG_NAME, properties); checkEquals(catalog, (JDBCCatalog) actualCatalog); }

Target:
public void test() { final CatalogDescriptor catalogDescriptor = new JDBCCatalogDescriptor(PostgresCatalog.DEFAULT_DATABASE, TEST_USERNAME, TEST_PWD, baseUrl); final Map<String, String> properties = catalogDescriptor.toProperties(); final Catalog actualCatalog = TableFactoryService.find(CatalogFactory.class, properties) .createCatalog(TEST_CATALOG_NAME, properties); checkEquals(catalog, (JDBCCatalog) actualCatalog); assertTrue(((JDBCCatalog) actualCatalog).getInternal() instanceof PostgresCatalog); }
Source:
public RespondingGatewayPatientLocationQueryResponseType processPatientLocationQuery( PatientLocationQueryRequestType request, AssertionType assertion, NhinTargetCommunitiesType targets) { LOG.debug("Begin EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); RespondingGatewayPatientLocationQueryResponseType response = new RespondingGatewayPatientLocationQueryResponseType(); try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.ENTITY_XDS_SECURED_SERVICE_NAME); ServicePortDescriptor<EntityPatientLocationQuerySecuredPortType> portDescriptor = getServicePortDescriptor(); CONNECTClient<EntityPatientLocationQuerySecuredPortType> client = getCONNECTClient(portDescriptor, url, assertion); RespondingGatewayPatientLocationQueryRequestType securedRequest = new RespondingGatewayPatientLocationQueryRequestType(); securedRequest.setNhinTargetCommunities(targets); securedRequest.setPatientLocationQueryRequest(request); response = (RespondingGatewayPatientLocationQueryResponseType) client .invokePort(EntityPatientLocationQuerySecuredPortType.class, "respondingGatewayPatientLocationQuery", securedRequest); } catch (Exception e) { LOG.error("Error calling respondingGatewayPatientLocationQuery: {}", e.getMessage(), e); throw new IllegalStateException("Error calling respondingGatewayPatientLocationQuery", e); } LOG.debug("End EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); return response; }

Target:
public RespondingGatewayPatientLocationQueryResponseType processPatientLocationQuery( PatientLocationQueryRequestType request, AssertionType assertion, NhinTargetCommunitiesType targets) { LOG.debug("Begin EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); RespondingGatewayPatientLocationQueryResponseType response = new RespondingGatewayPatientLocationQueryResponseType(); try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.PLQ_ENTITYSECURED_SERVICE_NAME); ServicePortDescriptor<EntityPatientLocationQuerySecuredPortType> portDescriptor = getServicePortDescriptor(); CONNECTClient<EntityPatientLocationQuerySecuredPortType> client = getCONNECTClient(portDescriptor, url, assertion); RespondingGatewayPatientLocationQueryRequestType securedRequest = new RespondingGatewayPatientLocationQueryRequestType(); securedRequest.setNhinTargetCommunities(targets); securedRequest.setPatientLocationQueryRequest(request); response = (RespondingGatewayPatientLocationQueryResponseType) client .invokePort(EntityPatientLocationQuerySecuredPortType.class, "respondingGatewayPatientLocationQuery", securedRequest); } catch (Exception e) { LOG.error("Error calling respondingGatewayPatientLocationQuery: {}", e.getMessage(), e); throw new IllegalStateException("Error calling respondingGatewayPatientLocationQuery", e); } LOG.debug("End EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); return response; }
Source:
public static void reportEvent(String category, String action, String label, int value) { if (analyticsDisabled()) { return; } getTracker().send(new HitBuilders.EventBuilder() .setCategory(category) .setAction(action) .setLabel(label) .setValue(value) .build()); }

Target:
private static void reportEvent(String category, String action, String label, int value) { if (analyticsDisabled() || versionIncompatible()) { return; } getTracker().send(new HitBuilders.EventBuilder() .setCategory(category) .setAction(action) .setLabel(label) .setValue(value) .build()); }
Source:
public void run() { try { while (!Thread.currentThread().isInterrupted()) { operatorChainManager.pickOperatorChain().processNextEvent(); if (threadManager.reapCheck()) { return; } } } catch (final InterruptedException e) { return; } }

Target:
public void run() { try { while (!Thread.currentThread().isInterrupted() && !closed) { operatorChainManager.pickOperatorChain().processNextEvent(); } } catch (final InterruptedException e) { return; } }
Source:
public RelOptCost getLowerBoundCost(RelSubset subset, RelMetadataQuery mq, VolcanoPlanner planner) { if (planner.isLogical(subset)) { return null; } RelOptCost winner = subset.getWinnerCost(); if (winner != null) { return winner; } if (!subset.isExplored()) { return null; } RelOptCost lowerBound = null; for (RelNode relNode : subset.getRels()) { try { RelOptCost lb = mq.getLowerBoundCost(relNode, planner); if (lb == null) { return null; } if (lowerBound == null || lb.isLt(lowerBound)) { lowerBound = lb; } } catch (CyclicMetadataException e) { if (lowerBound == null) { lowerBound = planner.getCostFactory().makeInfiniteCost(); } } } return lowerBound; }

Target:
public RelOptCost getLowerBoundCost(RelSubset subset, RelMetadataQuery mq, VolcanoPlanner planner) { if (planner.isLogical(subset)) { return null; } return subset.getWinnerCost(); }
Source:
public void commit(File stateDir, String objectId, Part part) { log.debug("Attempting to commit part to {}", objectId, part.getPartNumber(), stateDir.toString()); val mapper = new ObjectMapper(); try { byte[] content = mapper.writeValueAsBytes(part); val partFile = new File(getObjectStateDir(stateDir, objectId), getPartName(part)); Files.copy(new ByteArrayInputStream(content), partFile.toPath()); log.debug("Copied part to {}", part.getPartNumber(), partFile.toPath().toString()); } catch (IOException e) { log.error("Failed to create meta file ", stateDir.getAbsolutePath(), e); throw new NotRetryableException(e); } }

Target:
public void commit(File stateDir, String objectId, Part part) { log.debug("Attempting to commit part to {}", objectId, part.getPartNumber(), stateDir.toString()); try { byte[] content = MAPPER.writeValueAsBytes(part); val partFile = new File(getObjectStateDir(stateDir, objectId), getPartName(part)); Files.copy(new ByteArrayInputStream(content), partFile.toPath()); log.debug("Copied part to {}", part.getPartNumber(), partFile.toPath().toString()); } catch (IOException e) { log.error("Failed to create meta file ", stateDir.getAbsolutePath(), e); throw new NotRetryableException(e); } }
Source:
public void testElementsToSelectExpressionMigration() { copyFilesToTestProject(SiriusTestsPlugin.PLUGIN_ID, PATH, MODELER_FILE_NAME); ResourceSet set = new ResourceSetImpl(); Group vsmRoot = null; try { vsmRoot = (Group) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + MODELER_FILE_NAME, true), set); } catch (IOException e) { e.printStackTrace(); } AbstractToolDescription tool = getTool(vsmRoot, "Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), InitializeCreationToolElementsToSelectExpressionParticipant.ELEMENTS_TO_SELECT_EXPRESSION); tool = getTool(vsmRoot, "Initialized_Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), "[instance/]"); try { vsmRoot.eResource().save(Collections.emptyMap()); } catch (IOException e) { e.printStackTrace(); } String version = vsmRoot.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", VSMMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); }

Target:
public void testElementsToSelectExpressionMigration() throws Exception { copyFilesToTestProject(SiriusTestsPlugin.PLUGIN_ID, PATH, MODELER_FILE_NAME); ResourceSet set = new ResourceSetImpl(); Group vsmRoot = null; vsmRoot = (Group) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + MODELER_FILE_NAME, true), set); AbstractToolDescription tool = getTool(vsmRoot, "Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), InitializeCreationToolElementsToSelectExpressionParticipant.ELEMENTS_TO_SELECT_EXPRESSION); tool = getTool(vsmRoot, "Initialized_Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), "[instance/]"); try { vsmRoot.eResource().save(Collections.emptyMap()); } catch (IOException e) { e.printStackTrace(); } String version = vsmRoot.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", VSMMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); }
Source:
public URI getExternalUri() { String host = getHostname() .orElseGet(() -> { try { return new NetworkUtils().getNonLoopbackAddressOfThisMachine(); } catch (WebDriverException e) { String name = HostIdentifier.getHostName(); LOG.info("No network connection, guessing name: " + name); return name; } }); int port = getPort(); try { if (isSecure()) { return new URI("https", null, host, port, null, null, null); } else { return new URI("http", null, host, port, null, null, null); } } catch (URISyntaxException e) { throw new ConfigException("Cannot determine external URI: " + e.getMessage()); } }

Target:
public URI getExternalUri() { String host = getHostname() .orElseGet(() -> { try { return new NetworkUtils().getNonLoopbackAddressOfThisMachine(); } catch (WebDriverException e) { String name = HostIdentifier.getHostName(); LOG.info("No network connection, guessing name: " + name); return name; } }); int port = getPort(); try { return new URI(isSecure() ? "https" : "http", null, host, port, null, null, null); } catch (URISyntaxException e) { throw new ConfigException("Cannot determine external URI: " + e.getMessage()); } }