auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setUp() throws Exception { productReleaseDao = mock(ProductReleaseDao.class); productReleaseSdcDao = mock(ProductReleaseSdcDao.class); metadataDao = mock (MetadataDao.class); attributeDao = mock (AttributeDao.class); claudiaData = mock (ClaudiaData.class); manager = new ProductReleaseManagerImpl(); manager.setAttributeDao(attributeDao); manager.setMetadataDao(metadataDao); manager.setProductReleaseDao(productReleaseDao); manager.setProductReleaseSdcDao(productReleaseSdcDao); productReleasePM = new ProductRelease("product", "version"); productReleaseSDC = new ProductRelease("product", "version"); Metadata metadata1 = new Metadata("key1", "value1"); productReleasePM.addMetadata(metadata1); productReleaseSDC.addMetadata(metadata1); Metadata metadata2 = new Metadata("key2", "value2"); productReleasePM.addMetadata(metadata2); productReleaseSDC.addMetadata(metadata2); productReleaseSDC.addMetadata(metadata_diff); when(productReleaseSdcDao.load(eq("product"), eq("version"), any(ClaudiaData.class))).thenReturn(productReleaseSDC); when(productReleaseDao.load(any(String.class))).thenReturn(productReleasePM); when(metadataDao.create(any(Metadata.class))).thenReturn(metadata_diff); }

Target:
public void setUp() throws Exception { productReleaseDao = mock(ProductReleaseDao.class); productReleaseSdcDao = mock(ProductReleaseSdcDao.class); metadataDao = mock (MetadataDao.class); attributeDao = mock (AttributeDao.class); claudiaData = mock (ClaudiaData.class); manager = new ProductReleaseManagerImpl(); manager.setAttributeDao(attributeDao); manager.setMetadataDao(metadataDao); manager.setProductReleaseDao(productReleaseDao); manager.setProductReleaseSdcDao(productReleaseSdcDao); productReleasePM = new ProductRelease("product", "version"); productReleaseSDC = new ProductRelease("product", "version"); Metadata metadata1 = new Metadata("key1", "value1"); productReleasePM.addMetadata(metadata1); productReleaseSDC.addMetadata(metadata1); Metadata metadata2 = new Metadata("key2", "value2"); productReleasePM.addMetadata(metadata2); productReleaseSDC.addMetadata(metadata2); productReleaseSDC.addMetadata(metadata_diff); when(productReleaseSdcDao.load(eq("product"), eq("version"), any(ClaudiaData.class))) .thenReturn(productReleaseSDC); when(productReleaseDao.load(any(String.class))).thenReturn(productReleasePM); when(metadataDao.create(any(Metadata.class))).thenReturn(metadata_diff); when(metadataDao.load(any(String.class))).thenReturn(metadata_diff); }
Source:
public String getLabel() { if (tagType == ReaderTagType.DEFAULT) { return getTagTitle(); } else if (isTagAlphaNumeric(tagDisplayName)) { return tagDisplayName.toLowerCase(); } else if (hasTagTitle()) { return getTagTitle(); } else { return getTagDisplayName(); } }

Target:
public String getLabel() { if (tagType == ReaderTagType.DEFAULT) { return getTagTitle(); } else if (isTagDisplayNameAlphaNumeric()) { return getTagDisplayName().toLowerCase(); } else if (hasTagTitle()) { return getTagTitle(); } else { return getTagDisplayName(); } }
Source:
protected BreakpointContainer[] getContainers(IBreakpoint breakpoint) { if (isShowingGroups()) { IAdaptable[] categories = fOrganizers[0].getCategories(breakpoint); if (categories == null || categories.length == 0) { categories = OtherBreakpointCategory.getCategories(fOrganizers[0]); } BreakpointContainer[] containers = new BreakpointContainer[categories.length]; int index = 0; for (Object fElement : fElements) { BreakpointContainer container = (BreakpointContainer)fElement; for (IAdaptable category : categories) { if (container.getCategory().equals(category)) { containers[index] = container; index++; } } } return containers; } return null; }

Target:
protected BreakpointContainer[] getContainers(IBreakpoint breakpoint) { if (isShowingGroups()) { IAdaptable[] categories = fOrganizers[0].getCategories(breakpoint); if (categories == null || categories.length == 0) { categories = OtherBreakpointCategory.getCategories(fOrganizers[0]); } BreakpointContainer[] containers = new BreakpointContainer[categories.length]; int index = 0; for (Object element : fElements) { BreakpointContainer container = (BreakpointContainer)element; for (IAdaptable category : categories) { if (container.getCategory().equals(category)) { containers[index] = container; index++; } } } return containers; } return null; }
Source:
public Map<String, Set<String>> getPrincipalRoles(PID target) { List<PID> path = getPidPath(target); Map<String, Set<String>> inheritedPrincRoles = new HashMap<>(); Set<String> patronPrincipals = null; int depth = 0; for (; depth < path.size(); depth++) { PID pathPid = path.get(depth); if (depth < 2) { Map<String, Set<String>> objectPrincipalRoles = objectAclFactory.getPrincipalRoles(pathPid); mergePrincipalRoles(inheritedPrincRoles, objectPrincipalRoles); } else { if (inheritedPrincRoles.isEmpty()) { return inheritedPrincRoles; } if (patronPrincipals == null) { patronPrincipals = getPatronPrincipals(inheritedPrincRoles.keySet()); } if (patronPrincipals.size() == 0) { return inheritedPrincRoles; } removeRevokedPatronRoles(pathPid, inheritedPrincRoles, patronPrincipals); } } if (depth == 1) { Set<String> roles = new HashSet<>(); roles.add(UserRole.canViewOriginals.getPropertyString()); inheritedPrincRoles.put("everyone", roles); } return inheritedPrincRoles; }

