auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Map<String, List<BlackboardArtifact>> buildMap() throws TskCoreException, SQLException { Map<String, List<BlackboardArtifact>> acctMap = new HashMap<>(); List<BlackboardArtifact> contactList = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifacts(BlackboardArtifact.ARTIFACT_TYPE.TSK_CONTACT); for(BlackboardArtifact contactArtifact: contactList) { List<BlackboardAttribute> contactAttributes = contactArtifact.getAttributes(); for(BlackboardAttribute attribute: contactAttributes) { String typeName = attribute.getAttributeType().getTypeName(); if(typeName.startsWith("TSK_EMAIL") || typeName.startsWith("TSK_PHONE") || typeName.startsWith("TSK_NAME") || typeName.startsWith("TSK_ID")) { String accountID = attribute.getValueString(); <START> List<BlackboardArtifact> artifactList = acctMap.get(accountID); <END> if(artifactList == null) { artifactList = new ArrayList<>(); acctMap.put(accountID, artifactList); } if(!artifactList.contains(contactArtifact)) { artifactList.add(contactArtifact); } } } } return acctMap; }</code><technical_language>find acctMap.getOrDefault(accountID, new ArrayList<>()) useful here</technical_language>

Target:
private Map<String, List<BlackboardArtifact>> buildMap() throws TskCoreException, SQLException { Map<String, List<BlackboardArtifact>> acctMap = new HashMap<>(); List<BlackboardArtifact> contactList = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifacts(BlackboardArtifact.ARTIFACT_TYPE.TSK_CONTACT); for (BlackboardArtifact contactArtifact : contactList) { List<BlackboardAttribute> contactAttributes = contactArtifact.getAttributes(); for (BlackboardAttribute attribute : contactAttributes) { String typeName = attribute.getAttributeType().getTypeName(); if (typeName.startsWith("TSK_EMAIL") || typeName.startsWith("TSK_PHONE") || typeName.startsWith("TSK_NAME") || typeName.startsWith("TSK_ID")) { String accountID = attribute.getValueString(); List<BlackboardArtifact> artifactList = acctMap.getOrDefault(accountID, new ArrayList<>()); acctMap.put(accountID, artifactList); if (!artifactList.contains(contactArtifact)) { artifactList.add(contactArtifact); } } } } return acctMap; }
Source:
<code>public SnapshotInfo backupSnapshot(SnapshotInfo snapshotInfo) { if (!snapshotInfo.getLocationType().equals(Snapshot.LocationType.SECONDARY)) { markAsBackedUp((SnapshotObject)snapshotInfo); return snapshotInfo; } Preconditions.checkState(Snapshot.LocationType.SECONDARY.equals(snapshotInfo.getLocationType())); HostVO host = getHost(snapshotInfo.getVolumeId()); boolean canStorageSystemCreateVolumeFromSnapshot = canStorageSystemCreateVolumeFromSnapshot(snapshotInfo.getBaseVolume().getPoolId()); boolean computeClusterSupportsResign = clusterDao.getSupportsResigning(host.getClusterId()); if (!canStorageSystemCreateVolumeFromSnapshot || !computeClusterSupportsResign) { String mesg = "Cannot archive snapshot: Either canStorageSystemCreateVolumeFromSnapshot or " + "computeClusterSupportsResign were false. "; <START> s_logger.warn(mesg); <END> throw new CloudRuntimeException(mesg); } return snapshotSvr.backupSnapshot(snapshotInfo); }</code><technical_language>is message logged WARN ERROR</technical_language>

Target:
public SnapshotInfo backupSnapshot(SnapshotInfo snapshotInfo) { Preconditions.checkArgument(snapshotInfo != null, "backupSnapshot expects a valid snapshot"); if (snapshotInfo.getLocationType() != Snapshot.LocationType.SECONDARY) { markAsBackedUp((SnapshotObject)snapshotInfo); return snapshotInfo; } HostVO host = getHost(snapshotInfo.getVolumeId()); boolean canStorageSystemCreateVolumeFromSnapshot = canStorageSystemCreateVolumeFromSnapshot(snapshotInfo.getBaseVolume().getPoolId()); boolean computeClusterSupportsResign = clusterDao.getSupportsResigning(host.getClusterId()); if (!canStorageSystemCreateVolumeFromSnapshot || !computeClusterSupportsResign) { String mesg = "Cannot archive snapshot: Either canStorageSystemCreateVolumeFromSnapshot or " + "computeClusterSupportsResign were false. "; s_logger.warn(mesg); throw new CloudRuntimeException(mesg); } return snapshotSvr.backupSnapshot(snapshotInfo); }
Source:
<code>public void notifyChanged(Notification notification) { if (isFireLabelUpdateNotifications()) { if (!(notification instanceof IViewerNotification) || ((IViewerNotification)notification).isLabelUpdate()) { <START> CopyOnWriteArrayList<ILabelProviderListener> labelProviderListenersList = new CopyOnWriteArrayList<>(); <END> labelProviderListenersList.addAll(labelProviderListeners); for (ILabelProviderListener labelProviderListener : labelProviderListenersList) { labelProviderListener.labelProviderChanged(new LabelProviderChangedEvent(this, notification.getNotifier())); } } } }</code><technical_language>This need a CopyOnWriteArrayList, modified, synchronization other overhead provide value. Simply List<ILabelProviderListener> localCopy = new ArrayList<>(labelProviderListeners); iterating suffice</technical_language>

