auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String otherBranchCommit(Change change, PatchSet patchSet) throws RepositoryNotFoundException, IOException, PatchSetInfoNotAvailableException { Repository git = repoManager.openRepository(change.getProject()); String targetBranch = change.getDest().get(); String commitBranchFlag = "different branch commit"; try { RefDatabase refDb = git.getRefDatabase(); Ref targetRef = refDb.getRef(targetBranch); Collection<Ref> branches = refDb.getRefs(Constants.R_HEADS).values(); RevWalk rw = new RevWalk(git); RevCommit pushedCommit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); RevCommit target = rw.parseCommit(targetRef.getObjectId()); try { rw.markStart(pushedCommit); for (Ref branch : branches) { if (branch.getObjectId() != targetRef.getObjectId()) { rw.markUninteresting(rw.parseCommit(branch.getObjectId())); } } for (RevCommit n; (n = rw.next()) != null;) { if (n.equals(target)) { commitBranchFlag = "same branch commit"; break; } } } finally { rw.release(); } } finally { git.close(); } return commitBranchFlag; }

Target:
private boolean otherBranchCommit(Change change, PatchSet patchSet) throws RepositoryNotFoundException, IOException, PatchSetInfoNotAvailableException { Repository git = repoManager.openRepository(change.getProject()); String targetBranch = change.getDest().get(); boolean commitBranchFlag = true; try { RefDatabase refDb = git.getRefDatabase(); Ref targetRef = refDb.getRef(targetBranch); Collection<Ref> branches = refDb.getRefs(Constants.R_HEADS).values(); RevWalk rw = new RevWalk(git); RevCommit pushedCommit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); RevCommit target = rw.parseCommit(targetRef.getObjectId()); RevCommit mergeBase = null; RevFilter oldRevFilter = rw.getRevFilter(); try { rw.reset(); rw.setRevFilter(RevFilter.MERGE_BASE); rw.markStart(pushedCommit); rw.markStart(target); if (rw.next() != null) { mergeBase = rw.next(); } } finally { rw.reset(); rw.setRevFilter(oldRevFilter); } try { rw.markStart(pushedCommit); for (Ref branch : branches) { if (branch.getObjectId() != targetRef.getObjectId()) { rw.markUninteresting(rw.parseCommit(branch.getObjectId())); } } for (RevCommit n; (n = rw.next()) != null;) { if (n.equals(mergeBase)) { commitBranchFlag = false; break; } } } finally { rw.release(); } } finally { git.close(); } return commitBranchFlag; }
Source:
public boolean isResolved() { return resolveFuture == null || resolveFuture.isDone() || label != null; }

Target:
public boolean isResolved() { return (resolveFuture != null && resolveFuture.isDone()); }
Source:
public void updateJitter(long ssrc, StreamDirection direction, double jitter) { if (direction == StreamDirection.DOWNLOAD) { receiveStats.setJitter(jitter); ReceiveTrackStatsImpl receiveStat = receiveSsrcStats.get(ssrc); if (receiveStat != null) { receiveStat.setJitter(jitter); } } else if (direction == StreamDirection.UPLOAD) { sendStats.setJitter(jitter); SendTrackStatsImpl sendStats = sendSsrcStats.get(ssrc); if (sendStats != null) { sendStats.setJitter(jitter); } } }

Target:
public void updateJitter(long ssrc, StreamDirection direction, double jitter) { if (direction == StreamDirection.DOWNLOAD) { receiveStats.setJitter(jitter); ReceiveTrackStatsImpl receiveSsrcStat = receiveSsrcStats.get(ssrc); if (receiveSsrcStat != null) { receiveSsrcStat.setJitter(jitter); } } else if (direction == StreamDirection.UPLOAD) { sendStats.setJitter(jitter); SendTrackStatsImpl sendSsrcStat = sendSsrcStats.get(ssrc); if (sendSsrcStat != null) { sendSsrcStat.setJitter(jitter); } } }
Source:
public void start() throws Exception { MqttClientOptions options = new MqttClientOptions() .setPort(1883) .setHost("0.0.0.0"); MqttClient mqttClient = MqttClient.create(vertx, options); mqttClient.connect(ch -> { if(ch.succeeded()) { System.out.println("Connected to a server"); mqttClient.publish( MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE.getBytes()), MqttQoS.AT_MOST_ONCE, false, false, s -> System.out.println("Publish sent to a server")); } else { System.out.println("Failed to connect to a server"); System.out.println(ch.cause()); } }); }

