auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testChronologizeWithStartTimestampBeforeAndEndTimestampAfterAnyValuesChangeInKeyInRecord() { long record = Variables.register("record", client.create()); String key = Variables.register("key", TestData.getString()); int testSize = Variables.register("testSize", 5); Set<Object> initValues = Variables.register("initValues", Sets.newHashSet()); Timestamp startTimestamp = Variables.register("startTimestamp", Timestamp.now()); for (int i = 0; i < 100000000; i++); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Timestamp endTimestamp = Variables.register("endTimestamp", Timestamp.now()); for (int i = 0; i < 100000000; i++); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Map<Timestamp, Set<Object>> result = client.chronologize( key, record, startTimestamp, endTimestamp); Set<Object> lastResultSet = Iterables.getLast( result.values()); assertEquals(testSize, result.size()); assertEquals(testSize, lastResultSet.size()); }

Target:
public void testChronologizeWithStartTimestampBeforeAndEndTimestampAfterAnyValuesChangeInKeyInRecord() { long record = Variables.register("record", client.create()); String key = Variables.register("key", TestData.getString()); int testSize = Variables.register("testSize", 5); Set<Object> initValues = Variables.register("initValues", Sets.newHashSet()); Timestamp startTimestamp = Variables.register("startTimestamp", Timestamp.now()); StandardActions.wait(200, TimeUnit.MILLISECONDS); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Timestamp endTimestamp = Variables.register("endTimestamp", Timestamp.now()); StandardActions.wait(200, TimeUnit.MILLISECONDS); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Map<Timestamp, Set<Object>> result = client.chronologize(key, record, startTimestamp, endTimestamp); Set<Object> lastResultSet = Iterables.getLast(result.values()); result = Variables.register("result", result); assertEquals(testSize, result.size()); assertEquals(testSize, lastResultSet.size()); }
Source:
protected boolean migrateVm(VM vm, ExecutionContext parentContext) { boolean forceMigration = !getParameters().isInternal(); MigrateVmParameters parameters = new MigrateVmParameters(forceMigration, vm.getId()); ArrayList<Guid> dedicatedList = new ArrayList<>(vm.getDedicatedVmForVdsList()); if (dedicatedList != null && !dedicatedList.isEmpty()) { dedicatedList.remove(vm.getRunOnVds()); if (dedicatedList.isEmpty()) { setVm(vm); auditLogDirector.log(this, AuditLogType.VM_MIGRATION_NO_VDS_TO_MIGRATE_TO); return false; } parameters.setInitialHosts(dedicatedList); } parameters.setReason(MessageBundler.getMessage(AuditLogType.MIGRATION_REASON_HOST_IN_MAINTENANCE)); return runInternalAction(ActionType.MigrateVm, parameters, createMigrateVmContext(parentContext, vm)) .getSucceeded(); }

Target:
protected boolean migrateVm(VM vm, ExecutionContext parentContext) { boolean forceMigration = !getParameters().isInternal(); MigrateVmParameters parameters = new MigrateVmParameters(forceMigration, vm.getId()); parameters.setReason(MessageBundler.getMessage(AuditLogType.MIGRATION_REASON_HOST_IN_MAINTENANCE)); return runInternalAction(ActionType.MigrateVm, parameters, createMigrateVmContext(parentContext, vm)) .getSucceeded(); }
Source:
public boolean isEs6OrHigher() { Preconditions.checkState(this != NO_TRANSPILE); return this.toInteger() >= 6; }

Target:
public boolean isEs6OrHigher() { Preconditions.checkState(this != NO_TRANSPILE); switch (this) { case ECMASCRIPT6: case ECMASCRIPT6_STRICT: case ECMASCRIPT6_TYPED: return true; default: return false; } }
Source:
public static Optional<Path> getCurrentSavesDirectory() { final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0); if (optWorldServer.isPresent()) { return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath()); } else if (SpongeImpl.getGame().getState().ordinal() >= GameState.SERVER_ABOUT_TO_START.ordinal()) { MinecraftServer server = SpongeImpl.getServer(); return Optional.of(((MinecraftServerAccessor) server).accessor$getAnvilFile().toPath().resolve(server.getFolderName())); } return Optional.empty(); }

Target:
public static Optional<Path> getCurrentSavesDirectory() { final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0); if (optWorldServer.isPresent()) { return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath()); } else if (SpongeImpl.getGame().getState().ordinal() >= GameState.SERVER_ABOUT_TO_START.ordinal()) { final MinecraftServer server = SpongeImpl.getServer(); return Optional.of(((MinecraftServerAccessor) server).accessor$getAnvilFile().toPath().resolve(server.getFolderName())); } return Optional.empty(); }
Source:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { if (in.readBoolean()) { lengthLimit = Integer.MAX_VALUE; } else { lengthLimit = in.readInt(); } } else { lengthLimit = Integer.MAX_VALUE; } }

Target:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { lengthLimit = in.readInt(); } else { lengthLimit = Integer.MAX_VALUE; } }
Source:
private void initializeBuyClient() { Bundle bundle = getArguments(); String apiKey = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_API_KEY); String appId = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APP_ID); String shopDomain = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_DOMAIN); String applicationName = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APPLICATION_NAME); productId = bundle.getLong(ProductDetailsConfig.EXTRA_SHOP_PRODUCT_ID, -1); if (productId == -1) { productId = null; } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)) { product = Product.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)); variant = product.getVariants().get(0); } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_SHOP)) { shop = Shop.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_SHOP)); } final HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(BuildConfig.OKHTTP_LOG_LEVEL); buyClient = new BuyClientBuilder() .shopDomain(shopDomain) .apiKey(apiKey) .appId(appId) .applicationName(applicationName) .interceptors(logging) .build(); }

