auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void writeAsBibtexCitation(OutputStream os) throws IOException { Writer out = new BufferedWriter(new OutputStreamWriter(os, "utf-8")); if(getFileTitle() !=null && isDirect()) { out.write("@incollection{"); } else { out.write("@data{"); } out.write(persistentId.getIdentifier() + "_" + year + "," + "\r\n"); out.write("author = {"); out.write(String.join(" and ", authors)); out.write("},\r\n"); out.write("publisher = {"); out.write(publisher); out.write("},\r\n"); if(getFileTitle() !=null && isDirect()) { out.write("title = {"); out.write(fileTitle); out.write("},\r\n"); out.write("booktitle = {"); out.write(title); out.write("},\r\n"); } else { out.write("title = {"); out.write(title); out.write("},\r\n"); } if(getUNF() != null){ out.write("UNF = {"); out.write(UNF); out.write("},\r\n"); } out.write("year = {"); out.write(year); out.write("},\r\n"); out.write("version = {"); out.write(version); out.write("},\r\n"); out.write("doi = {"); out.write(persistentId.getAuthority()); out.write("/"); out.write(persistentId.getIdentifier()); out.write("},\r\n"); out.write("url = {"); out.write(persistentId.toURL().toString()); out.write("}\r\n"); out.write("}\r\n"); out.flush(); }

Target:
public void writeAsBibtexCitation(OutputStream os) throws IOException { Writer out = new BufferedWriter(new OutputStreamWriter(os, "utf-8")); if(getFileTitle() !=null && isDirect()) { out.write("@incollection{"); } else { out.write("@data{"); } out.write(persistentId.getIdentifier() + "_" + year + "," + "\r\n"); out.write("author = {"); out.write(String.join(" and ", authors)); out.write("},\r\n"); out.write("publisher = {"); out.write(publisher); out.write("},\r\n"); if(getFileTitle() !=null && isDirect()) { out.write("title = {"); out.write(fileTitle); out.write("},\r\n"); out.write("booktitle = {"); out.write(title); out.write("},\r\n"); } else { out.write("title = {"); out.write(title); out.write("},\r\n"); } if(UNF != null){ out.write("UNF = {"); out.write(UNF); out.write("},\r\n"); } out.write("year = {"); out.write(year); out.write("},\r\n"); out.write("version = {"); out.write(version); out.write("},\r\n"); out.write("doi = {"); out.write(persistentId.getAuthority()); out.write("/"); out.write(persistentId.getIdentifier()); out.write("},\r\n"); out.write("url = {"); out.write(persistentId.toURL().toString()); out.write("}\r\n"); out.write("}\r\n"); out.flush(); }
Source:
public void read(BitBuffer input) { alignRead(input, this.declaration); boolean signed = declaration.isSigned(); int length = declaration.getLength(); long bits = 0; ByteOrder previousByteOrder = input.getByteOrder(); if ((this.declaration.getByteOrder() != null) && (this.declaration.getByteOrder() != input.getByteOrder())) { input.setByteOrder(this.declaration.getByteOrder()); } if (length == 64) { bits = input.getLong(); } else if (length > 32) { long newPos = input.position() + length; bits = input.getLong(); input.position(newPos); long signedBit = 1L << length; long mask = signedBit - 1; bits &= mask; if (signed && signedBit != 0) { bits |= ~mask; } } else { bits = input.getInt(length, signed); if (!signed) { bits = bits & 0x00000000FFFFFFFFL; } } if (previousByteOrder != input.getByteOrder()) { input.setByteOrder(previousByteOrder); } value = bits; }

Target:
public void read(BitBuffer input) { alignRead(input, this.declaration); boolean signed = declaration.isSigned(); int length = declaration.getLength(); long bits = 0; ByteOrder previousByteOrder = input.getByteOrder(); if ((this.declaration.getByteOrder() != null) && (this.declaration.getByteOrder() != input.getByteOrder())) { input.setByteOrder(this.declaration.getByteOrder()); } if (length > 64) { throw new IllegalArgumentException("Cannot read an integer with over 64 bits. Length given: " + length ); } else if (length == 64) { bits = input.getLong(); } else if (length > 32) { bits = input.getLong(length, signed); } else { bits = input.getInt(length, signed); if (!signed) { bits = bits & 0x00000000FFFFFFFFL; } } if (previousByteOrder != input.getByteOrder()) { input.setByteOrder(previousByteOrder); } value = bits; }
Source:
private void serializeEntity(CanonicalPath entity, JsonGenerator jsonGenerator, String fieldName) throws IOException { jsonGenerator.writeFieldName(fieldName); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName(FIELD_ID); jsonGenerator.writeString(Inventory.getStableId(entity)); jsonGenerator.writeFieldName(FIELD_SHORT_ID); jsonGenerator.writeString(entity.getSegment().getElementId()); jsonGenerator.writeFieldName(FIELD_TYPE); jsonGenerator.writeString(entity.getSegment().getElementType().getSimpleName()); jsonGenerator.writeEndObject(); }

Target:
private void serializeEntity(CanonicalPath entity, JsonGenerator jsonGenerator, String fieldName) throws IOException { jsonGenerator.writeFieldName(fieldName); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName(FIELD_ID); jsonGenerator.writeString(entity.getPath().toString()); jsonGenerator.writeFieldName(FIELD_SHORT_ID); jsonGenerator.writeString(entity.getSegment().getElementId()); jsonGenerator.writeFieldName(FIELD_TYPE); jsonGenerator.writeString(entity.getSegment().getElementType().getSimpleName()); jsonGenerator.writeEndObject(); }
Source:
private String restoreSome(final Ds3ClientHelpers.ObjectChannelBuilder getter) throws IOException, SignatureException, XmlProcessingException, SSLSetupException { final Ds3ClientHelpers helper = getClientHelpers(); final Iterable<Contents> contents = helper.listObjects(this.bucketName, this.prefix); Iterable<Contents> filteredContents = null; if (sync) { filteredContents = filterContents(contents, this.outputPath); if (Iterables.isEmpty(filteredContents)) { return "SUCCESS: All files are up to date"; } } final Iterable<Ds3Object> objects = Iterables.transform( filteredContents == null ? contents : filteredContents, new Function<Contents, Ds3Object>() { @Override public Ds3Object apply(final Contents input) { return new Ds3Object(input.getKey(), input.getSize()); } }); final Ds3ClientHelpers.Job job = helper.startReadJob(this.bucketName, objects, ReadJobOptions.create() .withPriority(this.priority)); job.transfer(new LoggingFileObjectGetter(getter)); if (sync) { if (prefix != null) { return "SUCCESS: Synced all the objects that start with '" + this.prefix + "' from " + this.bucketName + " to " + this.outputPath.toString(); } else { return "SUCCESS: Synced all the objects from " + this.bucketName + " to " + this.outputPath.toString(); } } return "SUCCESS: Wrote all the objects that start with '"+ this.prefix +"' from " + this.bucketName + " to " + this.outputPath.toString(); }