Target:
public void start() throws Exception { MqttClientOptions options = new MqttClientOptions() .setPort(SERVER_PORT) .setHost(SERVER_HOST); MqttClient mqttClient = MqttClient.create(vertx, options); mqttClient.connect(ch -> { if (ch.succeeded()) { System.out.println("Connected to a server"); mqttClient.publish( MQTT_TOPIC, Buffer.buffer(MQTT_MESSAGE), MqttQoS.AT_MOST_ONCE, false, false, s -> mqttClient.disconnect(d -> System.out.println("Disconnected from server"))); } else { System.out.println("Failed to connect to a server"); System.out.println(ch.cause()); } }); }
Source:
public void setNodeIdentifier(String nodeIdentifier) throws CoreEnvironmentBeanException { if (nodeIdentifier == null) { tsLogger.i18NLogger.fatal_nodename_null(); throw new CoreEnvironmentBeanException(tsLogger.i18NLogger.get_fatal_nodename_null()); } try { if (nodeIdentifier.getBytes("UTF-8").length > NODE_NAME_SIZE) { tsLogger.i18NLogger.fatal_nodename_too_long(nodeIdentifier, NODE_NAME_SIZE); throw new CoreEnvironmentBeanException(tsLogger.i18NLogger.get_fatal_nodename_too_long(nodeIdentifier, NODE_NAME_SIZE)); } } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 is not supported"); } this.nodeIdentifier = nodeIdentifier; }

Target:
public void setNodeIdentifier(String nodeIdentifier) throws CoreEnvironmentBeanException { if (nodeIdentifier == null) { tsLogger.i18NLogger.fatal_nodename_null(); throw new CoreEnvironmentBeanException(tsLogger.i18NLogger.get_fatal_nodename_null()); } if (nodeIdentifier.getBytes(StandardCharsets.UTF_8).length > NODE_NAME_SIZE) { tsLogger.i18NLogger.fatal_nodename_too_long(nodeIdentifier, NODE_NAME_SIZE); throw new CoreEnvironmentBeanException(tsLogger.i18NLogger.get_fatal_nodename_too_long(nodeIdentifier, NODE_NAME_SIZE)); } this.nodeIdentifier = nodeIdentifier; }
Source:
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) { if (event != LifecycleEvent.UP) return; ServiceName serviceName = controller.getName(); if (!JBOSS_DEPLOYMENT.isParentOf(serviceName)) return; String simpleName = serviceName.getSimpleName(); if (simpleName.equals(Phase.DEPENDENCIES.toString())) { ServiceName parentName = serviceName.getParent(); ServiceController<?> parentController = controller.getServiceContainer().getService(parentName); DeploymentUnit depUnit = (DeploymentUnit) parentController.getValue(); ArquillianConfigBuilder.handleParseAnnotations(depUnit); } else if (simpleName.equals(Phase.INSTALL.toString())) { ServiceName parentName = serviceName.getParent(); ServiceController<?> parentController = controller.getServiceContainer().getService(parentName); DeploymentUnit depUnit = (DeploymentUnit) parentController.getValue(); Set<String> testClasses = ArquillianConfigBuilder.getClasses(depUnit); if (testClasses != null) { String duName = ArquillianConfigBuilder.getName(depUnit); ServiceName arqConfigSN = ServiceName.JBOSS.append("arquillian", "config", duName); ServiceBuilder<?> builder = serviceTarget.addService(arqConfigSN); ArquillianConfig arqConfig = new ArquillianConfig(arqConfigSN, testClasses, builder.requires(ArquillianService.SERVICE_NAME), builder.requires(parentController.getName())); builder.setInstance(arqConfig); builder.install(); log.infof("Arquillian deployment detected: %s", arqConfig); } } }

Target:
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) { if (event != LifecycleEvent.UP) return; ServiceName serviceName = controller.getName(); if (!JBOSS_DEPLOYMENT.isParentOf(serviceName)) return; String simpleName = serviceName.getSimpleName(); if (simpleName.equals(Phase.DEPENDENCIES.toString())) { ServiceName parentName = serviceName.getParent(); ServiceController<?> parentController = controller.getServiceContainer().getService(parentName); DeploymentUnit depUnit = (DeploymentUnit) parentController.getValue(); ArquillianConfigBuilder.handleParseAnnotations(depUnit); } else if (simpleName.equals(Phase.INSTALL.toString())) { ServiceName parentName = serviceName.getParent(); ServiceController<?> parentController = controller.getServiceContainer().getService(parentName); DeploymentUnit depUnit = (DeploymentUnit) parentController.getValue(); Set<String> testClasses = ArquillianConfigBuilder.getClasses(depUnit); if (testClasses != null) { String duName = ArquillianConfigBuilder.getName(depUnit); ServiceName arqConfigSN = ServiceName.JBOSS.append("arquillian", "config", duName); ServiceBuilder<ArquillianConfig> builder = (ServiceBuilder<ArquillianConfig>) serviceTarget.addService(arqConfigSN); ArquillianConfig arqConfig = new ArquillianConfig(arqConfigSN, testClasses, builder.requires(ArquillianService.SERVICE_NAME), builder.requires(parentController.getName())); arqConfig.addDeps(builder, controller); builder.setInstance(arqConfig); builder.install(); log.infof("Arquillian deployment detected: %s", arqConfig); } } }
Source:
public void apply( E workspaceEnvironment, RuntimeIdentity runtimeID, Collection<PluginFQN> pluginFQNs) throws InfrastructureException { E brokerEnvironment = brokerEnvironmentFactory.create(pluginFQNs, runtimeID); Map<String, PodData> workspacePods = workspaceEnvironment.getPodsData(); if (workspacePods.size() != 1) { throw new InfrastructureException( "Che plugins tooling configuration can be applied to a workspace with one pod only."); } PodData workspacePod = workspacePods.values().iterator().next(); Map<String, PodData> brokerPods = brokerEnvironment.getPodsData(); if (brokerPods.size() != 1) { throw new InfrastructureException("Broker environment must have only one Pod."); } PodData brokerPod = brokerPods.values().iterator().next(); List<Container> brokerContainers = brokerPod.getSpec().getContainers(); for (Container container : brokerContainers) { InternalMachineConfig brokerMachine = brokerEnvironment.getMachines().get(Names.machineName(brokerPod, container)); if (brokerMachine == null) { throw new InfrastructureException( String.format( "Could not find appropriate place for broker container %s", container.getName())); } workspaceEnvironment .getMachines() .put(Names.machineName(workspacePod, container), brokerMachine); } workspaceEnvironment.getConfigMaps().putAll(brokerEnvironment.getConfigMaps()); workspacePod.getSpec().getInitContainers().addAll(brokerPod.getSpec().getContainers()); workspacePod.getSpec().getVolumes().addAll(brokerPod.getSpec().getVolumes()); }

