auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void findMetrics( @Suspended final AsyncResponse asyncResponse, @ApiParam(value = "Queried metric type", required = false, allowableValues = "[gauge, availability, counter]") @QueryParam("type") MetricType metricType, @ApiParam(value = "List of tags", required = false) @QueryParam ("tags") Tags tags) { if(metricType != null && !MetricType.userTypes().stream().filter(t -> metricType == t) .findAny().isPresent()) { asyncResponse.resume(badRequest(new ApiError("Incorrect type param"))); return; } Observable<Metric> metricObservable = (tags == null) ? metricsService.findMetrics(tenantId, metricType) : metricsService.findMetricsWithTags(tenantId, tags.getTags(), metricType); metricObservable .map(MetricDefinition::new) .toList() .map(ApiUtils::collectionToResponse) .subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t))); }

Target:
public void findMetrics( @Suspended final AsyncResponse asyncResponse, @ApiParam(value = "Queried metric type", required = false, allowableValues = "[gauge, availability, counter]") @QueryParam("type") MetricType metricType, @ApiParam(value = "List of tags", required = false) @QueryParam ("tags") Tags tags) { if(metricType != null && !MetricType.userTypes().contains(metricType)) { asyncResponse.resume(badRequest(new ApiError("Incorrect type param"))); return; } Observable<Metric> metricObservable = (tags == null) ? metricsService.findMetrics(tenantId, metricType) : metricsService.findMetricsWithTags(tenantId, tags.getTags(), metricType); metricObservable .map(MetricDefinition::new) .toList() .map(ApiUtils::collectionToResponse) .subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t))); }
Source:
public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { ITmfStateInterval ret = super.doSingularQuery(t, attributeQuark); if (ret != null) { return ret; } fRwl.readLock().lock(); for (HTInterval interval : fCurrentChunk) { if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } fRwl.readLock().unlock(); for (Iterable<HTInterval> intervals : intervalQueue) { for (HTInterval interval : intervals) { if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } } return super.doSingularQuery(t, attributeQuark); }

Target:
public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { ITmfStateInterval ret = super.doSingularQuery(t, attributeQuark); if (ret != null) { return ret; } List<HTInterval> currentIntervals = fCurrentChunk; int size = currentIntervals.size(); for (int i = 0; i < size; i++) { HTInterval interval = currentIntervals.get(i); if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } for (Iterable<HTInterval> intervals : intervalQueue) { for (HTInterval interval : intervals) { if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } } return super.doSingularQuery(t, attributeQuark); }
Source:
public void processingInstruction(final String target, final String data) { final ProcessingInstruction pi = new ProcessingInstruction(); if (isBeforeRoot()) { nodesBeforeRoot.add(pi); } else if (isAfterRoot()) { nodesAfterRoot.add(pi); } else { final Element parent = stack.getLast().element; parent.addChild(pi); appendChars(false); } final int startOffset = content.length(); content.insertTagMarker(content.length()); content.insertText(content.length(), target + " " + data); content.insertTagMarker(content.length()); pi.associate(content, new ContentRange(startOffset, content.length() - 1)); trimLeading = false; }

Target:
public void processingInstruction(final String target, final String data) { final ProcessingInstruction pi = new ProcessingInstruction(target); if (isBeforeRoot()) { nodesBeforeRoot.add(pi); } else if (isAfterRoot()) { nodesAfterRoot.add(pi); } else { final Element parent = stack.getLast().element; parent.addChild(pi); appendChars(false); } final int startOffset = content.length(); content.insertTagMarker(content.length()); content.insertText(content.length(), data); content.insertTagMarker(content.length()); pi.associate(content, new ContentRange(startOffset, content.length() - 1)); trimLeading = false; }
Source:
public int getInt(int length, boolean signed) { if (length == 0) { return 0; } if (!canRead(length)) { throw new BufferOverflowException(); } int val = 0; boolean gotIt = false; if (this.pos % BitBuffer.BIT_CHAR == 0) { switch (length) { case BitBuffer.BIT_CHAR: val = this.buf.get((int) (this.pos / 8)); if (!signed) { val = val & 0xff; } gotIt = true; break; case BitBuffer.BIT_SHORT: val = this.buf.getShort((int) (this.pos / 8)); if (!signed) { val = val & 0xffff; } gotIt = true; break; case BitBuffer.BIT_INT: val = this.buf.getInt((int) (this.pos / 8)); gotIt = true; break; default: break; } } if (!gotIt) { if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { val = getIntLE(this.pos, length, signed); } else { val = getIntBE(this.pos, length, signed); } } this.pos += length; return val; }

Target:
private int getInt(int length, boolean signed) throws CTFReaderException { if (length == 0) { return 0; } if (!canRead(length)) { throw new CTFReaderException("Cannot read the integer, the buffer does not have enough remaining space. Requested:" + length); } int val = 0; boolean gotIt = false; if ((this.pos & (BitBuffer.BIT_CHAR - 1)) == 0) { switch (length) { case BitBuffer.BIT_CHAR: val = this.buf.get((int) (this.pos / 8)); if (!signed) { val = val & 0xff; } gotIt = true; break; case BitBuffer.BIT_SHORT: val = this.buf.getShort((int) (this.pos / 8)); if (!signed) { val = val & 0xffff; } gotIt = true; break; case BitBuffer.BIT_INT: val = this.buf.getInt((int) (this.pos / 8)); gotIt = true; break; default: break; } } if (!gotIt) { if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { val = getIntLE(this.pos, length, signed); } else { val = getIntBE(this.pos, length, signed); } } this.pos += length; return val; }
Source:
public void addColumn(long tableId, ColumnInfo column) { String columnType = sqlColumnType(column.getType()); if (columnType == null) { throw metadataError(new UnsupportedDataTypeException(column.getType().getDisplayName())); } String sql = format("ALTER TABLE %s ADD COLUMN (%s %s, %s %s)", shardIndexTable(tableId), minColumn(column.getColumnId()), columnType, maxColumn(column.getColumnId()), columnType); int attempts = 0; while (true) { attempts++; try (Handle handle = dbi.open()) { handle.execute(sql); } catch (DBIException e) { if (isSyntaxOrAccessError(e)) { return; } if (attempts >= MAX_ADD_COLUMN_ATTEMPTS) { throw metadataError(e); } log.warn(e, "Failed to alter table on attempt %s, will retry. SQL: %s", attempts, sql); try { SECONDS.sleep(3); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw metadataError(ie); } } } }

