auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>(); permissionList.addAll(super.getPermissionCheckSubjects()); permissionList.add(new PermissionSubject( getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permissionCheckSubjects == null) { permissionCheckSubjects = new ArrayList<PermissionSubject>(); permissionCheckSubjects.addAll(super.getPermissionCheckSubjects()); permissionCheckSubjects.add(new PermissionSubject( getParameters().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); } return permissionCheckSubjects; }
Source:
private <T extends FrameworkMember<T>> void addToAnnotationLists(T member, Map<Class<? extends Annotation>, List<T>> map) { for (Annotation each : member.getAnnotations()) { Class<? extends Annotation> type = each.annotationType(); List<T> members = getAnnotatedMembers(map, type, true); if (member.isShadowedBy(members)) { return; } if (runsTopToBottom(type)) { members.add(0, member); } else { members.add(member); } } }

Target:
private static <T extends FrameworkMember<T>> void addToAnnotationLists(T member, Map<Class<? extends Annotation>, List<T>> map) { for (Annotation each : member.getAnnotations()) { Class<? extends Annotation> type = each.annotationType(); List<T> members = getAnnotatedMembers(map, type, true); if (member.isShadowedBy(members)) { return; } if (runsTopToBottom(type)) { members.add(0, member); } else { members.add(member); } } }
Source:
public ObservationDetails(PricingEnvironment env, OvernightCompoundedRateObservation observation) { this.env = env; index = observation.getIndex(); fixingCalendar = index.getFixingCalendar(); indexFixingDateSeries = env.timeSeries(index); firstFixing = observation.getStartDate(); lastFixingP1 = observation.getEndDate(); lastFixing = fixingCalendar.previous(lastFixingP1); cutoffOffset = observation.getRateCutOffDays() > 1 ? observation.getRateCutOffDays() : 1; accrualFactorCutoff = new double[cutoffOffset-1]; LocalDate currentFixing = lastFixing; for(int i = 0 ; i < cutoffOffset-1; i++) { currentFixing = fixingCalendar.previous(currentFixing); LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); accrualFactorCutoff[i] = index.getDayCount().yearFraction(effectiveDate, maturityDate); } lastFixingNonCutoff = currentFixing; LocalDate startUnderlyingPeriod = index.calculateEffectiveFromFixing(firstFixing); LocalDate endUnderlyingPeriod = index.calculateMaturityFromEffective(index.calculateEffectiveFromFixing(lastFixing)); accrualFactorTotal = index.getDayCount().yearFraction(startUnderlyingPeriod, endUnderlyingPeriod); }

Target:
private ObservationDetails(PricingEnvironment env, OvernightCompoundedRateObservation observation) { this.env = env; index = observation.getIndex(); fixingCalendar = index.getFixingCalendar(); indexFixingDateSeries = env.timeSeries(index); firstFixing = observation.getStartDate(); lastFixingP1 = observation.getEndDate(); lastFixing = fixingCalendar.previous(lastFixingP1); cutoffOffset = Math.max(observation.getRateCutOffDays(), 1); accrualFactorCutoff = new double[cutoffOffset - 1]; LocalDate currentFixing = lastFixing; for (int i = 0; i < cutoffOffset - 1; i++) { currentFixing = fixingCalendar.previous(currentFixing); LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); accrualFactorCutoff[i] = index.getDayCount().yearFraction(effectiveDate, maturityDate); } lastFixingNonCutoff = currentFixing; LocalDate startUnderlyingPeriod = index.calculateEffectiveFromFixing(firstFixing); LocalDate endUnderlyingPeriod = index.calculateMaturityFromEffective(index.calculateEffectiveFromFixing(lastFixing)); accrualFactorTotal = index.getDayCount().yearFraction(startUnderlyingPeriod, endUnderlyingPeriod); }
Source:
private CommandStatus runWithDocker(final CommandContext context, final CommandRequest request) throws IOException { final Process p = startDockerProcess(context, request); clog.copyStdout(p, System.out); try { p.waitFor(); } catch (InterruptedException e) { throw Throwables.propagate(e); } return SimpleCommandStatus.of(request.getIoDirectory().toString(), p); }

Target:
private CommandStatus runWithDocker(final CommandContext context, final CommandRequest request) throws IOException { final Process p = startDockerProcess(context, request); clog.copyStdout(p, System.out); try { p.waitFor(); } catch (InterruptedException e) { throw Throwables.propagate(e); } return SimpleCommandStatus.of(p, request.getIoDirectory()); }
Source:
public void hasSameOrderableAs_shouldReturnTrueIfTheConceptsMatchAndHaveSameDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); Drug drug1 = new Drug(); drug1.setConcept(concept); order.setDrug(drug1); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrug(drug1); otherOrder.setDrugNonCoded("chrocine"); assertTrue(order.hasSameOrderableAs(otherOrder)); }

Target:
public void hasSameOrderableAs_shouldReturnTrueIfTheConceptsMatchAndHaveSameDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); order.setConcept(concept); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrugNonCoded("chrocine"); assertTrue(order.hasSameOrderableAs(otherOrder)); }
Source:
private void dispatchUploadAction(@NonNull final MediaModel media, @NonNull final SiteModel site) { if (media != null && site != null) { AppLog.i(AppLog.T.MEDIA, "Dispatching upload action for media with local id: " + media.getId() + " and path: " + media.getFilePath()); media.setUploadState(UploadState.UPLOADING.name()); mDispatcher.dispatch(MediaActionBuilder.newUpdateMediaAction(media)); MediaPayload payload = new MediaPayload(site, media); mDispatcher.dispatch(MediaActionBuilder.newUploadMediaAction(payload)); } }

Target:
private void dispatchUploadAction(@NonNull final MediaModel media, @NonNull final SiteModel site) { AppLog.i(AppLog.T.MEDIA, "Dispatching upload action for media with local id: " + media.getId() + " and path: " + media.getFilePath()); media.setUploadState(UploadState.UPLOADING.name()); mDispatcher.dispatch(MediaActionBuilder.newUpdateMediaAction(media)); MediaPayload payload = new MediaPayload(site, media); mDispatcher.dispatch(MediaActionBuilder.newUploadMediaAction(payload)); }
Source:
static Path resolvePath(Path file, String workingDirectory) { return file == null ? null : (file.isAbsolute() ? file : (file.getFileName().startsWith(File.separator) ? file.toAbsolutePath() : (Paths.get(workingDirectory, file.getFileName().toString())))); }

