auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void initialize(Props props) { logger.info("Initializing"); instance = new JobCallbackManager(props); isInitialized = true; }

Target:
public static void initialize(Props props) { if (isInitialized) { logger.info("Already initialized"); return; } logger.info("Initializing"); instance = new JobCallbackManager(props); isInitialized = true; }
Source:
public void flushAll( IPentahoSession session ) { final Lock writeLock = cacheLock.writeLock(); try { writeLock.lock(); resetCache( session ); flushHostedAndRemote( session ); MondrianServer mondrianServer = ( server != null ) ? server : MondrianServer.forId( null ); mondrianServer.getAggregationManager().getCacheControl( null, null ).flushSchemaCache(); } catch ( Exception e ) { throw new IOlapServiceException( e ); } finally { writeLock.unlock(); } }

Target:
public void flushAll( IPentahoSession session ) { final Lock writeLock = cacheLock.writeLock(); try { writeLock.lock(); resetCache( session ); flushHostedAndRemote( session ); if ( server != null ) { server.getAggregationManager().getCacheControl( null, null ).flushSchemaCache(); } MondrianServer.forId( null ).getAggregationManager().getCacheControl( null, null ).flushSchemaCache(); } catch ( Exception e ) { throw new IOlapServiceException( e ); } finally { writeLock.unlock(); } }
Source:
private void analyzeStatus(Status status, String configName, Map<String, String> params) { String statusString = params.get(status.getStatusKey()); String providerMessageId = params.get(status.getMessageIdKey()); SmsRecord smsRecord = findOrCreateSmsRecord(configName, providerMessageId, statusString); List<String> recipients = Collections.singletonList(smsRecord.getPhoneNumber()); if (statusString != null) { String eventSubject; if (statusString.matches(status.getStatusSuccess())) { smsRecord.setDeliveryStatus(statusString); eventSubject = SmsEventSubjects.DELIVERY_CONFIRMED; } else if (status.hasStatusFailure() && statusString.matches(status.getStatusFailure())) { smsRecord.setDeliveryStatus(statusString); eventSubject = SmsEventSubjects.FAILURE_CONFIRMED; } else { smsRecord.setDeliveryStatus(DeliveryStatuses.DISPATCHED); eventSubject = SmsEventSubjects.DISPATCHED; } eventRelay.sendEventMessage(outboundEvent(eventSubject, configName, recipients, smsRecord.getMessageContent(), smsRecord.getMotechId(), providerMessageId, null, statusString, now(), null)); } else { String msg = String.format("Likely template error, unable to extract status string. Config: %s, Parameters: %s", configName, params); LOGGER.error(msg); statusMessageService.warn(msg, SMS_MODULE); smsRecord.setDeliveryStatus(DeliveryStatuses.FAILURE_CONFIRMED); eventRelay.sendEventMessage(outboundEvent(SmsEventSubjects.FAILURE_CONFIRMED, configName, recipients, smsRecord.getMessageContent(), smsRecord.getMotechId(), providerMessageId, null, null, now(), null)); } smsRecordsDataService.create(smsRecord); }

Target:
private void analyzeStatus(Status status, String configName, Map<String, String> params) { String statusString = params.get(status.getStatusKey()); String providerMessageId = params.get(status.getMessageIdKey()); SmsRecord smsRecord = findOrCreateSmsRecord(configName, providerMessageId, statusString); List<String> recipients = Collections.singletonList(smsRecord.getPhoneNumber()); if (statusString != null) { String eventSubject; if (statusString.matches(status.getStatusSuccess())) { smsRecord.setDeliveryStatus(statusString); eventSubject = SmsEventSubjects.DELIVERY_CONFIRMED; } else if (status.hasStatusFailure() && statusString.matches(status.getStatusFailure())) { smsRecord.setDeliveryStatus(statusString); eventSubject = SmsEventSubjects.FAILURE_CONFIRMED; } else { smsRecord.setDeliveryStatus(statusString); eventSubject = SmsEventSubjects.DISPATCHED; } eventRelay.sendEventMessage(outboundEvent(eventSubject, configName, recipients, smsRecord.getMessageContent(), smsRecord.getMotechId(), providerMessageId, null, statusString, now(), null)); } else { String msg = String.format("Likely template error, unable to extract status string. Config: %s, Parameters: %s", configName, params); LOGGER.error(msg); statusMessageService.warn(msg, SMS_MODULE); smsRecord.setDeliveryStatus(DeliveryStatuses.FAILURE_CONFIRMED); eventRelay.sendEventMessage(outboundEvent(SmsEventSubjects.FAILURE_CONFIRMED, configName, recipients, smsRecord.getMessageContent(), smsRecord.getMotechId(), providerMessageId, null, null, now(), null)); } smsRecordsDataService.create(smsRecord); }
Source:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { SymbolicValue currentVal = context.getState().peekValue(); if (currentVal == null) { return context.getState(); } Tree toCheck = syntaxNode; if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree methodInvocation = (MethodInvocationTree) syntaxNode; toCheck = methodInvocation.methodSelect(); if (ExplodedGraphWalker.isObjectsMethod(methodInvocation, REQUIRE_NON_NULL_METHOD_NAME, 1)) { final List<SymbolicValue> values = context.getState().peekValues(2); return context.getState().addConstraint(values.get(1), ObjectConstraint.NOT_NULL); } else if (ExplodedGraphWalker.isObjectsMethod(methodInvocation, REQUIRE_NON_NULL_METHOD_NAME, 2) || ExplodedGraphWalker.isObjectsMethod(methodInvocation, REQUIRE_NON_NULL_METHOD_NAME, 2)) { final List<SymbolicValue> values = context.getState().peekValues(3); return context.getState().addConstraint(values.get(2), ObjectConstraint.NOT_NULL); } } if (toCheck.is(Tree.Kind.MEMBER_SELECT)) { return checkMemberSelect(context, (MemberSelectExpressionTree) toCheck, currentVal); } return context.getState(); }