Target:
public void apply( E workspaceEnvironment, RuntimeIdentity runtimeID, Collection<PluginFQN> pluginFQNs) throws InfrastructureException { E brokerEnvironment = brokerEnvironmentFactory.create(pluginFQNs, runtimeID); Map<String, PodData> workspacePods = workspaceEnvironment.getPodsData(); if (workspacePods.size() != 1) { throw new InfrastructureException( "Che plugins tooling configuration can be applied to a workspace with one pod only."); } PodData workspacePod = workspacePods.values().iterator().next(); Map<String, PodData> brokerPods = brokerEnvironment.getPodsData(); if (brokerPods.size() != 1) { throw new InfrastructureException("Broker environment must have only one Pod."); } PodData brokerPod = brokerPods.values().iterator().next(); List<Container> brokerContainers = brokerPod.getSpec().getContainers(); for (Container container : brokerContainers) { InternalMachineConfig brokerMachine = brokerEnvironment.getMachines().get(Names.machineName(brokerPod, container)); if (brokerMachine == null) { throw new InfrastructureException( String.format( "Could not retrieve the specification of the plugin broker container %s", container.getName())); } workspaceEnvironment .getMachines() .put(Names.machineName(workspacePod, container), brokerMachine); } workspaceEnvironment.getConfigMaps().putAll(brokerEnvironment.getConfigMaps()); workspacePod.getSpec().getInitContainers().addAll(brokerPod.getSpec().getContainers()); workspacePod.getSpec().getVolumes().addAll(brokerPod.getSpec().getVolumes()); }
Source:
protected void executeCommand() { DetachStorageDomainVDSCommandParameters detachParams = new DetachStorageDomainVDSCommandParameters(getVds().getStoragePoolId(), getParameters().getStorageDomainId(), Guid.Empty, 0); detachParams.setForce(true); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.DetachStorageDomain, detachParams); if (!returnValue.getSucceeded()) { log.warnFormat("Detaching Storage Domain {0} from it's previous storage pool has failed. " + "The meta data of the Storage Domain might still indicating that it is attached to the previous Storage Pool.", getParameters().getStorageDomainId()); } if (StringUtils.isEmpty(getStorageDomain().getStorage())) { getStorageDomain().setStorage( (String) Backend .getInstance() .runInternalAction( VdcActionType.AddStorageServerConnection, new StorageServerConnectionParametersBase(getStorageDomain().getStorageStaticData() .getConnection(), getVds().getId())).getActionReturnValue()); } addStorageDomainInDb(); updateStorageDomainDynamicFromIrs(); setSucceeded(true); }

Target:
protected void executeCommand() { if (StringUtils.isEmpty(getStorageDomain().getStorage())) { getStorageDomain().setStorage( (String) Backend .getInstance() .runInternalAction( VdcActionType.AddStorageServerConnection, new StorageServerConnectionParametersBase(getStorageDomain().getStorageStaticData() .getConnection(), getVds().getId())).getActionReturnValue()); } addStorageDomainInDb(); updateStorageDomainDynamicFromIrs(); setSucceeded(true); }
Source:
public void testBoletoExpirationDate() throws Throwable{ transaction = transactionFactory.createBoletoTransaction(); transaction.save(); Assert.assertEquals(transaction.getBoletoExpirationDate().toLocalDate(), DateTime.now().plusDays(4).toLocalDate() ); }

Target:
public void testBoletoExpirationDate() throws Throwable{ transaction = transactionFactory.createBoletoTransaction(); transaction.setBoletoExpirationDate(DateTime.now().plusDays(4)); transaction.save(); Assert.assertEquals(transaction.getBoletoExpirationDate().toLocalDate(), DateTime.now().plusDays(4).toLocalDate() ); }
Source:
public void canCreateEmptyRange() { assertThatCode(() -> new ColumnRangeSelection(BYTES_1, BYTES_1)).doesNotThrowAnyException(); }

Target:
public void canCreateEmptyRange() { assertThatThrownBy(() -> new ColumnRangeSelection(BYTES_1, BYTES_1)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("do not form a valid range"); }
Source:
private static void updateTestPointNumbersForAnntations(HashMap<String, Integer> idsToUpdate, JSONArray annotations, JSONObject discrepancies) throws JSONException { for (int j = 0; j < annotations.length(); j++) { JSONObject annotationAsJson = annotations.getJSONObject(j); DispoAnnotationData annotation = DispoUtil.jsonObjToDispoAnnotationData(annotationAsJson); JSONArray idsOfCoveredDiscrepancies = annotation.getIdsOfCoveredDiscrepancies(); int length = idsOfCoveredDiscrepancies.length(); for (int i = 0; i < length; i++) { String coveredId = idsOfCoveredDiscrepancies.getString(i); if (idsToUpdate.containsKey(coveredId)) { String newLocRef = rebuildLocRef(idsOfCoveredDiscrepancies, discrepancies, idsToUpdate); if (!newLocRef.isEmpty()) { annotation.setLocationRefs(newLocRef); } JSONObject updatedAnnotationAsJson = DispoUtil.annotationToJsonObj(annotation); annotations.put(annotation.getIndex(), updatedAnnotationAsJson); break; } } } }

Target:
private static void updateTestPointNumbersForAnntations(HashMap<String, Integer> idsToUpdate, JSONArray annotations, JSONObject discrepancies) throws JSONException { for (int j = 0; j < annotations.length(); j++) { JSONObject annotationAsJson = annotations.getJSONObject(j); DispoAnnotationData annotation = DispoUtil.jsonObjToDispoAnnotationData(annotationAsJson); JSONArray idsOfCoveredDiscrepancies = annotation.getIdsOfCoveredDiscrepancies(); updateIdsCoveredDiscrepancies(idsToUpdate, idsOfCoveredDiscrepancies, annotations, discrepancies, annotation); } }
Source:
public void init(CacheLoaderConfig config, Cache<?, ?> cache, StreamingMarshaller m) throws CacheLoaderException { super.init(config, cache, m); this.dbFactory = newDbFactory(); if (this.dbFactory == null) { throw new CacheLoaderException("Could not load any LevelDB Factories: " + Arrays.toString(DB_FACTORY_CLASS_NAMES)); } String dbFactoryClassName = this.dbFactory.getClass().getName(); if (dbFactoryClassName.equals("org.iq80.leveldb.impl.Iq80DBFactory")) { log.infoUsingJavaDbFactory(dbFactoryClassName); } else { log.infoUsingJNIDbFactory(dbFactoryClassName); } this.config = (LevelDBCacheStoreConfig) config; }

Target:
public void init(CacheLoaderConfig config, Cache<?, ?> cache, StreamingMarshaller m) throws CacheLoaderException { super.init(config, cache, m); this.config = (LevelDBCacheStoreConfig) config; this.dbFactory = newDbFactory(); if (this.dbFactory == null) { throw log.cannotLoadlevelDBFactories(Arrays.toString(DB_FACTORY_CLASS_NAMES)); } String dbFactoryClassName = this.dbFactory.getClass().getName(); if (dbFactoryClassName.equals("org.iq80.leveldb.impl.Iq80DBFactory")) { log.infoUsingJavaDbFactory(dbFactoryClassName); } else { log.infoUsingJNIDbFactory(dbFactoryClassName); } }
Source:
protected boolean canDoAction() { if (getParameters() == null) { return false; } else if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { return false; } return true; }

Target:
protected boolean canDoAction() { return (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())); }
Source:
public boolean filter(Object context, Descriptor descriptor) { LOGGER.log(Level.FINER, "filtering {0}", descriptor.getId()); if (descriptor instanceof OrganizationFolder.DescriptorImpl && (context instanceof View || context instanceof ViewGroup)) { if (ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class).isEmpty()) { return false; } boolean haveOne = false; for (SCMNavigatorDescriptor d: ExtensionList.lookup(SCMNavigatorDescriptor.class)) { if (d instanceof SingleSCMNavigator.DescriptorImpl) { continue; } if (haveOne) { return true; } haveOne = true; } return false; } return true; }