Target:
private String restoreSome(final Ds3ClientHelpers.ObjectChannelBuilder getter) throws IOException, SignatureException, XmlProcessingException, SSLSetupException { final Ds3ClientHelpers helper = getClientHelpers(); final Iterable<Contents> contents = helper.listObjects(this.bucketName, this.prefix); final Iterable<Contents> filteredContents; if (sync) { filteredContents = filterContents(contents, this.outputPath); if (Iterables.isEmpty(filteredContents)) { return "SUCCESS: All files are up to date"; } } else { filteredContents = null; } final Iterable<Ds3Object> objects = Iterables.transform( filteredContents == null ? contents : filteredContents, new Function<Contents, Ds3Object>() { @Override public Ds3Object apply(final Contents input) { return new Ds3Object(input.getKey(), input.getSize()); } }); final Ds3ClientHelpers.Job job = helper.startReadJob(this.bucketName, objects, ReadJobOptions.create() .withPriority(this.priority)); job.transfer(new LoggingFileObjectGetter(getter)); if (sync) { if (prefix != null) { return "SUCCESS: Synced all the objects that start with '" + this.prefix + "' from " + this.bucketName + " to " + this.outputPath.toString(); } else { return "SUCCESS: Synced all the objects from " + this.bucketName + " to " + this.outputPath.toString(); } } return "SUCCESS: Wrote all the objects that start with '"+ this.prefix +"' from " + this.bucketName + " to " + this.outputPath.toString(); }
Source:
public AddChargeParams build() { AddChargeParams addChargeParams = new AddChargeParams(); addChargeParams.amount = this.amount; addChargeParams.version = this.version; addChargeParams.returnUrl = this.returnUrl; addChargeParams.reference = this.reference; addChargeParams.chargeId = this.chargeId; addChargeParams.delayedCapture = this.delayedCapture; addChargeParams.externalMetadata = this.externalMetadata; addChargeParams.transactionId = this.transactionId; addChargeParams.createdDate = this.createdDate; addChargeParams.language = this.language; addChargeParams.externalChargeId = this.externalChargeId; addChargeParams.gatewayAccountId = this.gatewayAccountId; addChargeParams.description = this.description; addChargeParams.email = this.email; addChargeParams.corporateSurcharge = this.corporateSurcharge; addChargeParams.status = this.status; return addChargeParams; }

Target:
public AddChargeParams build() { return new AddChargeParams(this); }
Source:
public void whenEventExistsFindByNameReturnsSomething() throws NakadiException, DuplicatedEventTypeNameException, NoSuchEventTypeException { EventType eventType = buildEventType(); repository.saveEventType(eventType); EventType persistedEventType = repository.findByName(eventType.getName()); assertThat(persistedEventType, notNullValue()); }

Target:
public void whenEventExistsFindByNameReturnsSomething() throws Exception { EventType eventType1 = buildEventType(); EventType eventType2 = buildEventType(); eventType2.setName("event-name-2"); String insertSQL = "INSERT INTO zn_data.event_type (et_name, et_event_type_object) VALUES (?, to_json(?::json))"; template.update(insertSQL, eventType1.getName(), mapper.writer().writeValueAsString(eventType1)); template.update(insertSQL, eventType2.getName(), mapper.writer().writeValueAsString(eventType2)); EventType persistedEventType = repository.findByName(eventType2.getName()); assertThat(persistedEventType, notNullValue()); }
Source:
protected void performPut(long address, long newAddress, WrappedBytes key) { if (address == 0) { memoryLookup.putMemoryAddress(key, newAddress); entryCreated(newAddress); size.incrementAndGet(); } else { boolean shouldCreate = false; boolean foundKey = false; long prevAddress = 0; while (address != 0) { long nextAddress = offHeapEntryFactory.getNext(address); if (!foundKey) { if (offHeapEntryFactory.equalsKey(address, key)) { entryReplaced(newAddress, address); foundKey = true; if (prevAddress == 0) { if (nextAddress == 0) { shouldCreate = true; } else { memoryLookup.putMemoryAddress(key, nextAddress); } } else { offHeapEntryFactory.setNext(prevAddress, nextAddress); address = nextAddress; continue; } } } prevAddress = address; address = nextAddress; } if (!foundKey) { entryCreated(newAddress); size.incrementAndGet(); } if (shouldCreate) { memoryLookup.putMemoryAddress(key, newAddress); } else { offHeapEntryFactory.setNext(prevAddress, newAddress); } } }