Target:
public void notifyChanged(Notification notification) { if (isFireLabelUpdateNotifications()) { if (!(notification instanceof IViewerNotification) || ((IViewerNotification)notification).isLabelUpdate()) { List<ILabelProviderListener> localCopy = new ArrayList<>(labelProviderListeners); for (ILabelProviderListener labelProviderListener : localCopy) { labelProviderListener.labelProviderChanged(new LabelProviderChangedEvent(this, notification.getNotifier())); } } } }
Source:
<code>private void populateWrapperSupplier(ServletConfig config) { if (requestSupplier != null) { return; <START> } <END> String wrapperSupplierName = config.getInitParameter(WRAPPER_SUPPLIER_PARAM_NAME); if (StringUtils.isNotBlank(wrapperSupplierName)) { try { Class<?> wrapperClass = Class.forName(wrapperSupplierName); if (BiFunction.class.isAssignableFrom(wrapperClass)) { requestSupplier = (BiFunction<HttpServletRequest, String, HttpServletRequestWrapper>) wrapperClass.newInstance(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOGGER.debug( "Error converting to BiFunction<HttpServletRequest, String, HttpServletRequestWrapper>; " + "falling back to default", wrapperSupplierName, e); } } if (requestSupplier == null) { requestSupplier = DEFAULT_REQ_FUNC; } }</code><technical_language>Do methods need static</technical_language>

Target:
private synchronized void populateWrapperSupplier(ServletConfig config) { if (requestSupplier != null) { return; } String wrapperSupplierName = config.getInitParameter(WRAPPER_SUPPLIER_PARAM_NAME); if (StringUtils.isNotBlank(wrapperSupplierName)) { try { Class<?> wrapperClass = Class.forName(wrapperSupplierName); if (BiFunction.class.isAssignableFrom(wrapperClass)) { requestSupplier = (BiFunction<HttpServletRequest, String, HttpServletRequestWrapper>) wrapperClass.newInstance(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOGGER.debug( "Error converting to BiFunction<HttpServletRequest, String, HttpServletRequestWrapper>; " + "falling back to default", wrapperSupplierName, e); } } if (requestSupplier == null) { requestSupplier = DEFAULT_REQ_FUNC; } }
Source:
<code>public List<Label> mapAffinityLabels(Map<String, String> affinityLabelMap, String vmName, List<Label> affinityLabelsFromParam) { if (affinityLabelsFromParam == null) { return Collections.emptyList(); } List<Label> affinityLabelsToAdd = new ArrayList<>(); affinityLabelsFromParam.forEach(affinityLabel -> { log.info("Mapping affinity label '{}' for vm '{}'.", affinityLabel, vmName); String mappedAffinityLabelName = affinityLabelMap.get(affinityLabel); if (mappedAffinityLabelName == null) { affinityLabelsToAdd.add(affinityLabel); log.warn("Mapping for affinity label '{}' not found, will use the affinity label name from OVF", affinityLabel.getName()); } else { if (labelDao.getByName(mappedAffinityLabelName) == null) { <START> affinityLabelsToAdd.add(affinityLabel); <END> } else { log.info("Mapping for affinity label '{}' found, attempting to map to '{}'", affinityLabel.getName(), mappedAffinityLabelName); Label mappedAffinityLabel = labelDao.getByName(mappedAffinityLabelName); affinityLabelsToAdd.add(Optional.ofNullable(mappedAffinityLabel).orElse(affinityLabel)); } } }); return affinityLabelsToAdd; }</code><technical_language>add a warn here</technical_language>

Target:
public List<Label> mapAffinityLabels(Map<String, String> affinityLabelMap, String vmName, List<Label> affinityLabelsFromParam) { if (affinityLabelsFromParam == null) { return Collections.emptyList(); } List<Label> affinityLabelsToAdd = new ArrayList<>(); affinityLabelsFromParam.forEach(affinityLabel -> { log.info("Mapping affinity label '{}' for vm '{}'.", affinityLabel, vmName); String mappedAffinityLabelName = affinityLabelMap.get(affinityLabel); if (mappedAffinityLabelName == null) { affinityLabelsToAdd.add(affinityLabel); log.warn("Mapping for affinity label '{}' not found, will use the affinity label name from OVF", affinityLabel.getName()); } else { if (labelDao.getByName(mappedAffinityLabelName) == null) { log.warn("Mapping for affinity label '{}' not found, will use the affinity label name from OVF", affinityLabel.getName()); affinityLabelsToAdd.add(affinityLabel); } else { log.info("Mapping for affinity label '{}' found, attempting to map to '{}'", affinityLabel.getName(), mappedAffinityLabelName); Label mappedAffinityLabel = labelDao.getByName(mappedAffinityLabelName); affinityLabelsToAdd.add(Optional.ofNullable(mappedAffinityLabel).orElse(affinityLabel)); } } }); return affinityLabelsToAdd; }
Source:
<code>public void processEvent(Event event) { log.debug(String.format("Event: %s", event.getName())); for (String recipient : recipients) { log.debug(String.format("Recipient: %s", recipient)); for (FilterEntry entry : notify) { if (( entry.getEventName() == null || entry.getEventName().equals(event.getName()) ) && ( entry.getAddress() == null || entry.getAddress().equals(recipient) )) { log.debug(String.format("Entry match((%s)): %s", entry.isExclude() ? "exclude" : "include", entry)); if (!entry.isExclude()) { <START> Transport transport = transports.get(entry.getTransport()); <END> if (transport == null) { log.debug(String.format("Ignoring recipient '%s' as transport not registered", recipient)); } else { transport.dispatchEvent(event, entry.getAddress()); } } break; } } } }</code><technical_language>this logic modified in source I sent</technical_language>

Target:
public void processEvent(Event event) { log.debug(String.format("Event: %s", event.getName())); for (Recipient recipient : recipients) { log.debug(String.format("Recipient: %s", recipient)); for (FilterEntry entry : notify) { if (( entry.getEventName() == null || entry.getEventName().equals(event.getName()) ) && ( entry.getRecipient() == null || entry.getRecipient().equals(recipient) )) { log.debug(String.format("Entry match((%s)): %s", entry.isExclude() ? "exclude" : "include", entry)); if (!entry.isExclude()) { Transport transport = transports.get(recipient.getTransport()); if (transport == null) { log.debug(String.format("Ignoring recipient '%s' as transport not registered", recipient)); } else { transport.dispatchEvent(event, recipient.getName()); } } break; } } } }
Source:
<code>public void send(@RequestBody @Valid ContactRequest contactRequest) throws MessagingException { log.debug("send {}'s contact type with subject {}, body {}", contactRequest.motive, contactRequest.subject, contactRequest.body); String senderEmail = userInfoService.currentUser().getEmail(); String carbonCopy = null; if (contactRequest.copyToSender){ carbonCopy = senderEmail; } String subject = String.format("[%s by %s]%s",contactRequest.motive, userInfoService.currentUser().getNickname(), contactRequest.subject); <START> mailService.sendMail("contact@ozwillo.com", carbonCopy, senderEmail, subject, contactRequest.body); <END> }</code><technical_language>put contact email in configuration file</technical_language>

Target:
public void send(@RequestBody @Valid ContactRequest contactRequest) throws MessagingException { log.debug("send {}'s contact type with subject {}, body {}", contactRequest.motive, contactRequest.subject, contactRequest.body); String senderEmail = userInfoService.currentUser().getEmail(); String carbonCopy = null; if (contactRequest.copyToSender){ carbonCopy = senderEmail; } String subject = String.format("[%s by %s]%s",contactRequest.motive, userInfoService.currentUser().getNickname(), contactRequest.subject); mailService.sendMail(mailContact, carbonCopy, senderEmail, subject, contactRequest.body); }
Source:
<code>public void testEffectivelyReadOnlyHidesAddRemoveButtons() throws DatabindingFailedException, NoRendererFoundException, NoPropertyDescriptorFoundExeption { mockDataset(); when(getvControl().isAddRemoveDisabled()).thenReturn(false); when(getvControl().isEffectivelyEnabled()).thenReturn(true); when(getvControl().isEffectivelyReadonly()).thenReturn(true); when(getvControl().isVisible()).thenReturn(true); getShell().open(); final Control rendered = renderControl(new SWTGridCell(0, 2, getRenderer())); getRenderer().finalizeRendering(getShell()); assertControl(rendered); final GridTableViewerComposite tableViewerComposite = (GridTableViewerComposite) rendered; final Composite gridComposite = Composite.class.cast(tableViewerComposite.getChildren()[0]); final Composite buttonComposite = (Composite) Composite.class.cast(gridComposite.getChildren()[0]) .getChildren()[2]; assertEquals(0, buttonComposite.getChildren().length); final GridControlSWTRenderer swtRenderer = GridControlSWTRenderer.class.cast(getRenderer()); final Optional<Control> addRowButton = swtRenderer.getControlForAction(AddRowAction.ACTION_ID); final Optional<Control> removeRowButton = swtRenderer.getControlForAction(RemoveRowAction.ACTION_ID); final Optional<Control> duplicateRowButton = swtRenderer.getControlForAction(DuplicateRowAction.ACTION_ID); <START> assertTrue(!addRowButton.isPresent()); <END> assertTrue(!removeRowButton.isPresent()); assertTrue(!duplicateRowButton.isPresent()); }</code><technical_language>simply assertFalse</technical_language>

Target:
public void testEffectivelyReadOnlyHidesAddRemoveButtons() throws DatabindingFailedException, NoRendererFoundException, NoPropertyDescriptorFoundExeption { mockDataset(); when(getvControl().isAddRemoveDisabled()).thenReturn(false); when(getvControl().isEffectivelyEnabled()).thenReturn(true); when(getvControl().isEffectivelyReadonly()).thenReturn(true); when(getvControl().isVisible()).thenReturn(true); getShell().open(); final Control rendered = renderControl(new SWTGridCell(0, 2, getRenderer())); getRenderer().finalizeRendering(getShell()); assertControl(rendered); final GridTableViewerComposite tableViewerComposite = (GridTableViewerComposite) rendered; final Composite gridComposite = Composite.class.cast(tableViewerComposite.getChildren()[0]); final Composite buttonComposite = (Composite) Composite.class.cast(gridComposite.getChildren()[0]) .getChildren()[2]; assertEquals(0, buttonComposite.getChildren().length); final GridControlSWTRenderer swtRenderer = GridControlSWTRenderer.class.cast(getRenderer()); final Optional<Control> addRowButton = swtRenderer.getControlForAction(AddRowAction.ACTION_ID); final Optional<Control> removeRowButton = swtRenderer.getControlForAction(RemoveRowAction.ACTION_ID); final Optional<Control> duplicateRowButton = swtRenderer.getControlForAction(DuplicateRowAction.ACTION_ID); assertFalse(addRowButton.isPresent()); assertFalse(removeRowButton.isPresent()); assertFalse(duplicateRowButton.isPresent()); }
Source:
<code>public void testCraiFromFile() throws IOException { final List<CRAIEntry> index = new ArrayList<CRAIEntry>(); final CRAIEntry entry = new CRAIEntry(); entry.sequenceId = 0; entry.alignmentStart = 1; entry.alignmentSpan = 2; entry.sliceOffset = 3; entry.sliceSize = 4; entry.containerStartOffset = 5; index.add(entry); final File file = File.createTempFile("test", ".crai"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); final GZIPOutputStream gos = new GZIPOutputStream(fos); CRAIIndex.writeIndex(gos, index); gos.close(); final SAMSequenceDictionary dictionary = new SAMSequenceDictionary(); dictionary.addSequence(new SAMSequenceRecord("1", 100)); final SeekableStream baiStream = CRAIIndex.openCraiFileAsBaiStream(new SeekableBufferedStream(new SeekableFileStream(file)), dictionary); Assert.assertNotNull(baiStream); final DiskBasedBAMFileIndex bamIndex = new DiskBasedBAMFileIndex(baiStream, dictionary); final BAMFileSpan span = bamIndex.getSpanOverlapping(entry.sequenceId, entry.alignmentStart, entry.alignmentStart); Assert.assertNotNull(span); final long[] coordinateArray = span.toCoordinateArray(); Assert.assertEquals(coordinateArray.length, 2); Assert.assertEquals(coordinateArray[0] >> 16, entry.containerStartOffset); <START> Assert.assertEquals(coordinateArray[1] & 0xFFFF, 1); <END> }</code><technical_language>test cases share of code -- extract a shared helper method</technical_language>

Target:
public void testCraiFromFile() throws IOException { doCRAITest(this::getBaiStreamFromFile); }
Source:
<code>private String getFriendsPath( SourcePathResolver sourcePathResolver, ImmutableList<SourcePath> friendPathsSourcePaths) { ImmutableSortedSet<String> absoluteFriendPaths = ImmutableSortedSet.copyOf( friendPathsSourcePaths .stream() .map(path -> sourcePathResolver.getAbsolutePath(path).toString()) .collect(Collectors.toSet())); return "-Xfriend-paths=" <START> + absoluteFriendPaths.stream().reduce("", (path1, path2) -> path1 + "," + path2); <END> }</code><technical_language>list is empty, adds -Xfriend-paths= option</technical_language>

Target:
private String getFriendsPath( SourcePathResolver sourcePathResolver, ImmutableList<SourcePath> friendPathsSourcePaths) { if (friendPathsSourcePaths.isEmpty()) { return ""; } ImmutableSortedSet<String> absoluteFriendPaths = ImmutableSortedSet.copyOf( friendPathsSourcePaths .stream() .map(path -> sourcePathResolver.getAbsolutePath(path).toString()) .collect(Collectors.toSet())); return "-Xfriend-paths=" + absoluteFriendPaths.stream().reduce("", (path1, path2) -> path1 + "," + path2); }
Source:
<code>private AuthenticateResponse authenticate(URL authenticationUrl, String requestBody) throws Exception { Request request = new Request.Builder() .url(authenticationUrl) .addHeader("Content-Type", "application/json") <START> .addHeader("Accept", "application/json") <END> .post(RequestBody.create(JSON, requestBody)) .build(); RealmLog.debug("Authenticate: " + requestBody); Call call = client.newCall(request); Response response = call.execute(); return AuthenticateResponse.from(response); }</code><technical_language>This is default HTTP Connection, right</technical_language>

Target:
private AuthenticateResponse authenticate(URL authenticationUrl, String requestBody) throws Exception { Request request = new Request.Builder() .url(authenticationUrl) .addHeader("Content-Type", "application/json") .addHeader("Accept", "application/json") .post(RequestBody.create(JSON, requestBody)) .build(); Call call = client.newCall(request); Response response = call.execute(); return AuthenticateResponse.from(response); }
Source:
<code><START> public void changeMessageCommitFormatMultipleParagraph() throws Exception { <END> Change c = newChange(); ChangeUpdate update = newUpdate(c, changeOwner); update.setChangeMessage("Just a little code change.\n" + "Testing new line\n" + "\n" + "Testing multiple paragraphs."); update.commit(); assertEquals("refs/changes/01/1/meta", update.getRefName()); RevWalk walk = new RevWalk(repo); try { RevCommit commit = walk.parseCommit(update.getRevision()); walk.parseBody(commit); assertEquals("Update patch set 1\n" + "\n" + "Just a little code change.\nTesting new line\n" + "\n" + "Testing multiple paragraphs.\n" + "\n" + "Patch-set: 1\n", commit.getFullMessage()); } finally { walk.release(); } }</code><technical_language>I need a changeMessageWithMultipleParagraphs() test below, test parsing multiple paragraphs. If do drop this one</technical_language>

Target:
public void changeMessageCommitFormatMultipleParagraph() throws Exception { Change c = newChange(); ChangeUpdate update = newUpdate(c, changeOwner); update.setChangeMessage("Just a little code change.\n" + "Testing new line\n" + "\n" + "Testing multiple paragraphs."); update.commit(); assertEquals("refs/changes/01/1/meta", update.getRefName()); RevWalk walk = new RevWalk(repo); try { RevCommit commit = walk.parseCommit(update.getRevision()); walk.parseBody(commit); assertEquals("Update patch set 1\n" + "\n" + "Just a little code change.\n" + "Testing new line\n" + "\n" + "Testing multiple paragraphs.\n" + "\n" + "Patch-set: 1\n", commit.getFullMessage()); } finally { walk.release(); } }
Source:
<code>protected void UpdateDetailsAvailability() { <START> super.UpdateDetailsAvailability(); <END> for (EntityModel detailModel : getDetailModels()) { if (detailModel instanceof ClusterServiceModel) { detailModel.setIsAvailable(((VDSGroup) getSelectedItem()).supportsGlusterService()); } } }</code><technical_language>set ClusterServiceModel member, need for instanseof iteration</technical_language>

Target:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); getClusterServiceModel().setIsAvailable(((VDSGroup) getSelectedItem()).supportsGlusterService()); }
Source:
<code>public void isNotEmpty_acrossLinkingObjectListLink() { createIsEmptyDataSet(realm); <START> assertEquals(2, realm.where(AllJavaTypes.class).findAll().size()); <END> for (RealmFieldType type : SUPPORTED_IS_EMPTY_TYPES) { switch (type) { case STRING: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_STRING).count()); break; case BINARY: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_BINARY).count()); break; case LIST: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LIST).count()); break; case LINKING_OBJECTS: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_OBJECT).count()); assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_LIST).count()); break; default: fail("Unknown type: " + type); } } }</code><technical_language>Nice. Love it</technical_language>