Target:
public boolean filter(Object context, Descriptor descriptor) { LOGGER.log(Level.FINER, "filtering {0}", descriptor.getId()); if (descriptor instanceof OrganizationFolder.DescriptorImpl && (context instanceof View || context instanceof ViewGroup)) { if (ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class).isEmpty()) { return false; } boolean haveOne = false; for (SCMNavigatorDescriptor d: ExtensionList.lookup(SCMNavigatorDescriptor.class)) { if (d instanceof SingleSCMNavigator.DescriptorImpl) { continue; } if (haveOne || d.newInstance((String) null) == null) { return true; } haveOne = true; } return false; } return true; }
Source:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); MageObject sourceObject = source.getSourceObject(game); if (controller == null || sourceObject == null) { return false; } Map<UUID, Cards> cardsToDiscard = new HashMap<>(); for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player == null) { continue; } Cards cards = new CardsImpl(); Target target = new TargetDiscard(0, 3, new FilterCard(), playerId); player.chooseTarget(outcome, target, source, game); cards.addAll(target.getTargets()); cardsToDiscard.put(playerId, cards); } for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player != null) { Cards cardsPlayer = cardsToDiscard.get(playerId); cardsToDiscard.put(playerId, player.discard(cardsPlayer, source, game)); } } for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player == null) { continue; } Cards cardsPlayer = cardsToDiscard.get(playerId); if (cardsPlayer != null) { player.damage(3 - cardsPlayer.size(), source.getId(), game); } } return true; }

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); MageObject sourceObject = source.getSourceObject(game); if (controller == null || sourceObject == null) { return false; } Map<UUID, Cards> cardsToDiscard = new HashMap<>(); for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player == null) { continue; } Cards cards = new CardsImpl(); Target target = new TargetDiscard(0, 3, new FilterCard(), playerId); player.chooseTarget(Outcome.Discard, target, source, game); cards.addAll(target.getTargets()); cardsToDiscard.put(playerId, cards); } for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player != null) { Cards cardsPlayer = cardsToDiscard.get(playerId); cardsToDiscard.put(playerId, player.discard(cardsPlayer, source, game)); } } for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player == null) { continue; } Cards cardsPlayer = cardsToDiscard.get(playerId); if (cardsPlayer != null) { player.damage(3 - cardsPlayer.size(), source.getId(), game); } } return true; }
Source:
public RelBuilder filter(RexNode... predicates) { return filter(ImmutableList.copyOf(predicates), Collections.emptyList()); }

Target:
public RelBuilder filter(RexNode... predicates) { return filter(ImmutableSet.of(), Arrays.asList(predicates)); }
Source:
public void processElement(ProcessContext context) throws IOException { if (context.element() != null) { if (MapType.MAP.equals(properties.mapType.getValue())) { map(context.element(), context); } else { flatMap(context.element(), context); } } interpreter.cleanup(); }

Target:
public void processElement(ProcessContext context) throws IOException { if (context.element() != null) { if (MapType.MAP.equals(properties.mapType.getValue())) { map(context.element(), context); } else { flatMap(context.element(), context); } } }
Source:
public boolean execute(CommandSender sender, String label, String[] args) { if (!testPermission(sender)) return false; if (args.length == 0) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } final String stringTimeout = args[0]; int timeout; try { timeout = Integer.parseInt(stringTimeout); } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "'" + stringTimeout + "' is not a valid number"); return false; } if (timeout <= 0) { sender.sendMessage(ChatColor.RED + "Timeout has to be positive"); return false; } Bukkit.getServer().setIdleTimeout(timeout); Bukkit.broadcastMessage("The idle timeout has been set to '" + timeout + "' minutes."); return true; }

Target:
public boolean execute(CommandSender sender, String label, String[] args) { if (!testPermission(sender)) return false; if (args.length == 0) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } final String stringTimeout = args[0]; int timeout; try { timeout = Integer.parseInt(stringTimeout); } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "'" + stringTimeout + "' is not a valid number"); return false; } if (timeout <= 0) { sender.sendMessage(ChatColor.RED + "The number you have entered (" + timeout + ") is too small, it must be at least 1"); return false; } Bukkit.getServer().setIdleTimeout(timeout); sender.sendMessage("Successfully set the idle timeout to " + timeout + " minutes."); return true; }
Source:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Set<GrantedAuthority> authorities = getAuthorities(username); UserDetails user = this.inMemoryUserDetailsManager.loadUserByUsername(username); return new User(user.getUsername(), user.getPassword(), authorities); }

