auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String doIntercept(ActionInvocation invocation) throws Exception { Validator validator = this.beanValidationManager.getValidator(); if (validator == null) { LOG.debug("There is no Bean Validator configured in class path. Skipping Bean validation.."); return invocation.invoke(); } LOG.debug("Starting bean validation using validator: {}", validator.getClass()); Object action = invocation.getAction(); ActionProxy actionProxy = invocation.getProxy(); String methodName = actionProxy.getMethod(); if (LOG.isDebugEnabled()) { LOG.debug("Validating [{}/{}] with method [{}]", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName(), methodName); } Class<?>[] validationGroup = getValidationGroups(action, methodName); if (null == MethodUtils.getAnnotation(getActionMethod(action.getClass(), methodName), SkipValidation.class, true, true)) { performBeanValidation(action, validator, validationGroup); } return invocation.invoke(); }

Target:
protected String doIntercept(ActionInvocation invocation) throws Exception { Validator validator = this.beanValidationManager.getValidator(); if (validator == null) { LOG.debug("There is no Bean Validator configured in class path. Skipping Bean validation.."); return invocation.invoke(); } LOG.debug("Starting bean validation using validator: {}", validator.getClass()); Object action = invocation.getAction(); ActionProxy actionProxy = invocation.getProxy(); String methodName = actionProxy.getMethod(); LOG.debug("Validating [{}/{}] with method [{}]", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName(), methodName); if (null == MethodUtils.getAnnotation(getActionMethod(action.getClass(), methodName), SkipValidation.class, true, true)) { Class<?>[] validationGroup = getValidationGroups(action, methodName); performBeanValidation(action, validator, validationGroup); } return invocation.invoke(); }
Source:
public Response getDeviceInformation( @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { DeviceInformationManager informationManager; DeviceInfo deviceInfo; try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(id); deviceIdentifier.setType(type); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device information."; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceInfo).build(); }

Target:
public Response getDeviceInformation( @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { DeviceInformationManager informationManager; DeviceInfo deviceInfo; try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(id); deviceIdentifier.setType(type); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device information of id : " + id + " type : " + type ; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceInfo).build(); }
Source:
public long getMinEnd() { return fMinEnd != null ? fMinEnd : getNodeEnd(); }

Target:
public long getMinEnd() { return fMinEnd != null ? fMinEnd : getNodeStart(); }
Source:
public TabularData getRouteProperties() { try { final Map<String, Object> properties = route.getProperties(); final TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.camelRoutePropertiesTabularType()); final CompositeType ct = CamelOpenMBeanTypes.camelRoutePropertiesCompositeType(); for (Map.Entry<String, Object> entry : properties.entrySet()) { final String key = entry.getKey(); final String val = context.getTypeConverter().convertTo(String.class, entry.getValue()); CompositeData data = new CompositeDataSupport( ct, new String[]{ "name", "value"}, new Object[]{ key, val } ); answer.put(data); } return answer; } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }

Target:
public TabularData getRouteProperties() { try { final Map<String, Object> properties = route.getProperties(); final TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.camelRoutePropertiesTabularType()); final CompositeType ct = CamelOpenMBeanTypes.camelRoutePropertiesCompositeType(); for (Map.Entry<String, Object> entry : properties.entrySet()) { final String key = entry.getKey(); final String val = context.getTypeConverter().convertTo(String.class, entry.getValue()); CompositeData data = new CompositeDataSupport( ct, new String[]{"key", "value"}, new Object[]{key, val} ); answer.put(data); } return answer; } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }
Source:
private Schema getOutputSchema(FailureCollector collector) { List<Schema.Field> fields = new ArrayList<>(); List<String> fieldNames = new ArrayList<>(); String[] mappings = fieldTypeMapping.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); String fieldName = params[0].trim(); if (Strings.isNullOrEmpty(fieldName)) { collector.addFailure("Field name cannot be null or empty.", null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else if (params.length < 2 || Strings.isNullOrEmpty(params[1])) { collector.addFailure(String.format("A type must be provided for field '%s'.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { Schema.Field field = Schema.Field.of(fieldName, Schema.nullableOf(Schema.of(Schema.Type.valueOf( params[1].trim().toUpperCase())))); if (fieldNames.contains(field.getName())) { collector.addFailure(String.format("Field '%s' already has a type specified.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { fields.add(field); fieldNames.add(field.getName()); } } } collector.getOrThrowException(); return Schema.recordOf("record", fields); }

Target:
private Schema getOutputSchema(FailureCollector collector) { List<Schema.Field> fields = new ArrayList<>(); List<String> fieldNames = new ArrayList<>(); String[] mappings = fieldTypeMapping.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); String fieldName = params[0].trim(); if (Strings.isNullOrEmpty(fieldName)) { collector.addFailure("Field name cannot be null or empty.", null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else if (params.length < 2 || Strings.isNullOrEmpty(params[1])) { collector.addFailure(String.format("A type must be provided for field '%s'.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { Schema fieldSchema = Schema.of(Schema.Type.valueOf(params[1].trim().toUpperCase())); Schema.Field field = Schema.Field.of(fieldName, Schema.nullableOf(fieldSchema)); if (fieldNames.contains(field.getName())) { collector.addFailure(String.format("Field '%s' already has a type specified.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { fields.add(field); fieldNames.add(field.getName()); } } } collector.getOrThrowException(); return Schema.recordOf("record", fields); }
Source:
public void consumerChangeDetection() { Consumer existing = getFakeConsumer(); Set<ConsumerCapability> caps1 = new HashSet<ConsumerCapability>(); Set<ConsumerCapability> caps2 = new HashSet<ConsumerCapability>(); ConsumerCapability cca = new ConsumerCapability(existing, "capability_a"); ConsumerCapability ccb = new ConsumerCapability(existing, "capability_b"); ConsumerCapability ccc = new ConsumerCapability(existing, "capability_c"); caps1.add(cca); caps1.add(ccb); caps1.add(ccc); caps2.add(ccb); existing.setCapabilities(caps1); Consumer toUpdate = getFakeConsumer(); toUpdate.setCapabilities(caps1); assertFalse(resource.performConsumerUpdates(existing, toUpdate, null)); toUpdate.setCapabilities(caps2); assertTrue(resource.performConsumerUpdates(existing, toUpdate, null)); toUpdate.setCapabilities(null); assertFalse(resource.performConsumerUpdates(existing, toUpdate, null)); }

Target:
public void consumerChangeDetection() { Consumer existing = getFakeConsumer(); Set<ConsumerCapability> caps1 = new HashSet<ConsumerCapability>(); Set<ConsumerCapability> caps2 = new HashSet<ConsumerCapability>(); ConsumerCapability cca = new ConsumerCapability(existing, "capability_a"); ConsumerCapability ccb = new ConsumerCapability(existing, "capability_b"); ConsumerCapability ccc = new ConsumerCapability(existing, "capability_c"); caps1.add(cca); caps1.add(ccb); caps1.add(ccc); caps2.add(ccb); existing.setCapabilities(caps1); Consumer update = getFakeConsumer(); update.setCapabilities(caps1); assertFalse(resource.performConsumerUpdates(update, existing, null)); update.setCapabilities(caps2); assertTrue(resource.performConsumerUpdates(update, existing, null)); update = getFakeConsumer(); assertFalse(resource.performConsumerUpdates(update, existing, null)); }
Source:
public final boolean getBoolean(final String property) { final String val = this.properties.getProperty(property).toUpperCase(); if (val == null) throw new NullPointerException(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; }

Target:
public final boolean getBoolean(final String property) { final String val = this.properties.get(property).toUpperCase(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; }
Source:
private String formatLine(String str) { if (str.isEmpty()) { return ""; } else { String safeString = SafeHtmlUtils.htmlEscape(str); return "<nobr>" + safeString +"</nobr><br>"; } }

Target:
private String formatLine(String str) { if (str.trim().isEmpty()) { return ""; } else { String safeString; if (str.matches("\\[.*\\].*")) { safeString = SafeHtmlUtils.htmlEscape(str).replaceFirst("]", "]</span>"); return "<nobr><span style='color:gray;'>" + safeString +"</nobr><br>"; } else { safeString = SafeHtmlUtils.htmlEscape(str); return "<nobr>" + safeString +"</nobr><br>"; } } }
Source:
static public String sendHttpPutRequest(String url) { String response = null; try { return HttpUtil.executeUrl("PUT", url, 1000); } catch (IOException e) { logger.error("Fatal transport error: {}",e); } return response; }

Target:
static public String sendHttpPutRequest(String url) { String response = null; try { response = HttpUtil.executeUrl("PUT", url, 1000); } catch (IOException e) { logger.error("Fatal transport error: {}", e); } return response; }
Source:
private ArrayList<Integer> getAvailableSeasons() { final ArrayList<Integer> availableSeasons = new ArrayList<>(); for (Episode episode : show.episodes) { if (!availableSeasons.contains(episode.season)) { availableSeasons.add(episode.season); } } Collections.sort(availableSeasons); return availableSeasons; }

Target:
private List<Integer> getAvailableSeasons() { final List<Integer> availableSeasons = new ArrayList<>(); for (Episode episode : show.episodes) { if (!availableSeasons.contains(episode.season)) { availableSeasons.add(episode.season); } } Collections.sort(availableSeasons); return availableSeasons; }
Source:
public static synchronized void startAsynchronousLogging(){ if (m_asynchLoggerPool == null) { m_asynchLoggerPool = Boolean.getBoolean("DISABLE_ASYNC_LOGGING") ? null : new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new LoggerThreadFactory()); if (m_asynchLoggerPool != null) { try { m_asynchLoggerPool.submit(new Runnable() { @Override public void run() }).get(); } catch (InterruptedException | ExecutionException e) { } } } }

Target:
public static synchronized void startAsynchronousLogging(){ if (m_asynchLoggerPool == null && !Boolean.getBoolean("DISABLE_ASYNC_LOGGING")) { m_asynchLoggerPool = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new LoggerThreadFactory()); try { m_asynchLoggerPool.submit(new Runnable() { @Override public void run() }).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Unable to prime asynchronous logging", e); } } }
Source:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } try { String addrString = InetAddresses.toAddrString(InetAddress.getByAddress(getSlice(block, position).getBytes(0, 2 * Long.BYTES))); String prefixString = Integer.toString(getSlice(block, position).getByte(2 * Long.BYTES) & 0xff); return addrString + "/" + prefixString; } catch (UnknownHostException e) { throw new IllegalArgumentException(); } }

Target:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } try { String addrString = InetAddresses.toAddrString(InetAddress.getByAddress(getSlice(block, position).getBytes(0, 2 * Long.BYTES))); String prefixString = Integer.toString(getSlice(block, position).getByte(2 * Long.BYTES) & 0xff); return addrString + "/" + prefixString; } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } }
Source:
public String getForegroundWindowTitle() { if (!isOnWindows) { return null; } HWND window = User32.INSTANCE.GetForegroundWindow(); if (window != null) { char[] textBuffer = new char[255]; User32.INSTANCE.GetWindowText(window, textBuffer, 255); return new String(textBuffer).trim(); } else { return null; } }

Target:
private String getForegroundWindowTitle() { if (!isWindows) { return null; } HWND window = User32.INSTANCE.GetForegroundWindow(); if (window == null) { return null; } char[] textBuffer = new char[255]; User32.INSTANCE.GetWindowText(window, textBuffer, 255); return new String(textBuffer).trim(); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MultiSourceTrackingToken that = (MultiSourceTrackingToken) o; if (this.trackingTokens.size() != that.trackingTokens.size()) { return false; } for (Map.Entry<String, TrackingToken> trackingTokenEntry : trackingTokens.entrySet()) { try { if ( trackingTokenEntry.getValue() == null && that.trackingTokens.get(trackingTokenEntry.getKey()) == null) { return true; } if (!trackingTokenEntry.getValue().equals(that.trackingTokens.get(trackingTokenEntry.getKey()))) { return false; } } catch (NullPointerException ex) { logger.warn("A constituent token has not been initialized"); return false; } } return true; }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MultiSourceTrackingToken that = (MultiSourceTrackingToken) o; if (this.trackingTokens.size() != that.trackingTokens.size()) { return false; } return trackingTokens.entrySet() .stream() .allMatch(trackingTokenEntry -> Objects.equals(trackingTokenEntry.getValue(), that.trackingTokens.get(trackingTokenEntry.getKey()))); }
Source:
public static void setupRegionReplicaReplication(Configuration conf) throws IOException { if (!isRegionReplicaReplicationEnabled(conf)) { return; } try (Connection connection = ConnectionFactory.createConnection(conf); Admin admin = connection.getAdmin()) { ReplicationPeerConfig peerConfig = null; peerConfig = admin.getReplicationPeerConfig(REGION_REPLICA_REPLICATION_PEER); if (peerConfig == null) { LOG.info("Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist. Creating..."); peerConfig = new ReplicationPeerConfig(); peerConfig.setClusterKey(ZKConfig.getZooKeeperClusterKey(conf)); peerConfig.setReplicationEndpointImpl(RegionReplicaReplicationEndpoint.class.getName()); admin.addReplicationPeer(REGION_REPLICA_REPLICATION_PEER, peerConfig); } } catch (ReplicationPeerNotFoundException e) { LOG.warn( "Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist", e); } }

Target:
public static void setupRegionReplicaReplication(Configuration conf) throws IOException { if (!isRegionReplicaReplicationEnabled(conf)) { return; } try (Connection connection = ConnectionFactory.createConnection(conf); Admin admin = connection.getAdmin()) { ReplicationPeerConfig peerConfig = null; try { peerConfig = admin.getReplicationPeerConfig(REGION_REPLICA_REPLICATION_PEER); } catch (ReplicationPeerNotFoundException e) { LOG.warn( "Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist", e); } if (peerConfig == null) { LOG.info("Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist. Creating..."); peerConfig = new ReplicationPeerConfig(); peerConfig.setClusterKey(ZKConfig.getZooKeeperClusterKey(conf)); peerConfig.setReplicationEndpointImpl(RegionReplicaReplicationEndpoint.class.getName()); admin.addReplicationPeer(REGION_REPLICA_REPLICATION_PEER, peerConfig); } } }
Source:
public void beginFunction() { collectSet = new HashSet<>(); }

Target:
public void beginFunction() { collectSet.clear(); }
Source:
public ResourceCounter freeReservedSlot(AllocationID allocationId, @Nullable Throwable cause, long currentTime) { LOG.debug("Release slot {}.", allocationId); final Optional<AllocatedSlot> releasedSlot = slotPool.freeReservedSlot(allocationId, currentTime); Optional<ResourceCounter> previouslyFulfilledRequirement = releasedSlot.map(Collections::singleton).map(this::getFulfilledRequirements); releasedSlot.ifPresent(allocatedSlot -> { releasePayload(Collections.singleton(allocatedSlot), cause); tryToFulfillResourceRequirement(allocatedSlot); notifyNewSlots.accept(Collections.singletonList(allocatedSlot)); }); return previouslyFulfilledRequirement.orElseGet(ResourceCounter::empty); }

Target:
public ResourceCounter freeReservedSlot(AllocationID allocationId, @Nullable Throwable cause, long currentTime) { LOG.debug("Free reserved slot {}.", allocationId); final Optional<AllocatedSlot> freedSlot = slotPool.freeReservedSlot(allocationId, currentTime); Optional<ResourceCounter> previouslyFulfilledRequirement = freedSlot.map(Collections::singleton).map(this::getFulfilledRequirements); freedSlot.ifPresent(allocatedSlot -> { releasePayload(Collections.singleton(allocatedSlot), cause); tryToFulfillResourceRequirement(allocatedSlot); notifyNewSlots.accept(Collections.singletonList(allocatedSlot)); }); return previouslyFulfilledRequirement.orElseGet(ResourceCounter::empty); }
Source:
public long readFrom(ReadableByteChannel channel) throws IOException { long bytesRead = 0; if (buffer == null) { if (sizeBuffer == null) { sizeBuffer = ByteBufAllocator.DEFAULT.heapBuffer(8); } try { bytesRead = readBytesFromReadableByteChannel(channel, sizeBuffer); if (bytesRead < 0) { throw new EOFException(); } } catch (IOException e) { sizeBuffer.release(); sizeBuffer = null; throw e; } if (sizeBuffer.writerIndex() == sizeBuffer.capacity()) { sizeToRead = sizeBuffer.readLong(); sizeRead += 8; sizeBuffer.release(); buffer = ByteBufAllocator.DEFAULT.heapBuffer((int) sizeToRead - 8); } } if (buffer != null && sizeRead < sizeToRead) { long bytesReadFromChannel; try { bytesReadFromChannel = readBytesFromReadableByteChannel(channel, buffer); if (bytesReadFromChannel < 0) { throw new EOFException(); } } catch (IOException e) { buffer.release(); buffer = null; throw e; } sizeRead += bytesReadFromChannel; bytesRead += bytesReadFromChannel; } logger.trace("size read from channel {}", sizeRead); return bytesRead; }

Target:
public long readFrom(ReadableByteChannel channel) throws IOException { long bytesRead = 0; if (buffer == null) { if (sizeBuffer == null) { sizeBuffer = ByteBufAllocator.DEFAULT.heapBuffer(Long.BYTES); } try { bytesRead = readBytesFromReadableByteChannel(channel, sizeBuffer); if (bytesRead < 0) { throw new EOFException(); } } catch (IOException e) { sizeBuffer.release(); sizeBuffer = null; throw e; } if (sizeBuffer.writerIndex() == sizeBuffer.capacity()) { sizeToRead = sizeBuffer.readLong(); sizeRead += Long.BYTES; sizeBuffer.release(); buffer = ByteBufAllocator.DEFAULT.heapBuffer((int) sizeToRead - Long.BYTES); } } if (buffer != null && sizeRead < sizeToRead) { long bytesReadFromChannel; try { bytesReadFromChannel = readBytesFromReadableByteChannel(channel, buffer); if (bytesReadFromChannel < 0) { throw new EOFException(); } } catch (IOException e) { buffer.release(); buffer = null; throw e; } sizeRead += bytesReadFromChannel; bytesRead += bytesReadFromChannel; } logger.trace("size read from channel {}", sizeRead); return bytesRead; }
Source:
private JMenuItem createItemForUser(User user) { String userName = ModelFormatUtils.getDisplayName(user); String userNameShort = userName; int index = userNameShort.indexOf("@"); if (index > -1) { userNameShort = userNameShort.substring(0, index); } JMenuItem menuItem = new JMenuItem(menuItemPrefix + userNameShort); menuItem.setForeground(FOREGROUND_COLOR); menuItem.setBackground(BACKGROUND_COLOR); FollowModeManager currentFollowModeManager = followModeManager; User currentlyFollowedUser = null; if (currentFollowModeManager != null) { currentlyFollowedUser = currentFollowModeManager.getFollowedUser(); } if (currentlyFollowedUser != null) { String currentUserName = ModelFormatUtils.getDisplayName(currentlyFollowedUser); if (currentUserName.equalsIgnoreCase(userNameShort)) { menuItem.setEnabled(false); } } menuItem.setActionCommand(userName); menuItem.addActionListener(e -> followModeAction.execute(e.getActionCommand())); return menuItem; }

Target:
private JMenuItem createItemForUser(User user) { String userName = ModelFormatUtils.getDisplayName(user); String userNameShort = userName; int index = userNameShort.indexOf("@"); if (index > -1) { userNameShort = userNameShort.substring(0, index); } JMenuItem menuItem = new JBMenuItem(menuItemPrefix + userNameShort); menuItem.setForeground(FOREGROUND_COLOR); menuItem.setBackground(BACKGROUND_COLOR); FollowModeManager currentFollowModeManager = followModeManager; User currentlyFollowedUser = null; if (currentFollowModeManager != null) { currentlyFollowedUser = currentFollowModeManager.getFollowedUser(); } if (currentlyFollowedUser != null) { String currentUserName = ModelFormatUtils.getDisplayName(currentlyFollowedUser); if (currentUserName.equalsIgnoreCase(userNameShort)) { menuItem.setEnabled(false); } } menuItem.setActionCommand(userName); menuItem.addActionListener(e -> followModeAction.execute(e.getActionCommand())); return menuItem; }
Source:
public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); if (phoneNumber != null) { return PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164); } return null; }

