auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testNested() throws Exception { try { service.inPropagationRequired(outer -> { final Handle h = JdbiUtil.getHandle(outer); h.insert("insert into something (id, name) values (7, 'ignored')"); try { service.inNested(inner -> { final Handle h1 = JdbiUtil.getHandle(inner); h1.insert("insert into something (id, name) values (8, 'ignored again')"); int count = h1.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(2); throw new ForceRollback(); }); fail("should have thrown an exception"); } catch (ForceRollback e) { assertThat(e).isNotNull(); } int count = h.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(1); throw new ForceRollback(); }); fail("should have thrown an exception"); } catch (ForceRollback e) { assertThat(e).isNotNull(); } service.inPropagationRequired(dbi -> { final Handle h = JdbiUtil.getHandle(dbi); int count = h.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(0); }); }

Target:
public void testNested() throws Exception { assertThatExceptionOfType(ForceRollback.class).isThrownBy(()->{ service.inPropagationRequired(outer -> { final Handle h = JdbiUtil.getHandle(outer); h.insert("insert into something (id, name) values (7, 'ignored')"); assertThatExceptionOfType(ForceRollback.class).isThrownBy(()-> { service.inNested(inner -> { final Handle h1 = JdbiUtil.getHandle(inner); h1.insert("insert into something (id, name) values (8, 'ignored again')"); int count = h1.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(2); throw new ForceRollback(); }); }); int count = h.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(1); throw new ForceRollback(); }); }); service.inPropagationRequired(dbi -> { final Handle h = JdbiUtil.getHandle(dbi); int count = h.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(0); }); }
Source:
@Test(expected = Test.None.class) public void testResourceToURL_ExistingResourceAtSubPackage() throws Exception { IOUtils.resourceToURL("/org/apache/commons/io/FileUtilsTestDataCR.dat"); }

Target:
@Test public void testResourceToURL_ExistingResourceAtSubPackage() throws Exception { final URL url = IOUtils.resourceToURL("/org/apache/commons/io/FileUtilsTestDataCR.dat"); assertNotNull(url); assertTrue(url.getFile().endsWith("/org/apache/commons/io/FileUtilsTestDataCR.dat")); }
Source:
public static void drawCenterInside(Graphics2D g, BufferedImage source, Rectangle dstRect) { if (source == null) { return; } final int srcWidth = source.getWidth(); final int srcHeight = source.getHeight(); if (srcWidth * 1.0 / srcHeight > dstRect.width * 1.0 / dstRect.height) { final int scaledWidth = Math.max(1, dstRect.width); final int scaledHeight = Math.max(1, dstRect.width * srcHeight / srcWidth); Image scaledImage = scaledImage(source, scaledWidth, scaledHeight); g.drawImage(scaledImage, dstRect.x, dstRect.y + (dstRect.height - scaledHeight) / 2, dstRect.x + dstRect.width, dstRect.y + (dstRect.height - scaledHeight) / 2 + scaledHeight, 0, 0, 0 + scaledWidth, 0 + scaledHeight, null); } else { final int scaledWidth = Math.max(1, dstRect.height * srcWidth / srcHeight); final int scaledHeight = Math.max(1, dstRect.height); Image scaledImage = scaledImage(source, scaledWidth, scaledHeight); g.drawImage(scaledImage, dstRect.x + (dstRect.width - scaledWidth) / 2, dstRect.y, dstRect.x + (dstRect.width - scaledWidth) / 2 + scaledWidth, dstRect.y + dstRect.height, 0, 0, 0 + scaledWidth, 0 + scaledHeight, null); } }

Target:
public static void drawCenterInside(Graphics2D g, BufferedImage source, Rectangle dstRect) { final int srcWidth = source.getWidth(); final int srcHeight = source.getHeight(); if (srcWidth * 1.0 / srcHeight > dstRect.width * 1.0 / dstRect.height) { final int scaledWidth = Math.max(1, dstRect.width); final int scaledHeight = Math.max(1, dstRect.width * srcHeight / srcWidth); Image scaledImage = scaledImage(source, scaledWidth, scaledHeight); g.drawImage(scaledImage, dstRect.x, dstRect.y + (dstRect.height - scaledHeight) / 2, dstRect.x + dstRect.width, dstRect.y + (dstRect.height - scaledHeight) / 2 + scaledHeight, 0, 0, 0 + scaledWidth, 0 + scaledHeight, null); } else { final int scaledWidth = Math.max(1, dstRect.height * srcWidth / srcHeight); final int scaledHeight = Math.max(1, dstRect.height); Image scaledImage = scaledImage(source, scaledWidth, scaledHeight); g.drawImage(scaledImage, dstRect.x + (dstRect.width - scaledWidth) / 2, dstRect.y, dstRect.x + (dstRect.width - scaledWidth) / 2 + scaledWidth, dstRect.y + dstRect.height, 0, 0, 0 + scaledWidth, 0 + scaledHeight, null); } }
Source:
public void test_getImageDataCurrentZoom() { Rectangle bounds = new Rectangle(0, 0, 10, 20); Image image = new Image(display, bounds.width, bounds.height); image.dispose(); try { image.getImageDataAtCurrentZoom(); fail("No exception thrown for disposed image"); } catch (SWTException e) { assertSWTProblem("Incorrect exception thrown for disposed image", SWT.ERROR_GRAPHIC_DISPOSED, e); } image = new Image(display, bounds.width, bounds.height); ImageData imageDataAtCurrentZoom = image.getImageDataAtCurrentZoom(); image.dispose(); Rectangle boundsAtCurrentZoom = new Rectangle(0, 0, imageDataAtCurrentZoom.width, imageDataAtCurrentZoom.height); assertEquals(":a:", boundsAtCurrentZoom, DPIUtil.autoScaleUp(bounds)); ImageData imageData = new ImageData(bounds.width, bounds.height, 1, new PaletteData(new RGB[] {new RGB(0, 0, 0)})); image = new Image(display, imageData); imageDataAtCurrentZoom = image.getImageDataAtCurrentZoom(); image.dispose(); boundsAtCurrentZoom = new Rectangle(0, 0, imageDataAtCurrentZoom.width, imageDataAtCurrentZoom.height); assertEquals(":b:", boundsAtCurrentZoom, DPIUtil.autoScaleUp(bounds)); }