Target:
public Map<String, Set<String>> getPrincipalRoles(PID target) { List<PID> path = getPidPath(target); Map<String, Set<String>> inheritedPrincRoles = new HashMap<>(); Set<String> patronPrincipals = null; int depth = 0; for (; depth < path.size(); depth++) { PID pathPid = path.get(depth); if (depth < CONTENT_STARTING_DEPTH) { Map<String, Set<String>> objectPrincipalRoles = objectAclFactory.getPrincipalRoles(pathPid); mergePrincipalRoles(inheritedPrincRoles, objectPrincipalRoles); } else { if (inheritedPrincRoles.isEmpty()) { return inheritedPrincRoles; } if (patronPrincipals == null) { patronPrincipals = getPatronPrincipals(inheritedPrincRoles.keySet()); } if (patronPrincipals.size() == 0) { return inheritedPrincRoles; } revokedPatronRoles(pathPid, inheritedPrincRoles, patronPrincipals); } } if (depth == UNIT_PATH_DEPTH + 1) { Set<String> roles = new HashSet<>(); roles.add(UserRole.canViewOriginals.getPropertyString()); inheritedPrincRoles.put("everyone", roles); } return inheritedPrincRoles; }
Source:
@Override public void onReady() { Scope scope = currentTraceContext.maybeScope(invocationContext); try { delegate().onReady(); } finally { scope.close(); } }

Target:
@Override public void onReady() { try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { delegate().onReady(); } }
Source:
private LockResponse lock(LockDescriptor lockDescriptor) { TimelockService timelockService = new LegacyTimelockService(timestampService, lockService, lockClient); LockRequest lockRequest = LockRequest.of(ImmutableSet.of(lockDescriptor), 5_000); return timelockService.lock(lockRequest); }

Target:
private LockResponse lock(LockDescriptor lockDescriptor) { LockRequest lockRequest = LockRequest.of(ImmutableSet.of(lockDescriptor), 5_000); return timelockService.lock(lockRequest); }
Source:
public PackageBuilder getPackageBuilder() { if (packagingType.equals(MULE_DOMAIN_BUNDLE)) { return new DomainBundlePackageBuilder(); } PackagingOptions options = new PackagingOptions(onlyMuleSources, lightweightPackage, attachMuleSources); return new MulePackageBuilder().withPackagingOptions(options); }

Target:
public PackageBuilder getPackageBuilder() { PackagingOptions options = new PackagingOptions(onlyMuleSources, lightweightPackage, attachMuleSources); return PackageBuilderFactory.create(packagingType, options); }
Source:
private CopyCmdAnswer performCopyOfVdi(VolumeInfo volumeInfo, SnapshotInfo snapshotInfo, HostVO hostVO) { String value = _configDao.getValue(Config.PrimaryStorageDownloadWait.toString()); int primaryStorageDownloadWait = NumbersUtil.parseInt(value, Integer.parseInt(Config.PrimaryStorageDownloadWait.getDefaultValue())); CopyCommand copyCommand = new CopyCommand(snapshotInfo.getTO(), volumeInfo.getTO(), primaryStorageDownloadWait, VirtualMachineManager.ExecuteInSequence.value()); CopyCmdAnswer copyCmdAnswer = null; try { _volumeService.grantAccess(snapshotInfo, hostVO, snapshotInfo.getDataStore()); _volumeService.grantAccess(volumeInfo, hostVO, volumeInfo.getDataStore()); Map<String, String> srcDetails = getSnapshotDetails(snapshotInfo); copyCommand.setOptions(srcDetails); Map<String, String> destDetails = getVolumeDetails(volumeInfo); copyCommand.setOptions2(destDetails); copyCmdAnswer = (CopyCmdAnswer)_agentMgr.send(hostVO.getId(), copyCommand); } catch (Exception ex) { throw new CloudRuntimeException(ex.getMessage()); } finally { try { _volumeService.revokeAccess(snapshotInfo, hostVO, snapshotInfo.getDataStore()); } catch (Exception ex) { s_logger.debug(ex.getMessage(), ex); } try { _volumeService.revokeAccess(volumeInfo, hostVO, volumeInfo.getDataStore()); } catch (Exception ex) { s_logger.debug(ex.getMessage(), ex); } } return copyCmdAnswer; }

Target:
private CopyCmdAnswer performCopyOfVdi(VolumeInfo volumeInfo, SnapshotInfo snapshotInfo, HostVO hostVO) { String value = _configDao.getValue(Config.PrimaryStorageDownloadWait.toString()); int primaryStorageDownloadWait = NumbersUtil.parseInt(value, Integer.parseInt(Config.PrimaryStorageDownloadWait.getDefaultValue())); CopyCommand copyCommand = new CopyCommand(snapshotInfo.getTO(), volumeInfo.getTO(), primaryStorageDownloadWait, VirtualMachineManager.ExecuteInSequence.value()); CopyCmdAnswer copyCmdAnswer = null; try { _volumeService.grantAccess(snapshotInfo, hostVO, snapshotInfo.getDataStore()); _volumeService.grantAccess(volumeInfo, hostVO, volumeInfo.getDataStore()); Map<String, String> srcDetails = getSnapshotDetails(snapshotInfo); copyCommand.setOptions(srcDetails); Map<String, String> destDetails = getVolumeDetails(volumeInfo); copyCommand.setOptions2(destDetails); copyCmdAnswer = (CopyCmdAnswer)_agentMgr.send(hostVO.getId(), copyCommand); } catch (CloudRuntimeException | AgentUnavailableException | OperationTimedoutException ex) { String msg = "Failed to perform VDI copy : "; LOGGER.warn(msg, ex); throw new CloudRuntimeException(msg + ex.getMessage()); } finally { _volumeService.revokeAccess(snapshotInfo, hostVO, snapshotInfo.getDataStore()); _volumeService.revokeAccess(volumeInfo, hostVO, volumeInfo.getDataStore()); } return copyCmdAnswer; }
Source:
private ListenableFuture<Boolean> get(String key, OutputStream out, boolean actionResult) { boolean foundOnDisk = diskCache.toPath(key, actionResult).exists(); if (foundOnDisk) { return getFromCache(diskCache, key, out, actionResult); } else { return getFromRemoteAndSaveToDisk(key, out, actionResult); } }

Target:
private ListenableFuture<Boolean> get(String key, OutputStream out, boolean actionResult) { boolean foundOnDisk = actionResult ? diskCache.containsActionResult(key) : diskCache.contains(key); if (foundOnDisk) { return getFromCache(diskCache, key, out, actionResult); } else { return getFromRemoteAndSaveToDisk(key, out, actionResult); } }
Source:
private JoinEnumerationResult(Optional<PlanNode> planNode, PlanNodeCostEstimate cost) { this.planNode = requireNonNull(planNode); this.cost = requireNonNull(cost); checkArgument((cost.hasUnknownComponents() || cost.equals(INFINITE_COST)) && !planNode.isPresent() || (!cost.hasUnknownComponents() || !cost.equals(INFINITE_COST)) && planNode.isPresent(), "planNode should be present if and only if cost is known"); }

