auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void initializeRequestLogger() { if (requestLogger == null) { try { final String loggingType = props.getProperty("druid.request.logging.type"); if(loggingType != null && loggingType.equals("emitter")) { setRequestLogger(Initialization.makeEmittingRequestLogger( getProps(), getEmitter() )); } else { setRequestLogger(Initialization.makeFileRequestLogger( getJsonMapper(), getScheduledExecutorFactory(), getProps() )); } } catch (IOException e) { throw Throwables.propagate(e); } lifecycle.addManagedInstance(requestLogger); } }

Target:
private void initializeRequestLogger() { if (requestLogger == null) { try { final String loggingType = props.getProperty("druid.request.logging.type"); if("emitter".equals(loggingType)) { setRequestLogger(Initialization.makeEmittingRequestLogger( getProps(), getEmitter() )); } else { setRequestLogger(Initialization.makeFileRequestLogger( getJsonMapper(), getScheduledExecutorFactory(), getProps() )); } } catch (IOException e) { throw Throwables.propagate(e); } lifecycle.addManagedInstance(requestLogger); } }
Source:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The CountryNameUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; return PrimitiveObjectInspectorFactory.writableStringObjectInspector; }

Target:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { GenericUDFHelper argsHelper = new GenericUDFHelper(); argsHelper.checkArgsSize(arguments, 1, 1); argsHelper.checkArgPrimitive(arguments, 0); argsHelper.checkArgType(arguments, 0, PrimitiveCategory.STRING); argumentOI = (StringObjectInspector) arguments[0]; return PrimitiveObjectInspectorFactory.writableStringObjectInspector; }
Source:
public Object getObjectForTextSelection(TextSelection selection, IEditorPart editor) { if (editor instanceof CEditor) { TextSelection textSelection = selection; try { if (selection != null) { return SelectionConverter.getElementAtOffset(getInputCElement((CEditor) editor), textSelection); } else { ICElement element = getInputCElement((CEditor) editor); return element; } } catch (CModelException e) { } } return null; }

Target:
public Object getObjectForTextSelection(TextSelection selection, IEditorPart editor) { if (editor instanceof CEditor) { TextSelection textSelection = selection; try { ICElement element = getInputCElement((CEditor) editor); if (element != null) { if (selection != null) { return SelectionConverter.getElementAtOffset(element, textSelection); } else { return element; } } } catch (CModelException e) { } } return null; }
Source:
private Object[] createFileListInput() { try { IPackageFragment fPkgFragment= fResourceBundlePackage.getSelected(); if (fPkgFragment == null) return new Object[0]; List<Object> result= new ArrayList<>(1); for (Object n : fPkgFragment.getNonJavaResources()) { if (isPropertyFile(n)) { result.add(n); } } return result.toArray(); } catch (JavaModelException e) { ExceptionHandler.handle(e, NLSUIMessages.NLSAccessorConfigurationDialog_externalizing, NLSUIMessages .NLSAccessorConfigurationDialog_exception); return new Object[0]; } }

Target:
private Object[] createFileListInput() { try { IPackageFragment fPkgFragment= fResourceBundlePackage.getSelected(); if (fPkgFragment == null) return new Object[0]; List<Object> result= new ArrayList<>(1); for (Object nonJava : fPkgFragment.getNonJavaResources()) { if (isPropertyFile(nonJava)) { result.add(nonJava); } } return result.toArray(); } catch (JavaModelException e) { ExceptionHandler.handle(e, NLSUIMessages.NLSAccessorConfigurationDialog_externalizing, NLSUIMessages .NLSAccessorConfigurationDialog_exception); return new Object[0]; } }
Source:
public void run() { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(mContext); DataOutputStream dos = null; int ret = 1; String command = mContext.getApplicationInfo().dataDir + "/" + SyncthingService.BINARY_NAME; Process process = null; try { do { process = Runtime.getRuntime().exec("sh"); dos = new DataOutputStream(process.getOutputStream()); dos.writeBytes("HOME=" + Environment.getExternalStorageDirectory() + " "); dos.writeBytes("STTRACE=" + pm.getString("sttrace", "") + " "); dos.writeBytes("STNORESTART=1 "); dos.writeBytes("STNOUPGRADE=1 "); switch (mCommand) { case generate: dos.writeBytes(command + " -generate='" + mContext.getFilesDir() + "' -no-browser"); break; case main: dos.writeBytes(command + " -home='" + mContext.getFilesDir() + "' -no-browser"); break; case reset: dos.writeBytes(command + " -home='" + mContext.getFilesDir() + "' -reset"); break; case manual: dos.writeBytes(mManualCommand); break; default: Log.w(TAG, "Unknown command option"); } dos.writeBytes("\nexit\n"); dos.flush(); log(process.getInputStream(), Log.INFO); log(process.getErrorStream(), Log.WARN); ret = process.waitFor(); if (ret == 3) { Log.i(TAG, "Restarting syncthing"); mContext.startService(new Intent(mContext, SyncthingService.class) .setAction(SyncthingService.ACTION_RESTART)); } } while (ret == 3); } catch (IOException | InterruptedException e) { Log.e(TAG, "Failed to execute syncthing binary or read output", e); } finally { try { dos.close(); } catch (IOException e) { Log.w(TAG, "Failed to close shell stream", e); } process.destroy(); if (ret != 0) { Log.e(TAG_NATIVE, "Syncthing binary crashed with error code " + Integer.toString(ret)); } } }