Target:
private void initializeBuyClient() { Bundle bundle = getArguments(); String apiKey = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_API_KEY); String appId = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APP_ID); String shopDomain = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_DOMAIN); String applicationName = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APPLICATION_NAME); if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_PRODUCT_ID)) { productId = bundle.getLong(ProductDetailsConfig.EXTRA_SHOP_PRODUCT_ID, -1); } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)) { product = Product.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)); variant = product.getVariants().get(0); } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_SHOP)) { shop = Shop.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_SHOP)); } final HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(BuildConfig.OKHTTP_LOG_LEVEL); buyClient = new BuyClientBuilder() .shopDomain(shopDomain) .apiKey(apiKey) .appId(appId) .applicationName(applicationName) .interceptors(logging) .build(); }
Source:
public void receiveConnection(Socket sock) throws ConfigException { Long sid, protocolVersion; InetSocketAddress electionAddr = null; try { DataInputStream din = new DataInputStream(sock.getInputStream()); protocolVersion = din.readLong(); if (protocolVersion >= 0) { sid = protocolVersion; } else { try { InitialMessage init = InitialMessage.parse(protocolVersion, din); sid = init.sid; electionAddr = init.electionAddr; } catch (InitialMessage.InitialMessageException ex) { LOG.error(ex.toString()); closeSocket(sock); return; } } if (sid == QuorumPeer.OBSERVER_ID) { sid = observerCounter--; LOG.info("Setting arbitrary identifier to observer: {}", sid); } } catch (IOException e) { closeSocket(sock); LOG.warn("Exception reading or writing challenge: {}", e.toString()); return; } if (sid < self.getId()) { SendWorker sw = senderWorkerMap.get(sid); if (sw != null) { sw.finish(); } LOG.debug("Create new connection to server: {}", sid); closeSocket(sock); if (electionAddr != null) { connectOne(sid, electionAddr); } else { connectOne(sid); } }else if (sid == self.getId()) { closeSocket(sock); throw new ConfigException(String.format("Appearing duplicate SID: %s", sid)); } else { SendWorker sw = new SendWorker(sock, sid); RecvWorker rw = new RecvWorker(sock, sid, sw); sw.setRecv(rw); SendWorker vsw = senderWorkerMap.get(sid); if (vsw != null) { vsw.finish(); } senderWorkerMap.put(sid, sw); queueSendMap.putIfAbsent(sid, new ArrayBlockingQueue<ByteBuffer>(SEND_CAPACITY)); sw.start(); rw.start(); } }

Target:
public void receiveConnection(Socket sock) throws ConfigException { long sid, protocolVersion; InetSocketAddress electionAddr = null; try { DataInputStream din = new DataInputStream(sock.getInputStream()); protocolVersion = din.readLong(); if (protocolVersion >= 0) { sid = protocolVersion; } else { try { InitialMessage init = InitialMessage.parse(protocolVersion, din); sid = init.sid; electionAddr = init.electionAddr; } catch (InitialMessage.InitialMessageException ex) { LOG.error(ex.toString()); closeSocket(sock); return; } } if (sid == QuorumPeer.OBSERVER_ID) { sid = observerCounter--; LOG.info("Setting arbitrary identifier to observer: {}", sid); } } catch (IOException e) { closeSocket(sock); LOG.warn("Exception reading or writing challenge: {}", e.toString()); return; } if (sid < self.getId()) { SendWorker sw = senderWorkerMap.get(sid); if (sw != null) { sw.finish(); } LOG.debug("Create new connection to server: {}", sid); closeSocket(sock); if (electionAddr != null) { connectOne(sid, electionAddr); } else { connectOne(sid); } } else if (sid == self.getId()) { closeSocket(sock); throw new ConfigException(String.format("Duplicate SID %s found", sid)); } else { SendWorker sw = new SendWorker(sock, sid); RecvWorker rw = new RecvWorker(sock, sid, sw); sw.setRecv(rw); SendWorker vsw = senderWorkerMap.get(sid); if (vsw != null) { vsw.finish(); } senderWorkerMap.put(sid, sw); queueSendMap.putIfAbsent(sid, new ArrayBlockingQueue<ByteBuffer>(SEND_CAPACITY)); sw.start(); rw.start(); } }
Source:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display.getDefault().addFilter(SWT.MouseMove, fListener); } }); }

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fListener); } }); }
Source:
private void onLoginFailed(Throwable e) { logger.warn("Login failed", e); Platform.runLater(() -> { if (!(e instanceof CancellationException)) { loginErrorLabel.setText(e.getCause().getLocalizedMessage().toString().replace(". ",".\n")); loginErrorLabel.setVisible(true); } else { loginErrorLabel.setVisible(false); } setShowLoginProgress(false); }); }

