auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); final Set<DataSegment> segments = Sets.newHashSet(); for (final Interval bucket : granularitySpec.bucketIntervals()) { final List<ShardSpec> shardSpecs; if (targetPartitionSize > 0) { shardSpecs = determinePartitions( toolbox, new Schema( getDataSource(), spatialDimensions, aggregators, indexGranularity, new NoneShardSpec() ), bucket, targetPartitionSize ); } else { shardSpecs = ImmutableList.<ShardSpec>of(new NoneShardSpec()); } for (final ShardSpec shardSpec : shardSpecs) { final DataSegment segment = generateSegment( toolbox, new Schema( getDataSource(), spatialDimensions, aggregators, indexGranularity, shardSpec ), interval, myLock.getVersion() ); segments.add(segment); } } return TaskStatus.success(getId()); }

Target:
public TaskStatus run(TaskToolbox toolbox) throws Exception { final TaskLock myLock = Iterables.getOnlyElement(getTaskLocks(toolbox)); final Set<DataSegment> segments = Sets.newHashSet(); for (final Interval bucket : granularitySpec.bucketIntervals()) { final List<ShardSpec> shardSpecs; if (targetPartitionSize > 0) { shardSpecs = determinePartitions(bucket, targetPartitionSize); } else { shardSpecs = ImmutableList.<ShardSpec>of(new NoneShardSpec()); } for (final ShardSpec shardSpec : shardSpecs) { final DataSegment segment = generateSegment( toolbox, new Schema( getDataSource(), spatialDimensions, aggregators, indexGranularity, shardSpec ), bucket, myLock.getVersion() ); segments.add(segment); } } toolbox.getTaskActionClient().submit(new SegmentInsertAction(segments)); return TaskStatus.success(getId()); }
Source:
public static String formatFilePath(String basePath) { if (!basePath.endsWith("/")) { basePath += '/'; } return basePath; }

Target:
public static String formatFilePath(String basePath) { String path = basePath; if (!path.endsWith(File.separator)) { path += File.separator; } return path; }
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException { Response response = getRequestBuilder().post(Entity.entity( preparePayload(destAddress, message.trim()), mediaType)); if (response.getStatus() / 100 != 2) { throw new MessageException(response.readEntity(String.class)); } }

Target:
public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException { Response response = getRequestBuilder().post(Entity.entity(preparePayload(destAddress, message), mediaType)); if (response.getStatus() / 100 != 2) { throw new MessageException(response.readEntity(String.class)); } }
Source:
public void testEmpiBatchRunWorksOverMultipleTargetTypes() throws InterruptedException { for (int i =0; i < 10; i++) { createPatient(buildJanePatient()); } for(int i = 0; i< 10; i++) { createPractitioner(buildPractitionerWithNameAndId("test", "id")); } assertLinkCount(0); afterEmpiLatch.setExpectedCount(20); myEmpiBatchSvc.runEmpiOnAllTargetTypes(null); afterEmpiLatch.awaitExpected(); assertLinkCount(20); }

Target:
public void testEmpiBatchRunWorksOverMultipleTargetTypes() throws InterruptedException { for (int i =0; i < 10; i++) { createPatient(buildJanePatient()); } for(int i = 0; i< 10; i++) { createPractitioner(buildPractitionerWithNameAndId("test", "id")); } assertLinkCount(0); afterEmpiLatch.runWithExpectedCount(20, () -> myEmpiBatchSvc.runEmpiOnAllTargetTypes(null)); assertLinkCount(20); }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); try { InputStream is = getResources().getAssets().open("changelog.html"); mChangelog.setText(Html.fromHtml(Utils.inputStreamToString(is))); } catch (IOException e) { e.printStackTrace(); } }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); InputStream is = null; try { is = getResources().getAssets().open("changelog.html"); mChangelog.setText(Html.fromHtml(Utils.inputStreamToString(is))); } catch (IOException e) { Timber.e(e, e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { Timber.e(e, e.getMessage()); } } } }
Source:
@Test public void superClassOnlyValidForClasses() { TypeSpec.classBuilder("C").superclass(Object.class); try { TypeSpec.annotationBuilder("A").superclass(ClassName.get(Object.class)); fail(); } catch (IllegalStateException expected) { } try { TypeSpec.enumBuilder("E").superclass(ClassName.get(Object.class)); fail(); } catch (IllegalStateException expected) { } try { TypeSpec.interfaceBuilder("I").superclass(ClassName.get(Object.class)); fail(); } catch (IllegalStateException expected) { } }

Target:
@Test public void superClassOnlyValidForClasses() { try { TypeSpec.annotationBuilder("A").superclass(ClassName.get(Object.class)); fail(); } catch (IllegalStateException expected) { } try { TypeSpec.enumBuilder("E").superclass(ClassName.get(Object.class)); fail(); } catch (IllegalStateException expected) { } try { TypeSpec.interfaceBuilder("I").superclass(ClassName.get(Object.class)); fail(); } catch (IllegalStateException expected) { } }
Source:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); if (!StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion)) { return true; } return false; }

Target:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); return AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }
Source:
public Map<String, BuilderEnvironment> getEnvironments() { Map<String, BuilderEnvironment> env = new HashMap<>(); BuilderEnvironment builderEnvironment = DtoFactory.getInstance().createDto(BuilderEnvironment.class) .withId("default") .withIsDefault(true) .withDisplayName(this.getName()); env.put(builderEnvironment.getId(), builderEnvironment); return env; }

Target:
public Map<String, BuilderEnvironment> getEnvironments() { BuilderEnvironment builderEnvironment = DtoFactory.getInstance().createDto(BuilderEnvironment.class) .withId("default") .withIsDefault(true) .withDisplayName(this.getName()); return Collections.singletonMap(builderEnvironment.getId(), builderEnvironment); }
Source:
public String postText(String recordId, String title, String body, String resultsUrl) throws IOException, XMLStreamException, FactoryConfigurationError { establishSession(); String pid = recordId == null || recordId.length() == 0 ? session.userId : recordId; try { return createSoapFeedPost(pid, title, resultsUrl, body); } catch (SoapFaultException ex) { if (ex.getFaultCode().toLowerCase().contains("session")) { SessionCache.get().revoke(credentials); return postText(recordId, title, resultsUrl, body); } throw ex; } }