Target:
public void run() { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(mContext); DataOutputStream dos = null; int ret = 1; Process process = null; try { do { process = Runtime.getRuntime().exec("sh"); dos = new DataOutputStream(process.getOutputStream()); dos.writeBytes("HOME=" + Environment.getExternalStorageDirectory() + " "); dos.writeBytes("STTRACE=" + pm.getString("sttrace", "") + " "); dos.writeBytes("STNORESTART=1 "); dos.writeBytes("STNOUPGRADE=1 "); dos.writeBytes(mCommand); dos.writeBytes("\nexit\n"); dos.flush(); log(process.getInputStream(), Log.INFO); log(process.getErrorStream(), Log.WARN); niceSyncthing(); ret = process.waitFor(); if (ret == 3) { Log.i(TAG, "Restarting syncthing"); mContext.startService(new Intent(mContext, SyncthingService.class) .setAction(SyncthingService.ACTION_RESTART)); } } while (ret == 3); } catch (IOException | InterruptedException e) { Log.e(TAG, "Failed to execute syncthing binary or read output", e); } finally { try { dos.close(); } catch (IOException e) { Log.w(TAG, "Failed to close shell stream", e); } process.destroy(); if (ret != 0) { Log.e(TAG_NATIVE, "Syncthing binary crashed with error code " + Integer.toString(ret)); } } }
Source:
public boolean applyEffectBlock(ItemStack stack, World world, BlockPos pos, EnumFacing facing, double impactX, double impactY, double impactZ, EntityLivingBase caster) { Block block = world.getBlockState(pos).getBlock(); if (block instanceof BlockFlower || block instanceof BlockTallGrass){ world.setBlockState(pos, Blocks.tallgrass.getDefaultState()); return true; }else if (block == Blocks.grass || block == Blocks.mycelium || block == Blocks.sandstone || block == Blocks.dirt){ world.setBlockState(pos, Blocks.sand.getDefaultState()); return true; }else if (block == Blocks.stone){ world.setBlockState(pos, Blocks.cobblestone.getDefaultState()); return true; }else if (block == Blocks.stonebrick && world.getBlockState(pos).getBlock().getMetaFromState(world.getBlockState(pos)) != 2){ world.setBlockMetadataWithNotify(blockx, blocky, blockz, 2, 2); return true; } if (block == Blocks.water || block == Blocks.flowing_water){ world.setBlockState(pos, Blocks.air.getDefaultState()); return true; }else{ switch (facing){ case EAST: pos = pos.east(); break; case NORTH: pos = pos.north(); break; case SOUTH: pos = pos.south(); break; case WEST: pos = pos.west(); break; case DOWN: pos = pos.down(); break; case UP: pos = pos.up(); break; } block = world.getBlockState(pos).getBlock(); if (block == Blocks.water || block == Blocks.flowing_water){ world.setBlockState(pos, Blocks.air.getDefaultState()); return true; } } return false; }

Target:
public boolean applyEffectBlock(ItemStack stack, World world, BlockPos pos, EnumFacing facing, double impactX, double impactY, double impactZ, EntityLivingBase caster) { Block block = world.getBlockState(pos).getBlock(); if (block instanceof BlockFlower || block instanceof BlockTallGrass){ world.setBlockState(pos, Blocks.tallgrass.getDefaultState()); return true; }else if (block == Blocks.grass || block == Blocks.mycelium || block == Blocks.sandstone || block == Blocks.dirt){ world.setBlockState(pos, Blocks.sand.getDefaultState()); return true; }else if (block == Blocks.stone){ world.setBlockState(pos, Blocks.cobblestone.getDefaultState()); return true; }else if (block == Blocks.stonebrick && world.getBlockState(pos).getBlock().getMetaFromState(world.getBlockState(pos)) != 2){ world.setBlockMetadataWithNotify(blockx, blocky, blockz, 2, 2); return true; } if (block == Blocks.water || block == Blocks.flowing_water){ world.setBlockState(pos, Blocks.air.getDefaultState()); return true; }else{ pos = pos.offset(facing); block = world.getBlockState(pos).getBlock(); if (block == Blocks.water || block == Blocks.flowing_water){ world.setBlockState(pos, Blocks.air.getDefaultState()); return true; } } return false; }
Source:
private void captureScreenshot(ITestResult result) { Set<SeleniumWebDriver> webDrivers = new HashSet<>(); Object testInstance = result.getInstance(); collectInjectedWebDrivers(testInstance, webDrivers); webDrivers.forEach(webDriver -> captureScreenshot(result, webDriver)); webDrivers.forEach(webDriver -> dumpHtmlCodeFromTheCurrentPage(result, webDriver)); }

Target:
private void captureScreenshot(ITestResult result) { Set<SeleniumWebDriver> webDrivers = new HashSet<>(); Object testInstance = result.getInstance(); collectInjectedWebDrivers(testInstance, webDrivers); webDrivers.forEach(webDriver -> captureScreenshot(result, webDriver)); }
Source:
public void testDetectedPingedDownNodeCallingInfrastructureManagerInternalRemoveNodeTrueFlag() throws RMException, ClassNotFoundException { Node node = createNode(PROACTIVE_PROGRAMMING_NODE_URL); nodeSource.internalAddNode(node); nodeSource.detectedPingedDownNode(node.getNodeInformation().getURL()); verify(infrastructureManager).internalRemoveNode(any(Node.class), eq(true)); }

Target:
public void testDetectedPingedDownNodeCallingInfrastructureManagerInternalRemoveNodeTrueFlag() throws RMException, ClassNotFoundException { Node node = createNode(PROACTIVE_PROGRAMMING_NODE_URL); nodeSource.internalAddNode(node); nodeSource.detectedPingedDownNode(node.getNodeInformation().getURL()); verify(infrastructureManager).internalNotifyDownNode(any(Node.class)); }
Source:
public void bundleFinished(final BundleProcessor context, final Bundle bundle) { vetoes.remove(bundle.getBundleId(), context); if (vetoes.get(bundle.getBundleId()).isEmpty()) { logger.debug("Finished loading meta-data of bundle '{}'.", bundle.getSymbolicName()); synchronized (queue) { for (T object : queue.removeAll(bundle.getBundleId())) { action.apply(object); } } } else { logger.debug("'{}' still vetoed by '{}', queueing '{}'", bundle.getSymbolicName(), vetoes.get(bundle.getBundleId()), queue.get(bundle.getBundleId())); } }