Target:
private void onLoginFailed(Throwable e) { logger.warn("Login failed", e); Platform.runLater(() -> { if (!(e instanceof CancellationException)) { loginErrorLabel.setText(e.getCause().getLocalizedMessage()); loginErrorLabel.setVisible(true); } else { loginErrorLabel.setVisible(false); } setShowLoginProgress(false); }); }
Source:
public void shouldNotAllowInvalidTopicNames() { final String invalidName = "not:valid"; final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidName)); assert e.getMessage().equals("Invalid topology: Name \"" + invalidName + "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); }

Target:
public void shouldNotAllowInvalidTopicNames() { final String invalidName = "not:valid"; final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidName)); assertEquals(e.getMessage(), "Invalid topology: Name \"" + invalidName + "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); }
Source:
public void testCanParseTab() throws Exception { String sampleJson = "{\"field\":\"\tvalue\"}"; String sampleJson2 = "{\"\tfield\":{}}"; JSONTreeReader parser = new JSONTreeReader(new ByteArrayInputStream(sampleJson.getBytes("UTF-8"))); Token token = Token.Ignorable; int i = 0; try { while (token != null) { token = parser.next(); if (token == null) { break; } i++; if (i == 3) { Assert.assertEquals(Token.Value, token); Assert.assertEquals("field", parser.getFieldName()); } } } catch (Exception e) { Assert.fail(); } parser = new JSONTreeReader(new ByteArrayInputStream(sampleJson2.getBytes("UTF-8"))); token = Token.Ignorable; i = 0; try{ while(token != null){ token = parser.next(); if(token == null) { break; } i++; if(i == 3){ Assert.assertEquals(Token.StartEntity, token); Assert.assertEquals(parser.getFieldName(), "\tfield"); } } }catch(Exception e){ Assert.fail(); } }

Target:
public void testCanParseTab() throws Exception { String sampleJson = "{\"\tfield\":\t\"\tvalue\"}"; JSONTreeReader parser = new JSONTreeReader(new ByteArrayInputStream(sampleJson.getBytes("UTF-8"))); Token token = Token.Ignorable; int i = 0; try { while (token != null) { token = parser.next(); if (token == null) { break; } i++; if (i == 3) { Assert.assertEquals(Token.Value, token); Assert.assertEquals("\tfield", parser.getFieldName()); Assert.assertEquals("\tvalue", parser.getFieldValue()); } } }catch(Exception e){ Assert.fail(); } }
Source:
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_AND_MEDIA_PERMISSION_REQUEST_CODE: if (permissions == null || permissions.length == 0) { AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_INTERRUPTED); } else { for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { ToastUtils.showToast(this.getActivity(), getString(R.string .gravatar_camera_and_media_permission_required), ToastUtils.Duration.LONG); Map<String, Object> properties = new HashMap<>(); properties.put("permission denied", permissions[i]); AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_DENIED, properties); return; } } AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_ACCEPTED); askForCameraOrGallery(); } break; } }

Target:
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_AND_MEDIA_PERMISSION_REQUEST_CODE: if (permissions.length == 0) { AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_INTERRUPTED); } else { List<String> granted = new ArrayList<>(); List<String> denied = new ArrayList<>(); for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { granted.add(permissions[i]); } else { denied.add(permissions[i]); } } if (denied.size() == 0) { AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_ACCEPTED); askForCameraOrGallery(); } else { ToastUtils.showToast(this.getActivity(), getString(R.string .gravatar_camera_and_media_permission_required), ToastUtils.Duration.LONG); Map<String, Object> properties = new HashMap<>(); properties.put("permissions granted", granted.size() == 0 ? "[none]" : TextUtils .join(",", granted)); properties.put("permissions denied", TextUtils.join(",", denied)); AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_DENIED, properties); } } break; } }
Source:
public void loadFromIntent(Intent intent) { if (intent.hasExtra(KEY_FORM_RECORD_DESTINATION)) { this.mFormRecordDestination = intent.getStringExtra(KEY_FORM_RECORD_DESTINATION); } else { throw new RuntimeException("Access outside scoped storage in loading current form."); } }