Target:
private JoinEnumerationResult(Optional<PlanNode> planNode, PlanNodeCostEstimate cost) { this.planNode = requireNonNull(planNode, "planNode is null"); this.cost = requireNonNull(cost, "cost is null"); checkArgument((cost.hasUnknownComponents() || cost.equals(INFINITE_COST)) && !planNode.isPresent() || (!cost.hasUnknownComponents() || !cost.equals(INFINITE_COST)) && planNode.isPresent(), "planNode should be present if and only if cost is known"); }
Source:
public String toString() { return Objects.toStringHelper(this).add("uuid", uuid).add("description", description).add("osFamily", osFamily) .add("osVersion", osVersion).add("size", size).add("is64bit", is64bit).add("loginUser", loginUser) .toString(); }

Target:
public String toString() { return Objects.toStringHelper(this).omitNullValues().add("uuid", uuid).add("description", description) .add("osFamily", osFamily).add("osVersion", osVersion).add("size", size).add("is64bit", is64bit) .add("loginUser", loginUser).toString(); }
Source:
public PlanNodeCostEstimate calculateCost(PlanNode planNode, Lookup lookup, Session session, Map<Symbol, Type> types) { return UNKNOWN_COST; }

Target:
public PlanNodeCostEstimate calculateCost(PlanNode planNode, Lookup lookup, Session session, Map<Symbol, Type> types) { CostEstimator costEstimator = new CostEstimator( session, types, lookup, numberOfNodes); return planNode.accept(costEstimator, null); }
Source:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { SqsConfiguration configuration = new SqsConfiguration(); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Queue name must be specified."); } if (remaining.startsWith("arn:")) { String[] parts = remaining.split(":"); if (parts.length != 6 || !parts[2].equals("sqs")) { throw new IllegalArgumentException("Queue arn must be in format arn:aws:sqs:region:account:name."); } configuration.setRegion(parts[3]); configuration.setQueueOwnerAWSAccountId(parts[4]); configuration.setQueueName(parts[5]); } else { configuration.setQueueName(remaining); } if (configuration.getAmazonSQSClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("AmazonSQSClient or accessKey and secretKey must be specified."); } if (configuration.isExtendMessageVisibility() && (configuration.getVisibilityTimeout() == null)) { throw new IllegalArgumentException("Extending message visibility (extendMessageVisibility) requires visibilityTimeout to be set on the Endpoint."); } if (configuration.isFifoQueue() && configuration.getMessageGroupIdStrategy() == null) { throw new IllegalArgumentException("messageGroupIdStrategy must be set for FIFO queues."); } SqsEndpoint sqsEndpoint = new SqsEndpoint(uri, this, configuration); sqsEndpoint.setConsumerProperties(parameters); return sqsEndpoint; }

Target:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { SqsConfiguration configuration = new SqsConfiguration(); setProperties(configuration, parameters); if (remaining == null || remaining.trim().length() == 0) { throw new IllegalArgumentException("Queue name must be specified."); } if (remaining.startsWith("arn:")) { String[] parts = remaining.split(":"); if (parts.length != 6 || !parts[2].equals("sqs")) { throw new IllegalArgumentException("Queue arn must be in format arn:aws:sqs:region:account:name."); } configuration.setRegion(parts[3]); configuration.setQueueOwnerAWSAccountId(parts[4]); configuration.setQueueName(parts[5]); } else { configuration.setQueueName(remaining); } if (configuration.getAmazonSQSClient() == null && (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) { throw new IllegalArgumentException("AmazonSQSClient or accessKey and secretKey must be specified."); } if (configuration.isExtendMessageVisibility() && (configuration.getVisibilityTimeout() == null)) { throw new IllegalArgumentException("Extending message visibility (extendMessageVisibility) requires visibilityTimeout to be set on the Endpoint."); } if (configuration.isFifoQueue() && ObjectHelper.isEmpty(configuration.getMessageGroupIdStrategy())) { throw new IllegalArgumentException("messageGroupIdStrategy must be set for FIFO queues."); } SqsEndpoint sqsEndpoint = new SqsEndpoint(uri, this, configuration); sqsEndpoint.setConsumerProperties(parameters); return sqsEndpoint; }
Source:
private void disposeServices() { HashMap<Class<?>, Object> copy = new HashMap<>(services); Set<Entry<Class<?>, Object>> entrySet = copy.entrySet(); for (Entry<Class<?>, Object> entry : entrySet) { if (entry.getValue() instanceof IDisposable) { IDisposable iDisposable = (IDisposable) entry.getValue(); SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { iDisposable.dispose(); } @Override public void handleException(Throwable ex) { WorkbenchPlugin .log(StatusUtil.newStatus(IStatus.ERROR, "Error while disposing: " + iDisposable, ex)); } }); } services.remove(entry.getKey()); } }

Target:
private void disposeServices() { Iterator<Entry<Class<?>, Object>> iterator = services.entrySet().iterator(); while (iterator.hasNext()) { Entry<Class<?>, Object> entry = iterator.next(); if (entry.getValue() instanceof IDisposable) { IDisposable iDisposable = (IDisposable) entry.getValue(); SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { iDisposable.dispose(); } @Override public void handleException(Throwable ex) { WorkbenchPlugin .log(StatusUtil.newStatus(IStatus.ERROR, "Error while disposing: " + iDisposable.getClass().getName(), ex)); } }); } iterator.remove(); } }
Source:
private String updateSchema(byte[] byteContent) { String result = null; if (byteContent != null) { boolean modified = false; try { Document document = getSchemaDocument(byteContent); modified = handleUUIDElement(document); if (modified) { result = Util.formatXsdSource(Util.nodeToString(document)); } } catch (Exception e) { LOG.error(e.getMessage(), e); } } return result; }