Target:
protected void performPut(long address, long newAddress, WrappedBytes key) { if (address == 0) { memoryLookup.putMemoryAddress(key, newAddress); entryCreated(newAddress); size.incrementAndGet(); } else { boolean replaceHead = false; boolean foundKey = false; long prevAddress = 0; while (address != 0) { long nextAddress = offHeapEntryFactory.getNext(address); if (!foundKey) { if (offHeapEntryFactory.equalsKey(address, key)) { entryReplaced(newAddress, address); foundKey = true; if (prevAddress == 0) { if (nextAddress == 0) { replaceHead = true; } else { memoryLookup.putMemoryAddress(key, nextAddress); } } else { offHeapEntryFactory.setNext(prevAddress, nextAddress); address = nextAddress; continue; } } } prevAddress = address; address = nextAddress; } if (!foundKey) { entryCreated(newAddress); size.incrementAndGet(); } if (replaceHead) { memoryLookup.putMemoryAddress(key, newAddress); } else { offHeapEntryFactory.setNext(prevAddress, newAddress); } } }
Source:
protected void getTasksRequest(){ mSwipeLayout.setRefreshing(true); HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); TaskListRequest taskListRequest = new TaskListRequest(getActivity(), params, new Response.Listener<ArrayList<Task>>() { @Override public void onResponse(ArrayList<Task> tasks) { if (mArgs.getInt(OPTION) == USER) { tasks = getUserTasks(tasks); if (tasks.size() > 0) { showList(); setUserTasks(tasks); mUserTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mUserTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } else { if (tasks.size() > 0) { showList(); setAllTasks(tasks); mAllTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mAllTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } new CountDownTimer(2000, 1000) { public void onTick(long millisUntilFinished) public void onFinish() { if (mSwipeLayout != null) mSwipeLayout.setRefreshing(false); if (mNoTasks != null) mNoTasks.setRefreshing(false); } }.start(); } }, mSwipeLayout); mNetworkManager.getRequestQueue().add(taskListRequest); }

Target:
protected void getTasksRequest(){ mSwipeLayout.setRefreshing(true); HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); TaskListRequest taskListRequest = new TaskListRequest(getActivity(), params, new Response.Listener<ArrayList<Task>>() { @Override public void onResponse(ArrayList<Task> tasks) { if (mArgs.getInt(OPTION) == USER) { tasks = getUserTasks(tasks); if (tasks.size() > 0) { showList(); setUserTasks(tasks); mUserTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mUserTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } else { if (tasks.size() > 0) { showList(); setAllTasks(tasks); mAllTaskAdapter.notifyDataSetChanged(); for(int i=0; i < mAllTaskAdapter.getGroupCount(); i++) mListView.expandGroup(i); } else { hideList(); } } new CountDownTimer(1000, 1000) { public void onTick(long millisUntilFinished) public void onFinish() { if (mSwipeLayout != null) mSwipeLayout.setRefreshing(false); if (mNoTasks != null) mNoTasks.setRefreshing(false); } }.start(); } }, mSwipeLayout); mNetworkManager.getRequestQueue().add(taskListRequest); }
Source:
protected void endVmCommand() { super.endVmCommand(); getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); }

Target:
protected void endVmCommand() { getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); super.endVmCommand(); }
Source:
protected boolean processPayeeAchAccountNew(PayeeACHAccount payeeAchAccountNew, PayeeACHAccount payeeAchAccount) { boolean isSuccessful = true; try { payeeAchAccountNew = businessObjectService.save(payeeAchAccountNew); } catch (Exception e) { GlobalVariables.getMessageMap().putError("payeeAchAccount", KFSKeyConstants.ERROR_CUSTOM, e.getCause().getMessage()); if (ObjectUtils.isNotNull(payeeAchAccount)) { payeeAchAccount.setActive(true); payeeAchAccount = businessObjectService.save(payeeAchAccount); } isSuccessful = false; } return isSuccessful; }

Target:
protected boolean processPayeeAchAccountNew(PayeeACHAccount payeeAchAccountNew, PayeeACHAccount payeeAchAccount) { boolean successful = true; try { payeeAchAccountNew = businessObjectService.save(payeeAchAccountNew); } catch (Exception e) { GlobalVariables.getMessageMap().putError("payeeAchAccount", KFSKeyConstants.ERROR_CUSTOM, e.getCause().getMessage()); if (ObjectUtils.isNotNull(payeeAchAccount)) { payeeAchAccount.setActive(true); payeeAchAccount = businessObjectService.save(payeeAchAccount); } successful = false; } return successful; }
Source:
public void onContactsUpdate(final UpdateContacts updateContacts) { if (mPages == null || mPages.isEmpty()) { return; } for (BaseContactFragment fragment : mPages) { fragment.updateContacts(); } }

Target:
public void onContactsUpdate(final UpdateContacts updateContacts) { if (mPages != null && !mPages.isEmpty()) { for (BaseContactFragment fragment : mPages) { fragment.updateContacts(); } } }
Source:
public float onSeekBarProgressChanged(SeekBar seekBar, int progress, boolean fromUser, TextView txtvPosition, TextView seekDisplay) { if (fromUser && playbackService != null && media != null) { float prog = progress / ((float) seekBar.getMax()); int duration = media.getDuration(); TimeSpeedConverter converter = new TimeSpeedConverter(playbackService.getCurrentPlaybackSpeed()); int position = converter.convert((int) (prog * duration)); txtvPosition.setText(Converter.getDurationStringLong(position)); seekDisplay.setText(Converter.getDurationStringLong(position)); return prog; } return 0; }

Target:
public float onSeekBarProgressChanged(SeekBar seekBar, int progress, boolean fromUser, TextView txtvPosition, TextView seekDisplay) { if (fromUser && playbackService != null && media != null) { float prog = progress / ((float) seekBar.getMax()); int duration = media.getDuration(); if (duration == -1) duration = getDuration(); TimeSpeedConverter converter = new TimeSpeedConverter(playbackService.getCurrentPlaybackSpeed()); int position = converter.convert((int) (prog * duration)); txtvPosition.setText(Converter.getDurationStringLong(position)); seekDisplay.setText(Converter.getDurationStringLong(position)); return prog; } return 0; }
Source:
public LinkedHashMap<String,S> process(final int max) throws IOException, CompoundNotFoundException { if(closed) throw new IOException("Cannot perform action: resource has been closed."); LinkedHashMap<String,S> sequences = new LinkedHashMap<>(); @SuppressWarnings("unchecked") int i=0; while(true) { if(max>0 && i>=max) break; i++; String seqString = genbankParser.getSequence(bufferedReader, 0); if(seqString==null) break; @SuppressWarnings("unchecked") S sequence = (S) sequenceCreator.getSequence(seqString, 0); genbankParser.getSequenceHeaderParser().parseHeader(genbankParser.getHeader(), sequence); genbankParser.getFeatures().values().stream() .flatMap(List::stream) .forEach(sequence::addFeature); ArrayList<DBReferenceInfo> dbQualifier = genbankParser.getDatabaseReferences().get("db_xref"); if (dbQualifier != null){ DBReferenceInfo q = dbQualifier.get(0); sequence.setTaxonomy(new TaxonomyID(q.getDatabase()+":"+q.getId(), DataSource.GENBANK)); } sequences.put(sequence.getAccession().getID(), sequence); } return sequences; }