Target:
public void isNotEmpty_acrossLinkingObjectListLink() { createIsEmptyDataSet(realm); assertEquals(3, realm.where(AllJavaTypes.class).findAll().size()); for (RealmFieldType type : SUPPORTED_IS_EMPTY_TYPES) { switch (type) { case STRING: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_STRING).count()); break; case BINARY: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_BINARY).count()); break; case LIST: assertEquals(2, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LIST).count()); break; case LINKING_OBJECTS: assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_OBJECT).count()); assertEquals(1, realm.where(AllJavaTypes.class).isNotEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_LIST).count()); break; default: fail("Unknown type: " + type); } } }
Source:
<code>private boolean matchesIncludeExcludeList(List<Pattern> includeList, List<Pattern> excludeList, String name) { if ( includeList.size() > 0 ) { boolean found = false; for ( Pattern p : includeList ) { <START> found = found || p.matcher(name).find(); <END> } if ( !found ) return false; } for ( Pattern p : excludeList ) { if ( p.matcher(name).find() ) return false; } return true; }</code><technical_language>break if found</technical_language>

Target:
private boolean matchesIncludeExcludeList(List<Pattern> includeList, List<Pattern> excludeList, String name) { if ( includeList.size() > 0 ) { boolean found = false; for ( Pattern p : includeList ) { found = p.matcher(name).find(); if ( found ) break; } if ( !found ) return false; } for ( Pattern p : excludeList ) { if ( p.matcher(name).find() ) return false; } return true; }
Source:
<code>public void processOptions() { options = new PolylineOptions(); if (hasProperty(MapModule.PROPERTY_POINTS)) { processPoints(getProperty(MapModule.PROPERTY_POINTS), false); } if (hasProperty(MapModule.PROPERTY_STROKE_COLOR)) { options.color(TiConvert.toColor((String) getProperty(MapModule.PROPERTY_STROKE_COLOR))); } if (hasProperty(PolylineProxy.PROPERTY_STROKE_COLOR2)) { options.color(TiConvert.toColor((String) getProperty(PolylineProxy.PROPERTY_STROKE_COLOR2))); } if (hasProperty(MapModule.PROPERTY_STROKE_WIDTH)) { options.width(TiConvert.toFloat(getProperty(MapModule.PROPERTY_STROKE_WIDTH))); } if (hasProperty(PolylineProxy.PROPERTY_STROKE_WIDTH2)) { options.width(TiConvert.toFloat(getProperty(PolylineProxy.PROPERTY_STROKE_WIDTH2))); } if (hasProperty(PolylineProxy.PROPERTY_ZINDEX)) { options.zIndex(TiConvert.toFloat(getProperty(PolylineProxy.PROPERTY_ZINDEX))); } if (hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(getProperty(TiC.PROPERTY_TOUCH_ENABLED)); } if (hasProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2)) { if (getProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2) instanceof HashMap) { options.pattern( processPatternDefinition((HashMap) getProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2))); } else { options.pattern( processPatternDefinition(TiConvert.toInt(getProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2)))); } } if (hasProperty(PolylineProxy.PROPERTY_JOINT_TYPE)) { <START> options.jointType(TiConvert.toInt(getProperty(PolylineProxy.PROPERTY_JOINT_TYPE))); <END> } }</code><technical_language>a default for TiConvert</technical_language>