Target:
public void bundleFinished(final BundleProcessor context, final Bundle bundle) { vetoes.remove(bundle.getBundleId(), context); if (vetoes.get(bundle.getBundleId()).isEmpty()) { logger.debug("Finished loading meta-data of bundle '{}'.", bundle.getSymbolicName()); for (T object : queue.removeAll(bundle.getBundleId())) { action.apply(object); } } else { logger.debug("'{}' still vetoed by '{}', queueing '{}'", bundle.getSymbolicName(), vetoes.get(bundle.getBundleId()), queue.get(bundle.getBundleId())); } }
Source:
public void testTechnicalitiesCase001(Comparison comparison) throws IOException { EList<Conflict> conflicts = comparison.getConflicts(); assertEquals(1, conflicts.size()); Conflict conflict = conflicts.get(0); assertEquals(PSEUDO, conflict.getKind()); EList<Diff> differences = conflict.getDifferences(); assertEquals(2, differences.size()); TechnicalitiesFilter technicalitiesFilter = new TechnicalitiesFilter(); Predicate<? super EObject> predicate = technicalitiesFilter.getPredicateWhenSelected(); assertFalse(predicate.apply(differences.get(0))); assertFalse(predicate.apply(differences.get(1))); }

Target:
public void testTechnicalitiesCase001(Comparison comparison) throws IOException { ConflictsGroupImpl group = new ThreeWayComparisonGroupProvider.ConflictsGroupImpl(comparison, "Conflict", new TestECrossReferenceAdapter()); group.buildSubTree(); assertEquals(1, group.getChildren().size()); TreeNode conflictNode = group.getChildren().get(0); assertEquals(1, conflictNode.getChildren().size()); TreeNode matchNode = conflictNode.getChildren().get(0); assertEquals(2, matchNode.getChildren().size()); TechnicalitiesFilter filter = new TechnicalitiesFilter(); Predicate<? super EObject> selected = filter.getPredicateWhenSelected(); Predicate<? super EObject> unselected = filter.getPredicateWhenUnselected(); TreeNode diffNode1 = matchNode.getChildren().get(0); assertTrue(selected.apply(diffNode1)); assertFalse(unselected.apply(diffNode1)); TreeNode diffNode2 = matchNode.getChildren().get(1); assertTrue(selected.apply(diffNode2)); assertFalse(unselected.apply(diffNode2)); }
Source:
protected LicenseInfoParsingResult filterLicenses(LicenseInfoParsingResult result, Set<LicenseNameWithText> licencesToExclude) { Set<LicenseNameWithText> filteredLicenses = result.getLicenseInfo().getLicenseNamesWithTexts().stream().filter(license -> { for (LicenseNameWithText excludeLicense : licencesToExclude) { if (Strings.nullToEmpty(license.getLicenseName()).equals(Strings.nullToEmpty(excludeLicense.getLicenseName())) && Strings.nullToEmpty(license.getLicenseText()).equals(Strings.nullToEmpty(excludeLicense.getLicenseText())) && Strings.nullToEmpty(license.getAcknowledgements()) .equals(Strings.nullToEmpty(excludeLicense.getAcknowledgements()))) { return false; } } return true; }).collect(Collectors.toSet()); LicenseInfoParsingResult newResult = result.deepCopy(); newResult.getLicenseInfo().setLicenseNamesWithTexts(filteredLicenses); return newResult; }

Target:
protected LicenseInfoParsingResult filterLicenses(LicenseInfoParsingResult result, Set<LicenseNameWithText> licencesToExclude) { Set<LicenseNameWithText> filteredLicenses = result.getLicenseInfo().getLicenseNamesWithTexts().stream().filter(license -> { for (LicenseNameWithText excludeLicense : licencesToExclude) { if (LicenseNameWithTextUtils.licenseNameWithTextEquals(license, excludeLicense)) { return false; } } return true; }).collect(Collectors.toSet()); LicenseInfoParsingResult newResult = result.deepCopy(); newResult.getLicenseInfo().setLicenseNamesWithTexts(filteredLicenses); return newResult; }
Source:
public CalciteStatement createStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { try { return super.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } catch (SQLException e) { if (e.getCause().getCause() instanceof SQLException) { throw (SQLException) e.getCause().getCause(); } throw e; } }

Target:
public CalciteStatement createStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { try { return super.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } catch (SQLException e) { throw CalciteUtils.unwrapSqlException(e); } }
Source:
private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException { KeyPair keyPair = parent.getPrivateKey().find(ec2); if (keyPair == null) { LOGGER.log(Level.WARNING, "No matching keypair found on EC2. Is the EC2 private key a valid one?"); } return keyPair; }

Target:
private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException { KeyPair keyPair = parent.getPrivateKey().find(ec2); if (keyPair == null) { LOGGER.log(Level.INFO, "No matching keypair found on EC2. Is public key acquired via some other means?"); } return keyPair; }
Source:
public CacheSet<K> keySet() { CacheStream<K> stream = getDelegate().keySet().stream().map( new ValueToTypedValueFunction<>(dataTypedCacheManager.dataType, dataTypedCacheManager.marshaller)); return new SetAsCacheSet<>(stream.collect( CacheCollectors.serializableCollector(Collectors::toSet))); }

Target:
public CacheSet<K> keySet() { return new CacheSetMapper<>(getDelegate().keySet(), new ValueToTypedValueFunction<>( dataTypedCacheManager.dataType, dataTypedCacheManager.marshaller)); }
Source:
protected long[] sequentialTimestamps(int count, long firstValue) { assert count > 0; long[] timestamps = new long[count]; timestamps[0] = firstValue; for (int i = 1; i < timestamps.length; ++i) { timestamps[i] = timestamps[0] + i; } return timestamps; }