Target:
public void test_getImageDataCurrentZoom() { Rectangle bounds = new Rectangle(0, 0, 10, 20); Image image = new Image(display, bounds.width, bounds.height); image.dispose(); try { image.getImageDataAtCurrentZoom(); fail("No exception thrown for disposed image"); } catch (SWTException e) { assertSWTProblem("Incorrect exception thrown for disposed image", SWT.ERROR_GRAPHIC_DISPOSED, e); } image = new Image(display, bounds.width, bounds.height); ImageData imageDataAtCurrentZoom = image.getImageDataAtCurrentZoom(); image.dispose(); Rectangle boundsAtCurrentZoom = new Rectangle(0, 0, imageDataAtCurrentZoom.width, imageDataAtCurrentZoom.height); assertEquals(":a: Size of ImageData returned from Image.getImageDataAtCurrentZoom method doesn't return matches with bounds in Pixel values.", boundsAtCurrentZoom, DPIUtil.autoScaleUp(bounds)); ImageData imageData = new ImageData(bounds.width, bounds.height, 1, new PaletteData(new RGB[] {new RGB(0, 0, 0)})); image = new Image(display, imageData); imageDataAtCurrentZoom = image.getImageDataAtCurrentZoom(); image.dispose(); boundsAtCurrentZoom = new Rectangle(0, 0, imageDataAtCurrentZoom.width, imageDataAtCurrentZoom.height); assertEquals(":b: Size of ImageData returned from Image.getImageDataAtCurrentZoom method doesn't return matches with bounds in Pixel values.", boundsAtCurrentZoom, DPIUtil.autoScaleUp(bounds)); }
Source:
public void commitDeleteMethodArguments(JoinPoint jp) { for (Object arg : AspectUtil.collectArguments(jp)) { JaversType typeMapping = javers.getTypeMapping(arg.getClass()); if (typeMapping instanceof EntityType) { commitShallowDelete(arg); } else if (typeMapping instanceof PrimitiveOrValueType) { JaversAuditableDelete javersAuditableDelete = ((MethodSignature) jp.getSignature()).getMethod().getAnnotation(JaversAuditableDelete.class); Class<?> domainType = javersAuditableDelete.domainType(); if (domainType == Void.class) { throw new IllegalStateException("Committing by id requires a domain type"); } commitShallowDeleteById(arg, domainType); } } }

Target:
public void commitDeleteMethodArguments(JoinPoint jp) { for (Object arg : AspectUtil.collectArguments(jp)) { JaversType typeMapping = javers.getTypeMapping(arg.getClass()); if (typeMapping instanceof EntityType) { commitShallowDelete(arg); } else if (typeMapping instanceof PrimitiveOrValueType) { commitShallowDeleteById(arg, getDomainTypeForDelete(jp)); } } }
Source:
private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) { return new StringBuilder(url.length() + 12).append("#W").append(maxWidth) .append("#H").append(maxHeight).append("#S").append(scaleType.name()).append(url) .toString(); }

Target:
private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) { return new StringBuilder(url.length() + 12).append("#W").append(maxWidth) .append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url) .toString(); }
Source:
public static Set<Flag> addFlags(Set<Flag> flags, Set<Flag> newFlags) { if (newFlags == null || newFlags.isEmpty()) { return flags; } if (flags == null) { return newFlags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.addAll(newFlags); return copy; }

Target:
public static Set<Flag> addFlags(Set<Flag> flags, Set<Flag> newFlags) { if (newFlags == null || newFlags.isEmpty()) { return flags; } if (flags == null || flags.isEmpty()) { return newFlags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.addAll(newFlags); return copy; }
Source:
protected FileMonitoringController(FilePath ws) throws IOException, InterruptedException { ws.mkdirs(); controlDir(ws).mkdirs(); }

Target:
protected FileMonitoringController(FilePath ws) throws IOException, InterruptedException { ws.mkdirs(); FilePath cd = tempDir(ws).child("durable-" + Util.getDigestOf(UUID.randomUUID().toString()).substring(0,8)); cd.mkdirs(); controlDir = cd.getRemote(); }
Source:
public Object call(Object obj, Object[] args, Location loc, Environment env) throws EvalException, InterruptedException { Preconditions.checkNotNull(obj); Object result; try { result = method.invoke(obj, args); } catch (IllegalAccessException e) { throw new EvalException(loc, "Method invocation failed: " + e); } catch (InvocationTargetException e) { if (e.getCause() instanceof FuncallExpression.FuncallException) { throw new EvalException(loc, e.getCause().getMessage()); } else if (e.getCause() != null) { Throwables.throwIfUnchecked(e.getCause()); Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class); throw new EvalException.EvalExceptionWithJavaCause(loc, e.getCause()); } else { throw new EvalException(loc, "method invocation failed: " + e); } } if (method.getReturnType().equals(Void.TYPE)) { return Runtime.NONE; } if (result == null) { if (isAllowReturnNones()) { return Runtime.NONE; } else { throw new EvalException( loc, "method invocation returned None, please file a bug report: " + getName() + Printer.printAbbreviatedList(ImmutableList.copyOf(args), "(", ", ", ")", null)); } } result = SkylarkType.convertToSkylark(result, method, env); if (result != null && !EvalUtils.isSkylarkAcceptable(result.getClass())) { throw new EvalException( loc, Printer.format( "method '%s' returns an object of invalid type %r", getName(), result.getClass())); } return result; }

Target:
public Object call(Object obj, Object[] args, Location loc, Environment env) throws EvalException, InterruptedException { Preconditions.checkNotNull(obj); Object result; try { result = method.invoke(obj, args); } catch (IllegalAccessException e) { throw new EvalException(loc, "Method invocation failed: " + e); } catch (InvocationTargetException x) { Throwable e = x.getCause(); if (e == null) { throw new IllegalStateException( String.format( "causeless InvocationTargetException when calling %s with arguments %s at %s", obj, Arrays.toString(args), loc), x); } Throwables.propagateIfPossible(e, InterruptedException.class); if (e instanceof FuncallExpression.FuncallException) { throw new EvalException(loc, e.getMessage()); } if (e instanceof EvalException) { throw ((EvalException) e).ensureLocation(loc); } throw new EvalException.EvalExceptionWithJavaCause(loc, e); } if (method.getReturnType().equals(Void.TYPE)) { return Runtime.NONE; } if (result == null) { if (isAllowReturnNones()) { return Runtime.NONE; } else { throw new IllegalStateException( "method invocation returned None " + getName() + Printer.printAbbreviatedList(ImmutableList.copyOf(args), "(", ", ", ")", null)); } } result = SkylarkType.convertToSkylark(result, method, env); if (result != null && !EvalUtils.isSkylarkAcceptable(result.getClass())) { throw new EvalException( loc, Printer.format( "method '%s' returns an object of invalid type %r", getName(), result.getClass())); } return result; }
Source:
public KotlinLanguageModule() { super(NAME, null, TERSE_NAME, null, "kotlin"); addVersion("", null, true); }

Target:
public KotlinLanguageModule() { super(NAME, null, TERSE_NAME, null, "kt"); addVersion("1.3", null, true); }
Source:
private byte[] getSysMutexPhysicalTableNameBytes() throws IOException, SQLException { byte[] sysMutexPhysicalTableNameBytes = null; try(HBaseAdmin admin = getAdmin()) { if(admin.tableExists(PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME_BYTES)) { sysMutexPhysicalTableNameBytes = PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME_BYTES; } else if (admin.tableExists(SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, props).getName())) { sysMutexPhysicalTableNameBytes = SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, props).getName(); } } return sysMutexPhysicalTableNameBytes; }