Target:
static Path resolvePath(Path file, String workingDirectory) { if(file == null){ return null; }else if(file.isAbsolute()){ return file; }else if(file.getFileName().startsWith(File.separator)){ return file.toAbsolutePath(); }else{ return Paths.get(workingDirectory, file.getFileName().toString()); } }
Source:
public void usbSerialDeviceDiscovered(UsbSerialDeviceInformation usbSerialDeviceInformation) { logger.debug("Discovered new usb-serial device: {}", usbSerialDeviceInformation); previouslyDiscovered.add(usbSerialDeviceInformation); for (UsbSerialDiscoveryParticipant participant : discoveryParticipants) { DiscoveryResult result = participant.createResult(usbSerialDeviceInformation); if (result != null) { thingDiscovered(result); } } }

Target:
public void usbSerialDeviceDiscovered(UsbSerialDeviceInformation usbSerialDeviceInformation) { logger.debug("Discovered new USB-Serial device: {}", usbSerialDeviceInformation); previouslyDiscovered.add(usbSerialDeviceInformation); for (UsbSerialDiscoveryParticipant participant : discoveryParticipants) { DiscoveryResult result = participant.createResult(usbSerialDeviceInformation); if (result != null) { thingDiscovered(result); } } }
Source:
private synchronized void runWriteRequest(GPIORequestInfo requestInfo) { ChannelRecord record = requestInfo.channelRecord; if (!GPIOChannelDescriptor.DEFAULT_RESOURCE_NAME.equals(requestInfo.resourceName) && requestInfo.resourceDirection != null) { try { final TypedValue<Boolean> value = getBooleanValue(record.getValue()); this.gpioNames.add(requestInfo.resourceName); KuraGPIOPin pin = getPin(requestInfo.resourceName, requestInfo.resourceDirection, requestInfo.resourceMode, requestInfo.resourceTrigger); if (pin != null) { pin.setValue((boolean) value.getValue()); record.setChannelStatus(new ChannelStatus(SUCCESS)); record.setTimestamp(System.currentTimeMillis()); } } catch (IOException | KuraUnavailableDeviceException | KuraClosedDeviceException e) { record.setChannelStatus(new ChannelStatus(ChannelFlag.FAILURE, message.readFailed(), null)); record.setTimestamp(System.currentTimeMillis()); logger.warn(message.writeFailed()); } } else { record.setChannelStatus(new ChannelStatus(ChannelFlag.FAILURE, message.readFailed(), null)); record.setTimestamp(System.currentTimeMillis()); } }

Target:
private synchronized void runWriteRequest(GPIORequestInfo requestInfo) { ChannelRecord record = requestInfo.channelRecord; if (!GPIOChannelDescriptor.DEFAULT_RESOURCE_NAME.equals(requestInfo.resourceName) && requestInfo.resourceDirection != null) { try { final TypedValue<Boolean> value = getBooleanValue(record.getValue()); this.gpioNames.add(requestInfo.resourceName); KuraGPIOPin pin = getPin(requestInfo.resourceName, requestInfo.resourceDirection, requestInfo.resourceMode, requestInfo.resourceTrigger); if (pin != null) { pin.setValue((boolean) value.getValue()); record.setChannelStatus(new ChannelStatus(SUCCESS)); record.setTimestamp(System.currentTimeMillis()); } } catch (IOException | KuraUnavailableDeviceException | KuraClosedDeviceException e) { setFailureRecord(record, WRITE_FAILED_MESSAGE); } } else { setFailureRecord(record, WRITE_FAILED_MESSAGE); } }
Source:
protected Date convertDateTimeStringToDate(String dateString, boolean defaultUTC) { String localTimeRegex = "^(.*)([+-]{1}\\d\\d:\\d\\d)$"; Pattern localTimePattern = Pattern.compile(localTimeRegex); String utcPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"; String utcPattern1 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"; String localPattern = "yyyy-MM-dd'T'HH:mm:ssz"; String localPattern1 = "yyyy-MM-dd'Z'"; String pattern = "yyyy-MM-ddz"; String localPattern2 = "yyyy-MM-dd'T'HH:mm:ss"; Date dt = null; if (dateString == null || dateString.isEmpty()) { return null; } else { if (dateString.endsWith("Z")) { dt = parseDateTimeString(dateString, defaultUTC, utcPattern, pattern, localPattern1, utcPattern1); } else if (dateString.endsWith("z")) { dt = parseDateTimeString(dateString, defaultUTC, "yyyy-MM-dd'T'HH:mm:ss'z'"); } else { Matcher localTimeMatcher = localTimePattern.matcher(dateString); if (localTimeMatcher.find()) { log.debug("Pattern matched"); String date = localTimeMatcher.group(1); String zone = localTimeMatcher.group(2); dateString = String.format("%sGMT%s", date, zone); dt = parseDateTimeString(dateString, defaultUTC, localPattern, pattern); } else { dt = parseDateTimeString(dateString, defaultUTC, localPattern2); } } return dt; } }