Target:
public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); return phoneNumber != null ? PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164) : null; }
Source:
protected @NonNull List<@NonNull TimeGraphEntryModel> getTree(@NonNull ITmfStateSystem ss, @NonNull TimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { Builder<@NonNull TimeGraphEntryModel> builder = new Builder<>(); int quark = ITmfStateSystem.ROOT_ATTRIBUTE; long parentId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); builder.add(new TimeGraphEntryModel(parentId, -1, getTrace().getName(), getTrace().getStartTime().toNanos(), Long.MAX_VALUE)); addChildren(ss, builder, quark, parentId); return builder.build(); }

Target:
protected @NonNull List<@NonNull TimeGraphEntryModel> getTree(@NonNull ITmfStateSystem ss, @NonNull TimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { Builder<@NonNull TimeGraphEntryModel> builder = new Builder<>(); long parentId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); builder.add(new TimeGraphEntryModel(parentId, -1, getTrace().getName(), ss.getStartTime(), ss.getCurrentEndTime())); addChildren(ss, builder, ITmfStateSystem.ROOT_ATTRIBUTE, parentId); return builder.build(); }
Source:
public void parseMethodsInLike() throws Exception { this.assertTranslate("SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj where obj.first_name like LOWER('%DMIN%')", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 where ( obj_first_name1.value like LOWER ( '%DMIN%' ) ) and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); this.assertTranslate( "SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj where obj.first_name like LOWER(CONCAT('%', 'DMIN%'))", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 where ( obj_first_name1.value like LOWER ( CONCAT ( '%' , 'DMIN%' ) ) ) and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); }