Target:
public String postText(String recordId, String title, String body, String resultsUrl) throws IOException, XMLStreamException, FactoryConfigurationError { establishSession(); String trimmedRecordId = StringUtils.trim(recordId); String recordIdForPost = StringUtils.isEmpty(trimmedRecordId) ? session.userId : trimmedRecordId; try { return createSoapFeedPost(recordIdForPost, title, resultsUrl, body); } catch (SoapFaultException ex) { if (ex.getFaultCode().toLowerCase().contains("session")) { SessionCache.get().revoke(credentials); return postText(recordId, title, resultsUrl, body); } throw ex; } }
Source:
private String parseErrorMessage(List<String> messages) { for(String messgae: messages) { if (messgae.startsWith("$message")) { return messgae.substring(9); } } return ""; }

Target:
private String parseErrorMessage(List<String> messages) { for(String message: messages) { Matcher matcher = msgRegEx.matcher(message); if (matcher.matches()) { return matcher.group("error"); } } return ""; }
Source:
public List<Entry> findMyEntries(long userId) { return list(namedQuery("io.dockstore.webservice.core." + typeOfT.getSimpleName() + ".getEntriesByUserId").setParameter("userId", userId)); }

Target:
public List<T> findMyEntries(long userId) { return list(namedQuery("io.dockstore.webservice.core." + typeOfT.getSimpleName() + ".getEntriesByUserId").setParameter("userId", userId)); }
Source:
public boolean equals(Object o) { if (o instanceof CustomMethods == false) { return reverseEquals; } CustomMethods other = (CustomMethods) o; if (isValid() == other.isValid() && other.name.equals(name)) { return !reverseEquals; } else { return reverseEquals; } }

Target:
public boolean equals(Object o) { if (!(o instanceof CustomMethods)) { return reverseEquals; } CustomMethods other = (CustomMethods) o; if (isValid() == other.isValid() && other.name.equals(name)) { return !reverseEquals; } else { return reverseEquals; } }
Source:
public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double doubleSize) throws MaxChangedBlocksException { int size = (int) Math.ceil(doubleSize); int diameter = size * 2 + 1; BufferedImage resizedPattern = new BufferedImage(diameter, diameter, 1); Graphics2D graphic = null; try { graphic = resizedPattern.createGraphics(); graphic.drawImage(this.image, 0, 0, diameter, diameter, null); } finally { graphic.dispose(); } double random = RANDOM.nextDouble(); for (int offX = -size; offX <= size; offX++) { for (int offZ = -size; offZ <= size; offZ++) { int posX = position.getX() + offX; int posZ = position.getZ() + offZ; int posY = editSession.getHighestTerrainBlock(posX, posZ, 0, 255, editSession.getMask()); BlockVector3 block = BlockVector3.at(posX, posY, posZ); if (editSession.getMask() != null && !editSession.getMask().test(block)) { continue; } double height = getHeightAt(resizedPattern, offX + size, resizedPattern.getHeight() - 1 - (offZ + size)); if (random > 1 - height % 1) { height += 1; } BaseBlock baseBlock = fill ? editSession.getBlock(block).toBaseBlock() : null; for (int y = 0; y < height; y++) { if (fill) { if (!flat || block.getY() + y <= position.getY()) { editSession.setBlock(block.withY(block.getY() + y), baseBlock); } } else if ((!flat || block.getY() - y > position.getY()) && block.getY() - y >= 0 && (editSession.getMask() == null || editSession.getMask().test(block.withY(block.getY() - y)))) { editSession.setBlock(block.withY(block.getY() - y), BlockTypes.AIR.getDefaultState()); } } } } }

Target:
public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double doubleSize) throws MaxChangedBlocksException { int size = (int) Math.ceil(doubleSize); int diameter = size * 2 + 1; BufferedImage resizedPattern = new BufferedImage(diameter, diameter, 1); Graphics2D graphic = null; try { graphic = resizedPattern.createGraphics(); graphic.drawImage(this.image, 0, 0, diameter, diameter, null); } finally { graphic.dispose(); } double random = randomize ? RANDOM.nextDouble() : 0; for (int offX = -size; offX <= size; offX++) { for (int offZ = -size; offZ <= size; offZ++) { int posX = position.getX() + offX; int posZ = position.getZ() + offZ; int posY = editSession.getHighestTerrainBlock(posX, posZ, 0, 255, editSession.getMask()); BlockVector3 block = BlockVector3.at(posX, posY, posZ); if (editSession.getMask() != null && !editSession.getMask().test(block)) { continue; } double height = getHeightAt(resizedPattern, offX + size, resizedPattern.getHeight() - 1 - (offZ + size)); if (randomize && random > 1 - height % 1) { height += 1; } BaseBlock baseBlock = erase ? null : editSession.getBlock(block).toBaseBlock(); for (int y = 0; y < height; y++) { if (erase) { editSession.setBlock(block.withY(block.getY() - y), BlockTypes.AIR.getDefaultState()); } else if ((!flatten || block.getY() - y > position.getY()) && block.getY() - y >= 0) { if (!flatten || block.getY() + y <= position.getY()) { editSession.setBlock(block.withY(block.getY() + y), baseBlock); } } } } } }
Source:
public void placeRadiologyOrder_shouldCreateRadiologyOrderEncounterWithOrdererAndAttachedToExistingActiveVisitIfPatientHasActiveVisit() throws Exception { RadiologyOrder radiologyOrder = getUnsavedRadiologyOrder(); radiologyOrder.setPatient(patientService.getPatient(PATIENT_ID_WITH_NO_RADIOLOGY_ORDER_AND_NO_EXISTIG_ENCOUNTER_AND_ACTIVE_VISIT)); assertThat(encounterService.getEncountersByPatient(radiologyOrder.getPatient()), is(empty())); assertThat(visitService.getActiveVisitsByPatient(radiologyOrder.getPatient()), is(not(empty()))); assertThat(radiologyOrder.getEncounter(), is(nullValue())); radiologyOrder = radiologyService.placeRadiologyOrder(radiologyOrder); Encounter encounter = radiologyOrder.getEncounter(); assertThat(encounter, is(not(nullValue()))); assertThat(encounter.getEncounterProviders() .size(), is(1)); Iterator<EncounterProvider> encounterProviderIterator = encounter.getEncounterProviders() .iterator(); while (encounterProviderIterator.hasNext()) { EncounterProvider encounterProvider = encounterProviderIterator.next(); assertThat(encounterProvider.getProvider(), is(radiologyOrder.getOrderer())); } assertThat(encounterService.getEncountersByPatient(radiologyOrder.getPatient()) .size(), is(1)); assertThat(visitService.getActiveVisitsByPatient(radiologyOrder.getPatient()) .size(), is(1)); assertThat(orderService.getAllOrdersByPatient(radiologyOrder.getPatient()) .size(), is(1)); }