Target:
private byte[] getSysMutexPhysicalTableNameBytes() throws IOException, SQLException { byte[] sysMutexPhysicalTableNameBytes = null; try(HBaseAdmin admin = getAdmin()) { if(admin.tableExists(PhoenixDatabaseMetaData.SYSTEM_MUTEX_HBASE_TABLE_NAME)) { sysMutexPhysicalTableNameBytes = PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME_BYTES; } else if (admin.tableExists(TableName.valueOf( SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, props).getName()))) { sysMutexPhysicalTableNameBytes = SchemaUtil.getPhysicalTableName(PhoenixDatabaseMetaData.SYSTEM_MUTEX_NAME, props).getName(); } } return sysMutexPhysicalTableNameBytes; }
Source:
public List<PantsOutputMessage> parseCompilationOutputFile(String pathToFile) throws FileNotFoundException, IOException { assertNotNull(pathToFile); BufferedReader br = new BufferedReader(new FileReader(new File(pathToFile))); List<PantsOutputMessage> list = new ArrayList<PantsOutputMessage>(); for (String line; (line = br.readLine()) != null; ) { list.add(PantsOutputMessage.parseOutputMessage(line)); } return list; }

Target:
public List<PantsOutputMessage> parseCompilationOutputFile(String pathToFile) throws FileNotFoundException, IOException { assertNotNull(pathToFile); final List<String> lines = FileUtil.loadLines(new File(pathToFile)); assertNotNull(lines); List<PantsOutputMessage> list = new ArrayList<PantsOutputMessage>(); for (String line : lines) { list.add(PantsOutputMessage.parseOutputMessage(line)); } return list; }
Source:
public void shouldThrowExceptionMoreThanOneContact() throws Exception { Map<String, String> params = new HashMap<>(); UUID uuid = UUID.randomUUID(); params.put("uuid", uuid.toString()); Contact contact = new Contact(); contact.setName("Name"); contact.setUuid(uuid); contact.setPhone("1234567890"); ArrayList<String> urns = new ArrayList<>(); urns.add("tel:+1234567890"); contact.setUrns(urns); List<Contact> results = new ArrayList<>(); results.add(contact); results.add(contact); PaginatedResponse<Contact> paginatedResponse = new PaginatedResponse<>(); paginatedResponse.setCount("2"); paginatedResponse.setResults(results); String json = new ObjectMapper().writeValueAsString(paginatedResponse); InputStream inputStream = new ByteArrayInputStream(json.getBytes()); when(rapidProHttpClient.executeGet("/contacts", MediaFormat.JSON, params)).thenReturn(inputStream); Contact fromWebservice = contactWebService.getContactByUUID(uuid); }

Target:
public void shouldThrowExceptionMoreThanOneContact() throws Exception { Map<String, String> params = new HashMap<>(); UUID uuid = UUID.randomUUID(); params.put("uuid", uuid.toString()); Contact contact = new Contact(); contact.setName("Name"); contact.setUuid(uuid); contact.setPhone("1234567890"); ArrayList<String> urns = new ArrayList<>(); urns.add("tel:+1234567890"); contact.setUrns(urns); List<Contact> results = new ArrayList<>(); results.add(contact); results.add(contact); PaginatedResponse<Contact> paginatedResponse = new PaginatedResponse<>(); paginatedResponse.setCount("2"); paginatedResponse.setResults(results); String json = new ObjectMapper().writeValueAsString(paginatedResponse); InputStream inputStream = new ByteArrayInputStream(json.getBytes()); when(rapidProHttpClient.executeGet("/contacts", MediaFormat.JSON, params)).thenReturn(inputStream); contactWebService.getContactByUUID(uuid); }
Source:
public void testReplaceSubStringOfTopicWithHeaders() throws UnsupportedEncodingException { Sink kafkaSink = new KafkaSink(); Context context = prepareDefaultContext(); context.put(TOPIC_CONFIG, TestConstants.HEADER_TOPIC); Configurables.configure(kafkaSink, context); Channel memoryChannel = new MemoryChannel(); Configurables.configure(memoryChannel, context); kafkaSink.setChannel(memoryChannel); kafkaSink.start(); String msg = "test-replace-substring-of-topic-with-headers"; Map<String, String> headers = new HashMap<String, String>(); headers.put(TestConstants.HEADER_1_KEY, TestConstants.HEADER_1_VALUE); Transaction tx = memoryChannel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody(msg.getBytes(), headers); memoryChannel.put(event); tx.commit(); tx.close(); try { Sink.Status status = kafkaSink.process(); if (status == Sink.Status.BACKOFF) { fail("Error Occurred"); } } catch (EventDeliveryException ex) { } String fetchedMsg = new String((byte[]) testUtil.getNextMessageFromConsumer(TestConstants.HEADER_1_VALUE + "-topic").message()); assertEquals(msg, fetchedMsg); }