Target:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Set<GrantedAuthority> authorities = getAuthorities(username); UserDetails user; try { user = this.amBuilder.getDefaultUserDetailsService().loadUserByUsername(username); return new User(user.getUsername(), user.getPassword(), authorities); } catch (Exception e) { e.printStackTrace(); UsernameNotFoundException exception = new UsernameNotFoundException("Authentication failed.", e); LOG.warn("Failed to get user {}.", username, exception); throw exception; } }
Source:
private void doComplete() { if(!isCompleted) { isCompleted = true; responseStatusCallback.responseSendSuccessfully(); ctx.notifyDownstream(RESPONSE_COMPLETE_EVENT); resume(); } }

Target:
private void doComplete() { if(isCompleted.compareAndSet(false, true)) { responseStatusCallback.responseSendSuccessfully(); ctx.notifyDownstream(RESPONSE_COMPLETE_EVENT); resume(); } }
Source:
public void invite(InvitationDto dto, String from) throws MessagingException { User invitingUser = userRepository.findByUsername(from); Challenge challenge = challengeRepository.findOneWithOrganization(dto.getChallengeId()); if (challenge == null) { throw new IllegalArgumentException("invalid challenge"); } Organization organization = challenge.getOrganization(); boolean ok = false; for (OrganizationMember organizationMember : invitingUser.getOrganizations()) { if (organizationMember.isAdmin() && organizationMember.getKey().getOrganization().getId().equals(organization.getId())) { ok = true; break; } } if (!ok) { throw new AccessDeniedException("unauthorized"); } UserShowDto user = userService.findByEmail(dto.getEmail()); if (user == null) { UserCreateDto userCreateDto = new UserCreateDto(); userCreateDto.setEmail(dto.getEmail()); userCreateDto.setNick(new BigInteger(130, random).toString(32)); userCreateDto.setPassword(new BigInteger(130, random).toString(32)); userService.createFromDto(userCreateDto); } if (Arrays.asList(this.environment.getActiveProfiles()).contains("development")) { log.log(Level.ERROR, getUrl(challenge.getId())); } else { Map<String, Object> params = new HashMap<>(); params.put("organization", organization.getName()); params.put("url", getUrl(challenge.getId())); mailService.sendMail("user", dto.getEmail(), "Challenge invitation", "challenge-invite.html", params, Locale.ENGLISH); } }

Target:
public void invite(InvitationDto dto, String from) throws MessagingException { User invitingUser = userRepository.findByUsername(from); Challenge challenge = challengeRepository.findOneWithOrganization(dto.getChallengeId()); if (challenge == null) { throw new IllegalArgumentException("challenge.invalid"); } Organization organization = challenge.getOrganization(); boolean ok = false; for (OrganizationMember organizationMember : invitingUser.getOrganizations()) { if (organizationMember.isAdmin() && organizationMember.getKey().getOrganization().getId().equals(organization.getId())) { ok = true; break; } } if (!ok) { throw new AccessDeniedException("you are not an admin to the parent organization of the challenge"); } UserShowDto user = userService.findByEmail(dto.getEmail()); Map<String, Object> params = new HashMap<>(); if (user == null) { UserCreateDto userCreateDto = new UserCreateDto(); userCreateDto.setEmail(dto.getEmail()); userCreateDto.setNick(new BigInteger(130, random).toString(32)); userCreateDto.setPassword(new BigInteger(130, random).toString(32)); userService.createFromDto(userCreateDto); params.put("username", userCreateDto.getNick()); params.put("password", userCreateDto.getPassword()); } params.put("organization", organization.getName()); params.put("token", getToken(challenge.getId())); mailService.sendMail("user", dto.getEmail(), "Challenge invitation", "challenge-invite.html", params, Locale.ENGLISH); }
Source:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { String reason = null; if (args.length >= 2) { reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); } { if (!TFM_AdminList.isSuperAdmin(sender)) { sender.sendMessage(TFM_Command.MSG_NO_PERMS); } if (!TFM_AdminList.isSuperAdmin(sender_p)) { if (args.length < 1) { sender_p.kickPlayer(ChatColor.RED + "You have been kicked by: " + sender.getName() + "-" + " No reason given"); } } else { sender.sendMessage("You cannot kick admins!"); } if (!TFM_AdminList.isSuperAdmin(sender_p)) { sender_p.kickPlayer(ChatColor.RED + reason + "- " + sender.getName()); TFM_Util.bcastMsg(sender.getName() + "-" + " Kicking" + sender_p.getName() + ChatColor.YELLOW + "- " + reason , ChatColor.RED); } } return true; }

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { String reason = null; if (args.length >= 2) { reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); } if (!TFM_AdminList.isSuperAdmin(sender)) { sender.sendMessage(TFM_Command.MSG_NO_PERMS); } if (!TFM_AdminList.isSuperAdmin(sender_p)) { if (args.length < 1) { sender_p.kickPlayer(ChatColor.RED + "You have been kicked by: " + sender.getName() + "-" + " No reason given"); } } else { sender.sendMessage("You cannot kick admins!"); } if (!TFM_AdminList.isSuperAdmin(sender_p)) { TFM_Util.adminAction("Kicked for ", reason, true); TFM_Util.bcastMsg(sender.getName() + "-" + " Kicking" + sender_p.getName() + ChatColor.YELLOW + "- " + reason , ChatColor.RED); } return true; }
Source:
public Task<Tuple2<Integer, String>> build(final String hash, final InputStream body) throws IOException { if (hash == null) { String content = "Missing hash."; LOG.info(content); return Task.value(new Tuple2<>(HttpServletResponse.SC_BAD_REQUEST, content)); } else { if (_hashManager.contains(hash)) { LOG.info("hash found in cache: " + hash); return Task.value(new Tuple2<>(HttpServletResponse.SC_OK, "")); } else { if (body == null) { String content = "Missing body."; LOG.info(content); return Task.value(new Tuple2<>(HttpServletResponse.SC_BAD_REQUEST, content)); } else if (_dotLocation == null) { String content = "Missing dot."; LOG.info(content); return Task.value(new Tuple2<>(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, content)); } else { final Task<Exec.Result> buildTask = getBuildTask(hash, body); return buildTask.transform("result", result -> { Integer status = null; String content = null; if (result.isFailed()) { status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = result.getError().toString(); } else { switch (result.get().getStatus()) { case 0: _hashManager.add(hash); status = HttpServletResponse.SC_OK; content = ""; break; case 137: status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = "graphviz process was killed because it did not finish within " + _timeoutMs + "ms"; break; default: status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = writeGenericFailureInfo(result.get()); break; } } _inFlightBuildTasks.remove(hash, buildTask); return Success.of(new Tuple2<>(status, content)); }); } } } }