Target:
public void parseMethodsInLike() throws Exception { assertTranslate( "SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj " + "where obj.first_name like LOWER('%DMIN%')", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 " + "where ( obj_first_name1.value like LOWER ( '%DMIN%' ) ) " + "and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' " + "and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); assertTranslate( "SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj " + "where obj.first_name like LOWER(CONCAT('%', 'DMIN%'))", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 " + "where ( obj_first_name1.value like LOWER ( CONCAT ( '%' , 'DMIN%' ) ) ) " + "and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' " + "and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); }
Source:
private SchedulingManager mockScheduler() { SchedulingManager mock = Mockito.mock(SchedulingManager.class); Mockito.when(mock.getClusterPolicies()).thenReturn(Collections.<ClusterPolicy>emptyList()); return mock; }

Target:
private SchedulingManager mockScheduler() { SchedulingManager mock = mock(SchedulingManager.class); when(mock.getClusterPolicies()).thenReturn(Collections.<ClusterPolicy>emptyList()); return mock; }
Source:
public long blah(FContext ctx, int num, String Str, Event event) throws TException, AwesomeException, actual_base.java.api_exception { FBoundableMemoryOutputBuffer memoryBuffer = new FBoundableMemoryOutputBuffer(transport.getMaxRequestSize()); FProtocol oprot = this.protocolFactory.getProtocol(memoryBuffer); BlockingQueue<Object> result = new ArrayBlockingQueue<>(1); transport.register(ctx, recvBlahHandler(ctx, result)); try { oprot.writeRequestHeader(ctx); oprot.writeMessageBegin(new TMessage("blah", TMessageType.CALL, 0)); blah_args args = new blah_args(); args.setNum(num); args.setStr(Str); args.setEvent(event); args.write(oprot); oprot.writeMessageEnd(); transport.send(memoryBuffer.getWriteBytes()); Object res = null; try { res = result.poll(ctx.getTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new TApplicationException(TApplicationException.INTERNAL_ERROR, "blah interrupted: " + e.getMessage()); } if (res == null) { throw new FTimeoutException("blah timed out"); } if (res instanceof TException) { throw (TException) res; } blah_result r = (blah_result) res; if (r.isSetSuccess()) { return r.success; } if (r.awe != null) { throw r.awe; } if (r.api != null) { throw r.api; } throw new TApplicationException(TApplicationException.MISSING_RESULT, "blah failed: unknown result"); } finally { transport.unregister(ctx); } }

Target:
public long blah(FContext ctx, int num, String Str, Event event) throws TException, AwesomeException, actual_base.java.api_exception { TMemoryOutputBuffer memoryBuffer = new TMemoryOutputBuffer(transport.getRequestSizeLimit()); FProtocol oprot = this.protocolFactory.getProtocol(memoryBuffer); BlockingQueue<Object> result = new ArrayBlockingQueue<>(1); transport.register(ctx, recvBlahHandler(ctx, result)); try { oprot.writeRequestHeader(ctx); oprot.writeMessageBegin(new TMessage("blah", TMessageType.CALL, 0)); blah_args args = new blah_args(); args.setNum(num); args.setStr(Str); args.setEvent(event); args.write(oprot); oprot.writeMessageEnd(); transport.send(memoryBuffer.getWriteBytes()); Object res = null; try { res = result.poll(ctx.getTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new TApplicationException(TApplicationException.INTERNAL_ERROR, "blah interrupted: " + e.getMessage()); } if (res == null) { throw new FTimeoutException("blah timed out"); } if (res instanceof TException) { throw (TException) res; } blah_result r = (blah_result) res; if (r.isSetSuccess()) { return r.success; } if (r.awe != null) { throw r.awe; } if (r.api != null) { throw r.api; } throw new TApplicationException(TApplicationException.MISSING_RESULT, "blah failed: unknown result"); } finally { transport.unregister(ctx); } }
Source:
private AnnotationPainter initializeCommentColoring(ISourceViewer viewer) { AnnotationPainter commentPainter = new AnnotationPainter(viewer, null) { @Override protected IAnnotationModel findAnnotationModel(ISourceViewer sourceViewer) { if (sourceViewer.getDocument() instanceof CommentableCompareItem) { return ((CommentableCompareItem) sourceViewer.getDocument()).getEditableComments(); } return null; } @Override public void applyTextPresentation(TextPresentation tp) { AnnotationModel originalCommentsModel = ((CommentableCompareItem) viewer.getDocument()) .getEditableComments(); Iterator<?> it = originalCommentsModel.getAnnotationIterator(); while (it.hasNext()) { GerritCommentAnnotation object = (GerritCommentAnnotation) it.next(); Position positingExistingComment = originalCommentsModel.getPosition(object); StyleRange range; if (isToggle) { range = new StyleRange(positingExistingComment.getOffset(), positingExistingComment.getLength(), Display.getCurrent().getSystemColor(SWT.COLOR_BLACK), Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW)); setAnnotationTypeColor(GerritCommentAnnotation.TYPE, Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW)); isToggle = false; } else { range = new StyleRange(positingExistingComment.getOffset(), positingExistingComment.getLength(), Display.getCurrent().getSystemColor(SWT.COLOR_BLACK), Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW)); setAnnotationTypeColor(GerritCommentAnnotation.TYPE, Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW)); isToggle = true; } tp.mergeStyleRange(range); } super.applyTextPresentation(tp); } }; Object strategyID = new Object(); HighlightingStrategy paintingStrategy = new AnnotationPainter.HighlightingStrategy(); commentPainter.addTextStyleStrategy(strategyID, paintingStrategy); commentPainter.addAnnotationType(GerritCommentAnnotation.TYPE, strategyID); commentPainter.addHighlightAnnotationType(strategyID); return commentPainter; }