Target:
protected Date convertDateTimeStringToDate(String dateString, boolean defaultUTC) { String localTimeRegex = "^(.*)([+-]{1}\\d\\d:\\d\\d)$"; Pattern localTimePattern = Pattern.compile(localTimeRegex); String utcPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"; String utcPattern1 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"; String localPattern = "yyyy-MM-dd'T'HH:mm:ssz"; String localPattern1 = "yyyy-MM-dd'Z'"; String pattern = "yyyy-MM-ddz"; String localPattern2 = "yyyy-MM-dd'T'HH:mm:ss"; Date dt = null; if (dateString == null || dateString.isEmpty()) { return null; } else { if (dateString.endsWith("Z")) { dt = parseDateTimeString(dateString, defaultUTC, utcPattern, pattern, localPattern1, utcPattern1); } else if (dateString.endsWith("z")) { dt = parseDateTimeString(dateString, defaultUTC, "yyyy-MM-dd'T'HH:mm:ss'z'"); } else { Matcher localTimeMatcher = localTimePattern.matcher(dateString); if (localTimeMatcher.find()) { String date = localTimeMatcher.group(1); String zone = localTimeMatcher.group(2); dateString = String.format("%sGMT%s", date, zone); dt = parseDateTimeString(dateString, defaultUTC, localPattern, pattern); } else { dt = parseDateTimeString(dateString, defaultUTC, localPattern2); } } return dt; } }
Source:
GermplasmList createGermplasmList(final SaveListForm saveListForm, final Integer currentUserId) { final String listName = saveListForm.getListName().trim(); final String listType = saveListForm.getListType(); final String description = saveListForm.getListDescription(); GermplasmList parent = null; Integer parentId = null; GermplasmList gpList = null; if (saveListForm.getParentId() != null && !GermplasmTreeController.PROGRAM_LISTS.equals(saveListForm.getParentId()) && !GermplasmTreeController.CROP_LISTS.equals(saveListForm.getParentId())) { parentId = Integer.valueOf(saveListForm.getParentId()); gpList = this.germplasmListManager.getGermplasmListById(parentId); } if (gpList != null && gpList.isFolder()) { parent = gpList; } final Integer status = 1; final Long dateLong = Long .valueOf(DateUtil.convertToDBDateFormat(TermId.DATE_VARIABLE.getId(), saveListForm.getListDate())); final GermplasmList germplasmList = new GermplasmList(null, listName, dateLong, listType, currentUserId, description, parent, status, saveListForm.getListNotes()); if (!GermplasmTreeController.CROP_LISTS.equals(saveListForm.getParentId())) { germplasmList.setProgramUUID(this.getCurrentProgramUUID()); } else { germplasmList.setStatus(101); } return germplasmList; }

Target:
GermplasmList createGermplasmList(final SaveListForm saveListForm, final Integer currentUserId) { final String listName = saveListForm.getListName().trim(); final String listType = saveListForm.getListType(); final String description = saveListForm.getListDescription(); GermplasmList parent = null; Integer parentId = null; GermplasmList gpList = null; if (saveListForm.getParentId() != null && !GermplasmTreeController.PROGRAM_LISTS.equals(saveListForm.getParentId()) && !GermplasmTreeController.CROP_LISTS.equals(saveListForm.getParentId())) { parentId = Integer.valueOf(saveListForm.getParentId()); gpList = this.germplasmListManager.getGermplasmListById(parentId); } if (gpList != null && gpList.isFolder()) { parent = gpList; } final Integer status = 1; final Long dateLong = Long.valueOf(DateUtil.convertToDBDateFormat(TermId.DATE_VARIABLE.getId(), saveListForm.getListDate())); final GermplasmList germplasmList = new GermplasmList(null, listName, dateLong, listType, currentUserId, description, parent, status, saveListForm.getListNotes()); if (GermplasmTreeController.CROP_LISTS.equals(saveListForm.getParentId())) { germplasmList.setStatus(LOCKED_LIST_STATUS); } else { germplasmList.setProgramUUID(this.getCurrentProgramUUID()); } return germplasmList; }
Source:
private void log(QueryResponse queryResponse) { LOGGER.trace("AfterPostQueryFilter result size: {}", queryResponse.getResults().size()); LOGGER.trace("Total Hit count: {}", queryResponse.getHits()); if (LOGGER.isTraceEnabled() && queryResponse.getProcessingDetails() != null) { LOGGER.trace("Processing details count: {}", queryResponse.getProcessingDetails().size()); for (ProcessingDetails details : queryResponse.getProcessingDetails()) { if (details.getException() != null) { LOGGER.trace( "Source query exception", details.getSourceId(), details.getException()); } if (details.getWarnings() != null && details.getWarnings().size() > 0) { LOGGER.trace( "Source warnings: {}", details.getSourceId(), String.join(", ", details.getWarnings())); } } } }

Target:
private void log(QueryResponse queryResponse) { LOGGER.trace("AfterPostQueryFilter result size: {}", queryResponse.getResults().size()); LOGGER.trace("Total Hit count: {}", queryResponse.getHits()); if (LOGGER.isTraceEnabled() && queryResponse.getProcessingDetails() != null) { LOGGER.trace("Processing details count: {}", queryResponse.getProcessingDetails().size()); for (ProcessingDetails details : queryResponse.getProcessingDetails()) { if (details.getException() != null) { LOGGER.trace( "Source query exception", details.getSourceId(), details.getException()); } if (details.getWarnings() != null && !details.getWarnings().isEmpty()) { LOGGER.trace( "Source warnings: {}", details.getSourceId(), String.join(", ", details.getWarnings())); } } } }
Source:
public void deleteGroups(PerunSession perunSession, List<Group> groups, boolean forceDelete) throws GroupNotExistsException, InternalErrorException, PrivilegeException, GroupAlreadyRemovedException, RelationExistsException, GroupAlreadyRemovedFromResourceException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved, ExternallyManagedException { Utils.checkPerunSession(perunSession); Utils.notNull(groups, "groups"); for(Group group: groups) { getGroupsManagerBl().checkGroupExists(perunSession, group); if(getGroupsManagerBl().isGroupInStructureSynchronizationTree(perunSession, group) || getGroupsManagerBl().hasGroupSynchronizedChild(perunSession, group)) { throw new ExternallyManagedException("Group " + group + "or som of the subGroups are externally managed!"); } if(!AuthzResolver.isAuthorized(perunSession, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(perunSession, Role.GROUPADMIN, group)) { throw new PrivilegeException(perunSession, "deleteGroups"); } } getGroupsManagerBl().deleteGroups(perunSession, groups, forceDelete); }

Target:
public void deleteGroups(PerunSession perunSession, List<Group> groups, boolean forceDelete) throws GroupNotExistsException, InternalErrorException, PrivilegeException, GroupAlreadyRemovedException, RelationExistsException, GroupAlreadyRemovedFromResourceException, GroupRelationDoesNotExist, GroupRelationCannotBeRemoved, ExternallyManagedException { Utils.checkPerunSession(perunSession); Utils.notNull(groups, "groups"); for(Group group: groups) { getGroupsManagerBl().checkGroupExists(perunSession, group); if (getGroupsManagerBl().isGroupInStructureSynchronizationTree(perunSession, group) || getGroupsManagerBl().hasGroupSynchronizedChild(perunSession, group)) { throw new ExternallyManagedException("Group " + group + " or some of the subGroups are externally managed!"); } if(!AuthzResolver.isAuthorized(perunSession, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(perunSession, Role.GROUPADMIN, group)) { throw new PrivilegeException(perunSession, "deleteGroups"); } } getGroupsManagerBl().deleteGroups(perunSession, groups, forceDelete); }
Source:
public void updateBeforeModel() { beforeModel.setId(model.getId()); beforeModel.setTitle(model.getTitle()); beforeModel.setDescription(model.getDescription()); beforeModel.setEstimatedEffort(model.getEstimatedEffort()); beforeModel.setAssignedTo(model.getAssignedTo()); beforeModel.setActualEffort(model.getActualEffort()); beforeModel.setDueDate(model.getDueDate()); beforeModel.setStatus(model.getStatus()); beforeModel.setLabelColor(model.getLabelColor()); }

Target:
public void updateBeforeModel() { beforeModel.setTitle(model.getTitle()); beforeModel.setDescription(model.getDescription()); beforeModel.setEstimatedEffort(model.getEstimatedEffort()); beforeModel.setAssignedTo(model.getAssignedTo()); beforeModel.setActualEffort(model.getActualEffort()); beforeModel.setDueDate(model.getDueDate()); beforeModel.setStatus(model.getStatus()); beforeModel.setLabelColor(model.getLabelColor()); }
Source:
public static boolean isEmptyIndex(String indexName) { try (RestHighLevelClient client = restHighLevelClient()) { return 0L == client .search(new SearchRequest(indexName) .source(SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery())), RequestOptions.DEFAULT) .getHits().getTotalHits().value; } }

Target:
public static boolean isEmptyIndex(String indexName) { try (RestHighLevelClient client = restHighLevelClient()) { return 0L == SearchHitsUtil.getTotalCount(client .search(new SearchRequest(indexName) .source(SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery())), RequestOptions.DEFAULT) .getHits()); } }
Source:
public String getOperationDescription() { StringBuilder builder = new StringBuilder(); builder.append("The ").append(operationName).append(" operation concatenates all source fields "); builder.append("with the given concatenation string."); return builder.toString(); }