Target:
public void processOptions() { options = new PolylineOptions(); if (hasProperty(MapModule.PROPERTY_POINTS)) { processPoints(getProperty(MapModule.PROPERTY_POINTS), false); } if (hasProperty(MapModule.PROPERTY_STROKE_COLOR)) { options.color(TiConvert.toColor((String) getProperty(MapModule.PROPERTY_STROKE_COLOR))); } if (hasProperty(PolylineProxy.PROPERTY_STROKE_COLOR2)) { options.color(TiConvert.toColor((String) getProperty(PolylineProxy.PROPERTY_STROKE_COLOR2))); } if (hasProperty(MapModule.PROPERTY_STROKE_WIDTH)) { options.width(TiConvert.toFloat(getProperty(MapModule.PROPERTY_STROKE_WIDTH))); } if (hasProperty(PolylineProxy.PROPERTY_STROKE_WIDTH2)) { options.width(TiConvert.toFloat(getProperty(PolylineProxy.PROPERTY_STROKE_WIDTH2))); } if (hasProperty(PolylineProxy.PROPERTY_ZINDEX)) { options.zIndex(TiConvert.toFloat(getProperty(PolylineProxy.PROPERTY_ZINDEX))); } if (hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(getProperty(TiC.PROPERTY_TOUCH_ENABLED)); } if (hasProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2)) { if (getProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2) instanceof HashMap) { options.pattern( processPatternDefinition((HashMap) getProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2))); } else { options.pattern( processPatternDefinition(TiConvert.toInt(getProperty(PolylineProxy.PROPERTY_STROKE_PATTERN2)))); } } if (hasProperty(PolylineProxy.PROPERTY_JOINT_TYPE)) { options.jointType(TiConvert.toInt(getProperty(PolylineProxy.PROPERTY_JOINT_TYPE), 0)); } }
Source:
<code>public String getBackgroundData(){ String[] backgroundData = new String[this.getNumFields()]; for(int i = 0; i < this.getNumFields() ; ++i){ <START> backgroundData[i] = ""; <END> } return backgroundData; }</code><technical_language>this return blank strings</technical_language>