Target:
private AnnotationPainter initializeCommentColoring(ISourceViewer viewer) { return new CommentAnnotationPainter(viewer, null); }
Source:
private void handleBitbucketCloudEvent(Event event, Map postedEvent) { String repoProject = ""; String slug = ""; String hash = ""; String branch = ""; BitbucketCloudEvent bitbucketCloudEvent = objectMapper.convertValue(postedEvent, BitbucketCloudEvent.class); if (bitbucketCloudEvent.repository != null) { slug = emptyOrDefault(bitbucketCloudEvent.repository.fullName, ""); if (bitbucketCloudEvent.repository.owner != null) { repoProject = emptyOrDefault(bitbucketCloudEvent.repository.owner.username, ""); } } if (bitbucketCloudEvent.pullRequest != null) { BitbucketCloudEvent.PullRequest pullRequest = bitbucketCloudEvent.pullRequest; if (pullRequest.mergeCommit != null) { hash = emptyOrDefault(pullRequest.mergeCommit.hash, ""); } if (pullRequest.destination != null && pullRequest.destination.branch != null) { branch = emptyOrDefault(pullRequest.destination.branch.name, ""); } } else if (bitbucketCloudEvent.push != null) { BitbucketCloudEvent.Push push = bitbucketCloudEvent.push; if (push.changes.size() > 0) { BitbucketCloudEvent.Change change = push.changes.get(0); if (change.newObj != null) { branch = emptyOrDefault(change.newObj.name, ""); } if (change.commits.size() > 0) { BitbucketCloudEvent.Commit commit = change.commits.get(0); hash = emptyOrDefault(commit.hash,""); } } } event.content.put("repoProject", repoProject); event.content.put("slug", slug); event.content.put("hash", hash); event.content.put("branch", branch); }