Target:
public String getOperationDescription() { return theOperation().does("concatenates all source fields with the given concatenation string.") .toString(); }
Source:
public SweepResults accumulateWith(SweepResults other) { return SweepResults.builder() .cellTsPairsExamined(getCellTsPairsExamined() + other.getCellTsPairsExamined()) .staleValuesDeleted(getStaleValuesDeleted() + other.getStaleValuesDeleted()) .sweptTimestamp(Math.min(getSweptTimestamp(), other.getSweptTimestamp())) .nextStartRow(other.getNextStartRow()) .timeInMillis(getTimeInMillis() + other.getTimeInMillis()) .timeSweepStarted(getTimeSweepStarted()) .build(); }

Target:
public SweepResults accumulateWith(SweepResults other) { return SweepResults.builder() .nextStartRow(maxRowOptional(getNextStartRow(), other.getNextStartRow())) .cellTsPairsExamined(getCellTsPairsExamined() + other.getCellTsPairsExamined()) .staleValuesDeleted(getStaleValuesDeleted() + other.getStaleValuesDeleted()) .minSweptTimestamp(Math.min(getMinSweptTimestamp(), other.getMinSweptTimestamp())) .timeInMillis(getTimeInMillis() + other.getTimeInMillis()) .timeSweepStarted(Math.min(getTimeSweepStarted(), other.getTimeSweepStarted())) .build(); }
Source:
public <T> T createProxies( ServiceDiscoveryConfiguration discoveryConfig, String serviceName, Class<T> serviceClass) { Optional<ServiceConfiguration> maybeServiceConfig = discoveryConfig.getServiceConfiguration(serviceName); if (!maybeServiceConfig.isPresent()) { throw new RuntimeException("Unable to find the configuration for " + serviceName + "."); } return createProxies(maybeServiceConfig.get(), discoveryConfig.defaultSecurity(), serviceClass); }

Target:
public <T> T createProxies( ServiceDiscoveryConfiguration discoveryConfig, String serviceName, Class<T> serviceClass) { ServiceConfiguration serviceConfig = Preconditions.checkNotNull( discoveryConfig.getServices().get(serviceName), "Unable to find the configuration for " + serviceName + "."); Optional<SSLSocketFactory> socketFactory = Optional.absent(); Optional<SslConfiguration> sslConfig = discoveryConfig.getSslConfiguration(serviceName); if (sslConfig.isPresent()) { socketFactory = Optional.of(SslSocketFactories.createSslSocketFactory(sslConfig.get())); } Set<String> uris = Sets.newHashSet(serviceConfig.uris()); return createProxy(socketFactory, uris, serviceClass); }
Source:
boolean group() { if (!character('[')) { return false; } if (!range()) { return false; } CpuGroup group = new CpuGroup(); addCpuRangeToGroup(group); while (character(',')) { if (!range()) { return false; } addCpuRangeToGroup(group); } if (!character(']')) { return false; } if (character(':')) { if (!integer()) { return false; } group.threadCount = integer; if (group.threadCount == 0) { error("Thread count can't be 0."); } else if (group.threadCount > group.cpus.size()) { error("Thread count be larger than number of cpu's in the group. " + "Thread count = " + group.threadCount + " cpus:" + group.cpus); } } else { group.threadCount = group.cpus.size(); } groups.add(group); return true; }

Target:
boolean group() { if (!character('[')) { return false; } if (!range()) { return false; } CpuGroup group = new CpuGroup(); addCpuRangeToGroup(group); while (character(',')) { if (!range()) { return false; } addCpuRangeToGroup(group); } if (!character(']')) { return false; } if (character(':')) { if (!integer()) { return false; } group.threadCount = integer; if (group.threadCount == 0) { error("Thread count can't be 0."); } else if (group.threadCount > group.cpus.size()) { error("Thread count can't be larger than number of cpu's in the group. " + "Thread count = " + group.threadCount + " cpus:" + group.cpus); } } else { group.threadCount = group.cpus.size(); } groups.add(group); return true; }
Source:
private void updateSession( @Nonnull final MemcachedBackupSession session, @Nonnull final BackupSessionService backupSessionService ) { final Future<BackupResult> result = backupSessionService.backupSession( session, true ); try { if ( result.get().getStatus() != BackupResultStatus.SUCCESS ) { _log.warn( "Update for session (after unsuccessful ping) did not return SUCCESS, but " + result.get() ); } } catch ( final ExecutionException e ) { _log.warn( "An exception occurred when trying to update session " + session.getIdInternal(), e ); } catch ( final InterruptedException e ) { _log.warn( "Got interrupted while trying to update session " + session.getIdInternal(), e ); } }