Target:
public void placeRadiologyOrder_shouldCreateRadiologyOrderEncounterWithOrdererAndAttachedToExistingActiveVisitIfPatientHasActiveVisit() throws Exception { RadiologyOrder radiologyOrder = getUnsavedRadiologyOrder(); radiologyOrder.setPatient(patientService.getPatient(PATIENT_ID_WITH_NO_RADIOLOGY_ORDER_AND_NO_EXISTIG_ENCOUNTER_AND_ACTIVE_VISIT)); assertThat(encounterService.getEncountersByPatient(radiologyOrder.getPatient()), is(empty())); assertThat(visitService.getActiveVisitsByPatient(radiologyOrder.getPatient()), is(not(empty()))); Visit preExistingVisit = visitService.getActiveVisitsByPatient(radiologyOrder.getPatient()) .get(0); assertThat(radiologyOrder.getEncounter(), is(nullValue())); radiologyOrder = radiologyService.placeRadiologyOrder(radiologyOrder); Encounter encounter = radiologyOrder.getEncounter(); assertThat(encounter, is(not(nullValue()))); assertThat(encounter.getEncounterProviders() .size(), is(1)); assertThat(encounter.getEncounterProviders() .iterator() .next() .getProvider(), is(radiologyOrder.getOrderer())); assertThat(encounterService.getEncountersByPatient(radiologyOrder.getPatient()) .size(), is(1)); assertThat(visitService.getActiveVisitsByPatient(radiologyOrder.getPatient()) .size(), is(1)); assertThat(visitService.getActiveVisitsByPatient(radiologyOrder.getPatient()) .get(0), is(preExistingVisit)); assertThat(orderService.getAllOrdersByPatient(radiologyOrder.getPatient()) .size(), is(1)); }
Source:
private void populateSampleClasses(ModelMap model) throws IOException { List<SampleClass> sampleClasses = new ArrayList<>(); List<SampleClass> tissueClasses = new ArrayList<>(); for (SampleClass sc : sampleClassService.getAll()) { if (SampleTissue.CATEGORY_NAME.equals(sc.getSampleCategory())) { tissueClasses.add(sc); } else if (SampleStock.CATEGORY_NAME.equals(sc.getSampleCategory())) { tissueClasses.add(sc); } } Collections.sort(sampleClasses, new Comparator<SampleClass>() { @Override public int compare(SampleClass o1, SampleClass o2) { return o1.getAlias().compareTo(o2.getAlias()); } }); model.put("sampleClasses", sampleClasses); model.put("tissueClasses", tissueClasses); }

Target:
private void populateSampleClasses(ModelMap model) throws IOException { List<SampleClass> sampleClasses = new ArrayList<>(); List<SampleClass> tissueClasses = new ArrayList<>(); for (SampleClass sc : sampleClassService.getAll()) { if (SampleTissue.CATEGORY_NAME.equals(sc.getSampleCategory())) { tissueClasses.add(sc); sampleClasses.add(sc); } else if (SampleStock.CATEGORY_NAME.equals(sc.getSampleCategory())) { sampleClasses.add(sc); } } Collections.sort(sampleClasses, SAMPLECLASS_ALIAS); Collections.sort(tissueClasses, SAMPLECLASS_ALIAS); model.put("sampleClasses", sampleClasses); model.put("tissueClasses", tissueClasses); }
Source:
private byte[] idBufferBlob(final Entry e) { try { final InputStream raw = e.openInputStream(); if (raw == null) return zeroid; try { initializeDigestAndReadBuffer(); contentDigest.reset(); contentDigest.update(hblob); contentDigest.update((byte) ' '); final boolean canonicalizeEols; if (canonicalizeEolsForIdCalculation) { final InputStream is = e.openInputStream(); try { canonicalizeEols = !RawText.isBinary(is); } finally { is.close(); } } else { canonicalizeEols = false; } final long blobLength; if (!canonicalizeEols) { blobLength = e.getLength(); } else { final InputStream is = e.openInputStream(); try { blobLength = determineCanonicalizedLength(is); } finally { is.close(); } } long sz = blobLength; if (sz == 0) { contentDigest.update((byte) '0'); } else { final int bufn = contentReadBuffer.length; int p = bufn; do { contentReadBuffer[--p] = digits[(int) (sz % 10)]; sz /= 10; } while (sz > 0); contentDigest.update(contentReadBuffer, p, bufn - p); } contentDigest.update((byte) 0); final InputStream is = canonicalizeEols ? new EolCanonicalizingInputStream(raw) : raw; for (;;) { final int r = is.read(contentReadBuffer); if (r <= 0) break; contentDigest.update(contentReadBuffer, 0, r); sz += r; } if (sz != blobLength) return zeroid; return contentDigest.digest(); } finally { try { raw.close(); } catch (IOException err2) { } } } catch (IOException err) { return zeroid; } }