Target:
private String updateSchema(byte[] byteContent) { String result = null; if (byteContent != null) { boolean modified = false; try { Document document = getSchemaDocument(byteContent); modified = handleUUIDElement(document); if (modified) { result = Util.formatXsdSource(Util.nodeToString(document)); } } catch (Exception e) { LOG.error("Failed to update data model schema.", e); } } return result; }
Source:
public void removeUnusedTypes_EncapsulatingTypes_Test() { final String parentType = "com.spectralogic.Test.Parent"; final String childType = "com.spectralogic.Test.Child"; final String grandchildType = "com.spectralogic.Test.Grandchild"; final Ds3Type parentDs3Type = new Ds3Type( parentType, ImmutableList.of(new Ds3Element("Child", childType, null, null)), null); final Ds3Type childDs3Type = new Ds3Type( childType, ImmutableList.of( new Ds3Element("Grandchild", grandchildType, null, null)), null); final Ds3Type grandchildDs3Type = new Ds3Type( grandchildType, null, null); final ImmutableList<Ds3Request> requests = ImmutableList.of( new Ds3Request(null, null, null, null, null, null, null, null, null, false, null, ImmutableList.of( new Ds3Param(null, "java.util.UUID"), new Ds3Param(null, parentType)), null)); final ImmutableMap<String, Ds3Type> typeMap = ImmutableMap.of( parentType, parentDs3Type, childType, childDs3Type, grandchildType, grandchildDs3Type, "com.spectralogic.Test.UnusedType", new Ds3Type(null, null, null)); final ImmutableMap<String, Ds3Type> result = removeUnusedTypes(typeMap, requests); assertThat(result.size(), is(3)); assertTrue(result.containsKey(parentType)); assertTrue(result.containsKey(childType)); assertTrue(result.containsKey(grandchildType)); }

Target:
public void removeUnusedTypes_EncapsulatingTypes_Test() { final String parentType = "com.spectralogic.Test.Parent"; final String childType = "com.spectralogic.Test.Child"; final String grandchildType = "com.spectralogic.Test.Grandchild"; final Ds3Type parentDs3Type = createDs3TypeTestData( parentType, createDs3ElementListTestData("Child", childType)); final Ds3Type childDs3Type = createDs3TypeTestData( childType, createDs3ElementListTestData("Grandchild", grandchildType)); final Ds3Type grandchildDs3Type = createDs3TypeTestData(grandchildType); final ImmutableList<Ds3Request> requests = ImmutableList.of( createDs3RequestTestData( false, ImmutableList.of( createDs3ParamTestData("java.util.UUID"), new Ds3Param(null, parentType)), null)); final ImmutableMap<String, Ds3Type> typeMap = ImmutableMap.of( parentType, parentDs3Type, childType, childDs3Type, grandchildType, grandchildDs3Type, "com.spectralogic.Test.UnusedType", createEmptyDs3Type()); final ImmutableMap<String, Ds3Type> result = removeUnusedTypes(typeMap, requests); assertThat(result.size(), is(3)); assertTrue(result.containsKey(parentType)); assertTrue(result.containsKey(childType)); assertTrue(result.containsKey(grandchildType)); }
Source:
public Response create(@Context SecurityContext securityContext, @Required NewAccount newAccount) throws NotFoundException, ConflictException, ServerException { requiredNotNull(newAccount, "New account"); requiredNotNull(newAccount.getName(), "Account name"); if (newAccount.getAttributes() != null) { for (String attributeName : newAccount.getAttributes().keySet()) { validateAttributeName(attributeName); } } User current = null; if (securityContext.isUserInRole("user")) { current = userDao.getByAlias(securityContext.getUserPrincipal().getName()); if (accountDao.getByOwner(current.getId()).size() != 0) { throw new ConflictException(format("Account which owner is %s already exists", current.getId())); } } try { accountDao.getByName(newAccount.getName()); throw new ConflictException(format("Account with name %s already exists", newAccount.getName())); } catch (NotFoundException ignored) { } final String accountId = NameGenerator.generate(Account.class.getSimpleName().toLowerCase(), Constants.ID_LENGTH); final Account account = new Account(accountId, newAccount.getName()); accountDao.create(account); if (current != null) { final Member owner = new Member().withAccountId(accountId) .withUserId(current.getId()) .withRoles(Arrays.asList("account/owner")); accountDao.addMember(owner); LOG.info("EVENT#account-add-member# ACCOUNT-ID#{}# USER-ID#{}# ROLES#{}#", accountId, current.getId(), Arrays.asList("account/owner").toString()); } return Response.status(Response.Status.CREATED) .entity(toDescriptor(account)) .build(); }

Target:
public Response create(@Context SecurityContext securityContext, @Required NewAccount newAccount) throws NotFoundException, ConflictException, ServerException { requiredNotNull(newAccount, "New account"); requiredNotNull(newAccount.getName(), "Account name"); if (newAccount.getAttributes() != null) { for (String attributeName : newAccount.getAttributes().keySet()) { validateAttributeName(attributeName); } } User current = null; if (securityContext.isUserInRole("user")) { current = userDao.getByAlias(securityContext.getUserPrincipal().getName()); if (accountDao.getByOwner(current.getId()).size() != 0) { throw new ConflictException(format("Account which owner is %s already exists", current.getId())); } } try { accountDao.getByName(newAccount.getName()); throw new ConflictException(format("Account with name %s already exists", newAccount.getName())); } catch (NotFoundException ignored) { } final String accountId = NameGenerator.generate(Account.class.getSimpleName().toLowerCase(), Constants.ID_LENGTH); final Account account = new Account(accountId, newAccount.getName(), null, newAccount.getAttributes()); accountDao.create(account); if (current != null) { final Member owner = new Member().withAccountId(accountId) .withUserId(current.getId()) .withRoles(Arrays.asList("account/owner")); accountDao.addMember(owner); LOG.info("EVENT#account-add-member# ACCOUNT-ID#{}# USER-ID#{}# ROLES#{}#", accountId, current.getId(), Arrays.asList("account/owner").toString()); } return Response.status(Response.Status.CREATED) .entity(toDescriptor(account)) .build(); }
Source:
public ActionResult execute() { String studentId = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_ID); StudentProfileAttributes studentProfile = logic.getStudentProfile(studentId); if (studentProfile == null) { studentProfile = StudentProfileAttributes.builder(studentId).build(); } StudentProfile output = new StudentProfile(studentProfile); return new JsonResult(output); }