Target:
private void handleBitbucketCloudEvent(Event event, Map postedEvent) { String repoProject = ""; String slug = ""; String hash = ""; String branch = ""; BitbucketCloudEvent bitbucketCloudEvent = objectMapper.convertValue(postedEvent, BitbucketCloudEvent.class); if (bitbucketCloudEvent.repository != null) { slug = emptyOrDefault(bitbucketCloudEvent.repository.fullName, ""); if (bitbucketCloudEvent.repository.owner != null) { repoProject = emptyOrDefault(bitbucketCloudEvent.repository.owner.username, ""); } } if (bitbucketCloudEvent.pullRequest != null) { BitbucketCloudEvent.PullRequest pullRequest = bitbucketCloudEvent.pullRequest; if (pullRequest.mergeCommit != null) { hash = emptyOrDefault(pullRequest.mergeCommit.hash, ""); } if (pullRequest.destination != null && pullRequest.destination.branch != null) { branch = emptyOrDefault(pullRequest.destination.branch.name, ""); } } else if (bitbucketCloudEvent.push != null) { BitbucketCloudEvent.Push push = bitbucketCloudEvent.push; if (!push.changes.isEmpty()) { BitbucketCloudEvent.Change change = push.changes.get(0); if (change.newObj != null) { branch = emptyOrDefault(change.newObj.name, ""); } if (!change.commits.isEmpty()) { BitbucketCloudEvent.Commit commit = change.commits.get(0); hash = emptyOrDefault(commit.hash,""); } } } event.content.put("repoProject", repoProject); event.content.put("slug", slug); event.content.put("hash", hash); event.content.put("branch", branch); }
Source:
private void configWithValues(int maxCellTsPairsToExamine, int candidateBatchSize, int deleteBatchSize) { adjustableConfig = AdjustableSweepBatchConfigSource.create(() -> new SweepBatchConfig() { @Override public int maxCellTsPairsToExamine() { return maxCellTsPairsToExamine; } @Override public int candidateBatchSize() { return candidateBatchSize; } @Override public int deleteBatchSize() { return deleteBatchSize; } }); updatePreviousValues(); }