Target:
public long[] sequentialTimestamps(int count, long firstValue) { assert count > 0; long[] timestamps = new long[count]; timestamps[0] = firstValue; for (int i = 1; i < timestamps.length; ++i) { timestamps[i] = timestamps[0] + i; } return timestamps; }
Source:
public void test() { JavaCheckVerifier.verify("src/test/files/checks/security/LDAPDeserializationCheck.java", new LDAPDeserializationCheck()); JavaCheckVerifier.verifyNoIssueWithoutSemantic("src/test/files/checks/security/LDAPDeserializationCheck.java", new LDAPDeserializationCheck()); }

Target:
public void test() { JavaCheckVerifier.verify("src/test/files/checks/security/LDAPDeserializationCheck.java", new LDAPDeserializationCheck()); }
Source:
public static DataType projectRow(DataType dataType, int[][] indexPaths) { final List<RowField> updatedFields = new ArrayList<>(); final List<DataType> updatedChildren = new ArrayList<>(); Set<String> nameDomain = new HashSet<>(); int duplicateCount = 0; for (int[] indexPath : indexPaths) { DataType fieldType = dataType.getChildren().get(indexPath[0]); LogicalType fieldLogicalType = fieldType.getLogicalType(); StringBuilder builder = new StringBuilder(((RowType) dataType.getLogicalType()).getFieldNames().get(indexPath[0])); for (int index = 1; index < indexPath.length; index++) { Preconditions.checkArgument( hasRoot(fieldLogicalType, LogicalTypeRoot.ROW), "Row data type expected."); RowType rowtype = ((RowType) fieldLogicalType); builder.append("_").append(rowtype.getFieldNames().get(indexPath[index])); fieldLogicalType = rowtype.getFields().get(indexPath[index]).getType(); fieldType = fieldType.getChildren().get(indexPath[index]); } String path = builder.toString(); while (nameDomain.contains(path)) { path = builder.append("$").append(duplicateCount++).toString(); } updatedFields.add(new RowField(path, fieldLogicalType)); updatedChildren.add(fieldType); nameDomain.add(path); } return new FieldsDataType( new RowType(dataType.getLogicalType().isNullable(), updatedFields), dataType.getConversionClass(), updatedChildren); }

Target:
public static DataType projectRow(DataType dataType, int[][] indexPaths) { final List<RowField> updatedFields = new ArrayList<>(); final List<DataType> updatedChildren = new ArrayList<>(); Set<String> nameDomain = new HashSet<>(); int duplicateCount = 0; for (int[] indexPath : indexPaths) { DataType fieldType = dataType.getChildren().get(indexPath[0]); LogicalType fieldLogicalType = fieldType.getLogicalType(); StringBuilder builder = new StringBuilder(((RowType) dataType.getLogicalType()).getFieldNames().get(indexPath[0])); for (int index = 1; index < indexPath.length; index++) { Preconditions.checkArgument( hasRoot(fieldLogicalType, LogicalTypeRoot.ROW), "Row data type expected."); RowType rowtype = ((RowType) fieldLogicalType); builder.append("_").append(rowtype.getFieldNames().get(indexPath[index])); fieldLogicalType = rowtype.getFields().get(indexPath[index]).getType(); fieldType = fieldType.getChildren().get(indexPath[index]); } String path = builder.toString(); while (nameDomain.contains(path)) { path = builder.append("_$").append(duplicateCount++).toString(); } updatedFields.add(new RowField(path, fieldLogicalType)); updatedChildren.add(fieldType); nameDomain.add(path); } return new FieldsDataType( new RowType(dataType.getLogicalType().isNullable(), updatedFields), dataType.getConversionClass(), updatedChildren); }
Source:
public final static String generateHash(String data) throws Exception { String hashedData = data; try { byte[] bytes = data.getBytes(StandardCharsets.US_ASCII); MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(bytes, 0, bytes.length); byte[] digestBytes = digest.digest(); hashedData = Base64.encodeToString(digestBytes, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); } catch (Exception e) { throw e; } return hashedData; }

Target:
public final static String generateHash(String data) throws Exception { String hashedData = data; try { byte[] bytes = data.getBytes("US-ASCII"); MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(bytes, 0, bytes.length); byte[] digestBytes = digest.digest(); hashedData = Base64.encodeToString(digestBytes, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); } catch (Exception e) { throw e; } return hashedData; }
Source:
public static void addDiskImage(DiskImage image) { addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getId(), image.getstorage_ids().get(0))); }

Target:
public static void addDiskImage(DiskImage image) { addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getId(), getStorageDomainId(image))); }
Source:
public boolean isIgnoreFolder(boolean withDeleted, Project project, Folder folder) { boolean ignoreFolder = super.isIgnoreFolder(withDeleted, project, folder); if (ignoreFolder) { return true; } boolean isBusinessRules = folder.getLabel().equals(EResourceConstant.SYSTEM_INDICATORS_BUSINESS_RULES.getName()); boolean isPhoneNumber = folder.getLabel().equals(EResourceConstant.SYSTEM_INDICATORS_PHONENUMBER_STATISTICS.getName()); if (isBusinessRules || isPhoneNumber) { return true; } return false; }

Target:
public boolean isIgnoreFolder(boolean withDeleted, Project project, Folder folder) { boolean ignoreFolder = super.isIgnoreFolder(withDeleted, project, folder); if (ignoreFolder) { return true; } boolean isBusinessRules = EResourceConstant.SYSTEM_INDICATORS_BUSINESS_RULES.getName().equals(folder.getLabel()); boolean isPhoneNumber = EResourceConstant.SYSTEM_INDICATORS_PHONENUMBER_STATISTICS.getName().equals(folder.getLabel()); if (isBusinessRules || isPhoneNumber) { return true; } return false; }
Source:
public void getCasesTest() { TestCasesConfig config = mock(TestCasesConfig.class); expect(config.getTestCasesDirectory()).andReturn(new File("src/test/resources/cases/ok")); replay(config); Assert.assertEquals(4, new TestCasesProvider(config).getCases().size()); }