Target:
public ActionResult execute() { String studentId = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_ID); if (!studentId.equals(userInfo.id) && !isMasqueradeMode()) { return new JsonResult("You are not authorized to view this student's profile.", HttpStatus.SC_FORBIDDEN); } StudentProfileAttributes studentProfile = logic.getStudentProfile(studentId); String name = logic.getAccount(studentId).name; if (studentProfile == null) { studentProfile = StudentProfileAttributes.builder(studentId).build(); } StudentProfile output = new StudentProfile(name, studentProfile); return new JsonResult(output); }
Source:
protected Field(Type type, int repetitionLevel, int definitionLevel, boolean required) { this.type = type; this.repetitionLevel = repetitionLevel; this.definitionLevel = definitionLevel; this.required = required; }

Target:
protected Field(Type type, int repetitionLevel, int definitionLevel, boolean required) { this.type = requireNonNull(type, "type is required"); this.repetitionLevel = repetitionLevel; this.definitionLevel = definitionLevel; this.required = required; }
Source:
public static long readLongAttribute(String attributeName, long defaultValue) { try { String methodName = "get" + attributeName; if (methodName.equals("getFreePhysicalMemorySize") && GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED) { return defaultValue; } OperatingSystemMXBean systemMXBean = OPERATING_SYSTEM_MX_BEAN; Method method = systemMXBean.getClass().getMethod(methodName); try { method.setAccessible(true); } catch (Exception e) { return defaultValue; } Object value = method.invoke(systemMXBean); if (value == null) { return defaultValue; } if (value instanceof Long) { return (Long) value; } if (value instanceof Double) { double v = (Double) value; return Math.round(v * PERCENTAGE_MULTIPLIER); } if (value instanceof Number) { return ((Number) value).longValue(); } } catch (RuntimeException re) { throw re; } catch (Exception ignored) { ignore(ignored); } return defaultValue; }

Target:
public static long readLongAttribute(String attributeName, long defaultValue) { try { String methodName = "get" + attributeName; if (GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED && methodName.equals("getFreePhysicalMemorySize")) { return defaultValue; } OperatingSystemMXBean systemMXBean = OPERATING_SYSTEM_MX_BEAN; Method method = systemMXBean.getClass().getMethod(methodName); try { method.setAccessible(true); } catch (Exception e) { return defaultValue; } Object value = method.invoke(systemMXBean); if (value == null) { return defaultValue; } if (value instanceof Long) { return (Long) value; } if (value instanceof Double) { double v = (Double) value; return Math.round(v * PERCENTAGE_MULTIPLIER); } if (value instanceof Number) { return ((Number) value).longValue(); } } catch (RuntimeException re) { throw re; } catch (Exception ignored) { ignore(ignored); } return defaultValue; }
Source:
protected Optional<DyeColor> getVal(ItemStack container) { return Optional.of((DyeColor) (Object) EnumDyeColor.byMetadata(container.getItemDamage())); }

Target:
protected Optional<DyeColor> getVal(ItemStack container) { if(container.getItem().equals(Items.dye)) { return Optional.of((DyeColor) (Object) EnumDyeColor.byDyeDamage(container.getItemDamage())); } else { return Optional.of((DyeColor) (Object) EnumDyeColor.byMetadata(container.getItemDamage())); } }
Source:
private Map<String, DbParameterAccessor> getParamMap(DbObjectName qn, boolean isFunction) throws SQLException { Map<String, DbParameterAccessor> allParams = new HashMap<>(); try (ResultSet rs = getObjectParameters(qn, isFunction)) { while (rs.next()) { String paramName = defaultIfNull(rs.getString("COLUMN_NAME"), ""); allParams.put(NameNormaliser.normaliseName(paramName), crtProcDbParamAccessor(rs, isFunction)); } } return allParams; }

Target:
private Map<String, DbParameterAccessor> getParamMap(DbObjectName qn, boolean isFunction) throws SQLException { Map<String, DbParameterAccessor> allParams = new HashMap<>(); try (ResultSet rs = getObjectParameters(qn, isFunction)) { while (rs.next()) { String paramName = defaultIfNull(rs.getString("COLUMN_NAME"), ""); allParams.put(NameNormaliser.normaliseName(paramName), createObjectDbParamAccessor(paramName, rs, isFunction)); } } return allParams; }
Source:
public synchronized void reload() { if (directory == null || !directory.isDirectory() || !directory.canRead()) { LOGGER.log(Level.INFO, "plugin directory not found or not readable: {0}. " + "All requests allowed.", directory); return; } LOGGER.log(Level.INFO, "Plugins are being reloaded from " + directory.getAbsolutePath()); removeAll(); loader = (AuthorizationPluginClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new AuthorizationPluginClassLoader(directory); } }); removeAll(); plugins = new ArrayList<>(); List<File> classfiles = listFilesRec(".class"); List<File> jarfiles = listFiles(".jar"); for (File file : classfiles) { String classname = getClassName(file); if (classname.isEmpty()) { continue; } handleLoadClass(classname); } for (File file : jarfiles) { try (JarFile jar = new JarFile(file)) { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String classname = getClassName(entry); if (!entry.getName().endsWith(".class") || classname.isEmpty()) { continue; } handleLoadClass(classname); } } catch (IOException ex) { LOGGER.log(Level.INFO, "Could not manipulate with file because of: ", ex); } } for (IAuthorizationPlugin plugin : getPlugins()) { try { plugin.load(); } catch (Throwable ex) { LOGGER.log(Level.SEVERE, "Plugin \"" + plugin.getClass().getName() + "\" has failed while loading with exception:", ex); removePlugin(plugin); } } }