Target:
public LinkedHashMap<String,S> process(final int max) throws IOException, CompoundNotFoundException { if(closed){ throw new IOException("Cannot perform action: resource has been closed."); } LinkedHashMap<String,S> sequences = new LinkedHashMap<>(); @SuppressWarnings("unchecked") int i=0; while(true) { if(max>0 && i>=max) break; i++; String seqString = genbankParser.getSequence(bufferedReader, 0); if(seqString==null) break; @SuppressWarnings("unchecked") S sequence = (S) sequenceCreator.getSequence(seqString, 0); genbankParser.getSequenceHeaderParser().parseHeader(genbankParser.getHeader(), sequence); genbankParser.getFeatures().values().stream() .flatMap(List::stream) .forEach(sequence::addFeature); ArrayList<DBReferenceInfo> dbQualifier = genbankParser.getDatabaseReferences().get("db_xref"); if (dbQualifier != null){ DBReferenceInfo q = dbQualifier.get(0); sequence.setTaxonomy(new TaxonomyID(q.getDatabase()+":"+q.getId(), DataSource.GENBANK)); } sequences.put(sequence.getAccession().getID(), sequence); } return sequences; }
Source:
public Set<String> getResourceTypes() { if (myResourceNames == null) { myResourceNames = buildResourceNames(); } return myResourceNames; }

Target:
public Set<String> getResourceTypes() { Set<String> resourceNames = myResourceNames; if (resourceNames == null) { resourceNames = buildResourceNames(); myResourceNames = resourceNames; } return resourceNames; }
Source:
public void shouldUpdateModifiedTimestamp() { Person p = new Person("John", "Phiri"); p.setId(3); logNextTimestamp("now"); personDAO.insert(p); verifyLastTimestamp(T0); when(clock.instant()).thenReturn(T0.plusSeconds(10).toInstant()); Person personAfterCreate = personDAO.get(3); personAfterCreate.setLastName("Banda"); personDAO.updatePerson(personAfterCreate); verifyLastTimestamp(T0.plusSeconds(10)); Person personAfterUpdate = personDAO.get(3); assertThat(personAfterUpdate.getLastName()).isEqualToIgnoringCase("Banda"); assertThat(personAfterUpdate.getCreated()) .isEqualTo(T0_TIMESTAMP) .isEqualTo(personAfterCreate.getCreated()); assertThat(personAfterUpdate.getModified()) .isEqualTo(Timestamp.from(T0.plusSeconds(10).toInstant())); }