Target:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { SymbolicValue currentVal = context.getState().peekValue(); if (currentVal == null) { return context.getState(); } Tree toCheck = syntaxNode; if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree methodInvocation = (MethodInvocationTree) syntaxNode; toCheck = methodInvocation.methodSelect(); if (isObjectsRequireNonNullMethod(methodInvocation.symbol())) { int numberArguments = methodInvocation.arguments().size(); List<SymbolicValue> values = context.getState().peekValues(numberArguments + 1); return context.getState().addConstraint(values.get(numberArguments), ObjectConstraint.NOT_NULL); } } if (toCheck.is(Tree.Kind.MEMBER_SELECT)) { return checkMemberSelect(context, (MemberSelectExpressionTree) toCheck, currentVal); } return context.getState(); }
Source:
public boolean requestArmMode(String armMode, String pinCode) { logger.debug("requestArmMode(): armMode = {}", armMode == null ? "null" : armMode); boolean done = false; HashMap<String, Byte> codes = new HashMap<String, Byte>(); codes.put("Disarmed", (byte) 0x00); codes.put("Stay", (byte) 0x04); codes.put("Armed", (byte) 0x05); codes.put("StayInstant", (byte) 0x14); codes.put("ArmedInstant", (byte) 0x15); codes.put("Night", (byte) 0x04); codes.put("NightInstant", (byte) 0x14); Byte code = codes.get(armMode); if (code == null) { logger.warn("PowerMax alarm binding: invalid requested arm mode: {}", armMode); } else if ((pinCode == null) || (pinCode.length() != 4)) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } else { try { byte[] dynPart = new byte[3]; dynPart[0] = code; dynPart[1] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16); dynPart[2] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16); done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.ARM, dynPart), false, 0); } catch (NumberFormatException e) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } } return done; }

Target:
public boolean requestArmMode(String armMode, String pinCode) { logger.debug("requestArmMode(): armMode = {}", armMode); boolean done = false; HashMap<String, Byte> codes = new HashMap<String, Byte>(); codes.put("Disarmed", (byte) 0x00); codes.put("Stay", (byte) 0x04); codes.put("Armed", (byte) 0x05); codes.put("StayInstant", (byte) 0x14); codes.put("ArmedInstant", (byte) 0x15); codes.put("Night", (byte) 0x04); codes.put("NightInstant", (byte) 0x14); Byte code = codes.get(armMode); if (code == null) { logger.warn("PowerMax alarm binding: invalid requested arm mode: {}", armMode); } else if ((pinCode == null) || (pinCode.length() != 4)) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } else { try { byte[] dynPart = new byte[3]; dynPart[0] = code; dynPart[1] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16); dynPart[2] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16); done = sendMessage(new PowerMaxBaseMessage(PowerMaxSendType.ARM, dynPart), false, 0); } catch (NumberFormatException e) { logger.warn("PowerMax alarm binding: requested arm mode rejected due to invalid PIN code: {}", armMode); } } return done; }
Source:
public List<IEventDeclaration> getEventDeclarations() { ImmutableList.Builder<IEventDeclaration> builder = new ImmutableList.Builder<>(); for (IEventDeclaration ied : fEvents) { if (ied != null) { builder.add(ied); } } return builder.build(); }

Target:
public List<IEventDeclaration> getEventDeclarations() { ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; }
Source:
protected boolean canDoAction() { boolean canDo; canDo = vdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists(); if (canDo) { NetworkClusterValidator validator = new NetworkClusterValidator(getNetworkCluster(), getVdsGroup().getcompatibility_version()); canDo = (!NetworkUtils.isManagementNetwork(getNetwork()) || validate(validator.managementNetworkAttachment(getNetworkName()))) && validate(validator.migrationPropertySupported(getNetworkName())); } return canDo; }

Target:
protected boolean canDoAction() { return vdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists() && validateAttachment(); }
Source:
private String getOwnerText(IRepositoryElement element) { if (element instanceof TaskTask) { String owner = ((ITask) element).getOwner(); if (!Strings.isNullOrEmpty(owner)) { return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, owner); } return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, Messages.TaskListToolTip_Unassigned); } return null; }

Target:
private String getOwnerText(IRepositoryElement element) { if (element instanceof ITask && !(element instanceof LocalTask)) { String owner = ((ITask) element).getOwner(); if (!Strings.isNullOrEmpty(owner)) { return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, owner); } return NLS.bind(Messages.TaskListToolTip_Assigned_to_X, Messages.TaskListToolTip_Unassigned); } return null; }
Source:
private static Node compileFile(File file, String outDir) throws IOException, URISyntaxException { Node preludeTree = generateIRTree(new File(App.class.getResource("Prelude.bla").toURI())); Node programTree = generateIRTree(file); Node combinedTree = ((ProgramNode) preludeTree).addTree((ProgramNode) programTree); new File(outDir).mkdirs(); ASTVisitor graphVisitor = new Graphvizitor(outDir); combinedTree.accept(graphVisitor); IntrospectionPass introspectionPass = new IntrospectionPass(); combinedTree.accept(introspectionPass); ScopeChecker scopeVisitor = new ScopeChecker(); combinedTree.accept(scopeVisitor); ASTVisitor bytecodeVisitor = new BytecodeGenerator(outDir); combinedTree.accept(bytecodeVisitor); return combinedTree; }