Target:
private byte[] idBufferBlob(final Entry e) { try { final InputStream is = e.openInputStream(); if (is == null) return zeroid; try { initializeDigestAndReadBuffer(); final long length = e.getLength(); if (!options.isAutocrlf()) return calculateHash(is, length); if (length <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) { final byte[] bytes = IO.readFully(is, (int) length); if (RawText.isBinary(new ByteArrayInputStream(bytes))) return calculateHash(new ByteArrayInputStream(bytes), length); final long canonicalLength = determineCanonicalizedLength(new ByteArrayInputStream( bytes)); return calculateHash(new EolCanonicalizingInputStream( new ByteArrayInputStream(bytes)), canonicalLength); } final InputStream binaryIs = e.openInputStream(); try { if (RawText.isBinary(binaryIs)) return calculateHash(is, length); } finally { binaryIs.close(); } final long canonicalLength; final InputStream lengthIs = e.openInputStream(); try { canonicalLength = determineCanonicalizedLength(lengthIs); } finally { lengthIs.close(); } return calculateHash(new EolCanonicalizingInputStream(is), canonicalLength); } finally { try { is.close(); } catch (IOException err2) { } } } catch (IOException err) { return zeroid; } }
Source:
protected void linkToCatchBlocks(Block block, List<Block> catches) { if (block.exitBlock != null && block.exitBlock.isFinallyBlock) { for (Block catchBlock : catches) { block.exitBlock.addSuccessor(catchBlock); } } else { for (Block catchBlock : catches) { block.addSuccessor(catchBlock); } } }

Target:
protected void linkToCatchBlocks(Block block, List<Block> catches) { Block blockForSuccessor = block; if (block.exitBlock != null && block.exitBlock.isFinallyBlock) { blockForSuccessor = block.exitBlock; } for (Block catchBlock : catches) { blockForSuccessor.addSuccessor(catchBlock); } }
Source:
public void createContainerWithPortBindings() throws DockerException { int baseport = dockerRule.getKind().equals("jersey")? 11000: 12000; ExposedPort tcp22 = ExposedPort.tcp(22); ExposedPort tcp23 = ExposedPort.tcp(23); Ports portBindings = new Ports(); portBindings.bind(tcp22, Binding.bindPort(baseport + 22)); portBindings.bind(tcp23, Binding.bindPort(baseport + 23)); portBindings.bind(tcp23, Binding.bindPort(baseport + 24)); CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("true") .withExposedPorts(tcp22, tcp23).withPortBindings(portBindings).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec(); assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22)[0], is(equalTo(Binding.bindPort(baseport + 22)))); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[0], is(equalTo(Binding.bindPort(baseport + 23)))); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[1], is(equalTo(Binding.bindPort(baseport + 24)))); }

Target:
public void createContainerWithPortBindings() throws DockerException { int baseport = getFactoryType() == FactoryType.JERSEY? 11000: 12000; ExposedPort tcp22 = ExposedPort.tcp(22); ExposedPort tcp23 = ExposedPort.tcp(23); Ports portBindings = new Ports(); portBindings.bind(tcp22, Binding.bindPort(baseport + 22)); portBindings.bind(tcp23, Binding.bindPort(baseport + 23)); portBindings.bind(tcp23, Binding.bindPort(baseport + 24)); CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withCmd("true") .withExposedPorts(tcp22, tcp23).withPortBindings(portBindings).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec(); assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()), contains(tcp22, tcp23)); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22)[0], is(equalTo(Binding.bindPort(baseport + 22)))); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[0], is(equalTo(Binding.bindPort(baseport + 23)))); assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[1], is(equalTo(Binding.bindPort(baseport + 24)))); }
Source:
public String toString() { return "Binary{" + length() + " bytes, " + Arrays.toString(getBytesUnsafe()) + "}"; }

Target:
public String toString() { return "Binary{" + length() + (isBackingBytesReused ? " reused": " constant") + " bytes, " + Arrays.toString(getBytesUnsafe()) + "}"; }
Source:
public boolean isActive() { return disabled == false; }

Target:
public boolean isActive() { return !disabled; }
Source:
private void addStorageResource() { String storageAccountName = name.replaceAll("[^A-Za-z0-9 ]", "") + "stor"; String storageName = template.getImage().getName(); if (storageName.substring(0, CUSTOM_IMAGE_PREFIX.length()).equals(CUSTOM_IMAGE_PREFIX)) { storageAccountName = storageName.substring(CUSTOM_IMAGE_PREFIX.length()); } variables.put("storageAccountName", storageAccountName); ResourceDefinition storageAccount = ResourceDefinition.builder() .name("[variables('storageAccountName')]") .type("Microsoft.Storage/storageAccounts") .location(location) .apiVersion(STORAGE_API_VERSION) .properties( StorageServiceProperties.builder() .accountType(StorageService.AccountType.Standard_LRS) .build() ) .build(); resources.add(storageAccount); }

Target:
private void addStorageResource() { String storageAccountName = name.replaceAll("[^A-Za-z0-9 ]", "") + "stor"; String storageName = template.getImage().getName(); if (storageName.startsWith(CUSTOM_IMAGE_PREFIX)) { storageAccountName = storageName.substring(CUSTOM_IMAGE_PREFIX.length()); } variables.put("storageAccountName", storageAccountName); ResourceDefinition storageAccount = ResourceDefinition.builder() .name("[variables('storageAccountName')]") .type("Microsoft.Storage/storageAccounts") .location(location) .apiVersion(STORAGE_API_VERSION) .properties( StorageServiceProperties.builder() .accountType(StorageService.AccountType.Standard_LRS) .build() ) .build(); resources.add(storageAccount); }
Source:
public boolean isItemVisible(VirtualItem item) { for (VirtualItem element : fSelection) { VirtualItem selectionItem = element; while (selectionItem != null) { if (item.equals(selectionItem)) { return true; } selectionItem = selectionItem.getParent(); } } return false; }

Target:
public boolean isItemVisible(VirtualItem item) { for (VirtualItem selectionItem : fSelection) { while (selectionItem != null) { if (item.equals(selectionItem)) { return true; } selectionItem = selectionItem.getParent(); } } return false; }
Source:
private void checkSecureCall(MethodInvocationTree mit) { if (isSetSecureCall(mit) && mit.methodSelect().is(Tree.Kind.MEMBER_SELECT)) { ExpressionTree methodObject = ((MemberSelectExpressionTree) mit.methodSelect()).expression(); Boolean secureArgument = getBooleanValue(mit.arguments().get(0)); Boolean isFalse = secureArgument != null && !secureArgument; if (methodObject.is(Tree.Kind.IDENTIFIER)) { IdentifierTree identifierTree = (IdentifierTree) methodObject; if (!isFalse) { unsecuredCookies.remove(identifierTree.symbol()); } else if (identifierTree.symbol().owner().isMethodSymbol()) { unsecuredCookies.add((Symbol.VariableSymbol) identifierTree.symbol()); } } else if (isFalse) { unsecuredSetters.add(mit); } } }