Target:
public String getBackgroundData(){ synchronized(mAsyncLock) { loadVariableContext(); for(int i =0 ; i < this.getNumFields(); ++i ){ if(backgroundData[i] == null) { Text bg = fields[i].getBackground(); if(bg == null) { backgroundData[i] = "";} else { try { backgroundData[i] = bg.evaluate(context); } catch(XPathException xpe) { xpe.printStackTrace(); throw new RuntimeException("Invalid background output for field : " + fields[i].getHeader().toString()); } } } } return backgroundData; } }
Source:
<code>protected static String createRouteMetricName(final Http.Context context) { final Http.Request r = context.request(); final StringBuilder metricNameBuilder = new StringBuilder("rest_service/"); metricNameBuilder.append(r.method()); <START> final String route = context._requestHeader().tags().get("ROUTE_PATTERN").getOrElse( <END> new AbstractFunction0<String>() { @Override public String apply() { return ""; } }) .replaceAll("\\$([^<]+)<([^>]+)>", ":$1"); if (!Strings.isNullOrEmpty(route)) { if (!route.startsWith("/")) { metricNameBuilder.append("/"); } metricNameBuilder.append(route); if (!route.endsWith("/")) { metricNameBuilder.append("/"); } } return metricNameBuilder.toString(); }</code><technical_language>psf</technical_language>