Target:
private static Node compileFile(File file, String outDir) throws IOException { Node preludeTree = generateIRTree(App.class.getResourceAsStream("Prelude.bla"), "Babble\\Prelude.bla"); Node programTree = generateIRTree(new FileInputStream(file), file.getPath()); Node combinedTree = ((ProgramNode) preludeTree).addTree((ProgramNode) programTree); new File(outDir).mkdirs(); ASTVisitor graphVisitor = new Graphvizitor(outDir); combinedTree.accept(graphVisitor); IntrospectionPass introspectionPass = new IntrospectionPass(); combinedTree.accept(introspectionPass); ScopeChecker scopeVisitor = new ScopeChecker(); combinedTree.accept(scopeVisitor); ASTVisitor bytecodeVisitor = new BytecodeGenerator(outDir); combinedTree.accept(bytecodeVisitor); return combinedTree; }
Source:
public void validateIncompatibleJavadocCheckNames() throws IOException { final Stream<Class<?>> abstractJavadocCheckNames = CheckUtil.getCheckstyleChecks() .stream() .filter(AbstractJavadocCheck.class::isAssignableFrom); final Stream<Class<?>> otherJavadocCheckNames = Stream.of(JavadocStyleCheck.class); final Set<Class<?>> javadocCheckNames = Stream.concat(abstractJavadocCheckNames, otherJavadocCheckNames) .collect(Collectors.toSet()); assertWithMessage("INCOMPATIBLE_JAVADOC_CHECK_NAMES should contains all descendants " + "of AbstractJavadocCheck") .that(CheckUtil.getSimpleNames(javadocCheckNames)) .isEqualTo(INCOMPATIBLE_JAVADOC_CHECK_NAMES); }

Target:
public void validateIncompatibleJavadocCheckNames() throws IOException { final Set<Class<?>> abstractJavadocCheckNames = CheckUtil.getCheckstyleChecks() .stream() .filter(AbstractJavadocCheck.class::isAssignableFrom) .collect(Collectors.toSet()); abstractJavadocCheckNames.addAll(REGEXP_JAVADOC_CHECKS); assertWithMessage("INCOMPATIBLE_JAVADOC_CHECK_NAMES should contains all descendants " + "of AbstractJavadocCheck") .that(CheckUtil.getSimpleNames(abstractJavadocCheckNames)) .isEqualTo(INCOMPATIBLE_JAVADOC_CHECK_NAMES); }
Source:
private Map<Address, Address> parseResponse(InputStream is) throws IOException, URISyntaxException { JsonValue jsonValue = Json.parse(readInputStream(is)); List<JsonValue> response = jsonValue.asArray().values(); Map<Address, Address> privateToPublicAddresses = new HashMap<Address, Address>(); for (JsonValue value : response) { String privateAddress = value.asObject().get(PRIVATE_ADDRESS_PROPERTY).asString(); String publicAdress = value.asObject().get(PUBLIC_ADDRESS_PROPERTY).asString(); publicAdress = StringUtil.isNullOrEmptyAfterTrim(publicAdress) ? privateAddress : publicAdress; Address publicAddr = createAddress(publicAdress); privateToPublicAddresses.put(new Address(privateAddress, publicAddr.getPort()), publicAddr); } return privateToPublicAddresses; }

Target:
private Map<Address, Address> parseResponse(InputStream is) throws IOException { JsonValue jsonValue = Json.parse(readInputStream(is)); List<JsonValue> response = jsonValue.asArray().values(); Map<Address, Address> privateToPublicAddresses = new HashMap<Address, Address>(); for (JsonValue value : response) { String privateAddress = value.asObject().get(PRIVATE_ADDRESS_PROPERTY).asString(); String publicAddress = value.asObject().get(PUBLIC_ADDRESS_PROPERTY).asString(); Address publicAddr = createAddress(publicAddress); privateToPublicAddresses.put(new Address(privateAddress, publicAddr.getPort()), publicAddr); } return privateToPublicAddresses; }
Source:
public TriggerChannelTypeBuilderImpl(ChannelTypeUID channelTypeUID, String label) { super(channelTypeUID, label); }

Target:
TriggerChannelTypeBuilderImpl(ChannelTypeUID channelTypeUID, String label) { super(channelTypeUID, label); }
Source:
public void setRetryAnalyzer(Class<? extends IRetryAnalyzer> c) { m_retryAnalyzer = null; if (c == null) { return; } try { m_retryAnalyzer = c.newInstance(); } catch (InstantiationException | IllegalAccessException e) { } }

Target:
public void setRetryAnalyzer(Class<? extends IRetryAnalyzer> c) { if (isRetryAnalyzerNotTestNGInjected(c)) { m_retryAnalyzer = ClassHelper.newInstance(c); } }
Source:
private JButton getBtnApply() { if (btnApply == null) { btnApply = new JButton(); btnApply.setText(Constant.messages.getString("history.filter.button.apply")); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filter.setOpcodes(wsUiHelper.getSelectedOpcodeIntegers()); filter.setDirection(wsUiHelper.getDirection()); try{ filter.setPayloadFilter(wsUiHelper.getPattern(),wsUiHelper.getRegexCheckbox().isSelected(), wsUiHelper.getCaseIgnoreCheckbox().isSelected(),wsUiHelper.getInverseCheckbox().isSelected()); }catch(PatternSyntaxException patternException) { if(wsUiHelper.getRegexCheckbox().isSelected() ) { View.getSingleton().showWarningDialog(Constant.messages.getString("filter.replacedialog.invalidpattern")); wsUiHelper.getPatternTextField().grabFocus(); return; } } exitResult = JOptionPane.OK_OPTION; WebSocketMessagesViewFilterDialog.this.dispose(); } }); } return btnApply; }

Target:
private JButton getBtnApply() { if (btnApply == null) { btnApply = new JButton(); btnApply.setText(Constant.messages.getString("history.filter.button.apply")); btnApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filter.setOpcodes(wsUiHelper.getSelectedOpcodeIntegers()); filter.setDirection(wsUiHelper.getDirection()); if(filter.isValidPattern(wsUiHelper.getPattern(), wsUiHelper.getRegexCheckbox().isSelected())) { filter.setPayloadFilter(wsUiHelper.getPattern(), wsUiHelper.getRegexCheckbox().isSelected(), wsUiHelper.getCaseIgnoreCheckbox().isSelected(), wsUiHelper.getInverseCheckbox().isSelected()); }else{ View.getSingleton().showWarningDialog(Constant.messages.getString("filter.replacedialog.invalidpattern")); wsUiHelper.getPatternTextField().requestFocusInWindow(); return; } exitResult = JOptionPane.OK_OPTION; WebSocketMessagesViewFilterDialog.this.dispose(); } }); } return btnApply; }
Source:
private void scan(boolean isBackground) { for (MDNSDiscoveryParticipant participant : participants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), (System.currentTimeMillis() - start)); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } for (org.eclipse.smarthome.io.transport.mdns.discovery.MDNSDiscoveryParticipant participant : oldParticipants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), (System.currentTimeMillis() - start)); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } }

Target:
private void scan(boolean isBackground) { for (MDNSDiscoveryParticipant participant : participants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), System.currentTimeMillis() - start); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } for (org.eclipse.smarthome.io.transport.mdns.discovery.MDNSDiscoveryParticipant participant : oldParticipants) { long start = System.currentTimeMillis(); ServiceInfo[] services; if (isBackground) { services = mdnsClient.list(participant.getServiceType()); } else { services = mdnsClient.list(participant.getServiceType(), FOREGROUND_SCAN_TIMEOUT); } logger.debug("{} services found for {}; duration: {}ms", services.length, participant.getServiceType(), System.currentTimeMillis() - start); for (ServiceInfo service : services) { DiscoveryResult result = participant.createResult(service); if (result != null) { thingDiscovered(result); } } } }
Source:
public void testConflictedAttachment() throws Exception { Map<String, Object> foo1 = new HashMap<String, Object>(); foo1.put("_id", "doc-a"); Map<String, Object> atts = new HashMap<String, Object>(); Map<String, String> att = new HashMap<String, String>(); foo1.put("_attachments", atts); atts.put("att1", att); att.put("content_type", "text/plain"); att.put("data", "aGVsbG8="); foo1.put("foo", "(from remoteDb)"); Response response = remoteDb.create(foo1); MutableDocumentRevision rev = new MutableDocumentRevision(); rev.docId = "doc-a"; rev.body = DocumentBodyFactory.create("{\"foo\": \"local\"}".getBytes()); rev.attachments.put("att1", new UnsavedStreamAttachment( new ByteArrayInputStream("hello universe".getBytes()), "att1", "text/plain") ); this.datastore.createDocumentFromRevision(rev); this.push(); this.datastoreManager.deleteDatastore(this.datastore.getDatastoreName()); this.datastore = (DatastoreExtended)this.datastoreManager.openDatastore("foo-bar-baz"); this.pull(); DocumentRevision gotRev = this.datastore.getDocument("doc-a"); Assert.assertEquals(gotRev.getAttachments().size(), 1); Assert.assertEquals(gotRev.getBody().asMap().get("foo"), "local"); Assert.assertFalse(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello".getBytes()))); Assert.assertTrue(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello universe".getBytes()))); }