Target:
private void checkSecureCall(MethodInvocationTree mit) { if (isSetSecureCall(mit) && mit.methodSelect().is(Tree.Kind.MEMBER_SELECT)) { ExpressionTree methodObject = ((MemberSelectExpressionTree) mit.methodSelect()).expression(); Boolean secureArgument = getBooleanValue(mit.arguments().get(0)); boolean isFalse = secureArgument != null && !secureArgument; if (methodObject.is(Tree.Kind.IDENTIFIER)) { IdentifierTree identifierTree = (IdentifierTree) methodObject; if (!isFalse) { unsecuredCookies.remove(identifierTree.symbol()); } else if (identifierTree.symbol().owner().isMethodSymbol()) { unsecuredCookies.add((Symbol.VariableSymbol) identifierTree.symbol()); } } else if (isFalse) { unsecuredSetters.add(mit); } } }
Source:
} catch (NoSuchAlgorithmException e) { new RuntimeException("Unable to generate KeyPair", e); }

Target:
} catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); }
Source:
public void setEstimatedTimes(Map<Integer, Number> estimatedTimes) { for (int i = 0; i < actions.size(); i++) { if (estimatedTimes.containsKey(i)) { Optional<Number> estimate = Optional.of(estimatedTimes.get(i)); actions.get(i).setEstimatedTime(estimate); } else { actions.get(i).setEstimatedTime(Optional.empty()); } } }

Target:
public void setEstimatedTimes(Map<Integer, Number> estimatedTimes) { for (int i = 0; i < actions.size(); i++) { actions.get(i).setEstimatedTime(Optional.ofNullable(estimatedTimes.get(i))); } }
Source:
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) { return CompletableFuture .allOf(futures.toArray(new CompletableFuture<?>[futures.size()])) .thenApply(x -> futures.stream() .map(CompletableFuture::join) .collect(Collectors.toList())); }

Target:
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) { return allOf(futures).thenCompose(empty -> { CompletableFuture<List<T>> aggregated = CompletableFuture .completedFuture(new ArrayList<>()); for (CompletableFuture<T> future : futures) { aggregated = aggregated.thenCombine(future, (List<T> list, T value) -> { list.add(value); return list; }); } return aggregated; } ); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VdsStatistics other = (VdsStatistics) obj; return (ObjectUtils.objectsEqual(id, other.id) && ObjectUtils.bigDecimalEqual(cpu_idle, other.cpu_idle) && ObjectUtils.bigDecimalEqual(cpu_load, other.cpu_load) && ObjectUtils.bigDecimalEqual(cpu_sys, other.cpu_sys) && ObjectUtils.bigDecimalEqual(cpu_user, other.cpu_user) && ObjectUtils.objectsEqual(mem_available, other.mem_available) && ObjectUtils.objectsEqual(memFree, other.memFree) && ObjectUtils.objectsEqual(mem_shared, other.mem_shared) && ObjectUtils.objectsEqual(usage_cpu_percent, other.usage_cpu_percent) && ObjectUtils.objectsEqual(usage_network_percent, other.usage_network_percent) && ObjectUtils.objectsEqual(ksm_state, other.ksm_state) && ObjectUtils.objectsEqual(ksm_pages, other.ksm_pages) && ObjectUtils.objectsEqual(ksm_cpu_percent, other.ksm_cpu_percent) && ObjectUtils.objectsEqual(swap_total, other.swap_total) && ObjectUtils.objectsEqual(swap_free, other.swap_free) && (anonymousHugePages == other.anonymousHugePages) && (highlyAvailableScore == other.highlyAvailableScore) && (highlyAvailableIsConfigured == other.highlyAvailableIsConfigured) && (highlyAvailableIsActive == other.highlyAvailableIsActive) && (highlyAvailableGlobalMaintenance == other.highlyAvailableGlobalMaintenance) && (highlyAvailableLocalMaintenance == other.highlyAvailableLocalMaintenance) && uptime == other.uptime); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VdsStatistics other = (VdsStatistics) obj; return (ObjectUtils.objectsEqual(id, other.id) && ObjectUtils.bigDecimalEqual(cpu_idle, other.cpu_idle) && ObjectUtils.bigDecimalEqual(cpu_load, other.cpu_load) && ObjectUtils.bigDecimalEqual(cpu_sys, other.cpu_sys) && ObjectUtils.bigDecimalEqual(cpu_user, other.cpu_user) && ObjectUtils.objectsEqual(mem_available, other.mem_available) && ObjectUtils.objectsEqual(memFree, other.memFree) && ObjectUtils.objectsEqual(mem_shared, other.mem_shared) && ObjectUtils.objectsEqual(usage_cpu_percent, other.usage_cpu_percent) && ObjectUtils.objectsEqual(usage_network_percent, other.usage_network_percent) && ObjectUtils.objectsEqual(ksm_state, other.ksm_state) && ObjectUtils.objectsEqual(ksm_pages, other.ksm_pages) && ObjectUtils.objectsEqual(ksm_cpu_percent, other.ksm_cpu_percent) && ObjectUtils.objectsEqual(swap_total, other.swap_total) && ObjectUtils.objectsEqual(swap_free, other.swap_free) && (anonymousHugePages == other.anonymousHugePages) && (highlyAvailableScore == other.highlyAvailableScore) && (highlyAvailableIsConfigured == other.highlyAvailableIsConfigured) && (highlyAvailableIsActive == other.highlyAvailableIsActive) && (highlyAvailableGlobalMaintenance == other.highlyAvailableGlobalMaintenance) && (highlyAvailableLocalMaintenance == other.highlyAvailableLocalMaintenance) && ObjectUtils.objectsEqual(uptime, other.uptime)); }
Source:
public void write(DataOutput output) throws IOException { WritableUtils.writeVInt(output, returnCode.ordinal()); output.writeLong(mutationTime); output.writeBoolean(table != null); if (table != null) { table.write(output); } output.writeBoolean(column != null); if (column != null) { column.write(output); } if(tableNamesToDelete != null && tableNamesToDelete.size() > 0 ) { output.writeBoolean(true); output.writeInt(tableNamesToDelete.size()); for(byte[] tableName : tableNamesToDelete) { Bytes.writeByteArray(output,tableName); } } else { output.writeBoolean(false); } }