Target:
protected static String createRouteMetricName(final Http.Context context) { final Http.Request r = context.request(); final StringBuilder metricNameBuilder = new StringBuilder("rest_service/"); metricNameBuilder.append(r.method()); final String route = ROUTE_PATTERN_REGEX.matcher( Optional.ofNullable(context.request().tags().get(Router.Tags.ROUTE_PATTERN)).orElse("")) .replaceAll(":$1"); if (!Strings.isNullOrEmpty(route)) { if (!route.startsWith("/")) { metricNameBuilder.append("/"); } metricNameBuilder.append(route); if (!route.endsWith("/")) { metricNameBuilder.append("/"); } } return metricNameBuilder.toString(); }
Source:
<code>static private Server createServerOrApplyConfiguration(String jettyConfiguration, Server server) throws Exception { Resource jettyConfigurationFile = Resource.newResource(jettyConfiguration); if (jettyConfigurationFile == null || !jettyConfigurationFile.exists()) { jettyConfigurationFile = Resource.newClassPathResource(jettyConfiguration); if (jettyConfigurationFile == null || !jettyConfigurationFile.exists()) { throw new FileNotFoundException("Unable to find jetty configuration file either locally or on classpath [" + jettyConfiguration + "]"); } } <START> System.out.println("Using jetty configuration file to configure server: " + jettyConfigurationFile); <END> XmlConfiguration configuration = new XmlConfiguration(jettyConfigurationFile.getInputStream()); if (server == null) { return (Server)configuration.configure(); } else { return (Server)configuration.configure(server); } }</code><technical_language>done a logger</technical_language>

Target:
static private Server createServerOrApplyConfiguration(String jettyConfiguration, Server server) throws Exception { Resource jettyConfigurationFile = Resource.newResource(jettyConfiguration); if (jettyConfigurationFile == null || !jettyConfigurationFile.exists()) { jettyConfigurationFile = Resource.newClassPathResource(jettyConfiguration); if (jettyConfigurationFile == null || !jettyConfigurationFile.exists()) { throw new FileNotFoundException("Unable to find jetty configuration file either locally or on classpath [" + jettyConfiguration + "]"); } } logger.info("Using jetty configuration file to configure server: " + jettyConfigurationFile); XmlConfiguration configuration = new XmlConfiguration(jettyConfigurationFile.getInputStream()); if (server == null) { return (Server)configuration.configure(); } else { return (Server)configuration.configure(server); } }
Source:
<code>public Process runServer() throws IOException { final String serverConsoleLogPath = CORFU_LOG_PATH + File.separator + host + "_" + port + "_consolelog"; <START> System.out.println(serverConsoleLogPath); <END> File logPath = new File(getCorfuServerLogPath(host, port)); if (!logPath.exists()) { logPath.mkdir(); } ProcessBuilder builder = new ProcessBuilder(); if (!metricsConfigFile.isEmpty()) { addMetricsToProcessBuilder(builder, "corfu_server"); } else { builder.command("sh", "-c", "bin/corfu_server " + getOptionsString()); } builder.directory(new File(CORFU_PROJECT_DIR)); Process corfuServerProcess = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(corfuServerProcess.getInputStream(), serverConsoleLogPath); Executors.newSingleThreadExecutor().submit(streamGobbler); return corfuServerProcess; }</code><technical_language>please logger</technical_language>

Target:
public Process runServer() throws IOException { final String serverConsoleLogPath = CORFU_LOG_PATH + File.separator + host + "_" + port + "_consolelog"; File logPath = new File(getCorfuServerLogPath(host, port)); if (!logPath.exists()) { logPath.mkdir(); } ProcessBuilder builder = new ProcessBuilder(); if (!metricsConfigFile.isEmpty()) { addMetricsToProcessBuilder(builder, "corfu_server"); } else { builder.command("sh", "-c", "bin/corfu_server " + getOptionsString()); } builder.directory(new File(CORFU_PROJECT_DIR)); Process corfuServerProcess = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(corfuServerProcess.getInputStream(), serverConsoleLogPath); Executors.newSingleThreadExecutor().submit(streamGobbler); return corfuServerProcess; }
Source:
<code><START> public boolean checkUserExtSourceExistsById(PerunSession sess, int id) throws InternalErrorException { <END> try { return 1 == jdbc.queryForInt("select 1 from user_ext_sources where id=?", id); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>Check methods do return boolean. them, end error returned output</technical_language>

Target:
public void checkUserExtSourceExistsById(PerunSession sess, int id) throws InternalErrorException, UserExtSourceNotExistsException { try { boolean exists = 1 == jdbc.queryForInt("select 1 from user_ext_sources where id=?", id); if (!exists) throw new UserExtSourceNotExistsException("UserExtSource with ID=" + id + " doesn't exists."); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>public void updateUser(HttpServletRequest request, HttpServletResponse response, @PathVariable String uid) throws IOException { ResponseWriter writer = null; try { writer = writerResolver.writerFor(request, response); Id userId = Id.valueOf(idCodec.decode(uid)); User editingUser = userFetcher.userFor(request).get(); if (!editingUser.is(Role.ADMIN) && !editingUser.getId().equals(userId)) { throw new ResourceForbiddenException(); } Optional<User> existing = userStore.userForId(userId); if (existing.isPresent()) { User posted = deserialize(new InputStreamReader(request.getInputStream()), User.class); if (!editingUser.is(Role.ADMIN) && isUserRoleChanged(posted, existing.get())) { <START> throw InsufficientPrivilegeException.CANNOT_CHANGE_USER_ROLE; <END> } User modified = updateProfileFields(posted, existing.get(), editingUser); userStore.store(modified); UserAwareQueryResult<User> queryResult = UserAwareQueryResult.singleResult(modified, UserAwareQueryContext.standard()); resultWriter.write(queryResult, writer); } else { throw new NotFoundException(userId); } } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }</code><technical_language>I safe reuse exception instance repeatedly</technical_language>

Target:
public void updateUser(HttpServletRequest request, HttpServletResponse response, @PathVariable String uid) throws IOException { ResponseWriter writer = null; try { writer = writerResolver.writerFor(request, response); Id userId = Id.valueOf(idCodec.decode(uid)); User editingUser = userFetcher.userFor(request).get(); if (!editingUser.is(Role.ADMIN) && !editingUser.getId().equals(userId)) { throw new ResourceForbiddenException(); } Optional<User> existing = userStore.userForId(userId); if (existing.isPresent()) { User posted = deserialize(new InputStreamReader(request.getInputStream()), User.class); if (!editingUser.is(Role.ADMIN) && isUserRoleChanged(posted, existing.get())) { throw new InsufficientPrivilegeException("You do not have permission to change the user role"); } User modified = updateProfileFields(posted, existing.get(), editingUser); userStore.store(modified); UserAwareQueryResult<User> queryResult = UserAwareQueryResult.singleResult(modified, UserAwareQueryContext.standard()); resultWriter.write(queryResult, writer); } else { throw new NotFoundException(userId); } } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }
Source:
<code>public void unsubscribe(String tenant, String metricId, Subscription.SubscriptionOwner subscriptionOwner) { <START> unsubscribe(tenant, metricId, new HashSet<>(Arrays.asList(subscriptionOwner))); <END> }</code><technical_language>Collections.singleton(subscriptionOwner) is cheaper</technical_language>

Target:
public void unsubscribe(String tenant, String metricId, Subscription.SubscriptionOwner subscriptionOwner) { unsubscribe(tenant, metricId, Collections.singleton(subscriptionOwner)); }
Source:
<code>public void testReassignNotStartedWithEmptyTimeFormat() throws Exception { changeUser(USER_ADMINISTRATOR); Map<String, Object> parameters = new HashMap<>(); Long processInstanceId = null; try { processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_EVALUATION, parameters); List<TaskSummary> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); TaskSummary task = tasks.get(0); OrgEntities reassign = OrgEntities.builder().users(Arrays.asList(USER_JOHN)).build(); <START> assertExceptionContainsCorrectMessage(() -> userTaskAdminClient.reassignWhenNotStarted(CONTAINER_ID, task.getId(), "", reassign), "Error code: 400, message: \"Invalid time expression\"", "Invalid time expression"); <END> } finally { if (processInstanceId != null) { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } } }</code><technical_language>Please update test error assertion defined [1] functionality in place. [1] <LINK_0></technical_language>

Target:
public void testReassignNotStartedWithEmptyTimeFormat() throws Exception { changeUser(USER_ADMINISTRATOR); Map<String, Object> parameters = new HashMap<>(); Long processInstanceId = null; try { processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_EVALUATION, parameters); List<TaskSummary> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); TaskSummary task = tasks.get(0); OrgEntities reassign = OrgEntities.builder().users(Arrays.asList(USER_JOHN)).build(); assertClientException( () -> userTaskAdminClient.reassignWhenNotStarted(CONTAINER_ID, task.getId(), "", reassign), 400, "Invalid time expression", "Invalid time expression"); } finally { if (processInstanceId != null) { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } } }
Source:
<code>private List<UrlInfo> getEndPoints(NhinTargetSystemType target) { List<UrlInfo> endpoints = new ArrayList<>(); UrlInfo entry = new UrlInfo(); entry.setHcid(target.getHomeCommunity().getHomeCommunityId()); <START> entry.setUrl("https://localhost:8181/Gateway/PatientDiscovery/1_0/NhinService/NhinPatientDiscovery"); <END> endpoints.add(entry); return endpoints; }</code><technical_language>in this file, pull this out a constant</technical_language>