Target:
public void addColumn(long tableId, ColumnInfo column) { String columnType = sqlColumnType(column.getType()); if (columnType == null) { return; } String sql = format("ALTER TABLE %s ADD COLUMN (%s %s, %s %s)", shardIndexTable(tableId), minColumn(column.getColumnId()), columnType, maxColumn(column.getColumnId()), columnType); int attempts = 0; while (true) { attempts++; try (Handle handle = dbi.open()) { handle.execute(sql); } catch (DBIException e) { if (isSyntaxOrAccessError(e)) { return; } if (attempts >= MAX_ADD_COLUMN_ATTEMPTS) { throw metadataError(e); } log.warn(e, "Failed to alter table on attempt %s, will retry. SQL: %s", attempts, sql); try { SECONDS.sleep(3); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw metadataError(ie); } } } }
Source:
public void removeContext(IUndoContext context) { boolean recompute = false; if (triggeringOperation != null && triggeringOperation.hasContext(context)) { if (triggeringOperation.getContexts().length == 1) { remove(triggeringOperation); return; } triggeringOperation.removeContext(context); recompute = true; } ArrayList<IUndoableOperation> toBeRemoved = new ArrayList<>(); for (IUndoableOperation child : children) { if (child.hasContext(context)) { if (child.getContexts().length == 1) { toBeRemoved.add(child); } else { child.removeContext(context); } recompute = true; } } for (IUndoableOperation element : toBeRemoved) { remove(element); } if (recompute) { recomputeContexts(); } }

Target:
public void removeContext(IUndoContext context) { boolean recompute = false; if (triggeringOperation != null && triggeringOperation.hasContext(context)) { if (triggeringOperation.getContexts().length == 1) { remove(triggeringOperation); return; } triggeringOperation.removeContext(context); recompute = true; } ArrayList<IUndoableOperation> toBeRemoved = new ArrayList<>(); for (IUndoableOperation child : children) { if (child.hasContext(context)) { if (child.getContexts().length == 1) { toBeRemoved.add(child); } else { child.removeContext(context); } recompute = true; } } for (IUndoableOperation operation : toBeRemoved) { remove(operation); } if (recompute) { recomputeContexts(); } }
Source:
public static Object[] data() { if (Objects.equals(System.getenv().get("SKIP_BINARY_GENERATION"), "true")) { return new TestPlatform[]{TestPlatform.NATIVE, TestPlatform.ALPINE, TestPlatform.CENTOS, TestPlatform.UBUNTU, TestPlatform.NO_INIT, TestPlatform.SLIM}; } else { return TestPlatform.values(); } }

Target:
public static Object[] data() { if (Objects.equals(System.getenv().get("SKIP_DURABLE_TASK_BINARY_GENERATION"), "true")) { return new TestPlatform[]{TestPlatform.NATIVE, TestPlatform.ALPINE, TestPlatform.CENTOS, TestPlatform.UBUNTU, TestPlatform.NO_INIT, TestPlatform.SLIM}; } else { return TestPlatform.values(); } }
Source:
public boolean shouldSendEvent(Event event) { return event.getId().getLeastSignificantBits() % RATE_MULTIPLIER < sampleRate; }

Target:
public boolean shouldSendEvent(Event event) { return Math.abs(random.nextInt()) % RATE_MULTIPLIER < sampleRate; }
Source:
private List<ContainerId> previouslyAllocatedContainers(List<Container> containersListByYarn) { List<ContainerId> containersToRelease = new ArrayList<>(); if (containersListByYarn.size() != 0) { Map<String, Container> fromYarn = new HashMap<>(); Set<String> fromStreamingContainerManager = new HashSet<>(); LOG.debug("Containers list by YARN - {}", containersListByYarn); LOG.debug("Containers list by Streaming Container Manger - {}", dnmgr.getPhysicalPlan().getContainers()); for (Container container : containersListByYarn) { fromYarn.put(container.getId().toString(), container); } for (PTContainer ptContainer : dnmgr.getPhysicalPlan().getContainers()) { if (ptContainer.getExternalId() != null) { fromStreamingContainerManager.add(ptContainer.getExternalId()); } } for (PTContainer ptContainer : dnmgr.getPhysicalPlan().getContainers()) { String containerId = ptContainer.getExternalId(); Container container = fromYarn.get(containerId); if (container != null) { allocatedContainers.put(containerId, new AllocatedContainer(container)); fromYarn.remove(containerId); fromStreamingContainerManager.remove(containerId); } } for (Container container : fromYarn.values()) { containersToRelease.add(container.getId()); } if (fromYarn.size() != 0) { LOG.info("YARN returned has container(s) {}, with no corresponding container(s) in Physical Plan", fromYarn); } for (String containerId : fromStreamingContainerManager) { dnmgr.scheduleContainerRestart(containerId); } } else { dnmgr.deployAfterRestart(); } return containersToRelease; }