Target:
public void testReplaceSubStringOfTopicWithHeaders() throws UnsupportedEncodingException { Sink kafkaSink = new KafkaSink(); Context context = prepareDefaultContext(); context.put(TOPIC_CONFIG, TestConstants.HEADER_TOPIC); Configurables.configure(kafkaSink, context); Channel memoryChannel = new MemoryChannel(); Configurables.configure(memoryChannel, context); kafkaSink.setChannel(memoryChannel); kafkaSink.start(); String msg = "test-replace-substring-of-topic-with-headers"; Map<String, String> headers = new HashMap<>(); headers.put(TestConstants.HEADER_1_KEY, TestConstants.HEADER_1_VALUE); Transaction tx = memoryChannel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody(msg.getBytes(), headers); memoryChannel.put(event); tx.commit(); tx.close(); try { Sink.Status status = kafkaSink.process(); if (status == Sink.Status.BACKOFF) { fail("Error Occurred"); } } catch (EventDeliveryException ex) { } String fetchedMsg = new String((byte[]) testUtil.getNextMessageFromConsumer(TestConstants.HEADER_1_VALUE + "-topic").message()); assertEquals(msg, fetchedMsg); }
Source:
public DefaultAccount(final UUID id, @Nullable final DateTime createdDate, @Nullable final DateTime updatedDate, final String externalKey, final String email, final String name, final Integer firstNameLength, final Currency currency, final UUID parentAccountId, final Boolean isPaymentDelegatedToParent, final Integer billCycleDayLocal, final UUID paymentMethodId, final DateTimeZone timeZone, final String locale, final String address1, final String address2, final String companyName, final String city, final String stateOrProvince, final String country, final String postalCode, final String phone, final Boolean isMigrated, final Boolean isNotifiedForInvoices) { super(id, createdDate, updatedDate); this.externalKey = externalKey; this.email = email; this.name = name; this.firstNameLength = firstNameLength; this.currency = currency; this.parentAccountId = parentAccountId; this.isPaymentDelegatedToParent = isPaymentDelegatedToParent != null ? isPaymentDelegatedToParent : false; this.billCycleDayLocal = billCycleDayLocal == null ? DEFAULT_BILLING_CYCLE_DAY_LOCAL : billCycleDayLocal; this.paymentMethodId = paymentMethodId; this.timeZone = timeZone; this.locale = locale; this.address1 = address1; this.address2 = address2; this.companyName = companyName; this.city = city; this.stateOrProvince = stateOrProvince; this.postalCode = postalCode; this.country = country; this.phone = phone; this.isMigrated = isMigrated; this.isNotifiedForInvoices = isNotifiedForInvoices; }

Target:
public DefaultAccount(final UUID id, @Nullable final DateTime createdDate, @Nullable final DateTime updatedDate, final String externalKey, final String email, final String name, final Integer firstNameLength, final Currency currency, final UUID parentAccountId, final Boolean isPaymentDelegatedToParent, final Integer billCycleDayLocal, final UUID paymentMethodId, final DateTimeZone timeZone, final String locale, final String address1, final String address2, final String companyName, final String city, final String stateOrProvince, final String country, final String postalCode, final String phone, final Boolean isMigrated, final Boolean isNotifiedForInvoices) { super(id, createdDate, updatedDate); this.externalKey = externalKey; this.email = email; this.name = name; this.firstNameLength = firstNameLength; this.currency = currency; this.parentAccountId = parentAccountId; this.isPaymentDelegatedToParent = isPaymentDelegatedToParent; this.billCycleDayLocal = billCycleDayLocal == null ? DEFAULT_BILLING_CYCLE_DAY_LOCAL : billCycleDayLocal; this.paymentMethodId = paymentMethodId; this.timeZone = timeZone; this.locale = locale; this.address1 = address1; this.address2 = address2; this.companyName = companyName; this.city = city; this.stateOrProvince = stateOrProvince; this.postalCode = postalCode; this.country = country; this.phone = phone; this.isMigrated = isMigrated; this.isNotifiedForInvoices = isNotifiedForInvoices; }
Source:
public long sizeInBytes() { return super.sizeInBytes() + Blob_Id_Size_In_Bytes + blobId.sizeInBytes(); }

Target:
public long sizeInBytes() { return super.sizeInBytes() + blobId.sizeInBytes(); }
Source:
private static void addSingleHexByte(StringBuilder buf, byte b) { buf.append(HEX_VALUES.charAt(b)); }

Target:
private static void addSingleHexByte(StringBuilder buf, byte b) { buf.append(HEX_VALUES.charAt(b & 0x0F)); }
Source:
public @NonNull String eventKmemPageFree() { return "kmem:page_free"; }

Target:
public String eventKmemPageFree() { return "kmem:page_free"; }
Source:
public Key resolveSigningKey(JwsHeader header, Claims claims) { if (!MACHINE_TOKEN_KIND.equals(header.get("kind"))) { throw new NotMachineTokenJwtException(); } String wsId = claims.get(WORKSPACE_ID_CLAIM, String.class); try { return keyManager.getKeyPair(wsId).getPublic(); } catch (ServerException e) { throw new JwtException("Unable to fetch signature key pair:" + e.getMessage()); } }