Target:
public void write(DataOutput output) throws IOException { WritableUtils.writeVInt(output, returnCode.ordinal()); output.writeLong(mutationTime); output.writeBoolean(table != null); if (table != null) { table.write(output); } Bytes.writeByteArray(output, columnName == null ? ByteUtil.EMPTY_BYTE_ARRAY : columnName); if (columnName != null) { Bytes.writeByteArray(output, familyName == null ? ByteUtil.EMPTY_BYTE_ARRAY : familyName); } if(tableNamesToDelete != null && tableNamesToDelete.size() > 0 ) { output.writeBoolean(true); output.writeInt(tableNamesToDelete.size()); for(byte[] tableName : tableNamesToDelete) { Bytes.writeByteArray(output,tableName); } } else { output.writeBoolean(false); } }
Source:
private void setSegmentDuration(LiveStreamPacketizerCupertino cupertinoPacketizer, IMediaStream stream) { String streamName = stream.getName(); int segmentDuration = Constants.DEFAULT_CHUNK_DURATION_MILLISECONDS; boolean durationUpdated = false; String entryId = Utils.getEntryIdFromStreamName(streamName); try { KalturaLiveEntry liveEntry = Utils.getLiveEntryFromStream(stream); durationUpdated = isValidSegmentDuration(liveEntry.segmentDuration); if (durationUpdated) { segmentDuration = liveEntry.segmentDuration; logger.debug("(" + streamName + ") successfully set \"cupertinoChunkDurationTarget\" to " + segmentDuration + " milliseconds"); } else { logger.error("(" + streamName + ") failed to get \"segmentDuration\". Using default value, " + Constants.DEFAULT_CHUNK_DURATION_MILLISECONDS + " milliseconds. Call developer."); } } catch (Exception e) { if (!(e instanceof NullPointerException)) { logger.error("stream [" + streamName + "] failed to get segmentDuration. Using default value, \" + Constants.DEFAULT_CHUNK_DURATION_MILLISECONDS + \" milliseconds. Call developer." + e); } } cupertinoPacketizer.getProperties().setProperty("cupertinoChunkDurationTarget", segmentDuration); }

Target:
private void setSegmentDuration(LiveStreamPacketizerCupertino cupertinoPacketizer, IMediaStream stream) { String streamName = stream.getName(); int segmentDuration = Constants.DEFAULT_CHUNK_DURATION_MILLISECONDS; try { KalturaLiveEntry liveEntry = Utils.getLiveEntryFromStream(stream); if (isValidSegmentDuration(liveEntry.segmentDuration)) { segmentDuration = liveEntry.segmentDuration; logger.debug("(" + streamName + ") successfully set \"cupertinoChunkDurationTarget\" to " + segmentDuration + " milliseconds"); } else { logger.error("(" + streamName + ") failed to get \"segmentDuration\". Using default value, " + Constants.DEFAULT_CHUNK_DURATION_MILLISECONDS + " milliseconds. Call developer."); } } catch (Exception e) { logger.error("stream [" + streamName + "] failed to get segmentDuration. Using default value, \" + Constants.DEFAULT_CHUNK_DURATION_MILLISECONDS + \" milliseconds. Call developer." + e); } cupertinoPacketizer.getProperties().setProperty("cupertinoChunkDurationTarget", segmentDuration); }
Source:
public void delete(List<Delete> deletes) throws IOException { if (tx == null) { throw new IOException("Transaction not started"); } List<Delete> transactionalizedDeletes = new ArrayList<Delete>(deletes.size()); for (Delete delete : deletes) { Delete txDelete = transactionalizeAction(delete); transactionalizedDeletes.add(txDelete); } hTable.delete(transactionalizedDeletes); }

Target:
public void delete(List<Delete> deletes) throws IOException { if (tx == null) { throw new IOException("Transaction not started"); } List<Delete> transactionalizedDeletes = new ArrayList<>(deletes.size()); for (Delete delete : deletes) { Delete txDelete = transactionalizeAction(delete); transactionalizedDeletes.add(txDelete); } hTable.delete(transactionalizedDeletes); }
Source:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (senderIsConsole) { if (args.length == 0) { sender.sendMessage("When sending this command through console you must specify a player."); return true; } } Player player; if (args.length == 0) { player = sender_p; } else { if (args[0].equalsIgnoreCase("-a")) { if (!TFM_AdminList.isSuperAdmin(sender)) { sender.sendMessage(TFM_Command.MSG_NO_PERMS); return true; } for (Player targetPlayer : server.getOnlinePlayers()) { targetPlayer.setGameMode(GameMode.CREATIVE); } TFM_Util.adminAction(sender.getName(), "Changing everyone's gamemode to spectator mode.", false); return true; } if (!(senderIsConsole || TFM_AdminList.isSuperAdmin(sender))) { playerMsg("Only superadmins can change other user's gamemode."); return true; } player = getPlayer(args[0]); if (player == null) { sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); return true; } } playerMsg("Setting " + player.getName() + " to game mode 'Spectator Mode'."); playerMsg(player, sender.getName() + " set your game mode to 'Spectator Mode'."); player.setGameMode(GameMode.SPECTATOR); return true; }

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (senderIsConsole) { if (args.length == 0) { sender.sendMessage("When sending this command through console you must specify a player."); return true; } } Player player; if (args.length == 0) { player = sender_p; } else { if (args[0].equalsIgnoreCase("-a")) { if (!TFM_AdminList.isSuperAdmin(sender)) { sender.sendMessage(TFM_Command.MSG_NO_PERMS); return true; } for (Player targetPlayer : server.getOnlinePlayers()) { targetPlayer.setGameMode(GameMode.SPECTATOR); } TFM_Util.adminAction(sender.getName(), "Changing everyone's gamemode to spectator mode.", false); return true; } if (!(senderIsConsole || TFM_AdminList.isSuperAdmin(sender))) { playerMsg("Only superadmins can change other user's gamemode."); return true; } player = getPlayer(args[0]); if (player == null) { sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); return true; } } playerMsg("Setting " + player.getName() + " to game mode 'Spectator Mode'."); playerMsg(player, sender.getName() + " set your game mode to 'Spectator Mode'."); player.setGameMode(GameMode.SPECTATOR); return true; }
Source:
public void test() throws Exception { testDataFormat("asn1"); }