Target:
public Task<GraphvizResponse> build(final String hash, final InputStream body) throws IOException { if (hash == null) { String content = "Missing hash."; LOG.info(content); return Task.value(new GraphvizResponse(HttpServletResponse.SC_BAD_REQUEST, content)); } else { if (_hashManager.contains(hash)) { LOG.info("hash found in cache: " + hash); return Task.value(new GraphvizResponse(HttpServletResponse.SC_OK, "")); } else { if (body == null) { String content = "Missing body."; LOG.info(content); return Task.value(new GraphvizResponse(HttpServletResponse.SC_BAD_REQUEST, content)); } else if (_dotLocation == null) { String content = "Missing dot."; LOG.info(content); return Task.value(new GraphvizResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, content)); } else { final Task<Exec.Result> buildTask = getBuildTask(hash, body); return buildTask.transform("result", result -> { Integer status = null; String content = null; if (result.isFailed()) { status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = result.getError().toString(); } else { switch (result.get().getStatus()) { case 0: _hashManager.add(hash); status = HttpServletResponse.SC_OK; content = ""; break; case 137: status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = "graphviz process was killed because it did not finish within " + _timeoutMs + "ms"; break; default: status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = writeGenericFailureInfo(result.get()); break; } } _inFlightBuildTasks.remove(hash, buildTask); return Success.of(new GraphvizResponse(status, content)); }); } } } }
Source:
protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command) throws InterpretationException { ArrayList<Item> items = getMatchingItems(language, labelFragments, command.getClass()); if (items.size() < 1) { if ((command != null) && (getMatchingItems(language, labelFragments, null).size() >= 1)) { throw new InterpretationException( language.getString(COMMAND_NOT_ACCEPTED).replace("<cmd>", command.toString())); } else { throw new InterpretationException(language.getString(NO_OBJECTS)); } } else if (items.size() > 1) { throw new InterpretationException(language.getString(MULTIPLE_OBJECTS)); } else { Item item = items.get(0); if (command instanceof State) { try { State newState = (State) command; State oldState = item.getStateAs(newState.getClass()); if (oldState.equals(newState)) { String template = language.getString(STATE_ALREADY_SINGULAR); String cmdName = "state_" + command.toString().toLowerCase(); String stateText = null; try { stateText = language.getString(cmdName); } catch (Exception e) { stateText = language.getString(STATE_CURRENT); } return template.replace("<state>", stateText); } } catch (Exception ex) { logger.debug("Failed constructing response: {}", ex.getMessage()); return language.getString(ERROR); } } eventPublisher.post(ItemEventFactory.createCommandEvent(item.getName(), command)); return language.getString(OK); } }

Target:
protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command) throws InterpretationException { ArrayList<Item> items = getMatchingItems(language, labelFragments, command.getClass()); if (items.size() < 1) { if (getMatchingItems(language, labelFragments, null).size() >= 1) { throw new InterpretationException( language.getString(COMMAND_NOT_ACCEPTED).replace("<cmd>", command.toString())); } else { throw new InterpretationException(language.getString(NO_OBJECTS)); } } else if (items.size() > 1) { throw new InterpretationException(language.getString(MULTIPLE_OBJECTS)); } else { Item item = items.get(0); if (command instanceof State) { try { State newState = (State) command; State oldState = item.getStateAs(newState.getClass()); if (oldState.equals(newState)) { String template = language.getString(STATE_ALREADY_SINGULAR); String cmdName = "state_" + command.toString().toLowerCase(); String stateText = null; try { stateText = language.getString(cmdName); } catch (Exception e) { stateText = language.getString(STATE_CURRENT); } return template.replace("<state>", stateText); } } catch (Exception ex) { logger.debug("Failed constructing response: {}", ex.getMessage()); return language.getString(ERROR); } } eventPublisher.post(ItemEventFactory.createCommandEvent(item.getName(), command)); return language.getString(OK); } }
Source:
protected void endStepJobCommitted() { endStepJob(JobExecutionStatus.FINISHED, getStepMessageMap(JobExecutionStatus.FINISHED, " "), true); }

Target:
protected void endStepJobCommitted() { endStepJob(JobExecutionStatus.FINISHED, getStepMessageMap(JobExecutionStatus.FINISHED, null), true); }
Source:
private boolean validateResource(IResource resource) { boolean isValid = false; if (resource instanceof IContainer) { try { final IResource[] members = ((IContainer) resource).members(); for (IResource member : members) { isValid = validateResource(member); if (isValid) { break; } } } catch (final CoreException e) { } } else if (resource.getType() == IResource.FILE) { for (int i = 0; i < extensions.size(); i++) { if (extensions.get(i).equalsIgnoreCase(resource.getFileExtension())) { isValid = true; break; } } } return isValid; }

Target:
private boolean validateResource(IResource resource) { boolean isValid = false; if (resource instanceof IContainer) { try { final IResource[] members = ((IContainer) resource).members(); for (IResource member : members) { isValid = validateResource(member); if (isValid) { break; } } } catch (final CoreException e) { } } else if (resource.getType() == IResource.FILE) { for (String ext : extensions) { if (ext.equalsIgnoreCase(resource.getFileExtension())) { isValid = true; break; } } } return isValid; }
Source:
public OseePreparedStatement getBatchStatement(JdbcConnection connection, String query, int batchIncrementSize) throws SQLException { PreparedStatement preparedStatement = ((JdbcConnectionImpl) connection).prepareStatement(query); return new OseePreparedStatement(preparedStatement, batchIncrementSize); }