Target:
public Key resolveSigningKey(JwsHeader header, Claims claims) { if (!MACHINE_TOKEN_KIND.equals(header.get("kind"))) { throw new NotMachineTokenJwtException(); } String wsId = claims.get(WORKSPACE_ID_CLAIM, String.class); if (wsId == null) { throw new JwtException( "Unable to fetch signature key pair: no workspace id present in token"); } try { return keyManager.getKeyPair(wsId).getPublic(); } catch (ServerException e) { throw new JwtException("Unable to fetch signature key pair:" + e.getMessage()); } }
Source:
private ServiceConnection getServiceConnection() { return new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { if(DEBUG) Log.d(TAG, "Player service is disconnected"); unbind(); } @Override public void onServiceConnected(ComponentName name, IBinder service) { if(DEBUG) Log.d(TAG, "Player service is connected"); MainVideoPlayer.LocalBinder localBinder = (MainVideoPlayer.LocalBinder) service; mVideoPlayer = localBinder.getService(); player = localBinder.getPlayer(); startPlayerListener(); if(!player.isPlaying() && !player.isCompleted() && !player.isProgressLoopRunning()) mVideoPlayer.getView().setVisibility(View.GONE); if(mVideoPlayer.isFullscreen) { hideActionBar(); hideSystemUi(); } if(getView() == null) return; ViewGroup viewHolder = getView().findViewById( mVideoPlayer.isFullscreen? R.id.video_item_detail: R.id.detail_thumbnail_root_layout); if(mVideoPlayer.getView().getParent() == null) viewHolder.addView(mVideoPlayer.getView()); else if(getView().findViewById(R.id.aspectRatioLayout) == null) { removeVideoPlayerView(); viewHolder.addView(mVideoPlayer.getView()); hideMainVideoPlayer(); } player.useVideoSource(true); boolean isLandscape = getResources().getDisplayMetrics().heightPixels < getResources().getDisplayMetrics().widthPixels; if(isLandscape) { if((!player.isPlaying() && player.getPlayQueue() != playQueue) || player.getPlayQueue() == null) setupMainVideoPlayer(); if(player.isPlaying()) { player.isBackgroundPlayerSelected = false; player.checkLandscape(); } } else if(mVideoPlayer.isFullscreen) player.onFullScreenButtonClicked(); } }; }

Target:
private ServiceConnection getServiceConnection() { return new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { if (DEBUG) Log.d(TAG, "Player service is disconnected"); unbind(); } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (DEBUG) Log.d(TAG, "Player service is connected"); MainPlayerService.LocalBinder localBinder = (MainPlayerService.LocalBinder) service; playerService = localBinder.getService(); player = localBinder.getPlayer(); startPlayerListener(); hideActionBar(); hideSystemUi(); if (currentInfo == null) selectAndLoadVideo(serviceId, url, "", playQueue); if (!player.videoPlayerSelected()) return; if (player.getPlayQueue() != null) addVideoPlayerView(); boolean isLandscape = getResources().getDisplayMetrics().heightPixels < getResources().getDisplayMetrics().widthPixels; if (isLandscape) { checkLandscape(); } else if (player.isInFullscreen()) player.onFullScreenButtonClicked(); if (currentInfo != null && isAutoplayEnabled() && player.getParentActivity() == null || shouldOpenPlayerAfterServiceConnects) { setupMainPlayer(); shouldOpenPlayerAfterServiceConnects = false; } } }; }
Source:
public void testSimpleTransactionInAnotherThread() throws IgniteCheckedException { withAllIsolationsAndConcurrencies(new IgniteClosure<Object, Void>() { @Override public Void apply(Object o) { try { simpleTransactionInAnotherThread(); } catch (Exception ignore) { assert false : "Impossible situation"; } return null; } }); }

Target:
public void testSimpleTransactionInAnotherThread() throws Exception { runWithAllIsolations(new IgniteCallable<Void>() { @Override public Void call() throws Exception { simpleTransactionInAnotherThread(); return null; } }); }
Source:
public Req understand(final Comment.Smart comment, final URI home) throws IOException { new Answer(comment).post( true, String.format( QnDeploy.PHRASES.getString("QnDeploy.start"), home.toASCIIString() ) ); final Issue issue = comment.issue(); final Repo repo = issue.repo(); Logger.info( this, "deploy request found in %s#%d comment #%d", repo.coordinates(), issue.number(), comment.number() ); return new Req.Simple( "deploy", new MapOf<String, String>( new MapEntry<String, String>( "head_branch", "master" ), new MapEntry<>( "head", String.format( "git@github.com:%s.git", repo.coordinates() ) ) ) ); }

Target:
public Req understand(final Comment.Smart comment, final URI home) throws IOException { new Answer(comment).post( true, String.format( QnDeploy.PHRASES.getString("QnDeploy.start"), home.toASCIIString() ) ); final Issue issue = comment.issue(); final Repo repo = issue.repo(); Logger.info( this, "deploy request found in %s#%d comment #%d", repo.coordinates(), issue.number(), comment.number() ); return new Req.Simple( "deploy", new SolidMap<String, String>( new MapEntry<String, String>( "head_branch", "master" ), new MapEntry<>( "head", String.format( "git@github.com:%s.git", repo.coordinates() ) ) ) ); }
Source:
public void run() throws FileNotFoundException, IOException { ui.header("Container Process"); container.string("Run as", "user", username()); container.string("Java runtime", "javaHome", javaHome()); File myWar; try { myWar = GerritLauncher.getDistributionArchive(); } catch (FileNotFoundException e) { System.err.println("warn: Cannot find gerrit.war"); myWar = null; } String path = container.get("war"); System.out.println("1-PATH:" + path); if (path != null) { path = container.string("Gerrit runtime", "war", myWar != null ? myWar.getAbsolutePath() : null); if (path == null || path.isEmpty()) { throw die("container.war is required"); } System.out.println("1-PATH:" + path); System.out.println("1-myWar:" + myWar); } else if (myWar != null) { System.out.println("2-PATH:" + path); System.out.println("2-myWar:" + myWar); final boolean copy; final File siteWar = site.gerrit_war; if (siteWar.exists()) { copy = ui.yesno(true, "Upgrade %s", siteWar.getPath()); } else { copy = ui.yesno(true, "Copy gerrit.war to %s", siteWar.getPath()); if (copy) { container.unset("war"); } else { container.set("war", myWar.getAbsolutePath()); } } if (copy) { if (!ui.isBatch()) { System.err.format("Copying gerrit.war to %s", siteWar.getPath()); System.err.println(); } copy(siteWar, new FileInputStream(myWar)); } } }