Target:
public void test() throws Exception { testDataFormat(COMPONENT); }
Source:
public CommonProfileDefinition() { primary(EMAIL, Converters.STRING); primary(FIRST_NAME, Converters.STRING); primary(FAMILY_NAME, Converters.STRING); primary(DISPLAY_NAME, Converters.STRING); primary(GENDER, Converters.GENDER); primary(LOCALE, Converters.LOCALE); primary(PICTURE_URL, Converters.URL); primary(PROFILE_URL, Converters.URL); primary(LOCATION, Converters.STRING); primary(USERNAME, Converters.STRING); }

Target:
public CommonProfileDefinition() { primary(EMAIL, Converters.STRING); primary(FIRST_NAME, Converters.STRING); primary(FAMILY_NAME, Converters.STRING); primary(DISPLAY_NAME, Converters.STRING); primary(GENDER, Converters.GENDER); primary(LOCALE, Converters.LOCALE); primary(PICTURE_URL, Converters.URL); primary(PROFILE_URL, Converters.URL); primary(LOCATION, Converters.STRING); primary(Pac4jConstants.USERNAME, Converters.STRING); }
Source:
protected void recognizeArguments(CommandContext ctx) throws CommandFormatException { ModelNode op = new ModelNode(); op.get("operation").set("read-operation-description"); op.get("name").set("read-attribute"); OperationRequestAddress address = getOperationRequestAddress(ctx); op = getAddressNode(ctx, address, op); ModelNode returnVal = new ModelNode(); try { if( ctx.getModelControllerClient() != null ) { returnVal = ctx.getModelControllerClient().execute(op); } } catch (IOException e) { throw new CommandFormatException("Failed to read resource: " + e.getLocalizedMessage(), e); } final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine(); if( returnVal.hasDefined("outcome") && returnVal.get("outcome").asString().equals("success")){ ModelNode result = returnVal.get("result"); if(result.hasDefined("request-properties")){ ModelNode properties = result.get("request-properties"); if( !properties.hasDefined("resolve-expressions") && resolve.isPresent(parsedCmd)) { throw new OperationFormatException("Resolve Expression argument not available at this location."); } } } }

Target:
protected void recognizeArguments(CommandContext ctx) throws CommandFormatException { super.recognizeArguments(ctx); final ParsedCommandLine parsedCmd = ctx.getParsedCommandLine(); if(resolve.isPresent(parsedCmd)) { ModelNode op = new ModelNode(); op.get("operation").set("read-operation-description"); op.get("name").set("read-attribute"); OperationRequestAddress address = getOperationRequestAddress(ctx); op = getAddressNode(ctx, address, op); ModelNode returnVal = new ModelNode(); try { if (ctx.getModelControllerClient() != null) { returnVal = ctx.getModelControllerClient().execute(op); } } catch (IOException e) { throw new CommandFormatException("Failed to read resource: " + e.getLocalizedMessage(), e); } if (returnVal.hasDefined("outcome") && returnVal.get("outcome").asString().equals("success")) { ModelNode result = returnVal.get("result"); if (result.hasDefined("request-properties")) { ModelNode properties = result.get("request-properties"); if (!properties.hasDefined("resolve-expressions") && resolve.isPresent(parsedCmd)) { throw new OperationFormatException("Resolve Expression argument not available at this location."); } } } } }
Source:
public void testFailureRebindingEntityWhenFailAtEnd() throws Exception { RebindFailureMode danglingRefFailureMode = RebindFailureMode.CONTINUE; RebindFailureMode rebindFailureMode = RebindFailureMode.FAIL_AT_END; MyEntity origFailingE = origApp.createAndManageChild(EntitySpec.create(MyEntity.class) .impl(MyEntityFailingImpl.class) .configure(MyEntityFailingImpl.FAIL_ON_REBIND, true)); newManagementContext = new LocalManagementContext(); EntityManager newEntityManager = newManagementContext.getEntityManager(); RebindExceptionHandlerImpl exceptionHandler = new RebindExceptionHandlerImpl(danglingRefFailureMode, rebindFailureMode); try { newApp = rebind(newManagementContext, exceptionHandler); fail(); } catch (Exception e) { if (!e.toString().contains("Problems rebinding")) throw e; } assertEquals(toEntityIds(exceptionHandler.rebindEntityFailures.keySet()), ImmutableSet.of(origFailingE.getId())); assertEquals(toEntityIds(newEntityManager.getEntities()), ImmutableSet.of(origApp.getId(), origFailingE.getId())); }

Target:
public void testFailureRebindingEntityWhenFailAtEnd() throws Exception { RebindFailureMode danglingRefFailureMode = RebindFailureMode.CONTINUE; RebindFailureMode rebindFailureMode = RebindFailureMode.FAIL_AT_END; MyEntity origFailingE = origApp.createAndManageChild(EntitySpec.create(MyEntity.class) .impl(MyEntityFailingImpl.class) .configure(MyEntityFailingImpl.FAIL_ON_REBIND, true)); newManagementContext = new LocalManagementContext(); EntityManager newEntityManager = newManagementContext.getEntityManager(); RecordingRebindExceptionHandler exceptionHandler = new RecordingRebindExceptionHandler(danglingRefFailureMode, rebindFailureMode); try { newApp = rebind(newManagementContext, exceptionHandler); fail(); } catch (Exception e) { if (!e.toString().contains("Problems rebinding")) throw e; } assertEquals(toEntityIds(exceptionHandler.rebindEntityFailures.keySet()), ImmutableSet.of(origFailingE.getId())); assertEquals(toEntityIds(newEntityManager.getEntities()), ImmutableSet.of(origApp.getId(), origFailingE.getId())); }
Source:
protected EventLoop newChild(Executor executor, Object... args) throws Exception { return new LocalEventLoop(this, executor); }