Target:
public void getCasesTest() { TestCasesConfig config = mock(TestCasesConfig.class); expect(config.getTestCasesDirectory()).andReturn(new File("src/test/resources/cases/ok")); replay(config); Assert.assertEquals(4, new TestCasesProvider(config).getCases().size()); verify(config); }
Source:
public void testTextWrapBoundariesUpdatesOnRefresh() { tested.refresh(); verify(textDecorator).setTextBoundaries(any()); }

Target:
public void testTextWrapBoundariesUpdatesOnRefresh() { tested.refresh(); verify(textDecorator).setTextBoundaries(PATH.getBoundingBox()); }
Source:
public void testConsumedResultPartitionsProducers() { TestingInputsLocationsRetriever originalLocationRetriever = getOriginalLocationRetriever(); InputsLocationsRetriever availableInputsLocationsRetriever = new AvailableInputsLocationsRetriever(originalLocationRetriever); Collection<Collection<ExecutionVertexID>> producers = availableInputsLocationsRetriever.getConsumedResultPartitionsProducers(EV2); assertThat(producers.size(), is(1)); Collection<ExecutionVertexID> resultProducers = producers.iterator().next(); assertThat(resultProducers.size(), is(1)); assertThat(resultProducers.iterator().next(), is(EV1)); }

Target:
public void testConsumedResultPartitionsProducers() { TestingInputsLocationsRetriever originalLocationRetriever = getOriginalLocationRetriever(); InputsLocationsRetriever availableInputsLocationsRetriever = new AvailableInputsLocationsRetriever(originalLocationRetriever); Collection<Collection<ExecutionVertexID>> producers = availableInputsLocationsRetriever.getConsumedResultPartitionsProducers(EV2); assertThat(producers.size(), is(1)); Collection<ExecutionVertexID> resultProducers = producers.iterator().next(); assertThat(resultProducers, contains(EV1)); }
Source:
public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { log.warn("no load balancer"); return null; } Server server = null; int count = 0; while (server == null && count++ < 10) { List<Server> upList = lb.getServerList(availableOnlyServers); List<Server> allList = lb.getServerList(allServers); int upCount = upList.size(); int serverCount = allList.size(); if ((upCount == 0) || (serverCount == 0)) { log.warn("No up servers available from load balancer: " + lb); return null; } server = allList.get(incrementAndGetModulo(serverCount)); if (server == null) { Thread.yield(); continue; } if (server.isAlive() && (server.isReadyToServe())) { return (server); } server = null; } if (count >= 10) { log.warn("No available alive servers after 10 tries from load balancer: " + lb); } return server; }

Target:
public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { log.warn("no load balancer"); return null; } Server server = null; int count = 0; while (server == null && count++ < 10) { List<Server> reachableServers = lb.getReachableServers(); List<Server> allServers = lb.getAllServers(); int upCount = reachableServers.size(); int serverCount = allServers.size(); if ((upCount == 0) || (serverCount == 0)) { log.warn("No up servers available from load balancer: " + lb); return null; } int nextServerIndex = incrementAndGetModulo(serverCount); server = allServers.get(nextServerIndex); if (server == null) { Thread.yield(); continue; } if (server.isAlive() && (server.isReadyToServe())) { return (server); } server = null; } if (count >= 10) { log.warn("No available alive servers after 10 tries from load balancer: " + lb); } return server; }
Source:
private static byte[] transform(final InputStream body) throws IOException { final ByteArrayOutputStream result = new ByteArrayOutputStream(); final JsonReader reader = Json.createReader(body); final Map<String, ?> props = Collections.singletonMap( JsonGenerator.PRETTY_PRINTING, true ); final JsonWriterFactory factory = Json.createWriterFactory(props); final JsonWriter writer = factory.createWriter(result); try { final JsonObject obj = reader.readObject(); try { writer.writeObject(obj); } finally { writer.close(); } } catch (final JsonException ex) { throw new IOException(ex); } finally { reader.close(); } return result.toByteArray(); }

Target:
private static byte[] transform(final InputStream body) throws IOException { final ByteArrayOutputStream res = new ByteArrayOutputStream(); final JsonReader rdr = Json.createReader(body); try { final JsonObject obj = rdr.readObject(); final JsonWriter wrt = Json.createWriterFactory( Collections.singletonMap( JsonGenerator.PRETTY_PRINTING, true ) ).createWriter(res); try { wrt.writeObject(obj); } finally { wrt.close(); } } catch (final JsonException ex) { throw new IOException(ex); } finally { rdr.close(); } return res.toByteArray(); }
Source:
public Map<String, ValidationReport> uploadProject(final Project project, final File archive, final String fileType, final User uploader, final Props additionalProps) throws ProjectManagerException, ExecutorManagerException { log.info("Uploading files to " + project.getName()); final Map<String, ValidationReport> reports; File folder = null; final FlowLoader loader; try { folder = unzipProject(archive, fileType); File startupDependencies = getStartupDependenciesFile(folder); reports = startupDependencies.exists() ? this.archiveUnthinner.validateThinProject(project, folder, startupDependencies, additionalProps) : this.validatorUtils.validateProject(project, folder, additionalProps); if (reports.values().stream().anyMatch(r -> !r.getModifiedFiles().isEmpty() || !r.getRemovedFiles().isEmpty())) { updateProjectZip(archive, folder); } loader = this.flowLoaderFactory.createFlowLoader(folder); reports.put(DIRECTORY_FLOW_REPORT_KEY, loader.loadProjectFlow(project, folder)); if (!isReportStatusValid(reports, project)) { FlowLoaderUtils.cleanUpDir(folder); return reports; } File startupDependenciesOrNull = startupDependencies.exists() ? startupDependencies : null; persistProject(project, loader, archive, folder, startupDependenciesOrNull, uploader); if (startupDependencies.exists()) { commonMetrics.markUploadThinProject(); } else { commonMetrics.markUploadFatProject(); } } finally { FlowLoaderUtils.cleanUpDir(folder); } cleanUpProjectOldInstallations(project); return reports; }