Target:
public void run() throws FileNotFoundException, IOException { ui.header("Container Process"); container.string("Run as", "user", username()); container.string("Java runtime", "javaHome", javaHome()); File myWar; try { myWar = GerritLauncher.getDistributionArchive(); } catch (FileNotFoundException e) { System.err.println("warn: Cannot find gerrit.war"); myWar = null; } String path = container.get("war"); if (path != null) { path = container.string("Gerrit runtime", "war", myWar != null ? myWar.getAbsolutePath() : null); if (path == null || path.isEmpty()) { throw die("container.war is required"); } } else if (myWar != null) { final boolean copy; final File siteWar = site.gerrit_war; if (siteWar.exists()) { copy = ui.yesno(true, "Upgrade %s", siteWar.getPath()); } else { copy = ui.yesno(true, "Copy gerrit.war to %s", siteWar.getPath()); if (copy) { container.unset("war"); } else { container.set("war", myWar.getAbsolutePath()); } } if (copy) { if (!ui.isBatch()) { System.err.format("Copying gerrit.war to %s", siteWar.getPath()); System.err.println(); } copy(siteWar, new FileInputStream(myWar)); } } }
Source:
protected Publication( final ClientConductor clientConductor, final String channel, final int streamId, final int sessionId, final ReadablePosition positionLimit, final int channelStatusId, final LogBuffers logBuffers, final long originalRegistrationId, final long registrationId, final int maxMessageLength) { this.logMetaDataBuffer = logBuffers.metaDataBuffer(); this.termBufferLength = logBuffers.termLength(); this.maxMessageLength = maxMessageLength; this.maxPayloadLength = LogBufferDescriptor.mtuLength(logMetaDataBuffer) - HEADER_LENGTH; this.maxPossiblePosition = termBufferLength * (1L << 31L); this.conductor = clientConductor; this.channel = channel; this.streamId = streamId; this.sessionId = sessionId; this.initialTermId = LogBufferDescriptor.initialTermId(logMetaDataBuffer); this.originalRegistrationId = originalRegistrationId; this.registrationId = registrationId; this.positionLimit = positionLimit; this.channelStatusId = channelStatusId; this.logBuffers = logBuffers; this.positionBitsToShift = Integer.numberOfTrailingZeros(termBufferLength); this.headerWriter = HeaderWriter.newInstance(defaultFrameHeader(logMetaDataBuffer)); }