Target:
private void updateSession( @Nonnull final MemcachedBackupSession session, @Nonnull final BackupSessionService backupSessionService ) throws InterruptedException { final Future<BackupResult> result = backupSessionService.backupSession( session, true ); try { if ( result.get().getStatus() != BackupResultStatus.SUCCESS ) { _log.warn( "Update for session (after unsuccessful ping) did not return SUCCESS, but " + result.get() ); } } catch ( final ExecutionException e ) { _log.warn( "An exception occurred when trying to update session " + session.getIdInternal(), e ); } }
Source:
public byte[] serialize(PendingFileRecoverable pendingFileRecoverable) { if (!(pendingFileRecoverable instanceof HadoopPathBasedPartFileWriter.HadoopPathBasedPendingFileRecoverable)) { throw new UnsupportedOperationException("Only HadoopPathBasedPendingFileRecoverable is supported."); } HadoopPathBasedPendingFileRecoverable hadoopRecoverable = (HadoopPathBasedPendingFileRecoverable) pendingFileRecoverable; Path path = hadoopRecoverable.getPath(); Path inProgressPath = hadoopRecoverable.getInProgressPath(); byte[] pathBytes = path.toUri().toString().getBytes(CHARSET); byte[] inProgressBytes = inProgressPath.toUri().toString().getBytes(CHARSET); byte[] targetBytes = new byte[8 + pathBytes.length + 4 + inProgressBytes.length]; ByteBuffer bb = ByteBuffer.wrap(targetBytes).order(ByteOrder.LITTLE_ENDIAN); bb.putInt(MAGIC_NUMBER); bb.putInt(pathBytes.length); bb.put(pathBytes); bb.putInt(inProgressBytes.length); bb.put(inProgressBytes); return targetBytes; }

Target:
public byte[] serialize(PendingFileRecoverable pendingFileRecoverable) { if (!(pendingFileRecoverable instanceof HadoopPathBasedPartFileWriter.HadoopPathBasedPendingFileRecoverable)) { throw new UnsupportedOperationException("Only HadoopPathBasedPendingFileRecoverable is supported."); } HadoopPathBasedPendingFileRecoverable hadoopRecoverable = (HadoopPathBasedPendingFileRecoverable) pendingFileRecoverable; Path path = hadoopRecoverable.getTargetFilePath(); Path inProgressPath = hadoopRecoverable.getTempFilePath(); byte[] pathBytes = path.toUri().toString().getBytes(CHARSET); byte[] inProgressBytes = inProgressPath.toUri().toString().getBytes(CHARSET); byte[] targetBytes = new byte[12 + pathBytes.length + inProgressBytes.length]; ByteBuffer bb = ByteBuffer.wrap(targetBytes).order(ByteOrder.LITTLE_ENDIAN); bb.putInt(MAGIC_NUMBER); bb.putInt(pathBytes.length); bb.put(pathBytes); bb.putInt(inProgressBytes.length); bb.put(inProgressBytes); return targetBytes; }
Source:
public void validateCreateWithIncorrectJarFile() { deployment.setFile(noJar); Throwable throwable = catchThrowable(() -> deploymentValidator.validate(CREATE, deployment)); assertThat(throwable).isNotNull(); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); assertThat(throwable).hasMessageContaining("File does not contain valid JAR content:"); }

Target:
public void validateCreateWithIncorrectJarFile() { deployment.setFile(noJar); assertThatThrownBy(() -> deploymentValidator.validate(CREATE, deployment)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("File does not contain valid JAR content:"); }
Source:
public FilterResult filtered(HttpMessage message) { String uri = message.getRequestHeader().getURI().toString(); String contentType = message.getResponseHeader() .getHeader(HttpHeader.CONTENT_TYPE) .toLowerCase(Locale.ROOT); String responseBodyStart = StringUtils.left(message.getResponseBody().toString(), 250) .toLowerCase(Locale.ROOT); if (uri.endsWith(".graphql") || uri.endsWith(".graphqls") || contentType.startsWith("application/graphql")) { return FilterResult.WANTED; } if (responseBodyStart.contains("__schema") || responseBodyStart.contains("graphql")) { return FilterResult.WANTED; } return FilterResult.NOT_FILTERED; }

Target:
public FilterResult filtered(HttpMessage message) { if (MessageValidator.validate(message) != MessageValidator.Result.INVALID) { return FilterResult.WANTED; } return FilterResult.NOT_FILTERED; }
Source:
public void writeEncryptedCopyTo_wrongKeyLength() { byte[] wrongLentKey = new byte[42]; File destination = new File(configFactory.getRoot(), "wrong_key.realm"); thrown.expect(IllegalArgumentException.class); realm.writeEncryptedCopyTo(destination, wrongLentKey); }

Target:
public void writeEncryptedCopyTo_wrongKeyLength() { byte[] wrongLengthKey = new byte[42]; File destination = new File(configFactory.getRoot(), "wrong_key.realm"); thrown.expect(IllegalArgumentException.class); realm.writeEncryptedCopyTo(destination, wrongLengthKey); }
Source:
private long removeFile(Path path) { try { if (!useTrash || !fs.moveToTrash(path)) { fs.deleteRecursively(path); } return 1; } catch (FileNotFoundException ex) { } catch (IOException ex) { log.error("Unable to delete wal {}", path, ex); } return 0; }

Target:
private long removeFile(Path path) { try { if (!useTrash || !fs.moveToTrash(path)) { fs.deleteRecursively(path); } return 1; } catch (FileNotFoundException ex) { log.debug("Attempted to delete WAL that did not exists : {}", path, ex.getMessage()); } catch (IOException ex) { log.error("Unable to delete wal {}", path, ex); } return 0; }
Source:
public void testSuspendLongRunningCondition() throws Exception { String typeName = "MethodCall"; IJavaLineBreakpoint first = createLineBreakpoint(19, typeName); createConditionalLineBreakpoint(27, typeName, "for (int x = 0; x < 1000; x++) { System.out.println(x);} Thread.sleep(1000); return true;", true); IJavaThread thread = null; try { thread = launchToLineBreakpoint(typeName, first); IStackFrame top = thread.getTopStackFrame(); assertNotNull("Missing top frame", top); thread.resume(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) <= DEFAULT_TIMEOUT && !thread.isPerformingEvaluation()) { Thread.sleep(10); } assertTrue("Expected evaluation for second breakpoint", thread.isPerformingEvaluation()); thread.suspend(); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT, ProcessConsole.class); assertTrue("Thread should be suspended", thread.isSuspended()); IJavaStackFrame frame = (IJavaStackFrame) thread.getTopStackFrame(); assertNotNull("Missing top frame", frame); assertEquals("Wrong location", "calculateSum", frame.getName()); } finally { removeAllBreakpoints(); terminateAndRemove(thread); } }