Target:
public void shouldUpdateModifiedTimestamp() { Person p = new Person("John", "Phiri"); p.setId(3); logNextTimestamp("now"); personDAO.insert(p); verifyLastTimestamp(T0); clock.advance(10, SECONDS); Person personAfterCreate = personDAO.get(3); personAfterCreate.setLastName("Banda"); personDAO.updatePerson(personAfterCreate); verifyLastTimestamp(T0.plusSeconds(10)); Person personAfterUpdate = personDAO.get(3); assertThat(personAfterUpdate.getLastName()).isEqualToIgnoringCase("Banda"); assertThat(personAfterUpdate.getCreated()) .isEqualTo(T0_TIMESTAMP) .isEqualTo(personAfterCreate.getCreated()); assertThat(personAfterUpdate.getModified()) .isEqualTo(Timestamp.from(T0.plusSeconds(10).toInstant())); }
Source:
protected IManageablePage getPersistedPage(String sessionIdentifier, int id) { IgniteCache<Integer, BinarylizableWrapper> cache = getIgniteCache(sessionIdentifier); if (cache != null) { BinarylizableWrapper wrapper = cache.get(id); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Got for session '{}' and page id '{}'", wrapper, sessionIdentifier, id); } if (wrapper != null) { return wrapper.page; } } return null; }

Target:
protected IManageablePage getPersistedPage(String sessionIdentifier, int id) { IgniteCache<Integer, BinarylizableWrapper> cache = getIgniteCache(sessionIdentifier, false); if (cache != null) { BinarylizableWrapper wrapper = cache.get(id); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Got for session '{}' and page id '{}'", wrapper, sessionIdentifier, id); } if (wrapper != null) { return wrapper.page; } } return null; }
Source:
public void failValidationWithoutSchema() throws Exception { final Environment env = new Environment.Mock() .withFile( "src/main/resources/noschema.xml", "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ); final Validator validator = new XmlValidator(true); validator.validate(env); }

Target:
public void failValidationWithoutSchema() throws Exception { new XmlValidator(true).validate(new Environment.Mock() .withFile( "src/main/resources/noschema.xml", "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ) ); }
Source:
public void checkPrice(ProductItemPrice price) { assert price.getId() > 0 : price; assert price.getItemId() > 0 : price; assert price.getRecurringFee() != null || price.getHourlyRecurringFee() != null : price; }

Target:
public void checkPrice(ProductItemPrice price) { assertTrue(price.getId() > 0, "price id must be more than 0"); assertTrue(price.getItemId() > 0, "price itemId must be more than 0"); assertTrue(price.getRecurringFee() != null || price.getHourlyRecurringFee() != null, "price.getRecurringFee() must be not null OR price.getHourlyRecurringFee() must be not null"); }
Source:
private void checkPrivileges(User user) { List<String> requiredPrivs = user.getAllRoles().stream().peek(this::checkSuperUserPrivilege) .map(Role::getPrivileges).filter(Objects::nonNull).flatMap(Collection::stream) .map(Privilege::getPrivilege).filter(p -> !Context.hasPrivilege(p)).collect(Collectors.toList()); if (requiredPrivs.size() == 1) { throw new APIException("User.you.must.have.privilege", new Object[] { requiredPrivs.get(0) }); } else if (requiredPrivs.size() > 1) { throw new APIException(String.format(ERROR_FORMAT, String.join(", ", requiredPrivs))); } }

Target:
private void checkPrivileges(User user) { List<String> requiredPrivs = user.getAllRoles().stream().peek(this::checkSuperUserPrivilege) .map(Role::getPrivileges).filter(Objects::nonNull).flatMap(Collection::stream) .map(Privilege::getPrivilege).filter(p -> !Context.hasPrivilege(p)).collect(Collectors.toList()); if (requiredPrivs.size() == 1) { throw new APIException("User.you.must.have.privilege", new Object[] { requiredPrivs.get(0) }); } else if (requiredPrivs.size() > 1) { throw new APIException(String.format("ERROR_FORMAT", String.join(", ", requiredPrivs))); } }
Source:
public void testPersistentWatchInBackground() throws Exception { try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) { client.start(); client.blockUntilConnected(); CountDownLatch backgroundLatch = new CountDownLatch(1); BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); CountDownLatch latch = new CountDownLatch(3); Watcher watcher = event -> latch.countDown(); client.watchers().add().withMode(AddWatchMode.PERSISTENT).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test/foo"); client.create().creatingParentsIfNeeded().forPath("/test/foo"); client.setData().forPath("/test/foo", "hey".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(timing.awaitLatch(latch)); } }

Target:
public void testPersistentWatchInBackground() throws Exception { try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) { client.start(); client.blockUntilConnected(); CountDownLatch backgroundLatch = new CountDownLatch(1); BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); CountDownLatch latch = new CountDownLatch(3); Watcher watcher = event -> latch.countDown(); client.watchers().add().withMode(AddWatchMode.PERSISTENT).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test/foo"); client.create().creatingParentsIfNeeded().forPath("/test/foo"); client.setData().forPath("/test/foo", "hey".getBytes()); client.delete().forPath("/test/foo"); Assert.assertTrue(timing.awaitLatch(backgroundLatch)); Assert.assertTrue(timing.awaitLatch(latch)); } }
Source:
public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkArgument( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } request.setConfig(requestConfig.build()); return new ApacheHttpResponse(request, httpClient.execute(request)); }

Target:
public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkState( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } request.setConfig(requestConfig.build()); return new ApacheHttpResponse(request, httpClient.execute(request)); }
Source:
public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); if(this.convertedState==null){ System.err.println("this converted state is null? "); } copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; }

Target:
public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; }
Source:
private CompareInputAdapter getCompareInputAdapter(TreeNode node) { final Iterator<CompareInputAdapter> candidates = Iterables.filter(node.eAdapters(), CompareInputAdapter.class).iterator(); if (candidates.hasNext()) { return candidates.next(); } return null; }

Target:
private CompareInputAdapter getCompareInputAdapter(TreeNode node) { return (CompareInputAdapter)Iterators.tryFind(node.eAdapters().iterator(), instanceOf(CompareInputAdapter.class)).orNull(); }
Source:
private void flushHashTable(boolean complete) throws HiveException { countAfterReport = 0; if (complete) { for (Map.Entry<KeyWrapper, AggregationBuffer[]> entry : hashAggregations.entrySet()) { forward(entry.getKey().getKeyArray(), entry.getValue()); } hashAggregations = null; LOG.info("Hash Table completed flushed"); return; } int oldSize = hashAggregations.size(); LOG.info("Hash Tbl flush: #hash table = " + oldSize); Iterator<Map.Entry<KeyWrapper, AggregationBuffer[]>> iter = hashAggregations .entrySet().iterator(); int numDel = 0; while (iter.hasNext()) { Map.Entry<KeyWrapper, AggregationBuffer[]> m = iter.next(); forward(m.getKey().getKeyArray(), m.getValue()); iter.remove(); numDel++; if (numDel * 10 >= oldSize) { LOG.info("Hash Table flushed: new size = " + hashAggregations.size()); return; } } }

Target:
private void flushHashTable(boolean complete) throws HiveException { countAfterReport = 0; if (complete) { for (Map.Entry<KeyWrapper, AggregationBuffer[]> entry : hashAggregations.entrySet()) { forward(entry.getKey().getKeyArray(), entry.getValue()); } hashAggregations = null; LOG.info("Hash Table completed flushed"); return; } int oldSize = hashAggregations.size(); LOG.info("Hash Tbl flush: #hash table = {}", oldSize); Iterator<Map.Entry<KeyWrapper, AggregationBuffer[]>> iter = hashAggregations .entrySet().iterator(); int numDel = 0; while (iter.hasNext()) { Map.Entry<KeyWrapper, AggregationBuffer[]> m = iter.next(); forward(m.getKey().getKeyArray(), m.getValue()); iter.remove(); numDel++; if (numDel * 10 >= oldSize) { LOG.info("Hash Table flushed: new size = {}", hashAggregations.size()); return; } } }
Source:
public boolean isItemValidForSlot(int slot, ItemStack stack) { if (slot == SLOT_INPUT) { boolean b1 = FluidItemHelper.isContainer(stack); boolean b2 = FluidItemHelper.isEmptyContainer(stack); FluidStack filter = getFilterFluid(); boolean b3 = filter == null; boolean b4 = FluidItemHelper.containsFluid(stack, filter); return b1 && (b2 || b3 || b4); } return false; }

Target:
public boolean isItemValidForSlot(int slot, ItemStack stack) { if (slot == SLOT_INPUT) { if (!FluidItemHelper.isContainer(stack)) return false; if (FluidItemHelper.isEmptyContainer(stack)) return true; FluidStack filter = getFilterFluid(); return filter == null || FluidItemHelper.containsFluid(stack, filter); } return false; }
Source:
GdkColor getContextColor () { long fontHandle = fontHandle (); long context = OS.gtk_widget_get_style_context (fontHandle); GdkRGBA rgba = new GdkRGBA (); if (OS.GTK_VERSION < OS.VERSION(3, 18, 0)) { rgba = display.styleContextGetColor (context, OS.GTK_STATE_FLAG_NORMAL, rgba); } else { int styleState = OS.gtk_widget_get_state_flags(handle); rgba = display.styleContextGetColor (context, styleState, rgba); } return display.toGdkColor (rgba); }

Target:
GdkColor getContextColor () { long fontHandle = fontHandle (); long context = OS.gtk_widget_get_style_context (fontHandle); int styleState = OS.gtk_widget_get_state_flags(handle); GdkRGBA rgba = new GdkRGBA (); rgba = display.styleContextGetColor (context, styleState, rgba); return display.toGdkColor (rgba); }
Source:
public String getIoThreadsAndEmulatorPinningCpus(VM vm, Map<String, Object> cpuPinning, MemoizingSupplier<List<VdsNumaNode>> hostNumaNodesSupplier, int vdsCpuThreads) { if (vm.getVmType() != VmType.HighPerformance) { return null; } List<VmNumaNode> vmNumaNodes = vmNumaNodeDao.getAllVmNumaNodeByVmId(vm.getId()); Optional<VmNumaNode> pinnedVmNumaNode = vmNumaNodes.stream().filter(d -> !d.getVdsNumaNodeList().isEmpty()).findAny(); if (MapUtils.isEmpty(cpuPinning) || !pinnedVmNumaNode.isPresent() || vm.getNumOfIoThreads() == 0) { String msgReason1 = MapUtils.isEmpty(cpuPinning) ? "CPU Pinning topology is not set": ""; String msgReason2 = vm.getNumOfIoThreads() == 0 ? "IO Threads is not enabled": ""; String msgReason3 = !pinnedVmNumaNode.isPresent() ? "vm's virtual NUMA nodes are not pinned to host's NUMA nodes": ""; String finalMsgReason = Arrays.asList(msgReason1, msgReason2, msgReason3).stream().filter(r -> !r.isEmpty()).collect(Collectors.joining(", ")) + "."; log.warn("No IO thread(s) pinning and Emulator thread(s) pinning for High Performance VM due to wrong configuration: {}", vm.getName(), vm.getId(), finalMsgReason); return null; } return findCpusToPinIoAndEmulator(vm, cpuPinning, hostNumaNodesSupplier, vdsCpuThreads); }

Target:
public String getIoThreadsAndEmulatorPinningCpus(VM vm, Map<String, Object> cpuPinning, MemoizingSupplier<List<VdsNumaNode>> hostNumaNodesSupplier, int vdsCpuThreads) { if (vm.getVmType() != VmType.HighPerformance) { return null; } List<VmNumaNode> vmNumaNodes = vmNumaNodeDao.getAllVmNumaNodeByVmId(vm.getId()); Optional<VmNumaNode> pinnedVmNumaNode = vmNumaNodes.stream().filter(d -> !d.getVdsNumaNodeList().isEmpty()).findAny(); if (MapUtils.isEmpty(cpuPinning) || !pinnedVmNumaNode.isPresent() || vm.getNumOfIoThreads() == 0) { String msgReason1 = MapUtils.isEmpty(cpuPinning) ? "CPU Pinning topology is not set": null; String msgReason2 = vm.getNumOfIoThreads() == 0 ? "IO Threads is not enabled": null; String msgReason3 = !pinnedVmNumaNode.isPresent() ? "vm's virtual NUMA nodes are not pinned to host's NUMA nodes": null; String finalMsgReason = Arrays.asList(msgReason1, msgReason2, msgReason3).stream() .filter(Objects::nonNull).collect(Collectors.joining(", ")) + "."; log.warn("No IO thread(s) pinning and Emulator thread(s) pinning for High Performance VM due to wrong configuration: {}", vm.getName(), vm.getId(), finalMsgReason); return null; } return findCpusToPinIoAndEmulator(vm, cpuPinning, hostNumaNodesSupplier, vdsCpuThreads); }
Source:
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (expand) { monitor.beginTask("Tree item expansion", 1); TransactionalEditingDomain domain = session.getTransactionalEditingDomain(); CommandStack commandStack = domain.getCommandStack(); CompoundCommand expandDTreeItemCmd = new CompoundCommand("Expand " + dTreeItem.getName() + " tree item"); GlobalContext globalContext = new GlobalContext(session.getModelAccessor(), session.getInterpreter(), session.getSemanticResources()); expandDTreeItemCmd.append(new DTreeItemExpansionChangeCommand(globalContext, domain, dTreeItem, monitor, true)); if (!Platform.getPreferencesService().getBoolean(SiriusPlugin.ID, SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), false, null)) { SiriusCommand result = new SiriusCommand(domain); result.getTasks().add(new RefreshTreeElementTask(dTreeItem)); expandDTreeItemCmd.append(result); } commandStack.execute(expandDTreeItemCmd); } else { TransactionalEditingDomain domain = session.getTransactionalEditingDomain(); CommandStack commandStack = domain.getCommandStack(); GlobalContext globalContext = new GlobalContext(session.getModelAccessor(), session.getInterpreter(), session.getSemanticResources()); Command collapseDTreeItemCmd = new DTreeItemExpansionChangeCommand(globalContext, domain, dTreeItem, monitor, false); commandStack.execute(collapseDTreeItemCmd); } } finally { monitor.done(); } }

Target:
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { TransactionalEditingDomain domain = session.getTransactionalEditingDomain(); CommandStack commandStack = domain.getCommandStack(); GlobalContext globalContext = new GlobalContext(session.getModelAccessor(), session.getInterpreter(), session.getSemanticResources()); if (expand) { monitor.beginTask("Tree item expandion", 1); CompoundCommand expandDTreeItemCmd = new CompoundCommand("Expand " + dTreeItem.getName() + " tree item"); expandDTreeItemCmd.append(new DTreeItemExpansionChangeCommand(globalContext, domain, dTreeItem, monitor, true)); if (!Platform.getPreferencesService().getBoolean(SiriusPlugin.ID, SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), false, null)) { SiriusCommand result = new SiriusCommand(domain); result.getTasks().add(new RefreshTreeElementTask(dTreeItem)); expandDTreeItemCmd.append(result); } commandStack.execute(expandDTreeItemCmd); } else { monitor.beginTask("Tree item collabsing", 1); Command collapseDTreeItemCmd = new DTreeItemExpansionChangeCommand(globalContext, domain, dTreeItem, monitor, false); commandStack.execute(collapseDTreeItemCmd); } } finally { monitor.done(); } }
Source:
public void addAllKException(Collection<KException> kex) { if (this.options.warnings == GlobalOptions.Warnings.NONE) return; if (this.options.warnings == GlobalOptions.Warnings.ALL) { exceptions.addAll(kex); } else if (this.options.warnings == GlobalOptions.Warnings.NORMAL) { for (KException e : kex) { if (e.getType() != ExceptionType.HIDDENWARNING) exceptions.add(e); } } else throw new AssertionError("Unexpected warning type!"); }