Target:
private List<UrlInfo> getEndPoints(NhinTargetSystemType target) { List<UrlInfo> endpoints = new ArrayList<>(); UrlInfo entry = new UrlInfo(); entry.setHcid(target.getHomeCommunity().getHomeCommunityId()); entry.setUrl(PD_URL); endpoints.add(entry); return endpoints; }
Source:
<code>public static void main(String[] args) { String foo = System.getProperty("foo"); if (!"value 1".equals(foo)) { throw new IllegalStateException("foo system property mismatch (got [" + foo + "]"); } String bar = System.getProperty("bar"); if (!"value2".equals(bar)) { throw new IllegalStateException("bar system property mismatch (got [" + bar + "]"); } String property1 = System.getProperty("property1"); if (!"value1".equals(property1)) { throw new IllegalStateException("property1 system property mismatch (got [" + property1 + "]"); } String property2 = System.getProperty("property2"); <START> if (property2 != null && !property2.isEmpty()) { <END> throw new IllegalStateException("property2 system property mismatch (got [" + property2 + "]"); } String property3 = System.getProperty("property3"); if (!"run-jvmargs".equals(property3)) { throw new IllegalStateException("property3 system property mismatch (got [" + property3 + "]"); } System.out.println("I haz been run"); }</code><technical_language>a sample application I performance argument applies here</technical_language>

Target:
public static void main(String[] args) { String foo = System.getProperty("foo"); if (!"value 1".equals(foo)) { throw new IllegalStateException("foo system property mismatch (got [" + foo + "]"); } String bar = System.getProperty("bar"); if (!"value2".equals(bar)) { throw new IllegalStateException("bar system property mismatch (got [" + bar + "]"); } String property1 = System.getProperty("property1"); if (!"value1".equals(property1)) { throw new IllegalStateException("property1 system property mismatch (got [" + property1 + "]"); } String property2 = System.getProperty("property2"); if (!"".equals(property2)) { throw new IllegalStateException("property2 system property mismatch (got [" + property2 + "]"); } String property3 = System.getProperty("property3"); if (!"run-jvmargs".equals(property3)) { throw new IllegalStateException("property3 system property mismatch (got [" + property3 + "]"); } System.out.println("I haz been run"); }
Source:
<code>private Binary fromAvroString(Object value) { if (value instanceof Utf8) { Utf8 utf8 = (Utf8) value; <START> return Binary.fromConstantByteArray(utf8.getBytes(), 0, utf8.getByteLength()); <END> } return Binary.fromString(value.toString()); }</code><technical_language>Utf8 is immutable (unlike String). fromReusedByteArray here</technical_language>

Target:
private Binary fromAvroString(Object value) { if (value instanceof Utf8) { Utf8 utf8 = (Utf8) value; return Binary.fromReusedByteArray(utf8.getBytes(), 0, utf8.getByteLength()); } return Binary.fromString(value.toString()); }
Source:
<code>private void copyLibIndexCache() throws IOException { String libIndexCacheName = "lib.index.cache"; <START> File sourceLibDir = new File(project.getBuild().getDirectory(), libIndexCacheName); <END> File destLibDir = new File(sharedResourcesDirectory, libIndexCacheName); FileUtils.copyDirectory(sourceLibDir, destLibDir); }</code><technical_language>check if this file exists throw exception if not</technical_language>