Target:
public void testConflictedAttachment() throws Exception { Map<String, Object> foo1 = new HashMap<String, Object>(); foo1.put("_id", "doc-a"); Map<String, Object> atts = new HashMap<String, Object>(); Map<String, String> att = new HashMap<String, String>(); foo1.put("_attachments", atts); atts.put("att1", att); att.put("content_type", "text/plain"); att.put("data", "aGVsbG8="); foo1.put("foo", "(from remoteDb)"); Response response = remoteDb.create(foo1); MutableDocumentRevision rev = new MutableDocumentRevision(); rev.docId = "doc-a"; rev.body = DocumentBodyFactory.create("{\"foo\": \"local\"}".getBytes()); MutableDocumentRevision rev2 = this.datastore.createDocumentFromRevision(rev).mutableCopy(); rev2.attachments.put("att1", new UnsavedStreamAttachment( new ByteArrayInputStream("hello universe".getBytes()), "att1", "text/plain") ); this.datastore.updateDocumentFromRevision(rev2); this.push(); this.datastoreManager.deleteDatastore(this.datastore.getDatastoreName()); this.datastore = (DatastoreExtended)this.datastoreManager.openDatastore("foo-bar-baz"); this.pull(); DocumentRevision gotRev = this.datastore.getDocument("doc-a"); Assert.assertEquals(gotRev.getAttachments().size(), 1); Assert.assertEquals(gotRev.getBody().asMap().get("foo"), "local"); Assert.assertFalse(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello".getBytes()))); Assert.assertTrue(TestUtils.streamsEqual(gotRev.getAttachments().get("att1").getInputStream(), new ByteArrayInputStream("hello universe".getBytes()))); }
Source:
public void shouldUseCollectionConverterWhenItExists() { String expectedResult = "[\"testing\"]"; GsonJSONSerialization serialization = new GsonJSONSerialization(response, extractor, initializer, createBuilder(new CollectionSerializer()), serializee); serialization.withoutRoot().from(new MyCollection()).serialize(); assertThat(result(), is(equalTo(expectedResult))); }

Target:
public void shouldUseCollectionConverterWhenItExists() { GsonJSONSerialization serialization = serializationWithAdapter(new CollectionSerializer()); String expectedResult = "[\"testing\"]"; serialization.withoutRoot().from(new MyCollection()).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
Source:
public void write() throws StoreException { final Timer.Context context = metrics.indexFlushTime.time(); try { if (indexes.size() > 0) { Map.Entry<Long, IndexSegment> lastEntry = indexes.lastEntry(); IndexSegment currentInfo = lastEntry.getValue(); long fileEndPointerBeforeFlush = log.getLogEndOffset(); log.flush(); long lastOffset = lastEntry.getKey(); IndexSegment prevInfo = indexes.size() > 1 ? indexes.lowerEntry(lastOffset).getValue() : null; long currentLogEndPointer = log.getLogEndOffset(); while (prevInfo != null && !prevInfo.isMapped()) { if (prevInfo.getEndOffset() > currentLogEndPointer) { String message = "The read only index cannot have a file end pointer " + prevInfo.getEndOffset() + " greater than the log end offset " + currentLogEndPointer; throw new StoreException(message, StoreErrorCodes.IOError); } logger.info("Index : " + dataDir + " writing prev index with end offset " + prevInfo.getEndOffset()); prevInfo.writeIndexToFile(prevInfo.getEndOffset()); prevInfo.map(true); Map.Entry<Long, IndexSegment> infoEntry = indexes.lowerEntry(prevInfo.getStartOffset()); prevInfo = infoEntry != null ? infoEntry.getValue() : null; } currentInfo.writeIndexToFile(fileEndPointerBeforeFlush); } } catch (IOException e) { throw new StoreException("IO error while writing index to file", e, StoreErrorCodes.IOError); } finally { context.stop(); } }

Target:
public void write() throws StoreException { final Timer.Context context = metrics.indexFlushTime.time(); try { if (indexes.size() > 0) { Map.Entry<Long, IndexSegment> lastEntry = indexes.lastEntry(); IndexSegment currentInfo = lastEntry.getValue(); long currentIndexEndOffsetBeforeFlush = currentInfo.getEndOffset(); long logEndOffsetBeforeFlush = log.getLogEndOffset(); if (logEndOffsetBeforeFlush < currentIndexEndOffsetBeforeFlush) { throw new StoreException("LogEndOffset " + logEndOffsetBeforeFlush + " before flush cannot be less than " + "currentEndOffSet of index " + currentIndexEndOffsetBeforeFlush, StoreErrorCodes.Illegal_Index_State); } log.flush(); long lastOffset = lastEntry.getKey(); IndexSegment prevInfo = indexes.size() > 1 ? indexes.lowerEntry(lastOffset).getValue() : null; long currentLogEndPointer = log.getLogEndOffset(); while (prevInfo != null && !prevInfo.isMapped()) { if (prevInfo.getEndOffset() > currentLogEndPointer) { String message = "The read only index cannot have a file end pointer " + prevInfo.getEndOffset() + " greater than the log end offset " + currentLogEndPointer; throw new StoreException(message, StoreErrorCodes.IOError); } logger.info("Index : " + dataDir + " writing prev index with end offset " + prevInfo.getEndOffset()); prevInfo.writeIndexToFile(prevInfo.getEndOffset()); prevInfo.map(true); Map.Entry<Long, IndexSegment> infoEntry = indexes.lowerEntry(prevInfo.getStartOffset()); prevInfo = infoEntry != null ? infoEntry.getValue() : null; } currentInfo.writeIndexToFile(currentIndexEndOffsetBeforeFlush); } } catch (IOException e) { throw new StoreException("IO error while writing index to file", e, StoreErrorCodes.IOError); } finally { context.stop(); } }
Source:
public void addRow(Value[] values) { cloneLobs(values); if (distinct) { if (distinctRows != null) { ValueArray array = getArrayOfVisible(values); distinctRows.put(array, values); rowCount = distinctRows.size(); if (rowCount > maxMemoryRows) { createExternalResult(); rowCount = external.addRows(distinctRows.values()); distinctRows = null; } } else { rowCount = external.addRow(values); } } else { rows.add(values); rowCount++; if (rows.size() > maxMemoryRows) { if (external == null) { createExternalResult(); } addRowsToDisk(); } } }

Target:
public void addRow(Value[] values) { cloneLobs(values); if (distinct) { if (distinctRows != null) { ValueArray array = getArrayOfVisible(values); distinctRows.put(array, values); rowCount = distinctRows.size(); if (rowCount > maxMemoryRows) { createExternalResult(); rowCount = external.addRows(distinctRows.values()); distinctRows = null; } } else { rowCount = external.addRow(values); } } else { rows.add(values); rowCount++; if (rows.size() > maxMemoryRows) { addRowsToDisk(); } } }
Source:
public boolean isFirstData(){ if (index == 0){ return true; } else { return false; } }

Target:
public boolean isFirstData(){ return index == 0; }
Source:
public void testCreateDeleteFeedbackQuestion() throws InvalidParametersException, EntityAlreadyExistsException { ______TS("standard success case"); FeedbackQuestionAttributes fqa = getNewFeedbackQuestionAttributes(); fqDb.deleteEntity(fqa); fqDb.createEntity(fqa); verifyPresentInDatastore(fqa, true); ______TS("duplicate - with same id."); try { fqDb.createEntity(fqa); signalFailureToDetectException(); } catch (EntityAlreadyExistsException e) { AssertHelper.assertContains(String.format(QuestionsDb.ERROR_CREATE_ENTITY_ALREADY_EXISTS, fqa.getEntityTypeAsString()) + fqa.getIdentificationString(), e.getMessage()); } ______TS("delete - with id specified"); fqDb.deleteEntity(fqa); verifyAbsentInDatastore(fqa); ______TS("null params"); try { fqDb.createEntity(null); signalFailureToDetectException(); } catch (AssertionError e) { AssertHelper.assertContains(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getLocalizedMessage()); } ______TS("invalid params"); try { fqa.creatorEmail = "haha"; fqDb.createEntity(fqa); signalFailureToDetectException(); } catch (InvalidParametersException e) { AssertHelper.assertContains("Invalid creator's email", e.getLocalizedMessage()); } }

Target:
public void testCreateDeleteFeedbackQuestion() throws InvalidParametersException, EntityAlreadyExistsException { ______TS("standard success case"); FeedbackQuestionAttributes fqa = getNewFeedbackQuestionAttributes(); fqDb.deleteEntity(fqa); fqDb.createEntity(fqa); verifyPresentInDatastore(fqa, true); ______TS("duplicate - with same id."); try { fqDb.createEntity(fqa); signalFailureToDetectException(); } catch (EntityAlreadyExistsException e) { AssertHelper.assertContains(String.format(QuestionsDb.ERROR_CREATE_ENTITY_ALREADY_EXISTS, fqa.getEntityTypeAsString()) + fqa.getIdentificationString(), e.getMessage()); } ______TS("delete - with id specified"); fqDb.deleteEntity(fqa); verifyAbsentInDatastore(fqa); ______TS("null params"); try { fqDb.createEntity(null); signalFailureToDetectException(); } catch (AssertionError e) { AssertHelper.assertContains(Const.StatusCodes.DBLEVEL_NULL_INPUT, e.getLocalizedMessage()); } ______TS("invalid params"); try { fqa.creatorEmail = "invalidCreatorEmail"; fqDb.createEntity(fqa); signalFailureToDetectException(); } catch (InvalidParametersException e) { AssertHelper.assertContains("Invalid creator's email", e.getLocalizedMessage()); } }
Source:
public DfsBlockCacheConfig fromConfig(final Config rc) { setBlockLimit(rc.getLong("core", "dfs", "blockLimit", getBlockLimit())); setBlockSize(rc.getInt("core", "dfs", "blockSize", getBlockSize())); setReadAheadLimit(rc.getInt("core", "dfs", "readAheadLimit", getReadAheadLimit())); int readAheadThreads = rc.getInt("core", "dfs", "readAheadThreads", 0); if (0 < getReadAheadLimit() && 0 < readAheadThreads) { setReadAheadService(new ThreadPoolExecutor( 1, readAheadThreads, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1), new ThreadFactory() { private final String name = "JGit-DFS-ReadAhead"; private final AtomicInteger cnt = new AtomicInteger(); private final ThreadGroup group = new ThreadGroup(name); public Thread newThread(Runnable body) { int id = cnt.incrementAndGet(); Thread thread = new Thread(group, body, name + "-" + id); thread.setDaemon(true); thread.setContextClassLoader(getClass().getClassLoader()); return thread; } }, ReadAheadRejectedExecutionHandler.INSTANCE)); } return this; }

Target:
public DfsBlockCacheConfig fromConfig(final Config rc) { setBlockLimit(rc.getLong( CONFIG_CORE_SECTION, CONFIG_DFS_SECTION, CONFIG_KEY_BLOCK_LIMIT, getBlockLimit())); setBlockSize(rc.getInt( CONFIG_CORE_SECTION, CONFIG_DFS_SECTION, CONFIG_KEY_BLOCK_SIZE, getBlockSize())); setReadAheadLimit(rc.getInt( CONFIG_CORE_SECTION, CONFIG_DFS_SECTION, CONFIG_KEY_READ_AHEAD_LIMIT, getReadAheadLimit())); int readAheadThreads = rc.getInt( CONFIG_CORE_SECTION, CONFIG_DFS_SECTION, CONFIG_KEY_READ_AHEAD_THREADS, 0); if (0 < getReadAheadLimit() && 0 < readAheadThreads) { setReadAheadService(new ThreadPoolExecutor( 1, readAheadThreads, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1), new ThreadFactory() { private final String name = "JGit-DFS-ReadAhead"; private final AtomicInteger cnt = new AtomicInteger(); private final ThreadGroup group = new ThreadGroup(name); public Thread newThread(Runnable body) { int id = cnt.incrementAndGet(); Thread thread = new Thread(group, body, name + "-" + id); thread.setDaemon(true); thread.setContextClassLoader(getClass().getClassLoader()); return thread; } }, ReadAheadRejectedExecutionHandler.INSTANCE)); } return this; }
Source:
public void setInstallState(@Nonnull InstallState newState) { if(newState.equals(installState)) { return; } if(InstallState.INITIAL_SETUP_COMPLETED.equals(installState)) { throw new IllegalArgumentException("Setup has already been completed!"); } installState = newState; try { switch(newState) { case INITIAL_PLUGINS_INSTALLED: setInstallState(InstallState.CONFIGURING_SECURITY); break; case SECURITY_CONFIGURATION_COMPLETED: if(!HudsonPrivateSecurityRealm.requiresLocalUser(this)) { setInstallState(InstallState.INITIAL_SETUP_COMPLETED); } else { setInstallState(InstallState.CREATING_ADMIN_USER); } break; case ADMIN_USER_CREATED: setInstallState(InstallState.INITIAL_SETUP_COMPLETED); break; case INITIAL_SETUP_COMPLETED: initPostSetupTasks(); servletContext.setAttribute(WebAppMain.APP, this); break; default: } } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public void setInstallState(@Nonnull InstallState newState) { installState = newState; }
Source:
public TypedQuery<Long> buildCountQuery() { StringBuilder query = new StringBuilder() .append("SELECT ") .append(" COUNT(userdevfile) ") .append("FROM UserDevfilePermission permission ") .append("LEFT JOIN permission.userDevfile userdevfile ") .append(filter); TypedQuery<Long> typedQuery = entityManager.createQuery(query.toString(), Long.class); params.forEach((k, v) -> typedQuery.setParameter(k, v)); return typedQuery; }

Target:
public TypedQuery<Long> buildCountQuery() { StringBuilder query = new StringBuilder() .append("SELECT ") .append(" COUNT(userdevfile) ") .append("FROM UserDevfilePermission permission ") .append("LEFT JOIN permission.userDevfile userdevfile ") .append(filter); TypedQuery<Long> typedQuery = entityManager.createQuery(query.toString(), Long.class); params.forEach(typedQuery::setParameter); return typedQuery; }
Source:
private boolean mapTags(String value, Context context) throws IOException, InterruptedException { String[] elements = InputFormatter.splitInputString(value); if (elements == null) { return true; } for (int i = 0; i < elements.length; i++) { String firstTag = removeVersionFromName(elements[i]); for (int j = 0; j < elements.length; j++) { if (i != j) { String secondTag = removeVersionFromName(elements[j]); context.write(new RelationKey(firstTag, secondTag), MappingType.TAG); } } } return false; }

Target:
private boolean mapTags(String value, Context context) throws IOException, InterruptedException { String[] tags = InputFormatter.splitInputString(value); if (tags == null) { return true; } for (int i = 0; i < tags.length; i++) { String firstTag = removeVersionFromName(tags[i]); for (int j = 0; j < tags.length; j++) { if (i != j) { String secondTag = removeVersionFromName(tags[j]); context.write(new RelationKey(firstTag, secondTag), MappingType.TAG); } } } return false; }
Source:
public T getContent() { if (content == null) { try { if (Boolean.TRUE.equals(contentIsInitializing.get())) { throw new IllegalStateException( "The content is not yet initialized. " + "Infinite loop detected: you are calling a code inside 'initContent' " + "which directly or indirectly is calling 'getContent'/'initContent'. " + "You may not call any method on " + Composite.class.getSimpleName() + " instance until it initialized (inside 'getContent' or 'initContent'). " + "Call methods on the content component instead."); } contentIsInitializing.set(true); T newContent = initContent(); if (newContent == null) { throw new IllegalStateException( "initContent returned null instead of a component"); } setContent(newContent); } finally { contentIsInitializing.set(false); } } return content; }

Target:
public T getContent() { if (content == null) { try { if (Boolean.TRUE.equals(contentIsInitializing.get())) { throw new IllegalStateException( "The content is not yet initialized. " + "Detected direct or indirect call to 'getContent' from 'initContent'. " + "You may not call any framework method on a '" + Composite.class.getSimpleName() + "' instance before 'initContent' has completed initializing the component."); } contentIsInitializing.set(true); T newContent = initContent(); if (newContent == null) { throw new IllegalStateException( "initContent returned null instead of a component"); } setContent(newContent); } finally { contentIsInitializing.set(false); } } return content; }
Source:
private void addToUserProperties(String operation, String property, Object value) { if (userProperties.contains(property)) { Log.e(TAG, String.format("Already used property %s in previous operation, ignoring operation %s", property, operation)); return; } try { if (!userPropertiesOperations.has(operation)) { userPropertiesOperations.put(operation, new JSONObject()); } userPropertiesOperations.getJSONObject(operation).put(property, value); userProperties.add(property); } catch (JSONException e) { Log.e(TAG, e.toString()); } }

Target:
private void addToUserProperties(String operation, String property, Object value) { if (userProperties.contains(property)) { Log.w(TAG, String.format("Already used property %s in previous operation, ignoring operation %s", property, operation)); return; } try { if (!userPropertiesOperations.has(operation)) { userPropertiesOperations.put(operation, new JSONObject()); } userPropertiesOperations.getJSONObject(operation).put(property, value); userProperties.add(property); } catch (JSONException e) { Log.e(TAG, e.toString()); } }
Source:
public Response createMetric( @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { MetricId<?> id = new MetricId(tenantId, metricDefinition.getType(), metricDefinition.getId()); Metric<?> metric = new Metric<>(id, metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/{type}/{id}").build(MetricTypeTextConverter.getLongForm(id .getType()), id.getName()); try { Observable<Void> observable = metricsService.createMetric(metric); observable.toBlocking().lastOrDefault(null); return Response.created(location).build(); } catch (MetricAlreadyExistsException e) { String message = "A metric with name [" + e.getMetric().getId().getName() + "] already exists"; return Response.status(Response.Status.CONFLICT).entity(new ApiError(message)).build(); } catch (Exception e) { return ApiUtils.serverError(e); } }

Target:
public Response createMetric( @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { if(metricDefinition.getType() == null || !metricDefinition.getType().isUserType()) { return ApiUtils.badRequest(new ApiError("MetricDefinition type is invalid")); } MetricId<?> id = new MetricId(tenantId, metricDefinition.getType(), metricDefinition.getId()); Metric<?> metric = new Metric<>(id, metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/{type}/{id}").build(MetricTypeTextConverter.getLongForm(id .getType()), id.getName()); try { Observable<Void> observable = metricsService.createMetric(metric); observable.toBlocking().lastOrDefault(null); return Response.created(location).build(); } catch (MetricAlreadyExistsException e) { String message = "A metric with name [" + e.getMetric().getId().getName() + "] already exists"; return Response.status(Response.Status.CONFLICT).entity(new ApiError(message)).build(); } catch (Exception e) { return ApiUtils.serverError(e); } }
Source:
public Enumerable<Object[]> scan(DataContext root) { final List<ImmutableDruidServer> druidServers = serverView.getDruidServers(); final AuthenticationResult authenticationResult = (AuthenticationResult) root.get(PlannerContext.DATA_CTX_AUTHENTICATION_RESULT); final Access access = AuthorizationUtils.authorizeAllResourceActions( authenticationResult, Collections.singletonList(new ResourceAction(new Resource("STATE", ResourceType.STATE), Action.READ)), authorizerMapper ); if (!access.isAllowed()) { return Linq4j.asEnumerable(ImmutableList.of()); } final FluentIterable<Object[]> results = FluentIterable .from(druidServers) .transform(val -> new Object[]{ val.getHost(), val.getHost().split(":")[0], val.getHostAndPort() == null ? -1 : val.getHostAndPort().split(":")[1], val.getHostAndTlsPort() == null ? -1 : val.getHostAndTlsPort().split(":")[1], val.getType(), val.getTier(), val.getCurrSize(), val.getMaxSize() }); return Linq4j.asEnumerable(results); }

Target:
public Enumerable<Object[]> scan(DataContext root) { final List<ImmutableDruidServer> druidServers = serverView.getDruidServers(); final AuthenticationResult authenticationResult = (AuthenticationResult) root.get(PlannerContext.DATA_CTX_AUTHENTICATION_RESULT); final Access access = AuthorizationUtils.authorizeAllResourceActions( authenticationResult, Collections.singletonList(new ResourceAction(new Resource("STATE", ResourceType.STATE), Action.READ)), authorizerMapper ); if (!access.isAllowed()) { throw new ForbiddenException("Insufficient permission to view servers :" + access.toString()); } final FluentIterable<Object[]> results = FluentIterable .from(druidServers) .transform(val -> new Object[]{ val.getHost(), val.getHost().split(":")[0], val.getHostAndPort() == null ? -1 : val.getHostAndPort().split(":")[1], val.getHostAndTlsPort() == null ? -1 : val.getHostAndTlsPort().split(":")[1], val.getType(), val.getTier(), val.getCurrSize(), val.getMaxSize() }); return Linq4j.asEnumerable(results); }
Source:
protected Object getResourceAttributeValue(Attribute attr, Entity sourceEntity) { if (attr.getName().equals(GENERALIZED_INHERITANCE.getAttributeName())) { return getGeneralizedInheritance(sourceEntity); } String sourceName = CGDAttributeName.getCgdName(attr.getName()); if (sourceName == null) throw new IllegalArgumentException(String.format("%s not present in CGD data", attr.getName())); return sourceEntity.get(sourceName); }

Target:
protected Object getResourceAttributeValue(Attribute attr, Entity sourceEntity) { if (attr.getName().equals(GENERALIZED_INHERITANCE.getAttributeName())) { return getGeneralizedInheritance(sourceEntity); } String sourceName = CGDAttributeName.getCgdName(attr.getName()); if (sourceName == null) { throw new IllegalArgumentException(String.format("%s not present in CGD data", attr.getName())); } return sourceEntity.get(sourceName); }
Source:
public void searchAnalyzerWithoutAnalyzer() { SubTest.expectException( "Setting a search analyzer, without setting a normalizer on the same field", () -> setup( ctx -> { IndexSchemaElement root = ctx.getSchemaElement(); root.field( "myField", f -> f.asString() .searchAnalyzer( DefaultAnalysisDefinitions.ANALYZER_STANDARD_ENGLISH.name ) ) .toReference(); } ) ) .assertThrown() .isInstanceOf( SearchException.class ) .hasMessageMatching( FailureReportUtils.buildFailureReportPattern() .typeContext( TYPE_NAME ) .indexContext( INDEX_NAME ) .failure( "Cannot apply a search analyzer if an analyzer has not been defined on the same field", "'" + DefaultAnalysisDefinitions.ANALYZER_STANDARD_ENGLISH.name + "'" ) .build() ); }

Target:
public void searchAnalyzerWithoutAnalyzer() { SubTest.expectException( "Setting a search analyzer, without setting an analyzer on the same field", () -> setup( ctx -> { IndexSchemaElement root = ctx.getSchemaElement(); root.field( "myField", f -> f.asString() .searchAnalyzer( DefaultAnalysisDefinitions.ANALYZER_STANDARD_ENGLISH.name ) ) .toReference(); } ) ) .assertThrown() .isInstanceOf( SearchException.class ) .hasMessageMatching( FailureReportUtils.buildFailureReportPattern() .typeContext( TYPE_NAME ) .indexContext( INDEX_NAME ) .failure( "Cannot apply a search analyzer if an analyzer has not been defined on the same field", "'" + DefaultAnalysisDefinitions.ANALYZER_STANDARD_ENGLISH.name + "'" ) .build() ); }
Source:
private static long countMethodImplementations(IMethod method, IProgressMonitor monitor) throws CoreException { if (method == null) { return 0; } IType type= method.getDeclaringType(); IType[] results= type.newTypeHierarchy(monitor).getAllSubtypes(type); List<IType> list= Stream.of(results).filter(t -> t.getAncestor(IJavaElement.COMPILATION_UNIT) != null).collect(Collectors.toList()); long count= 0; for (IType t : list) { IMethod m= t.getMethod(method.getElementName(), method.getParameterTypes()); if (m.exists()) { ++count; } } return count; }

Target:
private static long countMethodImplementations(IMethod method, IProgressMonitor monitor) throws CoreException { if (method == null) { return 0; } IType type= method.getDeclaringType(); IType[] results= type.newTypeHierarchy(monitor).getAllSubtypes(type); List<IType> list= Stream.of(results).filter(t -> t.getAncestor(IJavaElement.COMPILATION_UNIT) != null).collect(Collectors.toList()); long count= list.stream().filter(t -> t.getMethod(method.getElementName(), method.getParameterTypes()).exists()).count(); return count; }
Source:
private final <T extends EObject> void fillCategory( SerializationNode category, Resource model, Class<T> categoryClass) { final List<T> categoryList = filterAllContents(model.getAllContents(), categoryClass); final Map<String, Integer> globalResNaming = new HashMap<String, Integer>(); for (T c : categoryList) { String name = RDONaming.getFullyQualifiedName(c); if (c instanceof ResourceCreateStatement) { if (!(c.eContainer() instanceof RDOModel)) continue; if (((ResourceCreateStatement) c).getName() == null) { final String typeName = ((ResourceCreateStatement) c) .getType().getName(); int count = 0; if (globalResNaming.containsKey(typeName)) { count = globalResNaming.get(typeName) + 1; } globalResNaming.put(typeName, count); name = name.substring(0, name.lastIndexOf('.') + 1) + typeName + "[" + count + "]"; } } SerializationNode child = category.addChild(name); if (c instanceof DecisionPointSearch) { for (SerializationLevel type : SerializationLevel.values()) child.addChild(child.getFullName() + "." + type.toString()); } if (c instanceof Pattern || c instanceof Event) { child.addChild(child.getFullName() + ".createdResources"); } } }

Target:
private final <T extends EObject> void fillCategory( SerializationNode category, Resource model, Class<T> categoryClass) { final List<T> categoryItems = filterAllContents(model.getAllContents(), categoryClass); final Map<String, Integer> instanceCountOfResourceType = new HashMap<String, Integer>(); for (T categoryItem : categoryItems) { String name = RDONaming.getFullyQualifiedName(categoryItem); if (categoryItem instanceof ResourceCreateStatement) { if (!(categoryItem.eContainer() instanceof RDOModel)) continue; if (((ResourceCreateStatement) categoryItem).getName() == null) { final String typeName = ((ResourceCreateStatement) categoryItem) .getType().getName(); int count = 0; if (instanceCountOfResourceType.containsKey(typeName)) { count = instanceCountOfResourceType.get(typeName) + 1; } instanceCountOfResourceType.put(typeName, count); name = name.substring(0, name.lastIndexOf('.') + 1) + typeName + "[" + count + "]"; } } SerializationNode child = category.addChild(name); if (categoryItem instanceof DecisionPointSearch) { for (SerializationLevel type : SerializationLevel.values()) child.addChild(child.getFullName() + "." + type.toString()); } if (categoryItem instanceof Pattern || categoryItem instanceof Event) { child.addChild(child.getFullName() + ".createdResources"); } } }
Source:
public Map<String, Object> getConfiguration() { return Collections.unmodifiableMap(configuration); }

Target:
public Map<String, Object> getConfiguration() { return configuration; }