Target:
private List<ContainerId> previouslyAllocatedContainers(List<Container> containersListByYarn) { List<ContainerId> containersToRelease = new ArrayList<>(); if (containersListByYarn.size() != 0) { LOG.debug("Containers list by YARN - {}", containersListByYarn); LOG.debug("Containers list by Streaming Container Manger - {}", dnmgr.getPhysicalPlan().getContainers()); Map<String, Container> fromYarn = new HashMap<>(); for (Container container : containersListByYarn) { fromYarn.put(container.getId().toString(), container); } for (PTContainer ptContainer : dnmgr.getPhysicalPlan().getContainers()) { String containerId = ptContainer.getExternalId(); if (containerId == null) { continue; } Container container = fromYarn.get(containerId); if (container != null) { allocatedContainers.put(containerId, new AllocatedContainer(container)); fromYarn.remove(containerId); } else { dnmgr.scheduleContainerRestart(containerId); } } for (Container container : fromYarn.values()) { containersToRelease.add(container.getId()); } if (fromYarn.size() != 0) { LOG.info("Containers list returned by YARN, has the following container(s) which are not present in PhysicalPlan {}", fromYarn); } } else { dnmgr.deployAfterRestart(); } return containersToRelease; }
Source:
@After public void teardown() throws IOException { File rootExpectedOutputDirectory = new File( "./" + absoluteManagedResource.substring( 2 ).split( "/" )[ 0 ] ); FileUtils.deleteDirectory( rootExpectedOutputDirectory ); File toDelete = new File( "./" + fileUrl.substring( 2 ).split( "/" )[ 0 ] ); FileUtils.deleteDirectory( toDelete ); }

Target:
@After public void teardown() throws IOException { File rootExpectedOutputDirectory = Paths.get( "." + File.separator + absoluteManagedResource.substring( 2 ).split( File.separator )[ 0 ] ).toFile(); FileUtils.deleteDirectory( rootExpectedOutputDirectory ); File toDelete = Paths.get( "." + File.separator + fileUrl.substring( 2 ).split( File.separator )[ 0 ] ).toFile(); FileUtils.deleteDirectory( toDelete ); }
Source:
private HttpResponse invokeService(String endpoint) throws IOException, ArtifactSynchronizerException { HttpGet method = new HttpGet(endpoint); URL synapseGetURL = new URL(endpoint); APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); String password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD); byte[] credentials = Base64.encodeBase64((username + ":" + password).getBytes (APIConstants.DigestAuthConstants.CHARSET)); int synapsePort = synapseGetURL .getPort(); String synapseProtocol = synapseGetURL .getProtocol(); method.setHeader("Authorization", "Basic " + new String(credentials, APIConstants.DigestAuthConstants.CHARSET)); HttpClient httpClient = APIUtil.getHttpClient(synapsePort, synapseProtocol); HttpResponse httpResponse = null; int retryCount = 0; boolean retry = false; do { try { httpResponse = httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < retrievalRetries) { retry = true; log.warn("Failed retrieving " + endpoint + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + retrievalTimeoutInSeconds + " seconds."); try { Thread.sleep(retrievalTimeoutInSeconds * 1000); } catch (InterruptedException e) { } } else { throw ex; } } } while (retry); if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) { log.error("Retrieving artifacts is unsuccessful"); throw new ArtifactSynchronizerException("Error while retrieving artifacts"); } return httpResponse; }

Target:
private CloseableHttpResponse invokeService(String endpoint) throws IOException { HttpGet method = new HttpGet(endpoint); URL url = new URL(endpoint); String username = eventHubConfigurationDto.getUsername(); String password = eventHubConfigurationDto.getPassword(); byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password). getBytes(APIConstants.DigestAuthConstants.CHARSET)); int port = url.getPort(); String protocol = url.getProtocol(); method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT , APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET)); HttpClient httpClient = APIUtil.getHttpClient(port, protocol); return APIUtil.executeHTTPRequest(method, httpClient); }
Source:
public DepositRecord createDepositRecord(PID pid, Model model) throws FedoraException { PID newPid = pidMinter.mintDepositRecordPid(); DepositRecord depositRecord = new DepositRecord(newPid, repoObjLoader, repoObjDataLoader, this); return depositRecord; }