Target:
public void loadFromIntent(Intent intent) { if (intent.hasExtra(KEY_FORM_RECORD_DESTINATION)) { this.mFormRecordDestination = intent.getStringExtra(KEY_FORM_RECORD_DESTINATION); } else { throw new RuntimeException("Invalid intent definition, no extra key instancedestination present in the intent."); } }
Source:
protected void createAndGetPDF(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { TempFile tempFile = null; String spec = null; try { httpServletRequest.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if (httpServletRequest.getMethod() == "POST") { try { purgeOldTemporaryFiles(); spec = getSpecFromPostBody(httpServletRequest); tempFile = doCreatePDFFile(spec, httpServletRequest); if (tempFile == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } } catch (Throwable e) { deleteFile(tempFile); error(httpServletResponse, e); return; } } else { spec = httpServletRequest.getParameter("spec"); } if (spec == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } try { tempFile = doCreatePDFFile(spec, httpServletRequest); sendPdfFile(httpServletResponse, tempFile, Boolean.parseBoolean(httpServletRequest.getParameter("inline"))); } catch (Throwable e) { error(httpServletResponse, e); } finally { deleteFile(tempFile); } }

Target:
protected void createAndGetPDF(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { TempFile tempFile = null; String spec = null; try { httpServletRequest.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if (httpServletRequest.getMethod() == "POST") { try { spec = getSpecFromPostBody(httpServletRequest); } catch (IOException e) { error(httpServletResponse, "Missing 'spec' in request body", 500); return; } } else { spec = httpServletRequest.getParameter("spec"); } if (spec == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } try { tempFile = doCreatePDFFile(spec, httpServletRequest); sendPdfFile(httpServletResponse, tempFile, Boolean.parseBoolean(httpServletRequest.getParameter("inline"))); } catch (Throwable e) { error(httpServletResponse, e); } finally { deleteFile(tempFile); } }
Source:
private void checkIfPartOfBuilding(Vector3f blockPos, EntityRef player) { HoldingComponent holdingComponent = player.getComponent(HoldingComponent.class); List<EntityRef> buildings = holdingComponent.constructedBuildings; for (EntityRef building : buildings) { ConstructedBuildingComponent buildingComponent = building.getComponent(ConstructedBuildingComponent.class); List<BlockRegion> buildingRegions = buildingComponent.boundingRegions; for (BlockRegion buildingRegion : buildingRegions) { Vector3i target = new Vector3i(blockPos, RoundingMode.FLOOR); if (buildingRegion.contains(target)) { this.buildingToUpgrade = building; holdingComponent.lastBuildingInteractedWith = building; player.saveComponent(holdingComponent); building.send(new OpenUpgradeScreenEvent()); } } } }

Target:
private void checkIfPartOfBuilding(Vector3f blockPos, EntityRef player) { HoldingComponent holdingComponent = player.getComponent(HoldingComponent.class); List<EntityRef> buildings = holdingComponent.constructedBuildings; for (EntityRef building : buildings) { ConstructedBuildingComponent buildingComponent = building.getComponent(ConstructedBuildingComponent.class); List<BlockRegion> buildingRegions = buildingComponent.boundingRegions; final Vector3i target = new Vector3i(blockPos, RoundingMode.FLOOR); for (BlockRegion buildingRegion : buildingRegions) { if (buildingRegion.contains(target)) { this.buildingToUpgrade = building; holdingComponent.lastBuildingInteractedWith = building; player.saveComponent(holdingComponent); building.send(new OpenUpgradeScreenEvent()); } } } }
Source:
public void usedExternalIdThrows() { mockHealthCodeAndAccountRetrieval(); STUDY.setExternalIdValidationEnabled(true); ExternalIdentifier identifier = ExternalIdentifier.create(STUDY.getStudyIdentifier(), EXTERNAL_ID); identifier.setHealthCode("AAA"); when(externalIdService.getExternalId(STUDY.getStudyIdentifier(), EXTERNAL_ID, false)).thenReturn(identifier); doThrow(new EntityAlreadyExistsException(Account.class, (String) null, (Map<String, Object>) null)) .when(accountDao).createAccount(any(), any(), any()); try { participantService.createParticipant(STUDY, PARTICIPANT, false); fail("Should have thrown exception"); } catch(EntityAlreadyExistsException e) { verify(accountWorkflowService, never()).sendEmailVerificationToken(any(), any(), any()); } }

Target:
public void usedExternalIdThrows() { mockHealthCodeAndAccountRetrieval(); STUDY.setExternalIdValidationEnabled(true); ExternalIdentifier identifier = ExternalIdentifier.create(STUDY.getStudyIdentifier(), EXTERNAL_ID); identifier.setHealthCode("AAA"); when(externalIdService.getExternalId(STUDY.getStudyIdentifier(), EXTERNAL_ID, false)).thenReturn(identifier); doThrow(new EntityAlreadyExistsException(Account.class, (String) null, (Map<String, Object>) null)) .when(accountDao).createAccount(any(), any(), any()); try { participantService.createParticipant(STUDY, PARTICIPANT, false); fail("Should have thrown exception"); } catch(EntityAlreadyExistsException e) { verify(accountDao, never()).createAccount(any(), any(), any()); verify(externalIdService, never()).commitAssignExternalId(any()); verify(accountWorkflowService, never()).sendEmailVerificationToken(any(), any(), any()); } }
Source:
public BlobItem(BlobItemInternal blobItemInternal) { this.name = blobItemInternal.getName(); this.deleted = blobItemInternal.isDeleted(); this.snapshot = blobItemInternal.getSnapshot(); this.properties = blobItemInternal.getProperties(); this.metadata = blobItemInternal.getMetadata(); this.versionId = blobItemInternal.getVersionId(); this.isCurrentVersion = blobItemInternal.isCurrentVersion(); this.isPrefix = blobItemInternal.isPrefix(); this.tags = new HashMap<>(); if (blobItemInternal.getBlobTags() != null && blobItemInternal.getBlobTags().getBlobTagSet() != null) { for (BlobTag tag : blobItemInternal.getBlobTags().getBlobTagSet()) { this.tags.put(tag.getKey(), tag.getValue()); } } }

Target:
public BlobItem(BlobItemInternal blobItemInternal) { this.name = blobItemInternal.getName(); this.deleted = blobItemInternal.isDeleted(); this.snapshot = blobItemInternal.getSnapshot(); this.properties = new BlobItemProperties(blobItemInternal.getProperties()); this.metadata = blobItemInternal.getMetadata(); this.versionId = blobItemInternal.getVersionId(); this.isCurrentVersion = blobItemInternal.isCurrentVersion(); this.isPrefix = blobItemInternal.isPrefix(); this.tags = new HashMap<>(); if (blobItemInternal.getBlobTags() != null && blobItemInternal.getBlobTags().getBlobTagSet() != null) { for (BlobTag tag : blobItemInternal.getBlobTags().getBlobTagSet()) { this.tags.put(tag.getKey(), tag.getValue()); } } }
Source:
public synchronized void transferMemory(LocalMemoryContext to) { checkArgument(to instanceof SimpleLocalMemoryContext, "to must be an instance of SimpleLocalMemoryContext"); checkState(!closed, "SimpleLocalMemoryContext is already closed"); SimpleLocalMemoryContext target = (SimpleLocalMemoryContext) to; AggregatedMemoryContext parent = parentMemoryContext; while (parent != null && parent != target.parentMemoryContext) { synchronized (parent) { parent.usedBytes -= usedBytes; } parent = parent.parentMemoryContext; } checkState(parent != null, "memory context state is corrupt"); synchronized (target) { target.usedBytes = AggregatedMemoryContext.addExact(target.usedBytes, usedBytes); } usedBytes = 0; }

Target:
public synchronized void transferMemory(LocalMemoryContext to) { checkArgument(to instanceof SimpleLocalMemoryContext, "to must be an instance of SimpleLocalMemoryContext"); checkState(!closed, "already closed"); SimpleLocalMemoryContext target = (SimpleLocalMemoryContext) to; checkMemoryContextState(target); AggregatedMemoryContext parent = parentMemoryContext; while (parent != null && parent != target.parentMemoryContext) { parent.addBytes(-usedBytes); parent = parent.getParent(); } target.addBytes(usedBytes); usedBytes = 0; }
Source:
public void testAbsolute() { DatasetRepository repo = DatasetRepositories.open("repo:file:/tmp/data"); repo.delete("test"); repo.create("test", descriptor); Dataset<Object> ds = Datasets.load("dataset:file:/tmp/data/test", Object.class); Assert.assertNotNull("Should load dataset", ds); Assert.assertTrue(ds instanceof FileSystemDataset); Assert.assertEquals("Locations should match", URI.create("file:/tmp/data/test"), ds.getDescriptor().getLocation()); Assert.assertEquals("Descriptors should match", repo.load("test").getDescriptor(), ds.getDescriptor()); repo.delete("test"); }

Target:
public void testAbsolute() { DatasetRepository repo = DatasetRepositories.open("repo:file:/tmp/data"); repo.delete("test"); repo.create("test", descriptor); Dataset<Record> ds = Datasets.<Record, Dataset<Record>> load("dataset:file:/tmp/data/test", Record.class); Assert.assertNotNull("Should load dataset", ds); Assert.assertTrue(ds instanceof FileSystemDataset); Assert.assertEquals("Locations should match", URI.create("file:/tmp/data/test"), ds.getDescriptor().getLocation()); Assert.assertEquals("Descriptors should match", repo.load("test").getDescriptor(), ds.getDescriptor()); repo.delete("test"); }
Source:
public CompletionTime processOneToOne(String tenantId, CompletionTimeProcessing completionTimeProcessing) throws RetryAttemptException{ if (completionTimeProcessing.getNumberOfRetries() < 1) { completionTimeProcessing.setNumberOfRetries(completionTimeProcessing.getNumberOfRetries() + 1); return null; } Span rootSpan = completionTimeProcessing.getRootSpan(); List<Span> trace = spanCache.getTrace(tenantId, rootSpan.getTraceId()); Annotation lastAnnotation = extractLastAnnotation(trace); CompletionTime completionTime = CompletionTimeUtil.spanToCompletionTime(rootSpan); if (lastAnnotation != null) { completionTime.setDuration(getTraceDuration(rootSpan, lastAnnotation.getTimestamp())); } completionTime.setProperties(extractProperties(trace)); log.debugf("SpanTraceCompletionTimeDeriver completionTime[%s]", completionTime); return completionTime; }

Target:
public CompletionTime processOneToOne(String tenantId, CompletionTimeProcessing completionTimeProcessing) throws RetryAttemptException { if (completionTimeProcessing.getCompletionTime() == null) { return null; } log.debugf("SpanTraceCompletionTimeDeriver completionTime[%s]", completionTimeProcessing.getCompletionTime()); return completionTimeProcessing.getCompletionTime(); }
Source:
private static Map<String, String> buildAliasMap(DnsResponse response, DnsCnameCache cache, EventLoop loop) { final int answerCount = response.count(DnsSection.ANSWER); Map<String, String> cnames = null; for (int i = 0; i < answerCount; i ++) { final DnsRecord r = response.recordAt(DnsSection.ANSWER, i); final DnsRecordType type = r.type(); if (type != DnsRecordType.CNAME) { continue; } if (!(r instanceof DnsRawRecord)) { continue; } final ByteBuf recordContent = ((ByteBufHolder) r).content(); final String domainName = decodeDomainName(recordContent); if (domainName == null) { continue; } if (cnames == null) { cnames = new HashMap<String, String>(min(8, answerCount)); } String name = r.name().toLowerCase(Locale.US); String mapping = domainName.toLowerCase(Locale.US); String nameWithDot = hostnameWithDot(name); String mappingWithDot = hostnameWithDot(mapping); if (!nameWithDot.equalsIgnoreCase(mappingWithDot)) { cache.cache(hostnameWithDot(name), hostnameWithDot(mapping), r.timeToLive(), loop); cnames.put(name, mapping); } } return cnames != null? cnames : Collections.<String, String>emptyMap(); }

Target:
private static Map<String, String> buildAliasMap(DnsResponse response, DnsCnameCache cache, EventLoop loop) { final int answerCount = response.count(DnsSection.ANSWER); Map<String, String> cnames = null; for (int i = 0; i < answerCount; i ++) { final DnsRecord r = response.recordAt(DnsSection.ANSWER, i); final DnsRecordType type = r.type(); if (type != DnsRecordType.CNAME) { continue; } if (!(r instanceof DnsRawRecord)) { continue; } final ByteBuf recordContent = ((ByteBufHolder) r).content(); final String domainName = decodeDomainName(recordContent); if (domainName == null) { continue; } if (cnames == null) { cnames = new HashMap<String, String>(min(8, answerCount)); } String name = r.name().toLowerCase(Locale.US); String mapping = domainName.toLowerCase(Locale.US); String nameWithDot = hostnameWithDot(name); String mappingWithDot = hostnameWithDot(mapping); if (!nameWithDot.equalsIgnoreCase(mappingWithDot)) { cache.cache(nameWithDot, mappingWithDot, r.timeToLive(), loop); cnames.put(name, mapping); } } return cnames != null? cnames : Collections.<String, String>emptyMap(); }
Source:
public SubTabDiskGeneralView(DetailModelProvider<DiskListModel, DiskGeneralModel> modelProvider) { super(modelProvider); formPanel = new GeneralFormPanel(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); driver.initialize(this); generateIds(); formBuilder = new FormBuilder(formPanel, 1, 8); formBuilder.addFormItem(new FormItem(constants.aliasDisk(), alias, 0, 0), 2, 10); formBuilder.addFormItem(new FormItem(constants.descriptionDisk(), description, 1, 0), 2, 10); formBuilder.addFormItem(new FormItem(constants.idDisk(), diskId, 2, 0), 2, 10); formBuilder.addFormItem(new FormItem(constants.lunIdSanStorage(), lunId, 4, 0) { @Override public boolean getIsAvailable() { return getDetailModel().isLun(); } }, 2, 10); formBuilder.addFormItem(new FormItem(constants.diskProfile(), diskProfileName, 5, 0) { @Override public boolean getIsAvailable() { return !getDetailModel().isLun(); } }, 2, 10); formBuilder.addFormItem(new FormItem(constants.quota(), quotaName, 6, 0) { @Override public boolean getIsAvailable() { return getDetailModel().isQuotaAvailable(); } }, 2, 10); formBuilder.addFormItem(new FormItem(constants.wipeAfterDelete(), wipeAfterDelete, 7, 0) { @Override public boolean getIsAvailable() { return getDetailModel().isImage(); } }, 2, 10); formBuilder.setRelativeColumnWidth(0, 12); }

Target:
public SubTabDiskGeneralView(DetailModelProvider<DiskListModel, DiskGeneralModel> modelProvider) { super(modelProvider); formPanel = new GeneralFormPanel(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); driver.initialize(this); generateIds(); formBuilder = new FormBuilder(formPanel, 1, 8); formBuilder.addFormItem(new FormItem(constants.aliasDisk(), alias, 0, 0), 2, 10); formBuilder.addFormItem(new FormItem(constants.descriptionDisk(), description, 1, 0), 2, 10); formBuilder.addFormItem(new FormItem(constants.idDisk(), diskId, 2, 0), 2, 10); formBuilder.addFormItem(new FormItem(constants.lunIdSanStorage(), lunId, 3, 0) { @Override public boolean getIsAvailable() { return getDetailModel().isLun(); } }, 2, 10); formBuilder.addFormItem(new FormItem(constants.diskProfile(), diskProfileName, 4, 0) { @Override public boolean getIsAvailable() { return !getDetailModel().isLun(); } }, 2, 10); formBuilder.addFormItem(new FormItem(constants.quota(), quotaName, 5, 0) { @Override public boolean getIsAvailable() { return getDetailModel().isQuotaAvailable(); } }, 2, 10); formBuilder.addFormItem(new FormItem(constants.wipeAfterDelete(), wipeAfterDelete, 6, 0) { @Override public boolean getIsAvailable() { return getDetailModel().isImage(); } }, 2, 10); formBuilder.setRelativeColumnWidth(0, 12); }
Source:
public void map() { if (!mapped) { final ResolvedType resolved = resolver.resolve(getType()); final ResolvedTypeWithMembers type = memberResolver.resolve(resolved, null, null); for (final ResolvedType resolvedType : resolved.getTypeParameters()) { addParameter(resolvedType.getErasedType()); } for (final ResolvedField field : type.getMemberFields()) { addField(field); } for (final ResolvedMethod memberMethod : type.getMemberMethods()) { addMethod(memberMethod); } mapped = true; } }

Target:
public void map() { if (!mapped) { final ResolvedType resolved = resolver.resolve(getType()); final ResolvedTypeWithMembers type = memberResolver.resolve(resolved, new StdConfiguration(AnnotationInclusion.INCLUDE_AND_INHERIT_IF_INHERITED), null); for (final ResolvedType resolvedType : resolved.getTypeParameters()) { addParameter(resolvedType.getErasedType()); } for (final ResolvedField field : type.getMemberFields()) { addField(field); } for (final ResolvedMethod memberMethod : type.getMemberMethods()) { addMethod(memberMethod); } mapped = true; } }
Source:
private static int computeElapsedTimeInSeconds(long startTime, long endTime) { return (int) (endTime - startTime / 1000); }

Target:
private static int computeElapsedTimeInSeconds(long startTime, long endTime) { return (int)((endTime - startTime) / 1000); }
Source:
private void load(int nodeSize, File fluoPropsFile, File out1) throws Exception { int ret = ToolRunner.run(new Load(), new String[] {"-D", "mapred.job.tracker=local", "-D", "fs.default.name=file:/ fluoPropsFile.getAbsolutePath(), out1.toURI().toString()}); Assert.assertEquals(0, ret); }

Target:
private void load(int nodeSize, File fluoPropsFile, File out1) throws Exception { int ret = ToolRunner.run(new Load(), new String[] {"-D", "mapred.job.tracker=local", "-D", "fs.defaultFS=file:/ fluoPropsFile.getAbsolutePath(), out1.toURI().toString()}); Assert.assertEquals(0, ret); }
Source:
public void testGetPropertyStoreWithTestStringData() throws IOException { String actual = new JerseyUriRequestBuilder("clusters/{}/propertyStore/NonZnRecord").format(TEST_CLUSTER) .isBodyReturnExpected(true).get(this); JsonNode jsonNode = OBJECT_MAPPER.readTree(actual); String payLoad = jsonNode.get("content").getValueAsText(); Assert.assertEquals(TEST_CONTENT, payLoad); }

Target:
public void testGetPropertyStoreWithTestStringData() throws IOException { String actual = new JerseyUriRequestBuilder("clusters/{}/propertyStore/NonZnRecord").format(TEST_CLUSTER) .isBodyReturnExpected(true).get(this); JsonNode jsonNode = OBJECT_MAPPER.readTree(actual); String payLoad = jsonNode.get(CONTENT_KEY).getValueAsText(); Assert.assertEquals(TEST_CONTENT, payLoad); }
Source:
void close(boolean sawErrors) throws IOException { if (memIters != null) { tablet.getTabletMemory().returnIterators(memIters); memIters = null; tablet.getDatafileManager().returnFilesForScan(fileReservationId); fileReservationId = -1; } synchronized (tablet) { if (tablet.removeScan(this) == 0) tablet.notifyAll(); } if (fileManager != null) { fileManager.releaseOpenFiles(sawErrors); fileManager = null; } try { if (statsIterator != null) { statsIterator.report(); statsIterator.close(); } if (iter != null) { iter.close(); } } catch (Exception e) { throw new IOException(e); } }

Target:
void close(boolean sawErrors) { if (memIters != null) { tablet.getTabletMemory().returnIterators(memIters); memIters = null; tablet.getDatafileManager().returnFilesForScan(fileReservationId); fileReservationId = -1; } synchronized (tablet) { if (tablet.removeScan(this) == 0) tablet.notifyAll(); } if (fileManager != null) { fileManager.releaseOpenFiles(sawErrors); fileManager = null; } if (statsIterator != null) { statsIterator.report(); } }
Source:
public void run(String... args) throws Exception { System.out.println("Running and exiting"); }

Target:
public void run(String... args) throws Exception { logger.info("Running conditional flow application..."); }
Source:
public void sendNotification(String providerId, Object payload, Notification notification, TaskTracker tracker) throws Exception { try { List<TranslatedNotification> translatedNotifications = ( List<TranslatedNotification>) payload; for(TranslatedNotification translatedNotification : translatedNotifications) { switch (translatedNotification.getType()) { case "toast": WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01(translatedNotification.getMessage().toString()).build(); service.pushToast(providerId, toast); break; case "badge": WnsBadge badge; if (translatedNotification.getMessage() instanceof Integer) { badge = new WnsBadgeBuilder().value((Integer) translatedNotification.getMessage()).build(); } else { badge = new WnsBadgeBuilder().value(translatedNotification.getMessage().toString()).build(); } service.pushBadge(providerId, badge); break; } } tracker.completed(); } catch (Exception e) { tracker.failed(0,e.toString()); LOG.error("Failed to send notification",e); } }

Target:
public void sendNotification(String providerId, Object payload, Notification notification, TaskTracker tracker) throws Exception { try { List<TranslatedNotification> translatedNotifications = ( List<TranslatedNotification>) payload; for(TranslatedNotification translatedNotification : translatedNotifications) { switch (translatedNotification.getType()) { case "toast": WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01(translatedNotification.getMessage().toString()).build(); service.pushToast(providerId, toast); break; case "badge": WnsBadge badge; if (translatedNotification.getMessage() instanceof Integer) { badge = new WnsBadgeBuilder().value((Integer) translatedNotification.getMessage()).build(); } else { badge = new WnsBadgeBuilder().value(translatedNotification.getMessage().toString()).build(); } service.pushBadge(providerId, badge); break; default : throw new IllegalArgumentException(translatedNotification.getType()+" does not match a valid notification type (toast,badge)."); } } tracker.completed(); } catch (Exception e) { tracker.failed(0,e.toString()); LOG.error("Failed to send notification",e); } }
Source:
private void updateReportDataClonedCashAdvanceCountAndAmountTotals(ConcurRequestExtractBatchReportData reportData, ConcurRequestExtractRequestDetailFileLine detailFileLine) { int count = reportData.getClonedCashAdvanceRequests().getRecordCount(); count++; reportData.getClonedCashAdvanceRequests().setRecordCount(count); KualiDecimal amount = reportData.getClonedCashAdvanceRequests().getDollarAmount(); reportData.getClonedCashAdvanceRequests().setDollarAmount(amount.add(detailFileLine.getRequestAmount())); }

Target:
private void updateReportDataClonedCashAdvanceCountAndAmountTotals(ConcurRequestExtractBatchReportData reportData, ConcurRequestExtractRequestDetailFileLine detailFileLine) { reportData.getClonedCashAdvanceRequests().incrementRecordCount(); reportData.getClonedCashAdvanceRequests().addDollarAmount(detailFileLine.getRequestAmount()); }
Source:
private String getAttachment() throws NotConnectedException, UnknownJobException, PermissionException, IOException { JobId jobID = jobState.getId(); List<TaskState> tasks = jobState.getTasks(); String attachLogPath = null; try { JobResult result = dbManager.loadJobResult(jobID); while (result == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { logger.info("Stack trace: ", e); } } String allRes = String.join(System.lineSeparator(), tasks.stream() .map(task -> "Task " + task.getId().toString() + " (" + task.getId().getReadableName() + ") :" + System.lineSeparator() + result.getAllResults() .get(task.getId() .getReadableName()) .getOutput() .getAllLogs()) .collect(Collectors.toList())); File file = File.createTempFile("job_logs", ".log"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(allRes); attachLogPath = file.getAbsolutePath(); } catch (IOException e) { jlogger.warn(jobState.getId(), "Failed to create attachment for email notification: " + e.getMessage()); logger.warn("Error creating attachment for email notification: " + e.getMessage(), e); } } catch (Exception e) { logger.warn("Error creating attachment for email notification: ", e); } return attachLogPath; }

Target:
private String getAttachment() throws NotConnectedException, UnknownJobException, PermissionException, IOException { JobId jobID = jobState.getId(); List<TaskState> tasks = jobState.getTasks(); String attachLogPath = null; try { JobResult result = dbManager.loadJobResult(jobID); String allRes = String.join(System.lineSeparator(), tasks.stream() .map(task -> "Task " + task.getId().toString() + " (" + task.getId().getReadableName() + ") :" + System.lineSeparator() + result.getAllResults() .get(task.getId() .getReadableName()) .getOutput() .getAllLogs()) .collect(Collectors.toList())); File file = File.createTempFile("job_logs", ".log"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(allRes); attachLogPath = file.getAbsolutePath(); } catch (IOException e) { jlogger.warn(jobState.getId(), "Failed to create attachment for email notification: " + e.getMessage()); logger.warn("Error creating attachment for email notification: " + e.getMessage(), e); } } catch (Exception e) { logger.warn("Error creating attachment for email notification: ", e); } return attachLogPath; }
Source:
private void calculateNormals() { List<Vector3f> vertices = getBindPoseVertexPositions(); List<Vector3f> normals = Lists.newArrayListWithCapacity(vertices.size()); for (int i = 0; i < vertices.size(); ++i) { normals.add(new Vector3f()); } Vector3f v1 = new Vector3f(); Vector3f v2 = new Vector3f(); Vector3f norm = new Vector3f(); for (int i = 0; i < indices.size() / 3; ++i) { Vector3f baseVert = vertices.get(indices.get(i * 3)); v1.sub(vertices.get(indices.get(i * 3 + 1)), baseVert); v2.sub(vertices.get(indices.get(i * 3 + 2)), baseVert); v1.normalize(); v2.normalize(); norm.cross(v1, v2); normals.get(indices.get(i * 3)).add(norm); normals.get(indices.get(i * 3 + 1)).add(norm); normals.get(indices.get(i * 3 + 2)).add(norm); } normals.forEach(Vector3f::normalize); Quaternionf inverseRot = new Quaternionf(); for (int vertIndex = 0; vertIndex < vertices.size(); ++vertIndex) { Vector3f normal = normals.get(vertIndex); for (int weightIndex = 0; weightIndex < vertexWeightCounts.get(vertIndex); ++weightIndex) { BoneWeight weight = weights.get(weightIndex + vertexStartWeights.get(vertIndex)); bones.get(weight.getBoneIndex()).getObjectRotation().invert(inverseRot); inverseRot.transform(normal, norm); weight.setNormal(norm); } } }

Target:
private void calculateNormals() { List<Vector3f> vertices = getBindPoseVertexPositions(); List<Vector3f> normals = Lists.newArrayListWithCapacity(vertices.size()); for (int i = 0; i < vertices.size(); ++i) { normals.add(new Vector3f()); } Vector3f v1 = new Vector3f(); Vector3f v2 = new Vector3f(); Vector3f norm = new Vector3f(); for (int i = 0; i < indices.size() / 3; ++i) { Vector3f baseVert = vertices.get(indices.get(i * 3)); vertices.get(indices.get(i * 3 + 1)).sub(baseVert, v1); vertices.get(indices.get(i * 3 + 2)).sub(baseVert, v2); v1.normalize(); v2.normalize(); norm.cross(v1, v2); normals.get(indices.get(i * 3)).add(norm); normals.get(indices.get(i * 3 + 1)).add(norm); normals.get(indices.get(i * 3 + 2)).add(norm); } normals.forEach(Vector3f::normalize); Quaternionf inverseRot = new Quaternionf(); for (int vertIndex = 0; vertIndex < vertices.size(); ++vertIndex) { Vector3f normal = normals.get(vertIndex); for (int weightIndex = 0; weightIndex < vertexWeightCounts.get(vertIndex); ++weightIndex) { BoneWeight weight = weights.get(weightIndex + vertexStartWeights.get(vertIndex)); bones.get(weight.getBoneIndex()).getObjectRotation().invert(inverseRot); inverseRot.transform(normal, norm); weight.setNormal(norm); } } }
Source:
protected static String getMavenXcodePluginArtifactId() throws IOException { return getProjectProperty("artifactId"); }

Target:
protected static String getMavenXcodePluginArtifactId() throws IOException { return getProjectProperty(ARTIFACT_ID); }
Source:
public static String getDomainFromResolverConf(final String file) { final InputStream in; try { in = new FileInputStream(file); } catch (FileNotFoundException e) { return ""; } final InputStreamReader isr = new InputStreamReader(in); final BufferedReader br = new BufferedReader(isr); try { String line; while ((line = br.readLine()) != null) { if (line.startsWith("domain")) { final StringTokenizer st = new StringTokenizer(line); st.nextToken(); if (!st.hasMoreTokens()) { continue; } return st.nextToken(); } } br.close(); } catch (IOException e) { } finally { try { br.close(); } catch (IOException e) { } } return ""; }

Target:
public static String getDomainFromResolverConf(final String file) { try (final InputStream in = new FileInputStream(file)) { final InputStreamReader isr = new InputStreamReader(in); try (final BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { if (line.startsWith("domain")) { final StringTokenizer st = new StringTokenizer(line); st.nextToken(); if (!st.hasMoreTokens()) { continue; } return st.nextToken(); } } } } catch (FileNotFoundException e) { log.warn("Resolver config file not found", e); } catch (IOException e) { log.warn("Error reading config file", e); } return ""; }