Target:
public void addAllKException(Collection<KException> kex) { for (KException e : kex) registerInternal(e); }
Source:
public Response get(@PathParam("id") UUIDParam id, @QueryParam("depth") @DefaultValue("1") int depth, @QueryParam("types") List<String> relationNames) { Optional<SearchResult> searchResult = searchStore.getSearchResult(id.get()); SXSSFWorkbook workbook = new SXSSFWorkbook(); if (searchResult.isPresent()) { final SearchResult result = searchResult.get(); workbook = excelExportService .searchResultToExcel(result.getSearchResult(), result.getSearchDescription().getType(), depth, relationNames); } else { workbook.createSheet("result").createRow(0).createCell(0).setCellValue("Search with id " + id + " not found."); } return Response.ok((StreamingOutput) workbook::write) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"result.xlsx\"") .build(); }

Target:
public Response get(@PathParam("id") UUIDParam id, @QueryParam("depth") @DefaultValue("1") int depth, @QueryParam("types") List<String> relationNames) { Optional<SearchResult> searchResult = searchStore.getSearchResult(id.get()); if (searchResult.isPresent()) { final SearchResult result = searchResult.get(); SXSSFWorkbook workbook = excelExportService .searchResultToExcel(result.getSearchResult(), result.getSearchDescription().getType(), depth, relationNames); return Response.ok((StreamingOutput) workbook::write) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"result.xlsx\"") .build(); } return Response .status(Response.Status.NOT_FOUND) .build(); }
Source:
private static void handleTraceContentChanged(TmfTraceElement traceElement) { Display.getDefault().asyncExec(() -> { boolean opened = false; for (ITmfTrace openedTrace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace trace : TmfTraceManager.getTraceSet(openedTrace)) { if (traceElement.getResource().equals(trace.getResource())) { opened = true; break; } } } if (!opened) { traceElement.deleteSupplementaryResources(); return; } if (!promptQueue.isEmpty()) { if (!promptQueue.contains(traceElement)) { promptQueue.add(traceElement); } return; } TmfTraceElement prompting = traceElement; while (prompting != null) { boolean always = Activator.getDefault().getPreferenceStore().getBoolean(ITmfUIPreferences.ALWAYS_CLOSE_ON_RESOURCE_CHANGE); if (always) { prompting.closeEditors(); prompting.deleteSupplementaryResources(); } else { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); MessageDialog messageDialog = new MessageDialog(shell, Messages.TmfProjectRegistry_TraceChangedDialogTitle, null, NLS.bind(Messages.TmfProjectRegistry_TraceChangedDialogMessage, prompting.getElementPath()), MessageDialog.QUESTION, 2, IDialogConstants.NO_LABEL, IDialogConstants.YES_LABEL, Messages.TmfProjectRegistry_Always); int returnCode = messageDialog.open(); if (returnCode >= 1) { prompting.closeEditors(); prompting.deleteSupplementaryResources(); } if (returnCode == 2) { Activator.getDefault().getPreferenceStore().setValue(ITmfUIPreferences.ALWAYS_CLOSE_ON_RESOURCE_CHANGE, true); } } prompting = promptQueue.poll(); } }); }