Target:
private void copyLibIndexCache() throws Exception { String libIndexCacheName = "lib.index.cache"; File sourceLibDir = new File(project.getBuild().getDirectory(), libIndexCacheName); if (!sourceLibDir.exists()) { throw new MojoExecutionException(sourceLibDir.getCanonicalPath() +" does not exist and cannot be installed"); } File destLibDir = new File(sharedResourcesDirectory, libIndexCacheName); FileUtils.copyDirectory(sourceLibDir, destLibDir); }
Source:
<code>public void saveParameterValues() { try { scriptGeneratorModel.saveParameterValues(); } catch (UnsupportedTypeException e) { MessageDialog.openWarning(DISPLAY.getActiveShell(), "Unsupported language", "Cannot generate script. Language to generate in is unsupported."); LOG.error(e); } catch (InvalidParamsException e) { MessageDialog.openWarning(DISPLAY.getActiveShell(), "Params Invalid", <START> "Cannot generate script. Parameters are invalid."); <END> LOG.error(e); } }</code><technical_language>"Cannot save parameters"</technical_language>

Target:
public void saveParameterValues() { Optional<String> fileName = openFileDialog(SWT.SAVE); if (fileName.isPresent()) { try { scriptGeneratorModel.saveParameters(fileName.get()); MessageDialog.openInformation(DISPLAY.getActiveShell(), "Saved", "File saved!"); } catch (NoScriptDefinitionSelectedException e) { LOG.error(e); MessageDialog.openWarning(DISPLAY.getActiveShell(), "No script definition selection", "Cannot generate script. No script definition has been selected"); } } }
Source:
<code>public List<ApplicationKeyJson> listKeys( @QueryParam("query") final String query ) { Applications applications = this.applicationService.getInstalledApplications(); if ( StringUtils.isNotBlank( query ) ) <START> { <END> applications = Applications.from( applications.stream(). filter( ( application ) -> containsIgnoreCase( application.getDisplayName(), query ) || containsIgnoreCase( application.getMaxSystemVersion(), query ) || containsIgnoreCase( application.getMinSystemVersion(), query ) || containsIgnoreCase( application.getSystemVersion(), query ) || containsIgnoreCase( application.getUrl(), query ) || containsIgnoreCase( application.getVendorName(), query ) || containsIgnoreCase( application.getVendorUrl(), query ) ). collect( Collectors.toList() ) ); } return applications.getApplicationKeys().stream().filter( applicationKey -> !ApplicationKey.from( "com.enonic.xp.admin.ui" ).equals( applicationKey ) && !ApplicationKey.from( "com.enonic.xp.app.standardidprovider" ).equals( applicationKey ) ) .map( ApplicationKeyJson::new ).collect( Collectors.toList() ); }</code><technical_language>This block extracted in a separate filterApplications method, is in 3 places in this class</technical_language>

Target:
public List<String> listKeys( @QueryParam("query") final String query ) { Applications applications = this.applicationService.getInstalledApplications(); applications = this.filterApplication( applications, query ); return applications.getApplicationKeys().stream().filter( applicationKey -> !ApplicationKey.from( "com.enonic.xp.admin.ui" ).equals( applicationKey ) && !ApplicationKey.from( "com.enonic.xp.app.standardidprovider" ).equals( applicationKey ) ) .map( applicationKey -> applicationKey.toString() ).collect( Collectors.toList() ); }
Source:
<code>private static void buildTargetRegions(BusinessEntity entity, OrganizationType org) { List<String> regions; if (entity.getCategoryBag() != null && CollectionUtils.isNotEmpty(entity.getCategoryBag().getKeyedReference())) { regions = new ArrayList<>(); for (KeyedReference keyRef : entity.getCategoryBag().getKeyedReference()) { <START> if (null != keyRef.getTModelKey() && keyRef.getTModelKey().equalsIgnoreCase(UDDI_STATE_KEY)) { <END> regions.add(keyRef.getKeyValue()); } } org.getTargetRegion().addAll(regions); } }</code><technical_language>remove null check reverse check "constant.equalsignorecases(variable)"</technical_language>

Target:
private static void buildTargetRegions(BusinessEntity entity, OrganizationType org) { List<String> regions; if (entity.getCategoryBag() != null && CollectionUtils.isNotEmpty(entity.getCategoryBag().getKeyedReference())) { regions = new ArrayList<>(); for (KeyedReference keyRef : entity.getCategoryBag().getKeyedReference()) { if (UDDIConstants.UDDI_STATE_KEY.equalsIgnoreCase(keyRef.getTModelKey())) { regions.add(keyRef.getKeyValue()); } } org.getTargetRegion().addAll(regions); } }
Source:
<code>private void loadMaps() throws CachePersistenceException { try { for (File file : dataDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(MAP_FILE_SUFFIX); } })) { FileInputStream fis = new FileInputStream(file); try { ObjectInputStream oin = new ObjectInputStream(fis); try { ConcurrentMap<?, ?> map = (ConcurrentMap<?, ?>) oin.readObject(); <START> knownMaps.put(file.getName().replace(MAP_FILE_SUFFIX, ""), map); <END> } finally { oin.close(); } } finally { fis.close(); } } } catch (Exception e) { knownMaps.clear(); throw new CachePersistenceException("Failed to load existing StateRepository data", e); } }</code><technical_language>case preserving filesystems bite here. map name need stored in file instead, name need md5 avoid clashes due casing</technical_language>

Target:
private void loadMaps() throws CachePersistenceException { try { for (File file : dataDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(MAP_FILE_SUFFIX); } })) { FileInputStream fis = new FileInputStream(file); try { ObjectInputStream oin = new ObjectInputStream(fis); try { String name = (String) oin.readObject(); Tuple tuple = (Tuple) oin.readObject(); knownMaps.put(name, tuple); } finally { oin.close(); } } finally { fis.close(); } } } catch (Exception e) { knownMaps.clear(); throw new CachePersistenceException("Failed to load existing StateRepository data", e); } }