Target:
protected Publication( final ClientConductor clientConductor, final String channel, final int streamId, final int sessionId, final ReadablePosition positionLimit, final int channelStatusId, final LogBuffers logBuffers, final long originalRegistrationId, final long registrationId, final int maxMessageLength) { final UnsafeBuffer logMetaDataBuffer = logBuffers.metaDataBuffer(); this.termBufferLength = logBuffers.termLength(); this.maxMessageLength = maxMessageLength; this.maxPayloadLength = LogBufferDescriptor.mtuLength(logMetaDataBuffer) - HEADER_LENGTH; this.maxPossiblePosition = termBufferLength * (1L << 31L); this.conductor = clientConductor; this.channel = channel; this.streamId = streamId; this.sessionId = sessionId; this.initialTermId = LogBufferDescriptor.initialTermId(logMetaDataBuffer); this.logMetaDataBuffer = logMetaDataBuffer; this.originalRegistrationId = originalRegistrationId; this.registrationId = registrationId; this.positionLimit = positionLimit; this.channelStatusId = channelStatusId; this.logBuffers = logBuffers; this.positionBitsToShift = Integer.numberOfTrailingZeros(termBufferLength); this.headerWriter = HeaderWriter.newInstance(defaultFrameHeader(logMetaDataBuffer)); }
Source:
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object message) throws Exception { if (message instanceof ControlMessage) { ControlMessage controlMessage = (ControlMessage) message; Kind kind = controlMessage.getKind(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encoding " + kind); } switch (kind) { case PREPARED: return encodePreparedMessage(ctx, channel, (PreparedMessage) controlMessage); case STARTED: return encodeStartedMessage(ctx, channel, (StartedMessage) controlMessage); case ERROR: return encodeErrorMessage(ctx, channel, (ErrorMessage) controlMessage); case FINISHED: return encodeFinishedMessage(ctx, channel, (FinishedMessage) controlMessage); case NOTIFY: return encodeNotifyMessage(ctx, channel, (NotifyMessage) controlMessage); case NOTIFIED: return encodedNotifiedMessage(ctx, channel, (NotifiedMessage) controlMessage); case DISPOSED: return encodedDisposedMessage(ctx, channel, (DisposedMessage) controlMessage); default: break; } } return message; }

Target:
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object message) throws Exception { if (message instanceof ControlMessage) { ControlMessage controlMessage = (ControlMessage) message; switch (controlMessage.getKind()) { case PREPARED: return encodePreparedMessage(ctx, channel, (PreparedMessage) controlMessage); case STARTED: return encodeStartedMessage(ctx, channel, (StartedMessage) controlMessage); case ERROR: return encodeErrorMessage(ctx, channel, (ErrorMessage) controlMessage); case FINISHED: return encodeFinishedMessage(ctx, channel, (FinishedMessage) controlMessage); case NOTIFY: return encodeNotifyMessage(ctx, channel, (NotifyMessage) controlMessage); case NOTIFIED: return encodedNotifiedMessage(ctx, channel, (NotifiedMessage) controlMessage); case DISPOSED: return encodedDisposedMessage(ctx, channel, (DisposedMessage) controlMessage); default: break; } } return message; }
Source:
public DataTransactionResult remove(DataHolder dataHolder) { if (supports(dataHolder)) { final DataTransactionBuilder builder = DataTransactionBuilder.builder(); final Optional<BreakableData> old = from(dataHolder); try { if (set((ItemStack) dataHolder, ImmutableSet.<BlockType>of())) { if (old.isPresent()) { builder.replace(old.get().getValues()); } return builder.result(DataTransactionResult.Type.SUCCESS).build(); } else { return builder.result(DataTransactionResult.Type.FAILURE).build(); } } catch (Exception e) { Sponge.getLogger().debug("An exception occurred when setting data: ", e); return builder.result(DataTransactionResult.Type.ERROR).build(); } } return DataTransactionBuilder.failNoData(); }

Target:
public DataTransactionResult remove(DataHolder dataHolder) { if (supports(dataHolder)) { final DataTransactionBuilder builder = DataTransactionBuilder.builder(); final Optional<BreakableData> old = from(dataHolder); try { if (set((ItemStack) dataHolder, ImmutableSet.<BlockType>of())) { if (old.isPresent()) { builder.replace(old.get().getValues()); } return builder.result(DataTransactionResult.Type.SUCCESS).build(); } else { return builder.result(DataTransactionResult.Type.FAILURE).build(); } } catch (Exception e) { Sponge.getLogger().debug("An exception occurred when removing data: ", e); return builder.result(DataTransactionResult.Type.ERROR).build(); } } return DataTransactionBuilder.failNoData(); }
Source:
public void fireClickEvent(Marker marker, AnnotationProxy annoProxy, String clickSource, boolean deselected) { KrollDict d = new KrollDict(); String title = null; String subtitle = null; boolean isDeselected = (deselected) ? true : false; TiMapInfoWindow infoWindow = annoProxy.getMapInfoWindow(); if (infoWindow != null) { title = infoWindow.getTitle(); subtitle = infoWindow.getSubtitle(); } d.put(TiC.PROPERTY_TITLE, title); d.put(TiC.PROPERTY_SUBTITLE, subtitle); d.put(TiC.PROPERTY_LATITUDE, marker.getPosition().latitude); d.put(TiC.PROPERTY_LONGITUDE, marker.getPosition().longitude); d.put(TiC.PROPERTY_ANNOTATION, annoProxy); d.put(MapModule.PROPERTY_MAP, proxy); d.put(TiC.PROPERTY_TYPE, TiC.EVENT_CLICK); d.put(TiC.PROPERTY_SOURCE, proxy); d.put(TiC.EVENT_PROPERTY_CLICKSOURCE, clickSource); d.put(MapModule.PROPERTY_DESELECTED, isDeselected); if (proxy != null) { proxy.fireEvent(TiC.EVENT_CLICK, d); } }

Target:
public void fireClickEvent(Marker marker, AnnotationProxy annoProxy, String clickSource, boolean deselected) { KrollDict d = new KrollDict(); String title = null; String subtitle = null; TiMapInfoWindow infoWindow = annoProxy.getMapInfoWindow(); if (infoWindow != null) { title = infoWindow.getTitle(); subtitle = infoWindow.getSubtitle(); } d.put(TiC.PROPERTY_TITLE, title); d.put(TiC.PROPERTY_SUBTITLE, subtitle); d.put(TiC.PROPERTY_LATITUDE, marker.getPosition().latitude); d.put(TiC.PROPERTY_LONGITUDE, marker.getPosition().longitude); d.put(TiC.PROPERTY_ANNOTATION, annoProxy); d.put(MapModule.PROPERTY_MAP, proxy); d.put(TiC.PROPERTY_TYPE, TiC.EVENT_CLICK); d.put(TiC.PROPERTY_SOURCE, proxy); d.put(TiC.EVENT_PROPERTY_CLICKSOURCE, clickSource); d.put(MapModule.PROPERTY_DESELECTED, deselected); if (proxy != null) { proxy.fireEvent(TiC.EVENT_CLICK, d); } }
Source:
protected void executeCommand() { if (shouldSkipCommandExecutionCached()) { setSucceeded(true); return; } executeVmCommand(); updateHeOvf(); }

Target:
protected void executeCommand() { if (shouldSkipCommandExecutionCached()) { setSucceeded(true); return; } executeVmCommand(); if (shouldUpdateHostedEngineOvf() && getVm().isHostedEngine() && getSucceeded()) { registerHeOvfUpdate(); } }
Source:
public List<Integer> getExternalContentIDs() { final List<Integer> contentIDs = new ArrayList<>(externalBlocks.size()); externalBlocks.forEach((i, b) -> contentIDs.add(i)); return contentIDs; }

Target:
public List<Integer> getExternalContentIDs() { return new ArrayList<>(externalBlocks.keySet()); }
Source:
private static void assignPreprocessorComments(NodeCommentMap commentMap, ArrayList<IASTComment> comments, IASTTranslationUnit tu) { IASTPreprocessorStatement[] preprocessorStatementsArray = tu.getAllPreprocessorStatements(); if (preprocessorStatementsArray == null) { return; } List<IASTPreprocessorStatement> preprocessorStatements = Arrays .asList(preprocessorStatementsArray); if (preprocessorStatements.isEmpty() || comments.isEmpty()) { return; } Iterator<IASTPreprocessorStatement> ppIter = preprocessorStatements.iterator(); Iterator<IASTComment> commentIter = comments.iterator(); IASTPreprocessorStatement curPPStatement = getNextNodeInTu(ppIter); IASTComment curComment = getNextNodeInTu(commentIter); while (curPPStatement != null && curComment != null) { int ppLineNr = curPPStatement.getFileLocation().getStartingLineNumber(); int commentLineNr = curComment.getFileLocation().getStartingLineNumber(); if (commentLineNr == ppLineNr) { commentMap.addTrailingCommentToNode(curPPStatement, curComment); commentIter.remove(); curComment = getNextNodeInTu(commentIter); } else if (commentLineNr > ppLineNr) { curPPStatement = getNextNodeInTu(ppIter); } else if (isCommentDirectlyBeforePreprocessorStatement(curComment, curPPStatement, tu)) { commentMap.addLeadingCommentToNode(curPPStatement, curComment); commentIter.remove(); curComment = getNextNodeInTu(commentIter); } else { curComment = getNextNodeInTu(commentIter); } } }

Target:
private static void assignPreprocessorComments(NodeCommentMap commentMap, ArrayList<IASTComment> comments, IASTTranslationUnit tu) { IASTPreprocessorStatement[] preprocessorStatementsArray = tu.getAllPreprocessorStatements(); if (preprocessorStatementsArray == null) { return; } List<IASTPreprocessorStatement> preprocessorStatements = Arrays .asList(preprocessorStatementsArray); if (preprocessorStatements.isEmpty() || comments.isEmpty()) { return; } Iterator<IASTPreprocessorStatement> statementsIter = preprocessorStatements.iterator(); Iterator<IASTComment> commentIter = comments.iterator(); IASTPreprocessorStatement curStatement = getNextNodeInTu(statementsIter); IASTComment curComment = getNextNodeInTu(commentIter); while (curStatement != null && curComment != null) { int statementLineNr = curStatement.getFileLocation().getStartingLineNumber(); int commentLineNr = curComment.getFileLocation().getStartingLineNumber(); if (commentLineNr == statementLineNr) { commentMap.addTrailingCommentToNode(curStatement, curComment); commentIter.remove(); curComment = getNextNodeInTu(commentIter); } else if (commentLineNr > statementLineNr) { curStatement = getNextNodeInTu(statementsIter); } else if (isCommentDirectlyBeforePreprocessorStatement(curComment, curStatement, tu)) { commentMap.addLeadingCommentToNode(curStatement, curComment); commentIter.remove(); curComment = getNextNodeInTu(commentIter); } else { curComment = getNextNodeInTu(commentIter); } } }
Source:
public Map<String, Product> getProducts(IOperationMonitor monitor) throws BugzillaRestException { return getContainer(client, monitor, "/product?type=accessible", new Function<ProductResponse, Product[]>() { public Product[] apply(ProductResponse input) { return input.getProducts(); } }, new Function<Product, String>() { public String apply(Product input) { return input.getName(); }; }, new TypeToken<ProductResponse>() { }); }

Target:
public Map<String, Product> getProducts(IOperationMonitor monitor) throws BugzillaRestException { return retrieveItems(monitor, "/product?type=accessible", new Function<ProductResponse, Product[]>() { public Product[] apply(ProductResponse input) { return input.getProducts(); } }, new TypeToken<ProductResponse>() { }); }
Source:
public void visit(NodeTraversal t, Node n, Node parent) { Node maybeCallNode = n.getFirstChild(); if (maybeCallNode == null || maybeCallNode.getToken() != Token.CALL) { return; } String callName = maybeCallNode.getFirstChild().getQualifiedName(); if (!"goog.scope".equals(callName)) { return; } Node blockOfScopeContents = n.getLastChild().getLastChild().getLastChild(); blockOfScopeContents.detachFromParent(); List<Node> scopeChildren = new ArrayList<>(); @Nullable Node maybeChildToAdd = blockOfScopeContents.getFirstChild(); while (maybeChildToAdd != null) { scopeChildren.add(maybeChildToAdd); maybeChildToAdd = maybeChildToAdd.getNext(); } Node insertAfterThisNode = n; for (Node scopeChild : scopeChildren) { scopeChild.detachFromParent(); n.getParent().addChildAfter(scopeChild, insertAfterThisNode); insertAfterThisNode = scopeChild; } n.detachFromParent(); compiler.reportCodeChange(); }

Target:
public void visit(NodeTraversal t, Node n, Node parent) { Node maybeCallNode = n.getFirstChild(); if (maybeCallNode == null || maybeCallNode.getToken() != Token.CALL) { return; } String callName = maybeCallNode.getFirstChild().getQualifiedName(); if (!"goog.scope".equals(callName)) { return; } Node blockOfScopeContents = n.getLastChild().getLastChild().getLastChild(); blockOfScopeContents.detachFromParent(); Node insertAfterThisNode = n; @Nullable Node nodeToMove = blockOfScopeContents.getFirstChild(); while (nodeToMove != null) { Node nextNodeToMove = nodeToMove.getNext(); nodeToMove.detachFromParent(); n.getParent().addChildAfter(nodeToMove, insertAfterThisNode); insertAfterThisNode = nodeToMove; nodeToMove = nextNodeToMove; } n.detachFromParent(); compiler.reportCodeChange(); }
Source:
public final Object processMessageGroup(MessageGroup group) { Assert.notNull(group, "MessageGroup must not be null"); Map<String, Object> headers = this.aggregateHeaders(group); Object payload = this.aggregatePayloads(group, headers); AbstractIntegrationMessageBuilder<?> builder; MessageBuilderFactory messageBuilderFactory = getMessageBuilderFactory(); if (payload instanceof Message<?>) { builder = messageBuilderFactory.fromMessage((Message<?>) payload).copyHeadersIfAbsent(headers); } else { builder = messageBuilderFactory.withPayload(payload).copyHeadersIfAbsent(headers); } return builder.popSequenceDetails().build(); }

Target:
public final Object processMessageGroup(MessageGroup group) { Assert.notNull(group, "MessageGroup must not be null"); Map<String, Object> headers = this.aggregateHeaders(group); Object payload = this.aggregatePayloads(group, headers); AbstractIntegrationMessageBuilder<?> builder; if (payload instanceof Message<?>) { builder = getMessageBuilderFactory().fromMessage((Message<?>) payload).copyHeadersIfAbsent(headers); } else { builder = getMessageBuilderFactory().withPayload(payload).copyHeadersIfAbsent(headers); } return builder.popSequenceDetails().build(); }
Source:
private void printElement(final PrintWriter stdout, TreeNode node, int level, boolean isLast, final TreeNode lastParentNode) { if (node.getProject() != null) { if (!currentTabSeparator.equals(" ")) { final String nodeProject = node.getProject().getName(); final String lastParentProject = lastParentNode.getProject().getName(); if (nodeProject.equals(lastParentProject)) { currentTabSeparator = " "; } } if (level > 0) { stdout.print(String.format("%-" + 4 * level + "s", currentTabSeparator)); } final String prefix = isLast ? LAST_NODE_PREFIX : NODE_PREFIX ; String printout; if (node.isVisible()) { printout = prefix + node.getProject().getName(); } else { printout = prefix + NOT_VISIBLE_PROJECT; } stdout.println(printout); stdout.flush(); } if (node.isLeaf()) { return; } else { final List<TreeNode> children = node.getChildren(); ++level; for(TreeNode treeNode : children) { final boolean isLastIndex = children.indexOf(treeNode) == children.size() - 1; printElement(stdout, treeNode, level, isLastIndex, lastParentNode); } } }

Target:
private void printElement(final PrintWriter stdout, TreeNode node, int level, boolean isLast, final TreeNode lastParentNode) { if (node.getProject() != null) { if (!currentTabSeparator.equals(" ")) { final String nodeProject = node.getProject().getName(); final String lastParentProject = lastParentNode.getProject().getName(); if (nodeProject.equals(lastParentProject)) { currentTabSeparator = " "; } } if (level > 0) { stdout.print(String.format("%-" + 4 * level + "s", currentTabSeparator)); } final String prefix = isLast ? LAST_NODE_PREFIX : NODE_PREFIX ; String printout; if (node.isVisible()) { printout = prefix + node.getProject().getName(); } else { printout = prefix + NOT_VISIBLE_PROJECT; } stdout.print(printout + "\n"); } if (node.isLeaf()) { return; } else { final List<TreeNode> children = node.getChildren(); ++level; for(TreeNode treeNode : children) { final boolean isLastIndex = children.indexOf(treeNode) == children.size() - 1; printElement(stdout, treeNode, level, isLastIndex, lastParentNode); } } }