Target:
public synchronized void reload() { if (pluginDirectory == null || !pluginDirectory.isDirectory() || !pluginDirectory.canRead()) { LOGGER.log(Level.WARNING, "plugin directory not found or not readable: {0}. " + "All requests allowed.", pluginDirectory); return; } LOGGER.log(Level.INFO, "Plugins are being reloaded from {0}", pluginDirectory.getAbsolutePath()); removeAll(); loader = (AuthorizationPluginClassLoader) AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { return new AuthorizationPluginClassLoader(pluginDirectory); } }); removeAll(); plugins = new ArrayList<>(); List<File> classfiles = listFilesRec(".class"); List<File> jarfiles = listFiles(".jar"); for (File file : classfiles) { String classname = getClassName(file); if (classname.isEmpty()) { continue; } handleLoadClass(classname); } for (File file : jarfiles) { try (JarFile jar = new JarFile(file)) { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String classname = getClassName(entry); if (!entry.getName().endsWith(".class") || classname.isEmpty()) { continue; } handleLoadClass(classname); } } catch (IOException ex) { LOGGER.log(Level.INFO, "Could not manipulate with file because of: ", ex); } } for (IAuthorizationPlugin plugin : getPlugins()) { try { plugin.load(); } catch (Throwable ex) { LOGGER.log(Level.SEVERE, "Plugin \"" + plugin.getClass().getName() + "\" has failed while loading with exception:", ex); removePlugin(plugin); } } }
Source:
public String getDisplayName() { return "Cron triggers monitor"; }

Target:
public String getDisplayName() { return Messages.SlowTriggerAdminMonitor_DisplayName(); }
Source:
public void testGetStateForMultipleTasks() throws Exception { String yummyTopic = "YummyPizza"; String saltyTopic = "SaltyPizza"; String saladTopic = "HealthySalad"; createTopic(_zkUtils, saladTopic); createTopic(_zkUtils, yummyTopic); createTopic(_zkUtils, saltyTopic); Datastream datastream = KafkaMirrorMakerConnectorTestUtils.createDatastream("pizzaStream", _broker, "\\w+Pizza"); List<DatastreamTask> tasks = ImmutableList.of(new DatastreamTaskImpl(Collections.singletonList(datastream)), new DatastreamTaskImpl(Collections.singletonList(datastream)), new DatastreamTaskImpl(Collections.singletonList(datastream))); MockDatastreamEventProducer datastreamProducer = new MockDatastreamEventProducer(); tasks.forEach(t -> ((DatastreamTaskImpl) t).setEventProducer(datastreamProducer)); KafkaMirrorMakerConnector connector = new KafkaMirrorMakerConnector("MirrorMakerConnector", getDefaultConfig(Optional.empty()), "testCluster"); connector.start(null); connector.onAssignmentChange(tasks); boolean pollResult = PollUtils.poll(() -> { String jsonStr = connector.process("/datastream_state?datastream=pizzaStream"); KafkaDatastreamStatesResponse response = KafkaDatastreamStatesResponse.fromJson(jsonStr); return response.getAssignedTopicPartitions().equals(ImmutableSet.of(new TopicPartition("SaltyPizza", 0), new TopicPartition("YummyPizza", 0))); }, POLL_PERIOD_MS, POLL_TIMEOUT_MS); Assert.assertTrue(pollResult); connector.stop(); }

Target:
public void testGetStateForMultipleTasks() throws Exception { List<String> topics = Arrays.asList("YummyPizza", "SaltyPizza", "HealthySalad"); topics.forEach(t -> createTopic(_zkUtils, t)); Datastream datastream = KafkaMirrorMakerConnectorTestUtils.createDatastream("pizzaStream", _broker, "\\w+Pizza"); List<DatastreamTask> tasks = ImmutableList.of(new DatastreamTaskImpl(Collections.singletonList(datastream)), new DatastreamTaskImpl(Collections.singletonList(datastream)), new DatastreamTaskImpl(Collections.singletonList(datastream))); MockDatastreamEventProducer datastreamProducer = new MockDatastreamEventProducer(); tasks.forEach(t -> ((DatastreamTaskImpl) t).setEventProducer(datastreamProducer)); KafkaMirrorMakerConnector connector = new KafkaMirrorMakerConnector("MirrorMakerConnector", getDefaultConfig(Optional.empty()), "testCluster"); connector.start(null); connector.onAssignmentChange(tasks); boolean hasExpectedTopicPartitions = PollUtils.poll(() -> { String jsonStr = connector.process("/datastream_state?datastream=pizzaStream"); KafkaDatastreamStatesResponse response = KafkaDatastreamStatesResponse.fromJson(jsonStr); return response.getAssignedTopicPartitions().equals(ImmutableSet.of(new TopicPartition("SaltyPizza", 0), new TopicPartition("YummyPizza", 0))); }, POLL_PERIOD_MS, POLL_TIMEOUT_MS); Assert.assertTrue(hasExpectedTopicPartitions); connector.stop(); }
Source:
public void testAccessors() { assertEquals("com.bugsnag.android.jvm.test", appData.get("packageName")); assertNull(appData.get("buildUUID")); assertTrue(((Long) appData.get("duration")) > 0); assertEquals(500L, appData.get("durationInForeground")); assertTrue((Boolean) appData.get("inForeground")); }

Target:
public void testAccessors() { assertEquals("com.bugsnag.android.core.test", appData.get("packageName")); assertNull(appData.get("buildUUID")); assertTrue(((Long) appData.get("duration")) > 0); assertEquals(500L, appData.get("durationInForeground")); assertTrue((Boolean) appData.get("inForeground")); }
Source:
private void calculateLocation() { try { mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); String providerName = null; if (isNetworkEnabled) { providerName = LocationManager.NETWORK_PROVIDER; } else if (isGPSEnabled) { providerName = LocationManager.GPS_PROVIDER; } else { String errorMessage = getResources().getString(R.string.unable_location_service_message); Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show(); return; } obtainCoordinates(providerName); } catch (Exception e) { e.printStackTrace(); } }

Target:
private void calculateLocation() { mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); String providerName = null; if (isNetworkEnabled) { providerName = LocationManager.NETWORK_PROVIDER; } else if (isGPSEnabled) { providerName = LocationManager.GPS_PROVIDER; } else { String errorMessage = getResources().getString(R.string.unable_location_service_message); Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show(); return; } obtainCoordinates(providerName); }
Source:
public List<Double> get(@PathParam("toItemID") String toItemID, @PathParam("itemID") List<PathSegment> pathSegmentList) { ALSServingModelManager alsServingModelManager = (ALSServingModelManager) servletContext.getAttribute(ModelManagerListener.MANAGER_KEY); ALSServingModel alsServingModel = alsServingModelManager.getModel(); return Arrays.asList(1.2, 3.4); }

Target:
public List<Double> get(@PathParam("toItemID") String toItemID, @PathParam("itemID") List<PathSegment> pathSegmentList) { return Arrays.asList(1.2, 3.4); }
Source:
public Stream<MessageHandlingMember<? super T>> getHandlers(Class<?> type) { return handlers.getOrDefault(type, new TreeSet<>(HandlerComparator.instance())) .stream(); }