Target:
public void testSuspendLongRunningCondition() throws Exception { String typeName = "MethodCall"; IJavaLineBreakpoint first = createLineBreakpoint(19, typeName); createConditionalLineBreakpoint(27, typeName, "for (int x = 0; x < 1000; x++) { System.out.println(x);} Thread.sleep(1000); return true;", true); IJavaThread thread= null; try { thread= launchToLineBreakpoint(typeName, first); IStackFrame top = thread.getTopStackFrame(); assertNotNull("Missing top frame", top); thread.resume(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) <= DEFAULT_TIMEOUT && !thread.isPerformingEvaluation()) { Thread.sleep(10); } assertTrue("Expected evaluation for second breakpoint", thread.isPerformingEvaluation()); thread.suspend(); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT, ProcessConsole.class); assertTrue("Thread should be suspended", thread.isSuspended()); IJavaStackFrame frame = (IJavaStackFrame) thread.getTopStackFrame(); assertNotNull("Missing top frame", frame); assertEquals("Wrong location", "calculateSum", frame.getName()); } finally { terminateAndRemove(thread); removeAllBreakpoints(); } }
Source:
public void verifyCategoryExhibition() { Assertion.assertTrue(categoryExhibition.size() == 4); }

Target:
public void verifyCategoryExhibition() { waitForElementByElement(categoryExhibition.get(0)); Assertion.assertTrue(categoryExhibition.size() == 4); }
Source:
public Iterator<T> iterator() { return new Iterator<T>() { private int index = 0; @Override public boolean hasNext() { return index < trie.size(); } @Override public T next() { final int trieIndex = index + indexShift; index++; return trie.get(trieIndex).get(); } }; }

Target:
public Iterator<T> iterator() { return new Iterator<T>() { private int index = indexShift; private final int size = trie.size() + indexShift; @Override public boolean hasNext() { return index < size; } @Override public T next() { return trie.get(index++).get(); } }; }
Source:
public void testlookupBySubscriptionIds() { Product product = new Product("someProduct", "An Extremely Great Product", owner, 10L); productCurator.create(product); Pool p = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId1 = Util.generateDbUUID(); p.setSourceSubscription(new SourceSubscription(subId1, "master")); poolCurator.create(p); Pool p2 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId2 = Util.generateDbUUID(); p2.setSourceSubscription(new SourceSubscription(subId2, "master")); poolCurator.create(p2); Pool p3 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId3 = Util.generateDbUUID(); p3.setSourceSubscription(new SourceSubscription(subId3, "master")); poolCurator.create(p3); List<Pool> pools = poolCurator.lookupBySubscriptionIds(Arrays.asList(subId1, subId2)); assertEquals(2, pools.size()); assertTrue(pools.contains(p)); assertTrue(pools.contains(p2)); assertTrue(!pools.contains(p3)); }

Target:
public void testlookupBySubscriptionIds() { Product product = new Product("someProduct", "An Extremely Great Product", owner, 10L); productCurator.create(product); Pool p = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId1 = Util.generateDbUUID(); p.setSourceSubscription(new SourceSubscription(subId1, "master")); poolCurator.create(p); Pool p2 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId2 = Util.generateDbUUID(); p2.setSourceSubscription(new SourceSubscription(subId2, "master")); poolCurator.create(p2); Pool p3 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId3 = Util.generateDbUUID(); p3.setSourceSubscription(new SourceSubscription(subId3, "master")); poolCurator.create(p3); List<Pool> pools = poolCurator.lookupBySubscriptionIds(Arrays.asList(subId1, subId2)); assertEquals(2, pools.size()); assertThat(pools, hasItems(p, p2)); assertThat(pools, not(hasItem(p3))); }
Source:
public void setReceivedAtWithSystemTimeInUTC() throws Exception { final EventType eventType = buildDefaultEventType(); final JSONObject event = buildBusinessEvent(); assertThat(event.getJSONObject("metadata").optString("received_at"), isEmptyString()); try { org.joda.time.DateTimeUtils.setCurrentMillisFixed(0); strategy.enrich(event, eventType); } finally { org.joda.time.DateTimeUtils.setCurrentMillisSystem(); } assertThat(event.getJSONObject("metadata").getString("received_at"), equalTo("1970-01-01T00:00:00.000Z")); }

Target:
public void setReceivedAtWithSystemTimeInUTC() throws Exception { final EventType eventType = buildDefaultEventType(); final JSONObject event = buildBusinessEvent(); assertThat(event.getJSONObject("metadata").optString("received_at"), isEmptyString()); try { DateTimeUtils.setCurrentMillisFixed(0); strategy.enrich(event, eventType); } finally { DateTimeUtils.setCurrentMillisSystem(); } assertThat(event.getJSONObject("metadata").getString("received_at"), equalTo("1970-01-01T00:00:00.000Z")); }
Source:
private DateTime getLocalToday(final Long accountId) { final Optional<TimeZoneHistory> optionalTimeZone = this.timeZoneHistoryDAODynamoDB.getCurrentTimeZone(accountId); if (optionalTimeZone.isPresent()) { final int offsetMillis = optionalTimeZone.get().offsetMillis; return DateTime.now(DateTimeZone.UTC).plusMillis(offsetMillis).withTimeAtStartOfDay(); } return DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay(); }