Target:
public OseePreparedStatement getBatchStatement(JdbcConnection connection, String query, int batchIncrementSize) { try { PreparedStatement preparedStatement = ((JdbcConnectionImpl) connection).prepareStatement(query); return new OseePreparedStatement(preparedStatement, batchIncrementSize); } catch (SQLException ex) { throw newJdbcException(ex); } }
Source:
public static Tuple<DocumentField, DocumentField> randomDocumentField(XContentType xContentType, boolean isMetafield, Predicate<String> excludeMetaFieldFilter) { if (isMetafield) { String metaField = randomValueOtherThanMany(excludeMetaFieldFilter, () -> randomFrom(MapperService.META_FIELDS_BEFORE_7DOT8)); DocumentField documentField; if (metaField.equals(IgnoredFieldMapper.NAME)) { int numValues = randomIntBetween(1, 3); List<Object> ignoredFields = new ArrayList<>(numValues); for (int i = 0; i < numValues; i++) { ignoredFields.add(randomAlphaOfLengthBetween(3, 10)); } documentField = new DocumentField(metaField, ignoredFields); } else { documentField = new DocumentField(metaField, Collections.singletonList(randomAlphaOfLengthBetween(3, 10))); } return Tuple.tuple(documentField, documentField); } else { String fieldName = randomAlphaOfLengthBetween(3, 10); Tuple<List<Object>, List<Object>> tuple = RandomObjects.randomStoredFieldValues(random(), xContentType); DocumentField input = new DocumentField(fieldName, tuple.v1()); DocumentField expected = new DocumentField(fieldName, tuple.v2()); return Tuple.tuple(input, expected); } }

Target:
public static Tuple<DocumentField, DocumentField> randomDocumentField(XContentType xContentType, boolean isMetafield, Predicate<String> excludeMetaFieldFilter) { if (isMetafield) { String metaField = randomValueOtherThanMany(excludeMetaFieldFilter, () -> randomFrom(IndicesModule.getBuiltInMetadataFields())); DocumentField documentField; if (metaField.equals(IgnoredFieldMapper.NAME)) { int numValues = randomIntBetween(1, 3); List<Object> ignoredFields = new ArrayList<>(numValues); for (int i = 0; i < numValues; i++) { ignoredFields.add(randomAlphaOfLengthBetween(3, 10)); } documentField = new DocumentField(metaField, ignoredFields); } else { documentField = new DocumentField(metaField, Collections.singletonList(randomAlphaOfLengthBetween(3, 10))); } return Tuple.tuple(documentField, documentField); } else { String fieldName = randomAlphaOfLengthBetween(3, 10); Tuple<List<Object>, List<Object>> tuple = RandomObjects.randomStoredFieldValues(random(), xContentType); DocumentField input = new DocumentField(fieldName, tuple.v1()); DocumentField expected = new DocumentField(fieldName, tuple.v2()); return Tuple.tuple(input, expected); } }
Source:
protected ContextBuilder builder(Properties overrides) { overrides.setProperty(Constants.PROPERTY_MAX_RETRIES, "1"); MockWebServer defaultServer = regionToServers.get(DEFAULT_REGION); return ContextBuilder.newBuilder(new EC2ApiMetadata()) .credentials(ACCESS_KEY, SECRET_KEY) .endpoint("http://" + defaultServer.getHostName() + ":" + defaultServer.getPort()) .overrides(overrides) .modules(modules); }

Target:
protected ContextBuilder builder(Properties overrides) { overrides.setProperty(Constants.PROPERTY_MAX_RETRIES, "1"); MockWebServer defaultServer = regionToServers.get(DEFAULT_REGION); return ContextBuilder.newBuilder(new EC2ApiMetadata()) .credentials(ACCESS_KEY, SECRET_KEY) .endpoint(defaultServer.getUrl("").toString()) .overrides(overrides) .modules(modules); }
Source:
public void close() throws IOException { try { super.close(); } finally { Log.d(K9MailLib.LOG_TAG, "deleting temp file"); boolean fileDeleteResult = mFile.delete(); if (!fileDeleteResult) Log.i(K9MailLib.LOG_TAG, "fail to delete temp file"); } }

Target:
public void close() throws IOException { try { super.close(); } finally { Log.d(K9MailLib.LOG_TAG, "deleting " + mFile.getName() + " file"); boolean fileSuccessfullyDeleted = mFile.delete(); if (!fileSuccessfullyDeleted){ Log.i(K9MailLib.LOG_TAG, "fail to delete " + mFile.getName() + " file"); } } }
Source:
public boolean fileRowCountMatchesHeaderRowCount(ConcurRequestExtractFile requestExtractFile) { int countEntryDetailLines = 0; List<ConcurRequestExtractRequestDetailFileLine> requestDetailLines = requestExtractFile.getRequestDetails(); for (ConcurRequestExtractRequestDetailFileLine detailLine : requestDetailLines) { countEntryDetailLines = countEntryDetailLines + detailLine.getRequestEntryDetails().size(); } if ((requestDetailLines.size() + countEntryDetailLines) == requestExtractFile.getRecordCount()) { return true; } else { LOG.error("Header row count validation failed. Header record count was =" +requestExtractFile.getRecordCount()+"= while file line count was =" +(requestDetailLines.size() + countEntryDetailLines)+ "="); return false; } }