Target:
public DepositRecord createDepositRecord(PID pid, Model model) throws FedoraException { URI path = pid.getRepositoryUri(); model = populateModelTypes(path, model, Arrays.asList(Cdr.DepositRecord)); try (FcrepoResponse response = getClient().put(path) .body(RDFModelUtil.streamModel(model), TURTLE_MIMETYPE) .perform()) { URI createdUri = response.getLocation(); ldpFactory.createDirectContainer(createdUri, Cdr.hasManifest, RepositoryPathConstants.DEPOSIT_MANIFEST_CONTAINER); addEventContainer(createdUri); } catch (IOException e) { throw new FedoraException("Unable to create deposit record at " + path, e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } DepositRecord depositRecord = new DepositRecord(pid, repoObjLoader, repoObjDataLoader, this); return depositRecord; }
Source:
public ApkSignature(File openFile) { super(); this.openFile = openFile; }

Target:
public ApkSignature(File openFile) { this.openFile = openFile; }
Source:
public void testSimple() throws Exception { final ModelConverter mr = modelResolver(); final Model model = mr.resolve(XmlDecoratedBean.class, new ModelConverterContextImpl(mr), null); assertTrue(model instanceof ModelImpl); final ModelImpl impl = (ModelImpl) model; final Xml xml = impl.getXml(); assertNotNull(xml); assertEquals(xml.getName(), "xmlDecoratedBean"); final ArrayProperty property = (ArrayProperty)impl.getProperties().get("items"); assertNotNull(property); final Xml propertyXml = property.getXml(); assertNotNull(propertyXml); assertEquals(propertyXml.getName(), "items"); assertTrue(propertyXml.getWrapped()); final Xml itemsXml = property.getItems().getXml(); assertNotNull(itemsXml); assertEquals(itemsXml.getName(), "item"); assertNotNull(impl.getProperties().get("elementC")); }

Target:
public void testSimple() throws Exception { final ModelConverter mr = modelResolver(); final Model model = mr.resolve(XmlDecoratedBean.class, new ModelConverterContextImpl(mr), null); assertTrue(model instanceof ModelImpl); final ModelImpl impl = (ModelImpl) model; final Xml xml = impl.getXml(); assertNotNull(xml); assertEquals(xml.getName(), "xmlDecoratedBean"); final ArrayProperty property = (ArrayProperty)impl.getProperties().get("elements"); assertNotNull(property); final Xml propertyXml = property.getXml(); assertNotNull(propertyXml); assertNull(propertyXml.getName()); assertTrue(propertyXml.getWrapped()); final Xml itemsXml = property.getItems().getXml(); assertNotNull(itemsXml); assertEquals(itemsXml.getName(), "element"); assertNotNull(impl.getProperties().get("elementC")); }
Source:
protected void ExecuteIrsBrokerCommand() { uuidReturn = getIrsProxy().mergeSnapshots(getParameters().getStorageDomainId().toString(), getParameters().getStoragePoolId().toString(), getParameters().getVmId().toString(), getParameters().getImageGroupId().toString(), getParameters().getImageId().toString(), getParameters().getImageId2().toString(), (Boolean.valueOf(getParameters().getPostZero())).toString().toLowerCase()); ProceedProxyReturnValue(); Guid taskID = new Guid(uuidReturn.mUuid); getVDSReturnValue() .setCreationInfo( new AsyncTaskCreationInfo(taskID, AsyncTaskType.mergeSnapshots, getParameters() .getStoragePoolId())); }

Target:
protected void ExecuteIrsBrokerCommand() { uuidReturn = getIrsProxy().mergeSnapshots(getParameters().getStorageDomainId().toString(), getParameters().getStoragePoolId().toString(), getParameters().getVmId().toString(), getParameters().getImageGroupId().toString(), getParameters().getImageId().toString(), getParameters().getImageId2().toString(), String.valueOf(getParameters().getPostZero()).toLowerCase()); ProceedProxyReturnValue(); Guid taskID = new Guid(uuidReturn.mUuid); getVDSReturnValue() .setCreationInfo( new AsyncTaskCreationInfo(taskID, AsyncTaskType.mergeSnapshots, getParameters() .getStoragePoolId())); }
Source:
public void registerModelAdapter(Class<?> adapterType, Object adapter) { if (DsfDebugOptions.DEBUG && DsfDebugOptions.DEBUG_SESSION && DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Registering model adapter %s of type %s to session %s (%s)", DsfPlugin.getDebugTime(), LoggingUtils.toString(adapter), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.put(adapterType, adapter); }

Target:
public void registerModelAdapter(Class<?> adapterType, Object adapter) { if (DsfDebugOptions.DEBUG_SESSION_MODEL_ADAPTERS) { String msg = new Formatter().format( "%s Registering model adapter %s of type %s to session %s (%s)", DsfPlugin.getDebugTime(), LoggingUtils.toString(adapter), adapterType.getName(), LoggingUtils.toString(this), getId() ).toString(); DsfDebugOptions.trace(msg); } fAdapters.put(adapterType, adapter); }
Source:
Map<String, String> getAPITypeParameters() throws BonitaHomeNotSetException, ServerAPIException { Map<String, String> parameters; try { parameters = APITypeManager.getAPITypeParameters(); } catch (IOException e) { throw new ServerAPIException(e); } return parameters; }

Target:
protected Map<String, String> getAPITypeParameters() throws BonitaHomeNotSetException, ServerAPIException { try { return APITypeManager.getAPITypeParameters(); } catch (IOException e) { throw new ServerAPIException(e); } }
Source:
public Map<String, Map> hostDevListByCaps() { Map resultMap = getDoneStatus(); Map<String, Map> infoMap = map(); try { infoMap.put("computer", getCapability()); infoMap.put("pci_0000_00_1b_0", getHardware(0)); infoMap.put("pci_0000_00_1b_1", getHardware(1)); infoMap.put("pci_0000_00_1b_2", getHardware(2)); infoMap.put("pci_0000_00_1b_3", getHardware(3)); infoMap.put("pci_0000_00_1b_4", getHardware(4)); infoMap.put("pci_0000_00_1b_5", getHardware(5)); infoMap.put("pci_0000_00_1b_6", getHardware(6)); infoMap.put("pci_0000_00_1b_7", getHardware(7)); infoMap.put("pci_0000_00_1b_8", getHardware(8)); infoMap.put("pci_0000_00_1b_9", getHardware(9)); infoMap.put("pci_0000_00_1b_10", getHardware(10)); infoMap.put("pci_0000_00_1b_11", getHardware(11)); infoMap.put("pci_0000_00_1f_12", getHardware(12)); resultMap.put("info", infoMap); } catch (NullPointerException e) { log.error("getHostDevListByCaps failed due to {}", e); throw error(e); } finally { return resultMap; } }

Target:
public Map<String, Map> hostDevListByCaps() { Map resultMap = getDoneStatus(); Map<String, Map> infoMap = map(); infoMap.put("computer", getCapability()); infoMap.put("pci_0000_00_1b_0", getHardware(0)); infoMap.put("pci_0000_00_1b_1", getHardware(1)); infoMap.put("pci_0000_00_1b_2", getHardware(2)); infoMap.put("pci_0000_00_1b_3", getHardware(3)); infoMap.put("pci_0000_00_1b_4", getHardware(4)); infoMap.put("pci_0000_00_1b_5", getHardware(5)); infoMap.put("pci_0000_00_1b_6", getHardware(6)); infoMap.put("pci_0000_00_1b_7", getHardware(7)); infoMap.put("pci_0000_00_1b_8", getHardware(8)); infoMap.put("pci_0000_00_1b_9", getHardware(9)); infoMap.put("pci_0000_00_1b_10", getHardware(10)); infoMap.put("pci_0000_00_1b_11", getHardware(11)); infoMap.put("pci_0000_00_1f_12", getHardware(12)); resultMap.put("info", infoMap); return resultMap; }
Source:
public void testGetCompletionTimesTwoFragmentInteractionP2PAsync() { Trace trace1 = new Trace(); trace1.setId("1_2ip2pasync"); trace1.setStartTime(System.currentTimeMillis() - 60000); Consumer c1 = new Consumer(); c1.setUri("testuri"); c1.setDuration(TimeUnit.NANOSECONDS.convert(3000, TimeUnit.MILLISECONDS)); trace1.getNodes().add(c1); Producer p1 = new Producer(); p1.setUri("testuri2"); p1.setBaseTime(TimeUnit.NANOSECONDS.convert(500, TimeUnit.MILLISECONDS)); p1.setDuration(TimeUnit.NANOSECONDS.convert(500, TimeUnit.MILLISECONDS)); p1.addInteractionCorrelationId("cid1_2ip2pasync"); c1.getNodes().add(p1); Trace trace2 = new Trace(); trace2.setId("2_2ip2pasync"); trace2.setStartTime(trace1.getStartTime() + 500); Consumer c2 = new Consumer(); c2.setUri("testuri2"); c2.setDuration(TimeUnit.NANOSECONDS.convert(4000, TimeUnit.MILLISECONDS)); c2.addInteractionCorrelationId("cid1_2ip2pasync"); trace2.getNodes().add(c2); try { publisher.publish(null, Arrays.asList(trace1, trace2)); } catch (Exception e1) { fail("Failed to store: " + e1); } Wait.until(() -> service.searchFragments(null, new Criteria()).size() == 2); Wait.until(() -> analytics.getTraceCompletionTimes(null, new Criteria()).size() == 1); List<CompletionTime> times = analytics.getTraceCompletionTimes(null, new Criteria()); assertNotNull(times); assertEquals(1, times.size()); assertEquals(4500, times.get(0).getDuration()); }

Target:
public void testGetCompletionTimesTwoFragmentInteractionP2PAsync() throws Exception { Trace trace1 = new Trace(); trace1.setId("1_2ip2pasync"); trace1.setStartTime(System.currentTimeMillis() - 60000); Consumer c1 = new Consumer(); c1.setUri("testuri"); c1.setDuration(TimeUnit.NANOSECONDS.convert(3000, TimeUnit.MILLISECONDS)); trace1.getNodes().add(c1); Producer p1 = new Producer(); p1.setUri("testuri2"); p1.setBaseTime(TimeUnit.NANOSECONDS.convert(500, TimeUnit.MILLISECONDS)); p1.setDuration(TimeUnit.NANOSECONDS.convert(500, TimeUnit.MILLISECONDS)); p1.addInteractionCorrelationId("cid1_2ip2pasync"); c1.getNodes().add(p1); Trace trace2 = new Trace(); trace2.setId("2_2ip2pasync"); trace2.setStartTime(trace1.getStartTime() + 500); Consumer c2 = new Consumer(); c2.setUri("testuri2"); c2.setDuration(TimeUnit.NANOSECONDS.convert(4000, TimeUnit.MILLISECONDS)); c2.addInteractionCorrelationId("cid1_2ip2pasync"); trace2.getNodes().add(c2); publisher.publish(null, Arrays.asList(trace1, trace2)); Wait.until(() -> service.searchFragments(null, new Criteria()).size() == 2); Wait.until(() -> analytics.getTraceCompletionTimes(null, new Criteria()).size() == 1); List<CompletionTime> times = analytics.getTraceCompletionTimes(null, new Criteria()); assertNotNull(times); assertEquals(1, times.size()); assertEquals(4500, times.get(0).getDuration()); }
Source:
public void testPathParamEncoding() throws Exception { Invokable<?, ?> method = method(TestPath.class, "onePathEncodedParam", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo/bar"))); assertRequestLineEquals(request, "GET http://localhost:9999/foo%2Fbar HTTP/1.1"); }

Target:
public void testPathParamEncoding() throws Exception { Invokable<?, ?> method = method(TestPath.class, "onePath", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo/bar"))); assertRequestLineEquals(request, "GET http://localhost:9999/foo/bar HTTP/1.1"); request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo%2Fbar"))); assertRequestLineEquals(request, "GET http://localhost:9999/foo%252Fbar HTTP/1.1"); method = method(TestPath.class, "encodedParams", String.class, String.class, String.class); request = processor.apply(Invocation.create(method, ImmutableList.<Object>of("encoded%2Fparam", "encode%2Fdouble", "foo%20bar"))); assertRequestLineEquals(request, "GET http://localhost:9999/encoded%2Fparam/encode%252Fdouble/foo%20bar HTTP/1.1"); }
Source:
protected HttpMessage prepareRequestMessage(UsernamePasswordAuthenticationCredentials credentials) throws URIException, HttpMalformedHeaderException, DatabaseException { URI requestURI = createLoginUrl(loginRequestURL, credentials.getUsername(), credentials.getPassword()); String requestBody = null; if (loginRequestBody != null && !loginRequestBody.isEmpty()) { requestBody = replaceUserData(loginRequestBody, credentials.getUsername(), credentials.getPassword(), paramEncoder); } HttpMessage requestMessage; if (this.loginSiteNode != null) { requestMessage = loginSiteNode.getHistoryReference().getHttpMessage().cloneRequest(); requestMessage.getRequestHeader().setURI(requestURI); if (requestBody != null) { requestMessage.getRequestBody().setBody(requestBody); requestMessage.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null); replaceAntiCsrfTokenAndCookieValueIfRequired(requestMessage); } } else { String method = (requestBody != null) ? HttpRequestHeader.POST : HttpRequestHeader.GET; requestMessage = new HttpMessage(); requestMessage.setRequestHeader( new HttpRequestHeader(method, requestURI, HttpHeader.HTTP10, Model.getSingleton().getOptionsParam().getConnectionParam())); if (requestBody != null) { requestMessage.getRequestHeader().setHeader(HttpHeader.CONTENT_TYPE, contentType); requestMessage.getRequestBody().setBody(requestBody); } } return requestMessage; }

Target:
protected HttpMessage prepareRequestMessage(UsernamePasswordAuthenticationCredentials credentials) throws URIException, HttpMalformedHeaderException, DatabaseException { URI requestURI = createLoginUrl(loginRequestURL, credentials.getUsername(), credentials.getPassword()); String requestBody = null; if (loginRequestBody != null && !loginRequestBody.isEmpty()) { requestBody = replaceUserData(loginRequestBody, credentials.getUsername(), credentials.getPassword(), paramEncoder); } HttpMessage requestMessage; if (this.loginSiteNode != null) { requestMessage = loginSiteNode.getHistoryReference().getHttpMessage().cloneRequest(); requestMessage.getRequestHeader().setURI(requestURI); if (requestBody != null) { requestMessage.getRequestBody().setBody(requestBody); requestMessage.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null); } } else { String method = (requestBody != null) ? HttpRequestHeader.POST : HttpRequestHeader.GET; requestMessage = new HttpMessage(); requestMessage.setRequestHeader( new HttpRequestHeader(method, requestURI, HttpHeader.HTTP10, Model.getSingleton().getOptionsParam().getConnectionParam())); if (requestBody != null) { requestMessage.getRequestHeader().setHeader(HttpHeader.CONTENT_TYPE, contentType); requestMessage.getRequestBody().setBody(requestBody); } } return requestMessage; }
Source:
public <T> T findAndDelete(final Query<T> query) { FindAndModifyOptions options = new FindAndModifyOptions() .remove(true) .returnNew(false) .upsert(false); return findAndDelete(query, options); }

Target:
public <T> T findAndDelete(final Query<T> query) { return findAndDelete(query, new FindAndModifyOptions()); }
Source:
public void writeNoWrap(final IDocumentFragment fragment, final OutputStream out) throws IOException { final org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(); for (final INode child : fragment.children()) { writeNodeNoWrap(child, doc); } final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(out, "UTF-8")); printWriter.print(doc.get()); printWriter.flush(); }

Target:
public void writeNoWrap(final IDocumentFragment fragment, final OutputStream out) throws IOException { final org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(); for (final INode child : fragment.children()) { writeNodeNoWrap(child, doc); } writeToOutputStream(out, doc); }
Source:
public DispatchRequest execute(LogInAction action, AsyncCallback<LogInResult> resultCallback, ExecuteCommand<LogInAction, LogInResult> executeCommand) { executeCommand.execute(action, resultCallback); return new CompletedDispatchRequest(); }

Target:
public DispatchRequest execute(LogInAction action, AsyncCallback<LogInResult> resultCallback, ExecuteCommand<LogInAction, LogInResult> executeCommand) { return executeCommand.execute(action, resultCallback); }
Source:
protected final void disposeSaslServer() { if (zooKeeperSaslServer != null) { try { zooKeeperSaslServer.dispose(); } catch (Exception e) { LOG.debug("ignoring exception during SaslServer dispose", e); } zooKeeperSaslServer = null; } }

Target:
protected final void disposeSaslServer() { if (zooKeeperSaslServer != null) { try { zooKeeperSaslServer.dispose(); } catch (SaslException e) { LOG.debug("ignoring exception during SaslServer dispose", e); } } }
Source:
private boolean isEcho(String itemName, State state) { String ignoreEventSetKey = itemName + state.toString(); if (ignoreEventSet.contains(ignoreEventSetKey)) { ignoreEventSet.remove(ignoreEventSetKey); logger.trace( "We received this event (item='{}', state='{}') from Nest, so we don't send it back again -> ignore!", itemName, state); return true; } else { return false; } }

Target:
private boolean isEcho(String itemName, State state) { String ignoreEventSetKey = itemName + state.toString(); if (ignoreEventSet.contains(ignoreEventSetKey)) { ignoreEventSet.remove(ignoreEventSetKey); logger.debug( "We received this event (item='{}', state='{}') from Nest, so we don't send it back again -> ignore!", itemName, state); return true; } else { return false; } }
Source:
public void completePluginConfigurationUpdate(PluginConfigurationUpdate update) { ConfigurationUpdateResponse response = configurationManager.executePluginConfigurationUpdate(update); Resource resource = update.getResource(); resource.setAgentSynchronizationNeeded(); entityManager.remove(resource.getPluginConfiguration()); setOrUpdatePluginConfiguration(resource, update.getConfiguration()); if (response.getStatus() == ConfigurationUpdateStatus.SUCCESS) { update.setStatus(ConfigurationUpdateStatus.SUCCESS); resource.setConnected(true); removeAnyExistingInvalidPluginConfigurationErrors(resource); entityManager.flush(); entityManager.merge(update); } else { handlePluginConfiguratonUpdateRemoteException(resource, response.getStatus().toString(), response.getErrorMessage()); update.setStatus(response.getStatus()); update.setErrorMessage(response.getErrorMessage()); } }

Target:
public void completePluginConfigurationUpdate(PluginConfigurationUpdate update) { ConfigurationUpdateResponse response = configurationManager.executePluginConfigurationUpdate(update); Resource resource = update.getResource(); resource.setAgentSynchronizationNeeded(); setOrUpdatePluginConfiguration(resource, update.getConfiguration()); if (response.getStatus() == ConfigurationUpdateStatus.SUCCESS) { update.setStatus(ConfigurationUpdateStatus.SUCCESS); resource.setConnected(true); removeAnyExistingInvalidPluginConfigurationErrors(resource); entityManager.flush(); entityManager.merge(update); } else { handlePluginConfiguratonUpdateRemoteException(resource, response.getStatus().toString(), response.getErrorMessage()); update.setStatus(response.getStatus()); update.setErrorMessage(response.getErrorMessage()); } }
Source:
public static YearMonthDateParameterMetadata of(LocalDate date, YearMonth yearMonth) { ArgChecker.notNull(yearMonth, "yearMonth"); return new YearMonthDateParameterMetadata(date, yearMonth, yearMonth.format(FORMATTER)); }

Target:
public static YearMonthDateParameterMetadata of(LocalDate date, YearMonth yearMonth) { ArgChecker.notNull(date, "date"); ArgChecker.notNull(yearMonth, "yearMonth"); return new YearMonthDateParameterMetadata(date, yearMonth, yearMonth.format(FORMATTER)); }
Source:
protected boolean checkEnvironment() { home = getHomeDir().getAbsoluteFile(); boolean success = home.mkdirs(); if (!success) { LOGGER.warning("Failed to create home directory: " + home); return false; } LOGGER.info(getApplicationName()+" home directory: "+home); if (!home.exists()) { context.setAttribute(APP,new NoHomeDirError(home)); return false; } return true; }

Target:
protected boolean checkEnvironment() { home = getHomeDir().getAbsoluteFile(); try { Files.createDirectories(home.toPath()); } catch (IOException ioe) { LOGGER.log(Level.WARNING, "Failed to create home directory: " + home, ioe); return false; } LOGGER.info(getApplicationName()+" home directory: "+home); if (!home.exists()) { context.setAttribute(APP,new NoHomeDirError(home)); return false; } return true; }
Source:
String getDescription() { return "A fault zone cannot contain more than 1 replicas of same partition"; }

Target:
String getDescription() { return "A fault zone cannot contain more than 1 replica of same partition"; }
Source:
public void setUp() throws CTFReaderException { fixture = new BitBuffer(java.nio.ByteBuffer.allocateDirect(128)); fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(fixture); }

Target:
public void setUp() throws CTFReaderException { fixture = new BitBuffer(ByteBuffer.allocateDirect(128)); fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(fixture); }
Source:
public CompositeDependencyResolver(List<DependencyResolver> dependencyResolvers) { this(); this.dependencyResolvers = dependencyResolvers; }

Target:
public CompositeDependencyResolver(List<DependencyResolver> dependencyResolvers) { super(); this.dependencyResolvers = dependencyResolvers; }
Source:
public void testFindMimeTypeNullFileName() { String mimeType = attachmentService.findMimeType(StringUtils.EMPTY); assertEquals(StringUtils.EMPTY, mimeType); }

Target:
public void testFindMimeTypeNullFileName() { String mimeType = attachmentService.findMimeType(null); assertEquals(StringUtils.EMPTY, mimeType); }
Source:
public void testJsonNullDiskDescription() throws IOException { String jsonDescription = null; jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", null); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }

Target:
public void testJsonNullDiskDescription() throws IOException { String jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", null); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }
Source:
public void getInstanceAsync_cancelBeforePostShouldNotCreateRealmInstanceOnTheCallerThread() { final RealmAsyncTask[] realmAsyncTasks = new RealmAsyncTask[1]; final Runnable finishedRunnable = new Runnable() { @Override public void run() { looperThread.testComplete(); } }; final RealmConfiguration configuration = looperThread.createConfigurationBuilder() .name("will_be_canceled") .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { looperThread.postRunnable(new Runnable() { @Override public void run() { assertNotNull(realmAsyncTasks[0]); realmAsyncTasks[0].cancel(); TestHelper.waitRealmThreadExecutorFinish(); looperThread.postRunnable(finishedRunnable); } }); } }) .build(); realmAsyncTasks[0] = Realm.getInstanceAsync(configuration, new Realm.Callback() { @Override public void onSuccess(Realm realm) { fail(); } }); }

Target:
public void getInstanceAsync_cancelBeforePostShouldNotCreateRealmInstanceOnTheCallerThread() { final AtomicReference<RealmAsyncTask> realmAsyncTasks = new AtomicReference<>(); final Runnable finishedRunnable = new Runnable() { @Override public void run() { looperThread.testComplete(); } }; final RealmConfiguration configuration = looperThread.createConfigurationBuilder() .name("will_be_canceled") .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { looperThread.postRunnable(new Runnable() { @Override public void run() { assertNotNull(realmAsyncTasks.get()); realmAsyncTasks.get().cancel(); TestHelper.waitRealmThreadExecutorFinish(); looperThread.postRunnable(finishedRunnable); } }); } }) .build(); realmAsyncTasks.set(Realm.getInstanceAsync(configuration, new Realm.Callback() { @Override public void onSuccess(Realm realm) { fail(); } })); }
Source:
public void createControl(Composite parent) { super.createControl(parent); final Composite control = (Composite) this.getControl(); control.setLayout(new GridLayout(2, false)); control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final Table selectedFiles = new Table(control, SWT.NONE); selectedFiles.clearAll(); selectedFiles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); Composite buttonArea = new Composite(control, SWT.None); buttonArea.setLayout(new RowLayout()); ((RowLayout) buttonArea.getLayout()).type = SWT.VERTICAL; buttonArea.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Button addFile = new Button(buttonArea, SWT.PUSH); addFile.setText("Add"); addFile.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog (Display.getCurrent().getActiveShell(), SWT.NONE); String fn = dialog.open(); if (null != fn) { File f = new File(fn); if (f.exists()) { getBatchWizard().addFile(fn, f); } } updateButtons(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); Button removeFile = new Button(buttonArea, SWT.PUSH); removeFile.setText("Remove"); removeFile.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { TableItem selectedToRemove[] = selectedFiles.getSelection(); for (TableItem victim : selectedToRemove) { String victimName = victim.getText(); ((BatchImportTraceWizard) getWizard()).removeFile(victimName); } updateButtons(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); this.setTitle("Pick directories and files to scan"); }

Target:
public void createControl(Composite parent) { super.createControl(parent); final Composite control = (Composite) this.getControl(); control.setLayout(new GridLayout(2, false)); control.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final Table selectedFiles = new Table(control, SWT.NONE); selectedFiles.clearAll(); selectedFiles.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); Composite buttonArea = new Composite(control, SWT.None); buttonArea.setLayout(new RowLayout()); ((RowLayout) buttonArea.getLayout()).type = SWT.VERTICAL; buttonArea.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Button addFile = new Button(buttonArea, SWT.PUSH); addFile.setText(Messages.ImportTraceWizardPageSelectDirectories_0); addFile.addSelectionListener(new AddFileHandler()); Button addDirectory = new Button(buttonArea, SWT.PUSH); addDirectory.setText(Messages.ImportTraceWizardPageSelectDirectories_1); addDirectory.addSelectionListener(new AddDirectoryHandler()); Button removeFile = new Button(buttonArea, SWT.PUSH); removeFile.setText(Messages.ImportTraceWizardPageSelectDirectories_2); removeFile.addSelectionListener(new RemoveFileHandler(selectedFiles)); this.setTitle(Messages.ImportTraceWizardPageSelectDirectories_3); }
Source:
public void run() { if (logger.isDebugEnabled()) { logger.debug("Triggered deadline"); } try { UnitOfWork<DeadlineMessage<?>> unitOfWork = new DefaultUnitOfWork<>(deadlineMessage); unitOfWork.attachTransaction(transactionManager); InterceptorChain chain = new DefaultInterceptorChain<>(unitOfWork, handlerInterceptors(), dm -> { executeScheduledDeadline(dm, deadlineScope); return null; }); unitOfWork.executeWithResult(chain::proceed); } catch (Exception e) { throw new DeadlineException(format("An error occurred while processing the deadline %s %s", deadlineName, deadlineId), e); } finally { scheduledTasks.remove(new DeadlineId(deadlineName, deadlineId)); } }

Target:
public void run() { if (logger.isDebugEnabled()) { logger.debug("Triggered deadline"); } try { UnitOfWork<DeadlineMessage<?>> unitOfWork = new DefaultUnitOfWork<>(deadlineMessage); unitOfWork.attachTransaction(transactionManager); InterceptorChain chain = new DefaultInterceptorChain<>(unitOfWork, handlerInterceptors(), deadlineMessage -> { executeScheduledDeadline(deadlineMessage, deadlineScope); return null; }); unitOfWork.executeWithResult(chain::proceed); } catch (Exception e) { throw new DeadlineException(format("An error occurred while triggering the deadline %s %s", deadlineName, deadlineId), e); } finally { scheduledTasks.remove(new DeadlineId(deadlineName, deadlineId)); } }
Source:
private boolean isNotSPM(VDSReturnValue returnValue) { return returnValue != null && returnValue.getVdsError() != null && returnValue.getVdsError().getCode() == VdcBllErrors.SpmStatusError; }

Target:
private boolean isNotSPM(VDSReturnValue returnValue) { return returnValue.getVdsError() != null && returnValue.getVdsError().getCode() == VdcBllErrors.SpmStatusError; }
Source:
public void addTagForEntity(TaggedEntity taggedEntity, Long tagId) { String entityTagUrl = String.format("%s/%s/%s/%s/%s", tagRootUrl, tagId, "entities", taggedEntity.getNamespace(), taggedEntity.getId()); Response responseObject = client.target(entityTagUrl).request().post(Entity.json(taggedEntity)); String response = responseObject.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode() | responseCode == CatalogResponse.ResponseMessage.EXCEPTION.getCode()) { throw new RuntimeException("Error occurred while tagging entity : "+ getResponseMessage(response)); } }