Target:
private static void handleTraceContentChanged(TmfTraceElement traceElement) { Display.getDefault().asyncExec(() -> { boolean opened = false; for (ITmfTrace openedTrace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace trace : TmfTraceManager.getTraceSet(openedTrace)) { if (traceElement.getResource().equals(trace.getResource())) { opened = true; break; } } } if (!opened) { traceElement.deleteSupplementaryResources(); return; } if (!promptQueue.isEmpty()) { if (!promptQueue.contains(traceElement)) { promptQueue.add(traceElement); } return; } promptQueue.add(traceElement); TmfTraceElement prompting = traceElement; while (prompting != null) { boolean always = Activator.getDefault().getPreferenceStore().getBoolean(ITmfUIPreferences.ALWAYS_CLOSE_ON_RESOURCE_CHANGE); if (always) { prompting.closeEditors(); prompting.deleteSupplementaryResources(); } else { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); MessageDialog messageDialog = new MessageDialog(shell, Messages.TmfProjectRegistry_TraceChangedDialogTitle, null, NLS.bind(Messages.TmfProjectRegistry_TraceChangedDialogMessage, prompting.getElementPath()), MessageDialog.QUESTION, 2, IDialogConstants.NO_LABEL, IDialogConstants.YES_LABEL, Messages.TmfProjectRegistry_Always); int returnCode = messageDialog.open(); if (returnCode >= 1) { prompting.closeEditors(); prompting.deleteSupplementaryResources(); } if (returnCode == 2) { Activator.getDefault().getPreferenceStore().setValue(ITmfUIPreferences.ALWAYS_CLOSE_ON_RESOURCE_CHANGE, true); } } promptQueue.remove(); prompting = promptQueue.peek(); } }); }
Source:
public ActionResponse execute(StatsTrendRequest parameter) throws QueryStoreException { if (null == parameter.getFilters()) { parameter.setFilters(Lists.<Filter>newArrayList(new AnyFilter(parameter.getTable()))); } String field = parameter.getField(); if (null == field || field.isEmpty()) { throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, "Invalid field name"); } try { AbstractAggregationBuilder aggregation = buildAggregation(parameter); SearchResponse response = getConnection().getClient().prepareSearch( ElasticsearchUtils.getIndices(parameter.getTable(), parameter)) .setTypes(ElasticsearchUtils.TYPE_NAME) .setQuery(new ElasticSearchQueryGenerator(parameter.getCombiner()).genFilter(parameter.getFilters())) .setSize(0) .setSearchType(SearchType.COUNT) .addAggregation(aggregation) .execute() .actionGet(); Aggregations aggregations = response.getAggregations(); if (aggregations != null) { return buildResponse(parameter, aggregations); } return null; } catch (Exception e) { logger.error("Error running stats query: ", e); throw new QueryStoreException(QueryStoreException.ErrorCode.QUERY_EXECUTION_ERROR, "Error running stats query.", e); } }