Target:
private void configWithValues(int maxCellTsPairsToExamine, int candidateBatchSize, int deleteBatchSize) { adjustableConfig = AdjustableSweepBatchConfigSource.create(() -> ImmutableSweepBatchConfig.builder() .maxCellTsPairsToExamine(maxCellTsPairsToExamine) .candidateBatchSize(candidateBatchSize) .deleteBatchSize(deleteBatchSize) .build() ); updatePreviousValues(); }
Source:
public Response cancelAction(@PathParam("id") String id) throws URISyntaxException { IAtsUser asUser = atsApi.getUserService().getUserByAccountId(httpHeaders); IAtsWorkItem workItem = atsApi.getQueryService().getWorkItem(id); if (workItem.isInWork()) { Conditions.assertNotNull(workItem, "workItem can not be found"); if (asUser == null) { asUser = AtsCoreUsers.SYSTEM_USER; } ActionOperations ops = new ActionOperations(asUser, workItem, atsApi); ops.setActionAttributeByType(id, AttributeKey.State.name(), Arrays.asList("Cancelled")); } String htmlUrl = atsApi.getWorkItemService().getHtmlUrl(workItem, atsApi); return Response.temporaryRedirect(new URI(htmlUrl)).build(); }

Target:
public Response cancelAction(@PathParam("id") String id) { IAtsUser asUser = atsApi.getUserService().getUserByAccountId(httpHeaders); IAtsWorkItem workItem = atsApi.getQueryService().getWorkItem(id); if (workItem.isInWork()) { Conditions.assertNotNull(workItem, "workItem can not be found"); if (asUser == null) { asUser = AtsCoreUsers.SYSTEM_USER; } ActionOperations ops = new ActionOperations(asUser, workItem, atsApi); ops.setActionAttributeByType(id, AttributeKey.State.name(), Arrays.asList("Cancelled")); } String htmlUrl = atsApi.getWorkItemService().getHtmlUrl(workItem, atsApi); try { return Response.temporaryRedirect(new URI(htmlUrl)).build(); } catch (Exception ex) { throw new OseeWrappedException(ex); } }
Source:
private <V> List<V> runAllTasksCancelOnFailure(List<Callable<V>> tasks) { if (tasks.size() == 1) { try { return Collections.singletonList(tasks.get(0).call()); } catch (Exception e) { throw Throwables.throwUncheckedException(e); } } List<Future<V>> futures = Lists.newArrayListWithCapacity(tasks.size()); for (Callable<V> task : tasks) { futures.add(executor.submit(task)); } try { List<V> results = Lists.newArrayListWithCapacity(tasks.size()); for (Future<V> future : futures) { results.add(future.get()); } return results; } catch (ExecutionException e) { throw Throwables.throwUncheckedException(e.getCause()); } catch (Exception e) { throw Throwables.throwUncheckedException(e); } finally { for (Future<V> future : futures) { future.cancel(true); } } }