Target:
public Stream<MessageHandlingMember<? super T>> getHandlers(Class<?> type) { return handlers.getOrDefault(type, emptySortedSet()) .stream(); }
Source:
private HashMap<Double, ArrayList<Integer>> orderBookCreator(String symbol) { HashMap<Double, ArrayList<Integer>> orderbook = new HashMap<Double, ArrayList<Integer>>(); ArrayList<Order> buyList = this.buyOrders.get(symbol); ArrayList<Order> sellList = this.sellOrders.get(symbol); for (Order o : buyList){ double key=o.getPrice(); ArrayList<Integer> temp=new ArrayList<Integer>(); if (orderbook.containsKey(key)){ temp.add(o.getSize()+orderbook.get(key).get(0)); temp.add(orderbook.get(key).get(1)); orderbook.replace(key, temp); } else{ temp.add(o.getSize()); temp.add(0); orderbook.put(key, temp); } } for (Order o : sellList){ double key=o.getPrice(); ArrayList<Integer> temp=new ArrayList<Integer>(); if (orderbook.containsKey(key)){ temp.add(orderbook.get(key).get(0)); temp.add(o.getSize()+orderbook.get(key).get(1)); orderbook.replace(key, temp); } else{ temp.add(0); temp.add(o.getSize()); orderbook.put(key, temp); } } return orderbook; }

Target:
private HashMap<Double, ArrayList<Integer>> orderBookCreator(String symbol) { HashMap<Double, ArrayList<Integer>> orderbook = new HashMap<Double, ArrayList<Integer>>(); ArrayList<Order> buyList = this.buyOrders.get(symbol); ArrayList<Order> sellList = this.sellOrders.get(symbol); for (Order order : buyList){ double key=order.getPrice(); ArrayList<Integer> temp=new ArrayList<Integer>(); if (orderbook.containsKey(key)){ temp.add(order.getSize()+orderbook.get(key).get(0)); temp.add(orderbook.get(key).get(1)); orderbook.replace(key, temp); } else{ temp.add(order.getSize()); temp.add(0); orderbook.put(key, temp); } } for (Order order : sellList){ double key=order.getPrice(); ArrayList<Integer> temp=new ArrayList<Integer>(); if (orderbook.containsKey(key)){ temp.add(orderbook.get(key).get(0)); temp.add(order.getSize()+orderbook.get(key).get(1)); orderbook.replace(key, temp); } else{ temp.add(0); temp.add(order.getSize()); orderbook.put(key, temp); } } return orderbook; }
Source:
protected Blob getContentBlob(Blob original, DocumentModel doc) { if (doc.getProperty(PICTURE_VIEWS_PROPERTY) != null) { MultiviewPicture multiviewPicture = doc.getAdapter(MultiviewPicture.class); for (PictureView view : multiviewPicture.getViews()) { if (view.getTitle().equals("FullHD") && view.getBlob() != null) { return view.getBlob(); } } } return original; }

Target:
protected Blob getContentBlob(Blob original, DocumentModel doc) { MultiviewPicture multiviewPicture = doc.getAdapter(MultiviewPicture.class); if (multiviewPicture != null) { for (PictureView view : multiviewPicture.getViews()) { if (view.getTitle().equals("FullHD") && view.getBlob() != null) { return view.getBlob(); } } } return original; }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof KeycloakStatusDTO) { KeycloakStatusDTO that = (KeycloakStatusDTO) obj; EqualsBuilder builder = new EqualsBuilder() .append(this.getMode(), that.getMode()) .append(this.getModeReason(), that.getModeReason()) .append(this.getModeChangeTime(), that.getModeChangeTime()) .append(this.getResult(), that.getResult()) .append(this.getVersion(), that.getVersion()) .append(this.getRulesVersion(), that.getRulesVersion()) .append(this.getRulesSource(), that.getRulesSource()) .append(this.getRelease(), that.getRelease()) .append(this.getStandalone(), that.getStandalone()) .append(this.getTimeUTC(), that.getTimeUTC()) .append(this.getManagerCapabilities(), that.getManagerCapabilities()) .append(this.getKeycloakRealm(), that.getKeycloakRealm()) .append(this.getKeycloakAuthUrl(), that.getKeycloakAuthUrl()) .append(this.getKeycloakResource(), that.getKeycloakResource()); return builder.isEquals(); } return false; }

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof KeycloakStatusDTO && super.equals(obj)) { KeycloakStatusDTO that = (KeycloakStatusDTO) obj; EqualsBuilder builder = new EqualsBuilder() .append(this.getKeycloakRealm(), that.getKeycloakRealm()) .append(this.getKeycloakAuthUrl(), that.getKeycloakAuthUrl()) .append(this.getKeycloakResource(), that.getKeycloakResource()); return builder.isEquals(); } return false; }
Source:
private boolean isOnBranch(RevCommit commit, String fullBranch) throws IOException { Ref developRef = repository.exactRef(fullBranch); try { List<Ref> list = Git.wrap(repository).branchList().setContains(commit.name()).call(); return list.contains(developRef); } catch (GitAPIException e) { throw new RuntimeException(e); } }

Target:
private boolean isOnBranch(RevCommit commit, String fullBranch) throws IOException { Ref branchRef = repository.exactRef(fullBranch); if (branchRef == null) { return false; } try { List<Ref> list = Git.wrap(repository).branchList().setContains(commit.name()).call(); return list.contains(branchRef); } catch (GitAPIException e) { throw new IOException(e); } }
Source:
public String getDisplayName() { return Messages.discover_pull_requests_from_origin(); }

Target:
public String getDisplayName() { return Messages.OriginPullRequestDiscoveryTrait_discoverPullRequestsFromOrigin(); }
Source:
public static TriggerUsage of(apex.jorje.data.ast.TriggerUsage apexTriggerUsage) { return APEX_TO_PMD.get(apexTriggerUsage); }