Target:
protected EventLoop newChild(Executor executor, Object... args) throws Exception { assert args == null || args.length == 0; return new LocalEventLoop(this, executor); }
Source:
public PingCommand getCurrentStatus(long id) { if (_relativePath == null || _relativePath.isEmpty()) { s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the relative path information"); _shouldAudit = true; return null; } if (_cmsUserLogin == null || _cmsUserLogin.isEmpty() || _cmsUserPassword == null || _cmsUserPassword.isEmpty()) { s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the CMS user information"); _shouldAudit = true; return null; } try { login(); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failed to ping to Nuage VSD on " + _name + " as user " + _cmsUserLogin, e); _shouldAudit = true; return null; } PingNuageVspCommand pingNuageVspCommand = new PingNuageVspCommand(Host.Type.L2Networking, id, _shouldAudit); _shouldAudit = false; return pingNuageVspCommand; }

Target:
public PingCommand getCurrentStatus(long id) { if (Strings.isNullOrEmpty(_relativePath)) { s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the relative path information"); _shouldAudit = true; return null; } if (Strings.isNullOrEmpty(_cmsUserLogin) || Strings.isNullOrEmpty(_cmsUserPassword)) { s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the CMS user information"); _shouldAudit = true; return null; } try { login(); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failed to ping to Nuage VSD on " + _name + " as user " + _cmsUserLogin, e); _shouldAudit = true; return null; } PingNuageVspCommand pingNuageVspCommand = new PingNuageVspCommand(Host.Type.L2Networking, id, _shouldAudit); _shouldAudit = false; return pingNuageVspCommand; }
Source:
public List<Map<String, Object>> getAllCalls(final String dataType, final Integer pageSize, final Integer pageNumber) { try { List<Map<String, Object>> brapiCalls; final String jsonPath; if (dataType != null) { jsonPath = "$.data[?('" + dataType + "' in @['datatypes'])]"; } else { jsonPath = "$.data.*"; } final InputStream is = CallServiceImpl.class.getClassLoader().getResourceAsStream("brapi/calls.json"); final String jsonTxt = IOUtils.toString( is ); brapiCalls = JsonPath.parse(jsonTxt).read(jsonPath); if (pageNumber != null && pageSize != null) { int maxLenght = pageSize * (pageNumber) + pageSize; if (maxLenght > brapiCalls.size()) { maxLenght = brapiCalls.size(); } int minLenght = (pageNumber - 1) * pageSize; if (minLenght < 0) { minLenght = 0; } brapiCalls = brapiCalls.subList(minLenght, maxLenght); } return brapiCalls; } catch (final IOException e) { e.printStackTrace(); } return null; }

Target:
public List<Map<String, Object>> getAllCalls(final String dataType, final Integer pageSize, final Integer pageNumber) { try { List<Map<String, Object>> brapiCalls; final String jsonPath; if (dataType != null) { jsonPath = "$.data[?('" + dataType + "' in @['datatypes'])]"; } else { jsonPath = "$.data.*"; } final InputStream is = CallServiceImpl.class.getClassLoader().getResourceAsStream("brapi/calls.json"); final String jsonTxt = IOUtils.toString( is ); brapiCalls = JsonPath.parse(jsonTxt).read(jsonPath); if (pageNumber != null && pageSize != null) { int maxLenght = pageSize * (pageNumber) + pageSize; if (maxLenght > brapiCalls.size()) { maxLenght = brapiCalls.size(); } int minLenght = (pageNumber - 1) * pageSize; if (minLenght < 0) { minLenght = 0; } brapiCalls = brapiCalls.subList(minLenght, maxLenght); } return brapiCalls; } catch (final IOException e) { e.printStackTrace(); return null; } }
Source:
public static void setUp() throws IOException, BadPcapFileException, TmfTraceException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); if (trace.getPath().getFileName().toString().endsWith(".pcapng")) { try (PcapFile pcap = new PcapNgFile(trace.getPath());) { PcapTrace pcapTrace = new PcapTrace(); pcapTrace.initTrace(null, trace.getPath().toString(), PcapEvent.class); fEvent = pcapTrace.parseEvent(new TmfContext(new TmfLongLocation(3), 3)); pcapTrace.dispose(); } }else { try (PcapFile pcap = new PcapOldFile(trace.getPath());) { PcapTrace pcapTrace = new PcapTrace(); pcapTrace.initTrace(null, trace.getPath().toString(), PcapEvent.class); fEvent = pcapTrace.parseEvent(new TmfContext(new TmfLongLocation(3), 3)); pcapTrace.dispose(); } } List<TmfPcapProtocol> list = new ArrayList<>(); list.add(TmfPcapProtocol.PCAP); list.add(TmfPcapProtocol.ETHERNET_II); list.add(TmfPcapProtocol.IPV4); list.add(TmfPcapProtocol.TCP); list.add(TmfPcapProtocol.UNKNOWN); fProtocolList = ImmutableList.copyOf(list); }

Target:
public static void setUp() throws IOException, BadPcapFileException, TmfTraceException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); PcapTrace pcapTrace = new PcapTrace(); pcapTrace.initTrace(null, trace.getPath().toString(), PcapEvent.class); fEvent = pcapTrace.parseEvent(new TmfContext(new TmfLongLocation(3), 3)); pcapTrace.dispose(); List<TmfPcapProtocol> list = new ArrayList<>(); list.add(TmfPcapProtocol.PCAP); list.add(TmfPcapProtocol.ETHERNET_II); list.add(TmfPcapProtocol.IPV4); list.add(TmfPcapProtocol.TCP); list.add(TmfPcapProtocol.UNKNOWN); fProtocolList = ImmutableList.copyOf(list); }