Target:
public Map<String, ValidationReport> uploadProject(final Project project, final File archive, final String fileType, final User uploader, final Props additionalProps) throws ProjectManagerException, ExecutorManagerException { log.info("Uploading files to " + project.getName()); final Map<String, ValidationReport> reports; File folder = null; final FlowLoader loader; try { folder = unzipProject(archive, fileType); final File startupDependencies = getStartupDependenciesFile(folder); final boolean isThinProject = startupDependencies.exists(); reports = isThinProject ? this.archiveUnthinner.validateThinProject(project, folder, startupDependencies, additionalProps) : this.validatorUtils.validateProject(project, folder, additionalProps); if (reports.values().stream().anyMatch(r -> !r.getModifiedFiles().isEmpty() || !r.getRemovedFiles().isEmpty())) { updateProjectZip(archive, folder); } loader = this.flowLoaderFactory.createFlowLoader(folder); reports.put(DIRECTORY_FLOW_REPORT_KEY, loader.loadProjectFlow(project, folder)); if (!isReportStatusValid(reports, project)) { FlowLoaderUtils.cleanUpDir(folder); return reports; } final File startupDependenciesOrNull = isThinProject ? startupDependencies : null; persistProject(project, loader, archive, folder, startupDependenciesOrNull, uploader); if (isThinProject) { commonMetrics.markUploadThinProject(); } else { commonMetrics.markUploadFatProject(); } } finally { FlowLoaderUtils.cleanUpDir(folder); } cleanUpProjectOldInstallations(project); return reports; }
Source:
public Configuration load(File file) throws ConfigurationLoadingException { LOG.debug("Start initializing loader with file: {}", file.getAbsolutePath()); Properties properties = new Properties(); InputStream is = null; try { is = new FileInputStream(file); properties.load(is); is.close(); LOG.debug("Loader successfully initialized with file: {}", file.getAbsolutePath()); } catch (IOException e) { LOG.error("Can not load properties: {}", e.getMessage()); throw new ConfigurationLoadingException(e.getMessage()); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { LOG.error("Can not close input stream for file {}: {}", file.getAbsolutePath(), e.getMessage()); } } return new ConfigurationImpl(properties); }

Target:
public Configuration load(File file) throws ConfigurationLoadingException { LOG.debug("Start initializing loader with file: {}", file.getAbsolutePath()); Properties properties = new Properties(); try { InputStream is = new FileInputStream(file); try { properties.load(is); LOG.debug("Loader successfully initialized with file: {}", file.getAbsolutePath()); } finally { Closeables.closeQuietly(is); } } catch (IOException e) { LOG.error("Cannot load properties", e); throw new ConfigurationLoadingException("Cannot load properties: " + e.getMessage()); } return new ConfigurationImpl(properties); }
Source:
public final void setUpMuleContext() throws Exception { if (!logConfigured) { configureLoggingForTest(getClass()); logConfigured = true; } workingDirectory.create(); String workingDirectoryOldValue = System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectory.getRoot().getAbsolutePath()); try { doSetUpBeforeMuleContextCreation(); muleContext = createMuleContext(); if (doTestClassInjection()) { muleContext.getInjector().inject(this); } if (isStartContext() && muleContext != null && !muleContext.isStarted()) { startMuleContext(); } doSetUp(); } catch (LifecycleException e) { if (LIFECYCLE_EXCEPTION_COMPONENT_FIELD != null) { LIFECYCLE_EXCEPTION_COMPONENT_FIELD.set(e, null); } } finally { if (workingDirectoryOldValue != null) { System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectoryOldValue); } else { System.clearProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY); } } }

Target:
public final void setUpMuleContext() throws Exception { if (!logConfigured) { configureLoggingForTest(getClass()); logConfigured = true; } workingDirectory.create(); String workingDirectoryOldValue = System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectory.getRoot().getAbsolutePath()); try { doSetUpBeforeMuleContextCreation(); muleContext = createMuleContext(); if (doTestClassInjection()) { muleContext.getInjector().inject(this); } if (isStartContext() && muleContext != null && !muleContext.isStarted()) { startMuleContext(); } doSetUp(); } catch (LifecycleException e) { if (LIFECYCLE_EXCEPTION_COMPONENT_FIELD != null) { LIFECYCLE_EXCEPTION_COMPONENT_FIELD.set(e, null); } throw e; } finally { if (workingDirectoryOldValue != null) { System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectoryOldValue); } else { System.clearProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY); } } }
Source:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_travel_guide_activity, menu); MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (query != null) query = query.trim().toLowerCase(); if (query == null || query.trim().equals("")) query = "Any"; city = query; Log.d("CITY", query); setContentFragment(TripPlanListFragment.newInstance(city, group, season)); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_travel_guide_activity, menu); MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (TextUtils.isEmpty(query)) query = "Any"; city = query.trim(); setContentFragment(TripPlanListFragment.newInstance(city, group, season)); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; }
Source:
public boolean contains(Object o) { for (SoftReference<T> ref : buffer) { T item = getItem(ref); if (item != null) { return true; } } return false; }

Target:
public boolean contains(Object o) { checkQueue(); for (SoftReference<T> ref : buffer) { T item = getItem(ref); if (item.equals(o)) { return true; } } return false; }
Source:
public DataSource lookup(SQLDataSetDef def) throws Exception { InitialContext ctx = new InitialContext(); return (DataSource) ctx.lookup(def.getDataSource()); }