Target:
private <V> List<V> runAllTasksCancelOnFailure(List<Callable<V>> tasks) { if (tasks.size() == 1) { try { return Collections.singletonList(tasks.get(0).call()); } catch (Exception e) { throw Throwables.unwrapAndThrowUncheckedException(e); } } List<Future<V>> futures = Lists.newArrayListWithCapacity(tasks.size()); for (Callable<V> task : tasks) { futures.add(executor.submit(task)); } try { List<V> results = Lists.newArrayListWithCapacity(tasks.size()); for (Future<V> future : futures) { results.add(future.get()); } return results; } catch (Exception e) { throw Throwables.unwrapAndThrowUncheckedException(e); } finally { for (Future<V> future : futures) { future.cancel(true); } } }
Source:
public Boolean visitScope(Scope scope) { Provider<ScopeCleanupMarker> scopedMarkerProvider = scope.scope(Key.get(ScopeCleanupMarker.class), markerProvider); ManagedInstanceAction instanceAction = new ManagedInstanceAction(injectee, lifecycleActions); ScopeCleanupMarker marker = scopedMarkerProvider.get(); Integer markerKey = System.identityHashCode(marker); synchronized(scopedCleanupActions) { if (scopedCleanupActions.containsKey(markerKey)) { scopedCleanupActions.get(markerKey).add(scopedMarkerProvider, instanceAction); } else { scopedCleanupActions.put(markerKey, new ScopeCleanupAction(markerKey, scopedMarkerProvider, marker, markerReferenceQueue, instanceAction)); } } return true; }

Target:
public Boolean visitScope(Scope scope) { Provider<ScopeCleanupMarker> scopedMarkerProvider = scope.scope(MARKER_KEY, markerProvider); ManagedInstanceAction instanceAction = new ManagedInstanceAction(injectee, lifecycleActions); ScopeCleanupMarker marker = scopedMarkerProvider.get(); UUID markerKey = marker.getId(); synchronized(scopedCleanupActions) { if (scopedCleanupActions.containsKey(markerKey)) { scopedCleanupActions.get(markerKey).add(scopedMarkerProvider, instanceAction); } else { scopedCleanupActions.put(markerKey, new ScopeCleanupAction(markerKey, scopedMarkerProvider, marker, markerReferenceQueue, instanceAction)); } } return true; }
Source:
public long deleteAll(Iterator<ObjectId> ids) { long count = 0; while (ids.hasNext()) { if (delete(ids.next())) count += 1; } return count; }

Target:
public long deleteAll(Iterator<ObjectId> ids) { Iterator<List<ObjectId>> chunks = Iterators.partition(ids, 500); long count = 0; while (chunks.hasNext()) { count += deleteChunk(chunks.next()); } return count; }
Source:
protected abstract PollingResult checkForChanges(Job<?, ?> project) throws IOException, InterruptedException; public boolean checkout(Run<?, ?> build, Launcher launcher, FilePath jenkinsWorkspace, TaskListener listener, File changelogFile) throws IOException, InterruptedException { setup(launcher, jenkinsWorkspace, listener); if(server.isServerDisabled()){ listener.fatalError("Checkout skipped due to server disabled!"); throw new InterruptedException(); } if (StringUtils.isEmpty(scm.getDepot())) { throw new IllegalStateException("Must specify a depot"); } if (StringUtils.isEmpty(scm.getStream())) { throw new IllegalStateException("Must specify a stream"); } final EnvVars environment = build.getEnvironment(listener); accurevEnv.putAll(environment); localStream = environment.expand(scm.getStream()); listener.getLogger().println("Getting a list of streams..."); final Map<String, AccurevStream> streams = ShowStreams.getStreams(scm, localStream, server, accurevEnv, jenkinsWorkspace, listener, launcher); if (streams == null) { throw new IllegalStateException("Stream(s) not found"); } if (!streams.containsKey(localStream)) { listener.fatalError("The specified stream, '" + localStream + "' does not appear to exist!"); throw new IllegalStateException("Specified stream not found"); } if (server.isUseColor()) { setStreamColor(); } return checkout(build, changelogFile) && populate(build) && captureChangeLog(build, changelogFile, streams); }