Target:
public void addTagForEntity(TaggedEntity taggedEntity, Long tagId) { String entityTagUrl = String.format("%s/%s/%s/%s/%s", tagRootUrl, tagId, "entities", taggedEntity.getNamespace(), taggedEntity.getId()); Response responseObject = client.target(entityTagUrl).request().post(Entity.json(taggedEntity)); String response = responseObject.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode != CatalogResponse.ResponseMessage.SUCCESS.getCode()) { throw new RuntimeException("Error occurred while tagging entity : "+ getResponseMessage(response)); } }
Source:
public static String getWorkerPrefix(Map conf, TopologyDetails info) { conf = getFullTopologyConfig(conf, info); String prefix = (String) conf.get(WORKER_NAME_PREFIX); String delimiter = (String) conf.get(WORKER_NAME_PREFIX_DELIMITER); if (prefix == null) prefix = ""; if (delimiter == null) delimiter = DEFAULT_DELIMITER; return prefix + info.getName() + delimiter; }

Target:
public static String getWorkerPrefix(Map conf, TopologyDetails info) { Map topologyConf = getFullTopologyConfig(conf, info); String prefix = Optional.fromNullable((String) topologyConf.get(WORKER_NAME_PREFIX)).or(""); return prefix + info.getName() + getWorkerPrefixDelimiter(conf); }
Source:
public void test_int_and_long_value() throws Exception { Integer[] expectedIntegerValues = {42, -7, 3, null, null, 0xff, 0b0100, 5678, 0xFF, 0b1100110}; Long[] expectedLongValues = {42L, 42L, -7L, -7L, +3L, +3L, null, null, 0xFFL, null, null, null, Long.MAX_VALUE, Long.MAX_VALUE, 0b11010010_01101001_10010100_10010010L, 10010L, 0xFFL, 102L}; int i = 0; int j = 0; for (VariableTree variableTree : variables) { if (variableTree.simpleName().name().startsWith("x")) { assertThat(LiteralUtils.intLiteralValue(variableTree.initializer())).isEqualTo(expectedIntegerValues[i++]); } else if (variableTree.simpleName().name().startsWith("y")) { assertThat(LiteralUtils.longLiteralValue(variableTree.initializer())).isEqualTo(expectedLongValues[j++]); } } }

Target:
public void test_int_and_long_value() throws Exception { Integer[] expectedIntegerValues = {42, -7, 3, null, null, 0xff, 0b0100, 5678, 0xFF, 0b1100110}; Long[] expectedLongValues = {42L, 42L, -7L, -7L, +3L, +3L, null, null, 0xFFL, null, null, null, Long.MAX_VALUE, Long.MAX_VALUE, 0b11010010_01101001_10010100_10010010L, 10010L, 0xFFL, 0b1100110L}; int i = 0; int j = 0; for (VariableTree variableTree : variables) { if (variableTree.simpleName().name().startsWith("x")) { assertThat(LiteralUtils.intLiteralValue(variableTree.initializer())).isEqualTo(expectedIntegerValues[i++]); } else if (variableTree.simpleName().name().startsWith("y")) { assertThat(LiteralUtils.longLiteralValue(variableTree.initializer())).isEqualTo(expectedLongValues[j++]); } } }