Target:
public DataSource lookup(SQLDataSetDef def) throws Exception { return InitialContext.doLookup(def.getDataSource()); }
Source:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { if (String.class.equals(type)) { return Optional.empty(); } return Optional.of((rs, i, ctx) -> { ColumnMapper<String> jsonStringMapper = JdbiOptionals.findFirstPresent( () -> ctx.findColumnMapperFor(QualifiedType.of(String.class).with(Json.class)).map(JsonColumnMapperFactory::asStringMapper), () -> ctx.findColumnMapperFor(String.class)) .orElseThrow(() -> new UnableToProduceResultException(JSON_NOT_RETRIEVABLE, ctx)); String json = jsonStringMapper.map(rs, i, ctx); return json == null ? null : ctx.getConfig(JsonConfig.class).getJsonMapper().fromJson(type, json, ctx); }); }

Target:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { if (String.class.equals(type)) { return Optional.empty(); } return Optional.of((rs, i, ctx) -> { ColumnMapper<String> jsonStringMapper = JdbiOptionals.findFirstPresent( () -> ctx.findColumnMapperFor(QualifiedType.of(String.class).with(Json.class)), () -> ctx.findColumnMapperFor(String.class)) .orElseThrow(() -> new UnableToProduceResultException(JSON_NOT_RETRIEVABLE, ctx)); String json = jsonStringMapper.map(rs, i, ctx); return json == null ? null : ctx.getConfig(JsonConfig.class).getJsonMapper().fromJson(type, json, ctx); }); }
Source:
public void testPerformanceSpelVersusInvocable() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("messageAndHeader", Message.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); Message<String> message = MessageBuilder.withPayload("foo").setHeader("number", 42).build(); StopWatch stopWatch = new StopWatch("SpEL vs Invocable Performance"); stopWatch.start("SpEL"); int count = 10_000; for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); processor = new MethodInvokingMessageProcessor(service, method); stopWatch.start("Invocable"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); SpelParserConfiguration config = TestUtils.getPropertyValue(processor, "delegate.handlerMethod.EXPRESSION_PARSER.configuration", SpelParserConfiguration.class); new DirectFieldAccessor(config).setPropertyValue("compilerMode", SpelCompilerMode.IMMEDIATE); processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); stopWatch.start("Compiled SpEL"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); System.clearProperty("spring.expression.compiler.mode"); logger.warn(stopWatch.prettyPrint()); }

Target:
public void testPerformanceSpelVersusInvocable() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); Message<Integer> message = MessageBuilder.withPayload(42).build(); StopWatch stopWatch = new StopWatch("SpEL vs Invocable Performance"); stopWatch.start("SpEL"); int count = 20_000; for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); processor = new MethodInvokingMessageProcessor(service, method); stopWatch.start("Invocable"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); SpelParserConfiguration config = TestUtils.getPropertyValue(processor, "delegate.handlerMethod.EXPRESSION_PARSER.configuration", SpelParserConfiguration.class); new DirectFieldAccessor(config).setPropertyValue("compilerMode", SpelCompilerMode.IMMEDIATE); processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); stopWatch.start("Compiled SpEL"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); logger.warn(stopWatch.prettyPrint()); }
Source:
protected void executeCommand() { VmBackup vmBackup = getParameters().getVmBackup(); vmBackup.setDisks(getDisks()); log.info("Creating VmBackup entity for VM '{}'", vmBackup.getVmId()); Guid vmBackupId = createVmBackup(); log.info("Created VmBackup entity '{}'", vmBackupId); if (vmBackup.getFromCheckpointId() != null) { log.info("Redefine previous VM checkpoints for VM '{}'", vmBackup.getVmId()); if (!redefineVmCheckpoints()) { setCommandStatus(CommandStatus.FAILED); return; } log.info("Successfully redefined previous VM checkpoints for VM '{}'", vmBackup.getVmId()); } if (FeatureSupported.isIncrementalBackupSupported(getCluster().getCompatibilityVersion()) && !isBackupContainsRawDisksOnly()) { log.info("Creating VmCheckpoint entity for VM '{}'", vmBackup.getVmId()); Guid vmCheckpointId = createVmCheckpoint(); log.info("Created VmCheckpoint entity '{}'", vmCheckpointId); vmBackup.setToCheckpointId(vmCheckpointId); TransactionSupport.executeInNewTransaction(() -> { vmBackupDao.update(vmBackup); return null; }); } else { log.info("Skip checkpoint creation for VM '{}'", vmBackup.getVmId()); } updateVmBackupPhase(VmBackupPhase.STARTING); persistCommandIfNeeded(); setActionReturnValue(vmBackupId); setSucceeded(true); }

Target:
protected void executeCommand() { VmBackup vmBackup = getParameters().getVmBackup(); vmBackup.setDisks(getDisks()); log.info("Creating VmBackup entity for VM '{}'", vmBackup.getVmId()); Guid vmBackupId = createVmBackup(); log.info("Created VmBackup entity '{}'", vmBackupId); if (vmBackup.getFromCheckpointId() != null) { log.info("Redefine previous VM checkpoints for VM '{}'", vmBackup.getVmId()); if (!redefineVmCheckpoints()) { setCommandStatus(CommandStatus.FAILED); return; } log.info("Successfully redefined previous VM checkpoints for VM '{}'", vmBackup.getVmId()); } if (FeatureSupported.isIncrementalBackupSupported(getCluster().getCompatibilityVersion()) && !isBackupContainsRawDisksOnly()) { log.info("Creating VmCheckpoint entity for VM '{}'", vmBackup.getVmId()); Guid vmCheckpointId = createVmCheckpoint(); log.info("Created VmCheckpoint entity '{}'", vmCheckpointId); getParameters().setToCheckpointId(vmCheckpointId); } else { log.info("Skip checkpoint creation for VM '{}'", vmBackup.getVmId()); } updateVmBackupPhase(VmBackupPhase.STARTING); persistCommandIfNeeded(); setActionReturnValue(vmBackupId); setSucceeded(true); }
Source:
public void testPodServiceAccountName() { assertEquals(SERVICE_ACCOUNT_NAME, this.resultPod.getSpec().getServiceAccountName()); }