Target:
private DateTime getLocalToday(final Long accountId) { final Optional<TimeZoneHistory> optionalTimeZone = this.timeZoneHistoryDAODynamoDB.getCurrentTimeZone(accountId); final DateTime now = DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay(); if (optionalTimeZone.isPresent()) { return now.plusMillis(optionalTimeZone.get().offsetMillis); } return now; }
Source:
public List<ContentDTO> getAvailableNotificationsForUser(final RegisteredUserDTO user) throws ContentManagerException, SegueDatabaseException { Map<Entry<BooleanOperator, String>, List<String>> fieldsToMatch = Maps.newHashMap(); List<String> newArrayList = Lists.newArrayList(); newArrayList.add("notification"); fieldsToMatch.put(immutableEntry(BooleanOperator.AND, Constants.TYPE_FIELDNAME), newArrayList); ResultsWrapper<ContentDTO> allContentNotifications = this.contentManager .findByFieldNames(this.contentIndex, fieldsToMatch, 0, -1); Map<String, IUserNotification> listOfRecordedNotifications = getMapOfRecordedNotifications(user); List<ContentDTO> resultsToReturn = Lists.newArrayList(); for (ContentDTO c : allContentNotifications.getResults()) { IUserNotification record = listOfRecordedNotifications.get(c.getId()); if (!(c instanceof NotificationDTO)) { continue; } NotificationDTO notification = (NotificationDTO) c; if (notification.getExpiry() != null && new Date().after(notification.getExpiry())) { continue; } if (c.getTags().iterator().next().equals(user.getRole().toString().toLowerCase())) { if (null == record) { resultsToReturn.add(c); } else if (record.getStatus().equals(NotificationStatus.POSTPONED)) { Calendar postPoneExpiry = Calendar.getInstance(); postPoneExpiry.setTime(record.getCreated()); postPoneExpiry.add(Calendar.SECOND, Constants.NUMBER_SECONDS_IN_ONE_DAY); if (new Date().after(postPoneExpiry.getTime())) { resultsToReturn.add(c); } } else { continue; } } } return resultsToReturn; }

Target:
public List<ContentDTO> getAvailableNotificationsForUser(final RegisteredUserDTO user) throws ContentManagerException, SegueDatabaseException { Map<Entry<BooleanOperator, String>, List<String>> fieldsToMatch = Maps.newHashMap(); List<String> newArrayList = Lists.newArrayList(); newArrayList.add("notification"); fieldsToMatch.put(immutableEntry(BooleanOperator.AND, Constants.TYPE_FIELDNAME), newArrayList); ResultsWrapper<ContentDTO> allContentNotifications = this.contentManager .findByFieldNames(this.contentIndex, fieldsToMatch, 0, -1); Map<String, IUserNotification> listOfRecordedNotifications = getMapOfRecordedNotifications(user); List<ContentDTO> resultsToReturn = Lists.newArrayList(); for (ContentDTO c : allContentNotifications.getResults()) { IUserNotification record = listOfRecordedNotifications.get(c.getId()); if (!(c instanceof NotificationDTO)) { continue; } NotificationDTO notification = (NotificationDTO) c; if (notification.getExpiry() != null && new Date().after(notification.getExpiry())) { continue; } String roleTag = user.getRole().name().toLowerCase(); if (null == c.getTags() || !c.getTags().contains(roleTag)) { continue; } if (null == record) { resultsToReturn.add(c); } else if (record.getStatus().equals(NotificationStatus.POSTPONED)) { Calendar postPoneExpiry = Calendar.getInstance(); postPoneExpiry.setTime(record.getCreated()); postPoneExpiry.add(Calendar.SECOND, Constants.NUMBER_SECONDS_IN_ONE_DAY); if (new Date().after(postPoneExpiry.getTime())) { resultsToReturn.add(c); } } else { continue; } } return resultsToReturn; }
Source:
public void check() { Preconditions.checkState(sslSocketFactory().isPresent() == trustManager().isPresent(), "Must set either both sslSocketFactory and TrustManager, or neither"); }

Target:
public void check() { Preconditions.checkState(sslSocketFactory().isPresent() == trustManager().isPresent(), "Must set either both SslSocketFactory and TrustManager, or neither"); }
Source:
public Void apply(KVariable k) { hasConfigVar = true; return null; }

Target:
public void apply(KVariable k) { hasConfigVar = true; }
Source:
private void displayLangLinks() { if (languageEntries.size() == 0) { langLinksEmpty.setEmptyText(R.string.langlinks_empty); ViewAnimations.crossFade(langLinksProgress, langLinksEmpty); } else { adapter = new LangLinksAdapter(languageEntries, getEntriesByAppLanguages()); langLinksEmpty.setEmptyText(R.string.langlinks_no_match); langLinksList.setAdapter(adapter); langLinksList.setLayoutManager(new LinearLayoutManager(this)); searchActionModeCallback = new LanguageSearchCallback(); disposables.add(ServiceFactory.get(app.getWikiSite()).getSiteMatrix() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(SiteMatrix::getSites) .subscribe(sites -> { langLinksProgress.setVisibility(View.INVISIBLE); siteInfoList = sites; adapter.notifyDataSetChanged(); }, throwable -> { langLinksProgress.setVisibility(View.INVISIBLE); adapter.notifyDataSetChanged(); })); ViewAnimations.crossFade(langLinksProgress, langLinksList); } invalidateOptionsMenu(); }