Target:
protected abstract PollingResult checkForChanges(Job<?, ?> project) throws IOException, InterruptedException; public boolean checkout(Run<?, ?> build, Launcher launcher, FilePath jenkinsWorkspace, TaskListener listener, File changelogFile) throws IOException, InterruptedException { setup(launcher, jenkinsWorkspace, listener); if(server.isServerDisabled()){ listener.fatalError("Checkout skipped due to server disabled!"); throw new InterruptedException("Checkout skipped"); } if (StringUtils.isEmpty(scm.getDepot())) { throw new IllegalStateException("Must specify a depot"); } if (StringUtils.isEmpty(scm.getStream())) { throw new IllegalStateException("Must specify a stream"); } final EnvVars environment = build.getEnvironment(listener); accurevEnv.putAll(environment); localStream = environment.expand(scm.getStream()); listener.getLogger().println("Getting a list of streams..."); final Map<String, AccurevStream> streams = ShowStreams.getStreams(scm, localStream, server, accurevEnv, jenkinsWorkspace, listener, launcher); if (streams == null) { throw new IllegalStateException("Stream(s) not found"); } if (!streams.containsKey(localStream)) { listener.fatalError("The specified stream, '" + localStream + "' does not appear to exist!"); throw new IllegalStateException("Specified stream not found"); } if (server.isUseColor()) { setStreamColor(); } return checkout(build, changelogFile) && populate(build) && captureChangeLog(build, changelogFile, streams); }
Source:
protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command) throws InterpretationException { ArrayList<Item> items = getMatchingItems(language, labelFragments, command.getClass()); if (items.size() < 1) { throw new InterpretationException(language.getString("no_objects")); } else if (items.size() > 1) { throw new InterpretationException(language.getString("multiple_objects")); } else { Item item = items.get(0); if (command instanceof State) { try { State newState = (State) command; State oldState = item.getStateAs(newState.getClass()); if (oldState.equals(newState)) { String template = language.getString("state_already_singular"); String cmdName = "state_" + command.toString().toLowerCase(); String stateText = null; try { stateText = language.getString(cmdName); } catch (Exception e) { stateText = language.getString("state_current"); } return template.replace("<state>", stateText); } } catch (Exception ex) { logger.debug("Failed constructing response: {}", ex.getMessage()); return language.getString(ERROR); } } eventPublisher.post(ItemEventFactory.createCommandEvent(item.getName(), command)); return language.getString(OK); } }

Target:
protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command) throws InterpretationException { ArrayList<Item> items = getMatchingItems(language, labelFragments, command.getClass()); if (items.size() < 1) { throw new InterpretationException(language.getString(NO_OBJECTS)); } else if (items.size() > 1) { throw new InterpretationException(language.getString(MULTIPLE_OBJECTS)); } else { Item item = items.get(0); if (command instanceof State) { try { State newState = (State) command; State oldState = item.getStateAs(newState.getClass()); if (oldState.equals(newState)) { String template = language.getString(STATE_ALREADY_SINGULAR); String cmdName = "state_" + command.toString().toLowerCase(); String stateText = null; try { stateText = language.getString(cmdName); } catch (Exception e) { stateText = language.getString(STATE_CURRENT); } return template.replace("<state>", stateText); } } catch (Exception ex) { logger.debug("Failed constructing response: {}", ex.getMessage()); return language.getString(ERROR); } } eventPublisher.post(ItemEventFactory.createCommandEvent(item.getName(), command)); return language.getString(OK); } }
Source:
public Map<String, Object> moveStudyFolder(final HttpServletRequest req) { final String sourceId = req.getParameter("sourceId"); final String targetId = req.getParameter("targetId"); final Map<String, Object> resultsMap = new HashMap<>(); try { final GermplasmList gpList = this.germplasmListManager.getGermplasmListById(Integer.parseInt(sourceId)); if (targetId != null && PROGRAM_LISTS.equals(targetId) && CROP_LISTS.equals(targetId)) { final GermplasmList parent = this.germplasmListManager.getGermplasmListById(Integer.parseInt(targetId)); gpList.setParent(parent); } else { gpList.setParent(null); } if (CROP_LISTS.equals(targetId)) { gpList.setProgramUUID(null); } else { gpList.setProgramUUID(this.contextUtil.getCurrentProgramUUID()); } this.germplasmListManager.updateGermplasmList(gpList); } catch (final Exception e) { GermplasmTreeController.LOG.error(e.getMessage(), e); } return resultsMap; }

Target:
public Map<String, Object> moveStudyFolder(final HttpServletRequest req) { final String sourceId = req.getParameter("sourceId"); final String targetId = req.getParameter("targetId"); final Map<String, Object> resultsMap = new HashMap<>(); try { final GermplasmList gpList = this.germplasmListManager.getGermplasmListById(Integer.parseInt(sourceId)); if (targetId == null || PROGRAM_LISTS.equals(targetId) || CROP_LISTS.equals(targetId)) { gpList.setParent(null); } else { final GermplasmList parent = this.germplasmListManager.getGermplasmListById(Integer.parseInt(targetId)); gpList.setParent(parent); } if (CROP_LISTS.equals(targetId)) { gpList.setProgramUUID(null); } else { gpList.setProgramUUID(this.contextUtil.getCurrentProgramUUID()); } this.germplasmListManager.updateGermplasmList(gpList); } catch (final Exception e) { GermplasmTreeController.LOG.error(e.getMessage(), e); } return resultsMap; }