Target:
private boolean fileRowCountMatchesHeaderRowCount(ConcurRequestExtractFile requestExtractFile) { int fileLineCount = getTotalRequestFileRowCount(requestExtractFile); if (fileLineCount == requestExtractFile.getRecordCount()) { return true; } else { LOG.error("Header row count validation failed. Header record count was =" + requestExtractFile.getRecordCount() + "= while file line count was =" + fileLineCount + "="); return false; } }
Source:
public void testErrorPrecedenceWithSpecialCase() throws Exception { doPut(); Map<ServerErrorCode, RouterErrorCode> serverErrorToRouterError = new HashMap<>(); serverErrorToRouterError.put(ServerErrorCode.Blob_Deleted, RouterErrorCode.BlobDeleted); serverErrorToRouterError.put(ServerErrorCode.Blob_Expired, RouterErrorCode.BlobExpired); serverErrorToRouterError.put(ServerErrorCode.Blob_Authorization_Failure, RouterErrorCode.BlobAuthorizationFailure); for (Map.Entry<ServerErrorCode, RouterErrorCode> entry : serverErrorToRouterError.entrySet()) { Map<ServerErrorCode, Integer> errorCounts = new HashMap<>(); errorCounts.put(ServerErrorCode.Blob_Not_Found, replicasCount - 1); errorCounts.put(entry.getKey(), 1); System.out.println(errorCounts); testWithErrorCodes(errorCounts, mockServerLayout, entry.getValue(), getErrorCodeChecker); } }

Target:
public void testErrorPrecedenceWithSpecialCase() throws Exception { doPut(); Map<ServerErrorCode, RouterErrorCode> serverErrorToRouterError = new HashMap<>(); serverErrorToRouterError.put(ServerErrorCode.Blob_Deleted, RouterErrorCode.BlobDeleted); serverErrorToRouterError.put(ServerErrorCode.Blob_Expired, RouterErrorCode.BlobExpired); serverErrorToRouterError.put(ServerErrorCode.Blob_Authorization_Failure, RouterErrorCode.BlobAuthorizationFailure); for (Map.Entry<ServerErrorCode, RouterErrorCode> entry : serverErrorToRouterError.entrySet()) { Map<ServerErrorCode, Integer> errorCounts = new HashMap<>(); errorCounts.put(ServerErrorCode.Blob_Not_Found, replicasCount - 1); errorCounts.put(entry.getKey(), 1); testWithErrorCodes(errorCounts, mockServerLayout, entry.getValue(), getErrorCodeChecker); } }
Source:
static void install(OperationContext context, List<String> exposedSubsystems) { ImmutableManagementResourceRegistration rootResourceRegistration = context.getRootResourceRegistration(); Resource rootResource = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(MicroProfileMetricsSubsystemDefinition.WILDFLY_REGISTRATION_SERVICE); final ServiceName modelControllerName = Services.JBOSS_SERVER_CONTROLLER; Supplier<ModelController> modelController = serviceBuilder.requires(modelControllerName); serviceBuilder.requires(CONFIG_PROVIDER); MetricsRegistrationService service = new MetricsRegistrationService(rootResourceRegistration, rootResource, modelController, exposedSubsystems); serviceBuilder.setInstance(service) .install(); }

Target:
static void install(OperationContext context, List<String> exposedSubsystems) { ImmutableManagementResourceRegistration rootResourceRegistration = context.getRootResourceRegistration(); Resource rootResource = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(WILDFLY_REGISTRATION_SERVICE); Supplier<ModelControllerClientFactory> modelControllerClientFactory = serviceBuilder.requires(context.getCapabilityServiceName(CLIENT_FACTORY_CAPABILITY, ModelControllerClientFactory.class)); Supplier<Executor> managementExecutor = serviceBuilder.requires(context.getCapabilityServiceName(MANAGEMENT_EXECUTOR, Executor.class)); serviceBuilder.requires(CONFIG_PROVIDER); MetricsRegistrationService service = new MetricsRegistrationService(rootResourceRegistration, rootResource, modelControllerClientFactory, managementExecutor, exposedSubsystems); serviceBuilder.setInstance(service) .install(); }
Source:
public JobOrder instantiateForInsert() { JobOrder entity = new JobOrder(); entity.setEmploymentType("W2"); entity.setStartDate(new DateTime()); return entity; }

Target:
public JobOrder instantiateForInsert() { JobOrder entity = new JobOrder(); entity.setEmploymentType("Contract"); entity.setStartDate(new DateTime()); entity.setClientCorporation(new ClientCorporation(1)); entity.setClientContact(new ClientContact(1)); entity.setOwner(new CorporateUser(1)); return entity; }
Source:
public int read(byte[] b, int off, int len) throws IOException { Memory readBuffer = new Memory(len); WinBase.OVERLAPPED olap = new WinBase.OVERLAPPED(); olap.hEvent = readerWaitable; olap.write(); boolean immediate = API.ReadFile(handle, readBuffer, len, null, olap.getPointer()); if (!immediate) { int lastError = API.GetLastError(); if (lastError != WinError.ERROR_IO_PENDING) { throw new IOException("ReadFile() failed: " + lastError); } } IntByReference r = new IntByReference(); if (!API.GetOverlappedResult(handle, olap.getPointer(), r, true)) { int lastError = API.GetLastError(); throw new IOException("GetOverlappedResult() failed for read operation: " + lastError); } int actualLen = r.getValue(); byte[] byteArray = readBuffer.getByteArray(0, actualLen); System.arraycopy(byteArray, 0, b, off, actualLen); return actualLen; }

Target:
public int read(byte[] b, int off, int len) throws IOException { Memory readBuffer = new Memory(len); WinBase.OVERLAPPED olap = new WinBase.OVERLAPPED(); olap.hEvent = readerWaitable; olap.write(); boolean immediate = API.ReadFile(handle, readBuffer, len, null, olap.getPointer()); if (!immediate) { int lastError = API.GetLastError(); if (lastError != WinError.ERROR_IO_PENDING) { throw new IOException("ReadFile() failed: " + lastError); } } IntByReference r = new IntByReference(); if (!API.GetOverlappedResult(handle, olap.getPointer(), r, true)) { int lastError = API.GetLastError(); throw new IOException("GetOverlappedResult() failed for read operation: " + lastError); } int actualLen = r.getValue(); if (requireStrictLength && (actualLen != len)) { throw new IOException("ReadFile() read less bytes than requested: expected " + len + " bytes, but read " + actualLen + " bytes"); } byte[] byteArray = readBuffer.getByteArray(0, actualLen); System.arraycopy(byteArray, 0, b, off, actualLen); return actualLen; }