Target:
public void testPodServiceAccountName() { assertThat(this.resultPod.getSpec().getServiceAccountName(), is(SERVICE_ACCOUNT_NAME)); }
Source:
private void reload(final Reload<T> message) { final Optional<String> eTag = message.getETag(); final CachedJob<T> cachedJob; _periodicMetrics.recordCounter("job_executor_actor_reloads", 1); try { cachedJob = initializeOrEnsureRefMatch(unsafeJobRefCast(message.getJobRef())); if (eTag.isPresent()) { cachedJob.reloadIfOutdated(_injector, eTag.get()); } else { cachedJob.reload(_injector); } } catch (final NoSuchElementException error) { LOGGER.warn() .setMessage("tried to reload job, but job no longer exists in repository") .addData("ref", message.getJobRef()) .log(); killSelf(); return; } getSelf().tell(Tick.INSTANCE, getSelf()); }

Target:
private void reload(final Reload<T> message) { final Optional<String> eTag = message.getETag(); final CachedJob<T> cachedJob; _periodicMetrics.recordCounter("job_executor_actor_reloads", 1); try { cachedJob = initializeOrEnsureRefMatch(unsafeJobRefCast(message.getJobRef())); if (eTag.isPresent()) { cachedJob.reloadIfOutdated(_injector, eTag.get()); } else { cachedJob.reload(_injector); } } catch (final NoSuchJobException error) { LOGGER.warn() .setMessage("tried to reload job, but job no longer exists in repository") .addData("ref", message.getJobRef()) .log(); killSelf(); return; } timers().startPeriodicTimer(PERIODIC_TICK_TIMER_NAME, Tick.INSTANCE, TICK_INTERVAL); getSelf().tell(Tick.INSTANCE, getSelf()); }
Source:
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + BUFFER_MESSAGES_TO_REMOVE); removedMessage.stream().forEach(receivedMessage -> { System.out.println("Removed Message sequence : " + receivedMessage.getSequenceNumber()); }); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } if (messagesDeferred.get().size() > 0) { try { List<Long> listOfDeferredMessages = messagesDeferred.get(); for (Long seqNumber : listOfDeferredMessages) { ServiceBusReceivedMessage deferredMessages = receiver.receiveDeferredMessage(seqNumber); receiver.complete(deferredMessages); } } catch (Exception e) { logger.warning("Error occurred when draining deferred messages Entity : " + receiver.getEntityPath(), e); } messagesDeferred.set(new ArrayList<>()); } dispose(receiver, sender, receiveAndDeleteReceiver); }

Target:
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + BUFFER_MESSAGES_TO_REMOVE); removedMessage.stream().forEach(receivedMessage -> { logger.info("Removed Message Seq: ", receivedMessage.getSequenceNumber()); }); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } if (messagesDeferred.get().size() > 0) { try { List<Long> listOfDeferredMessages = messagesDeferred.get(); for (Long seqNumber : listOfDeferredMessages) { ServiceBusReceivedMessage deferredMessages = receiver.receiveDeferredMessage(seqNumber); receiver.complete(deferredMessages); } } catch (Exception e) { logger.warning("Error occurred when draining deferred messages Entity: ", receiver.getEntityPath(), e); } } dispose(receiver, sender, receiveAndDeleteReceiver); }
Source:
public boolean checkout() throws IOException { toBeDeleted.clear(); if (headCommitTree != null) preScanTwoTrees(); else prescanOneTree(); if (!conflicts.isEmpty()) { if (failOnConflict) { dc.unlock(); throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()])); } else cleanUpConflicts(); } builder.finish(); File file=null; String last = ""; for (int i = removed.size() - 1; i >= 0; i--) { String r = removed.get(i); file = new File(repo.getWorkTree(), r); if (!file.delete() && file.exists()) toBeDeleted.add(r); else { if (!isSamePrefix(r, last)) removeEmptyParents(file); last = r; } } if (file != null) removeEmptyParents(file); for (String path : updated.keySet()) { file = new File(repo.getWorkTree(), path); FileUtils.mkdirs(file.getParentFile(), true); file.createNewFile(); DirCacheEntry entry = dc.getEntry(path); checkoutEntry(repo, file, entry); } if (!builder.commit()) { dc.unlock(); throw new IndexWriteException(); } return toBeDeleted.size() == 0; }

Target:
public boolean checkout() throws IOException { toBeDeleted.clear(); if (headCommitTree != null) preScanTwoTrees(); else prescanOneTree(); if (!conflicts.isEmpty()) { if (failOnConflict) { dc.unlock(); throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()])); } else cleanUpConflicts(); } builder.finish(); File file=null; String last = ""; for (int i = removed.size() - 1; i >= 0; i--) { String r = removed.get(i); file = new File(repo.getWorkTree(), r); if (!file.delete() && file.exists()) toBeDeleted.add(r); else { if (!isSamePrefix(r, last)) removeEmptyParents(file); last = r; } } if (file != null) removeEmptyParents(file); for (String path : updated.keySet()) { file = new File(repo.getWorkTree(), path); if (!file.getParentFile().mkdirs()) { } file.createNewFile(); DirCacheEntry entry = dc.getEntry(path); checkoutEntry(repo, file, entry); } if (!builder.commit()) { dc.unlock(); throw new IndexWriteException(); } return toBeDeleted.size() == 0; }