Target:
public ActionResponse execute(StatsTrendRequest parameter) throws QueryStoreException { parameter.setTable(ElasticsearchUtils.getValidTableName(getParameter().getTable())); if (parameter.getTable() == null) { throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, "Invalid table name"); } if (null == parameter.getFilters()) { parameter.setFilters(Lists.<Filter>newArrayList(new AnyFilter(parameter.getTable()))); } String field = parameter.getField(); if (null == field || field.isEmpty()) { throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, "Invalid field name"); } try { AbstractAggregationBuilder aggregation = buildAggregation(parameter); SearchResponse response = getConnection().getClient().prepareSearch( ElasticsearchUtils.getIndices(parameter.getTable(), parameter)) .setTypes(ElasticsearchUtils.DOCUMENT_TYPE_NAME) .setQuery(new ElasticSearchQueryGenerator(parameter.getCombiner()).genFilter(parameter.getFilters())) .setSize(0) .setSearchType(SearchType.COUNT) .addAggregation(aggregation) .execute() .actionGet(); Aggregations aggregations = response.getAggregations(); if (aggregations != null) { return buildResponse(parameter, aggregations); } return null; } catch (Exception e) { logger.error("Error running stats query: ", e); throw new QueryStoreException(QueryStoreException.ErrorCode.QUERY_EXECUTION_ERROR, "Error running stats query.", e); } }
Source:
public void initialize(final Context context) { super.initialize(context); String outNodeId = element.getTargetNode() != null ? element.getTargetNode().getUUID() : null; if (null != outNodeId) { ArrayParser outgoingParser = new ArrayParser("outgoing"); outgoingParser.addParser(new ObjectParser("").addParser(new StringFieldParser("resourceId", outNodeId))); super.addParser(outgoingParser); } ViewConnector viewConnector = (ViewConnector) element.getContent(); ObjectParser docker1ObjParser; if (viewConnector.hasValidSourceMagnetCoords()) { docker1ObjParser = new ObjectParser("") .addParser(new IntegerFieldParser("x", viewConnector.getSourceMagnetX().intValue())) .addParser(new IntegerFieldParser("y", viewConnector.getSourceMagnetY().intValue())); } else { docker1ObjParser = new ObjectParser("") .addParser(new IntegerFieldParser("x", -1)) .addParser(new IntegerFieldParser("y", -1)); } ObjectParser docker2ObjParser; if (viewConnector.hasValidTargetMagnetCoords()) { docker2ObjParser = new ObjectParser("") .addParser(new IntegerFieldParser("x", viewConnector.getTargetMagnetX().intValue())) .addParser(new IntegerFieldParser("y", viewConnector.getTargetMagnetY().intValue())); } else { docker2ObjParser = new ObjectParser("") .addParser(new IntegerFieldParser("x", -1)) .addParser(new IntegerFieldParser("y", -1)); } ArrayParser dockersParser = new ArrayParser("dockers") .addParser(docker1ObjParser) .addParser(docker2ObjParser); super.addParser(dockersParser); }

Target:
public void initialize(final Context context) { super.initialize(context); String outNodeId = element.getTargetNode() != null ? element.getTargetNode().getUUID() : null; if (null != outNodeId) { ArrayParser outgoingParser = new ArrayParser("outgoing"); outgoingParser.addParser(new ObjectParser("").addParser(new StringFieldParser("resourceId", outNodeId))); super.addParser(outgoingParser); } ViewConnector viewConnector = (ViewConnector) element.getContent(); ObjectParser docker1ObjParser = createDockerObjectParser(viewConnector.getSourceMagnet()); ObjectParser docker2ObjParser = createDockerObjectParser(viewConnector.getTargetMagnet()); ArrayParser dockersParser = new ArrayParser("dockers") .addParser(docker1ObjParser) .addParser(docker2ObjParser); super.addParser(dockersParser); }
Source:
public void handle(MotechEvent event) { if (!getIsHandled()) { setIsHandled(true); LOGGER.info("Handling the motech event with subject: {}", event.getSubject()); Map<String, Object> eventParams = event.getParameters(); eventParams.putAll(event.getMetadata()); TasksEventParser parser = null; if (eventParams != null) { parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY)); } String triggerSubject = parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), eventParams); Map<String, Object> parameters = parser == null ? eventParams : parser.parseEventParameters(event.getSubject(), eventParams); List<Task> tasks = taskService.findActiveTasksForTriggerSubject(triggerSubject); for (Task task : tasks) { handleTask(task, parameters, false); } setIsHandled(false); } }

Target:
public void handle(MotechEvent event) { LOGGER.info("Handling the motech event with subject: {}", event.getSubject()); Map<String, Object> eventParams = event.getParameters(); eventParams.putAll(event.getMetadata()); TasksEventParser parser = null; if (eventParams != null) { parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY)); } String triggerSubject = parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), eventParams); Map<String, Object> parameters = parser == null ? eventParams : parser.parseEventParameters(event.getSubject(), eventParams); List<Task> tasks = taskService.findActiveTasksForTriggerSubject(triggerSubject); for (Task task : tasks) { checkAndHandleTask(task, parameters, false); } }