Target:
private void displayLangLinks() { if (languageEntries.size() == 0) { langLinksEmpty.setEmptyText(R.string.langlinks_empty); ViewAnimations.crossFade(langLinksProgress, langLinksEmpty); } else { adapter = new LangLinksAdapter(languageEntries, getEntriesByAppLanguages()); langLinksEmpty.setEmptyText(R.string.langlinks_no_match); langLinksList.setAdapter(adapter); langLinksList.setLayoutManager(new LinearLayoutManager(this)); searchActionModeCallback = new LanguageSearchCallback(); disposables.add(ServiceFactory.get(app.getWikiSite()).getSiteMatrix() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(SiteMatrix::getSites) .subscribe(sites -> siteInfoList = sites, L::e, () -> { langLinksProgress.setVisibility(View.INVISIBLE); adapter.notifyDataSetChanged(); })); ViewAnimations.crossFade(langLinksProgress, langLinksList); } invalidateOptionsMenu(); }
Source:
public void testBuilderWithGivenSchema() { TableSchema oriSchema = TableSchema.builder() .field("a", DataTypes.INT().notNull()) .field("b", DataTypes.STRING()) .field("c", DataTypes.INT(), "a + 1") .field("t", DataTypes.TIMESTAMP(3)) .primaryKey("ct1", new String[] {"a"}) .watermark("t", "t", DataTypes.TIMESTAMP(3)) .build(); TableSchema newSchema = TableSchemaUtils.builderWithGivenSchema(oriSchema).build(); final String expected = "root\n" + " |-- a: INT NOT NULL\n" + " |-- b: STRING\n" + " |-- c: INT AS a + 1\n" + " |-- t: TIMESTAMP(3)\n" + " |-- WATERMARK FOR t AS t\n" + " |-- CONSTRAINT ct1 PRIMARY KEY (a)\n"; assertEquals(expected, newSchema.toString()); }

Target:
public void testBuilderWithGivenSchema() { TableSchema oriSchema = TableSchema.builder() .field("a", DataTypes.INT().notNull()) .field("b", DataTypes.STRING()) .field("c", DataTypes.INT(), "a + 1") .field("t", DataTypes.TIMESTAMP(3)) .primaryKey("ct1", new String[] {"a"}) .watermark("t", "t", DataTypes.TIMESTAMP(3)) .build(); TableSchema newSchema = TableSchemaUtils.builderWithGivenSchema(oriSchema).build(); assertEquals(oriSchema, newSchema); }
Source:
public void onCompleted() { if (once.compareAndSet(0, 1)) { long c = produced; if (c != 0L) { parent.produced(c); } parent.completeInner(); } }

Target:
public void onCompleted() { if (once.compareAndSet(false, true)) { ConcatSubscriber<T> p = parent; p.produced(produced); p.completeInner(); } }
Source:
public void stop() { synchronized (startStopSync) { if (!started) { LOG.debug("Already stopped, ignoring"); return; } try { serviceDiscovery.close(); } catch (IOException e) { throw Throwables.propagate(e); } started = false; } }

Target:
public void stop() { synchronized (startStopSync) { if (!started) { LOG.debug("Already stopped, ignoring"); return; } announcer.unannounce(announcePath); LOG.info("Unannouncing start time on [%s]", announcePath); started = false; } }
Source:
public void channelRead0(ChannelHandlerContext ctx, HttpObject in) { responseParts.offer(ReferenceCountUtil.retain(in)); if (in instanceof HttpResponse && in.getDecoderResult().isSuccess()) { isKeepAlive = HttpHeaders.isKeepAlive((HttpResponse) in); } else if (in.getDecoderResult().isFailure()) { Throwable cause = in.getDecoderResult().cause(); if (cause instanceof Exception) { exception = (Exception) in.getDecoderResult().cause(); } else { exception = new Exception("Encountered Throwable when trying to decode response. Message: " + cause.getMessage()); } invokeFutureAndCallback(); } if (in instanceof LastHttpContent) { if (isKeepAlive) { invokeFutureAndCallback(); } else { ctx.close(); } } }

Target:
public void channelRead0(ChannelHandlerContext ctx, HttpObject in) { responseParts.offer(ReferenceCountUtil.retain(in)); if (in instanceof HttpResponse && in.getDecoderResult().isSuccess()) { isKeepAlive = HttpHeaders.isKeepAlive((HttpResponse) in); } else if (in.getDecoderResult().isFailure()) { Throwable cause = in.getDecoderResult().cause(); if (cause instanceof Exception) { exception = (Exception) cause; } else { exception = new Exception("Encountered Throwable when trying to decode response. Message: " + cause.getMessage()); } invokeFutureAndCallback(); } if (in instanceof LastHttpContent) { if (isKeepAlive) { invokeFutureAndCallback(); } else { ctx.close(); } } }
Source:
public void checkGroup(long userId, long groupId) throws SecurityException { if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { Iterator<Long> iterator = getUserPermissions(userId).iterator(); boolean managed = false; while (!managed && iterator.hasNext()) { managed = getGroupPermissions(iterator.next()).contains(groupId); } if (!managed) { throw new SecurityException("Group access denied"); } } }

Target:
public void checkGroup(long userId, long groupId) throws SecurityException { if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { checkManager(userId); for (long managedUserId : getUserPermissions(userId)) { if (getGroupPermissions(managedUserId).contains(groupId)) { return; } } throw new SecurityException("Group access denied"); } }
Source:
public static String printRequestParameters(HttpServletRequest request) { StringBuilder requestParameters = new StringBuilder(); requestParameters.append('{'); for (Enumeration<?> f = request.getParameterNames(); f.hasMoreElements();) { String paramet = new String(f.nextElement().toString()); requestParameters.append(paramet).append("::"); String[] parameterValues = request.getParameterValues(paramet); for (int j = 0; j < parameterValues.length; j++) { requestParameters.append(parameterValues[j]).append(" } requestParameters.setLength(requestParameters.length() - 2); requestParameters.append(", "); } if (!requestParameters.toString().equals("{")) { requestParameters.setLength(requestParameters.length() - 2); } return requestParameters.append("}").toString(); }

Target:
public static String printRequestParameters(HttpServletRequest request) { StringBuilder requestParameters = new StringBuilder(); requestParameters.append('{'); for (Enumeration<?> f = request.getParameterNames(); f.hasMoreElements();) { String param = new String(f.nextElement().toString()); requestParameters.append(param).append("::"); String[] parameterValues = request.getParameterValues(param); for (int j = 0; j < parameterValues.length; j++) { requestParameters.append(parameterValues[j]).append(" } requestParameters.setLength(requestParameters.length() - 2); requestParameters.append(", "); } if (!"{".equals(requestParameters.toString())) { requestParameters.setLength(requestParameters.length() - 2); } return requestParameters.append("}").toString(); }