Target:
public static TriggerUsage of(apex.jorje.data.ast.TriggerUsage apexTriggerUsage) { TriggerUsage result = APEX_TO_PMD.get(apexTriggerUsage); if (result != null) { return result; } throw new NoSuchElementException("Unknown TriggerUsage value '" + apexTriggerUsage.name() + "'"); }
Source:
protected static ICPPEvaluation maybeApplyConversion(ICPPEvaluation argument, IType targetType, IASTNode point, boolean allowContextualConversion) { IType type = argument.getType(point); IType uqType= SemanticUtil.getNestedType(type, TDEF | REF | CVTYPE); ValueCategory valueCategory = argument.getValueCategory(point); ICPPFunction conversion = null; if (uqType instanceof ICPPClassType) { try { Cost cost = Conversions.initializationByConversion(valueCategory, type, (ICPPClassType) uqType, targetType, false, point, allowContextualConversion); conversion = cost.getUserDefinedConversion(); } catch (DOMException e) { CCorePlugin.log(e); } } if (conversion != null) { if (!conversion.isConstexpr()) { return EvalFixed.INCOMPLETE; } ICPPEvaluation eval; if (conversion instanceof ICPPMethod) { eval = new EvalMemberAccess(uqType, valueCategory, conversion, false, point); } else { eval = new EvalBinding(conversion, null, (IBinding) null); } argument = new EvalFunctionCall(new ICPPEvaluation[] {eval}, null, (IBinding) null); } return argument; }

Target:
protected static ICPPEvaluation maybeApplyConversion(ICPPEvaluation argument, IType targetType, IASTNode point, boolean allowContextualConversion) { IType type = argument.getType(point); IType uqType= SemanticUtil.getNestedType(type, TDEF | REF | CVTYPE); ValueCategory valueCategory = argument.getValueCategory(point); ICPPFunction conversion = null; if (uqType instanceof ICPPClassType) { try { Cost cost = Conversions.initializationByConversion(valueCategory, type, (ICPPClassType) uqType, targetType, false, point, allowContextualConversion); conversion = cost.getUserDefinedConversion(); } catch (DOMException e) { CCorePlugin.log(e); } } if (conversion != null) { if (!conversion.isConstexpr()) { return EvalFixed.INCOMPLETE; } ICPPEvaluation eval = new EvalMemberAccess(uqType, valueCategory, conversion, argument, false, point); argument = new EvalFunctionCall(new ICPPEvaluation[] { eval }, null, (IBinding) null); } return argument; }
Source:
public boolean shouldSuspend(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { if (shouldValidateOnBudgetTotal()) { LOG.debug("shouldSuspend, validating based on award budget total"); KualiDecimal totalAmountBilledToDate = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getTotalAmountBilledToDate(); Award award = (Award) contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getAward(); AwardExtendedAttribute awardExtension = (AwardExtendedAttribute) award.getExtension(); KualiDecimal budgetTotalAmount = awardExtension.getBudgetTotalAmount(); if (ObjectUtils.isNull(budgetTotalAmount)) { LOG.error("shouldSuspend, no budget amount set, setting budget amount to 0, wich will cause a suspension."); budgetTotalAmount = KualiDecimal.ZERO; } if (LOG.isDebugEnabled()) { LOG.debug("shouldSuspend, award proposal number: " + award.getProposalNumber() + " totalAmountBilledToDate: " + totalAmountBilledToDate + " budgetTotalAmount: " + budgetTotalAmount); } return totalAmountBilledToDate.isGreaterThan(budgetTotalAmount); } else { LOG.debug("shouldSuspend, validating based on award total"); return super.shouldSuspend(contractsGrantsInvoiceDocument); } }

Target:
public boolean shouldSuspend(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { if (shouldValidateOnBudgetTotal()) { LOG.debug("shouldSuspend, validating based on award budget total"); KualiDecimal totalAmountBilledToDate = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getTotalAmountBilledToDate(); Award award = (Award) contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getAward(); AwardExtendedAttribute awardExtension = (AwardExtendedAttribute) award.getExtension(); KualiDecimal budgetTotalAmount = awardExtension.getBudgetTotalAmount(); if (ObjectUtils.isNull(budgetTotalAmount)) { LOG.error("shouldSuspend, no budget amount set, setting budget amount to 0, which will cause a suspension."); budgetTotalAmount = KualiDecimal.ZERO; } if (LOG.isDebugEnabled()) { LOG.debug("shouldSuspend, award proposal number: " + award.getProposalNumber() + " totalAmountBilledToDate: " + totalAmountBilledToDate + " budgetTotalAmount: " + budgetTotalAmount); } return totalAmountBilledToDate.isGreaterThan(budgetTotalAmount); } else { LOG.debug("shouldSuspend, validating based on award total"); return super.shouldSuspend(contractsGrantsInvoiceDocument); } }
Source:
public static long zip(File directory, OutputStream out) throws IOException { if (!directory.isDirectory()) { throw new IOException(String.format("directory[%s] is not a directory", directory)); } final File[] files = directory.listFiles(); if (files == null) { throw new IAE("Directory not found [%s]", directory.getAbsolutePath()); } long totalSize = 0; try (final ZipOutputStream zipOut = new ZipOutputStream(out)) { for (File file : files) { log.info("Adding file[%s] with size[%,d]. Total size so far[%,d]", file, file.length(), totalSize); if (file.length() >= Integer.MAX_VALUE) { zipOut.finish(); throw new IOException(String.format("file[%s] too large [%,d]", file, file.length())); } zipOut.putNextEntry(new ZipEntry(file.getName())); try (InputStream inputStream = new FileInputStream(file)) { totalSize += ByteStreams.copy(inputStream, zipOut); } } zipOut.closeEntry(); } return totalSize; }

Target:
public static long zip(File directory, OutputStream out) throws IOException { if (!directory.isDirectory()) { throw new IOException(String.format("directory[%s] is not a directory", directory)); } final File[] files = directory.listFiles(); long totalSize = 0; try (final ZipOutputStream zipOut = new ZipOutputStream(out)) { for (File file : files) { log.info("Adding file[%s] with size[%,d]. Total size so far[%,d]", file, file.length(), totalSize); if (file.length() >= Integer.MAX_VALUE) { zipOut.finish(); throw new IOException(String.format("file[%s] too large [%,d]", file, file.length())); } zipOut.putNextEntry(new ZipEntry(file.getName())); totalSize += Files.asByteSource(file).copyTo(zipOut); } zipOut.closeEntry(); } return totalSize; }