auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<QuotaUpdate> findLimited(int limit) throws StorageException { ArrayList<QuotaUpdate> resultList; PreparedStatement s = null; ResultSet result = null; try { Connection conn = mysqlConnector.obtainSession(); s = conn.prepareStatement(FIND_QUERY); s.setInt(1, limit); result = s.executeQuery(); resultList = new ArrayList<>(); while (result.next()) { int id = result.getInt(ID); int inodeId = result.getInt(INODE_ID); int namespaceDelta = result.getInt(NAMESPACE_DELTA); long diskspaceDelta = result.getLong(STORAGE_SPACE_DELTA); Map<QuotaUpdate.StorageType, Long> typeSpaceDelta = new HashMap<>(); typeSpaceDelta.put(QuotaUpdate.StorageType.DISK, result.getLong(TYPESPACE_DELTA_DISK)); typeSpaceDelta.put(QuotaUpdate.StorageType.SSD, result.getLong(TYPESPACE_DELTA_SSD)); typeSpaceDelta.put(QuotaUpdate.StorageType.RAID5, result.getLong(TYPESPACE_DELTA_RAID5)); typeSpaceDelta.put(QuotaUpdate.StorageType.ARCHIVE, result.getLong(TYPESPACE_DELTA_ARCHIVE)); typeSpaceDelta.put(QuotaUpdate.StorageType.DB, result.getLong(TYPESPACE_DELTA_DB)); resultList .add(new QuotaUpdate(id, inodeId, namespaceDelta, diskspaceDelta, typeSpaceDelta)); } } catch (SQLException ex) { throw HopsSQLExceptionHelper.wrap(ex); } finally { if (s != null) { try { s.close(); } catch (SQLException ex) { } } if (result != null) { try { result.close(); } catch (SQLException ex) { } } mysqlConnector.closeSession(); } return resultList; }

Target:
public List<QuotaUpdate> findLimited(int limit) throws StorageException { ArrayList<QuotaUpdate> resultList; PreparedStatement s = null; ResultSet result = null; try { Connection conn = mysqlConnector.obtainSession(); s = conn.prepareStatement(FIND_QUERY); s.setInt(1, limit); result = s.executeQuery(); resultList = new ArrayList<>(); while (result.next()) { int id = result.getInt(ID); int inodeId = result.getInt(INODE_ID); int namespaceDelta = result.getInt(NAMESPACE_DELTA); long diskspaceDelta = result.getLong(STORAGE_SPACE_DELTA); Map<QuotaUpdate.StorageType, Long> typeSpaceDelta = new HashMap<>(); typeSpaceDelta.put(QuotaUpdate.StorageType.DISK, result.getLong(TYPESPACE_DELTA_DISK)); typeSpaceDelta.put(QuotaUpdate.StorageType.SSD, result.getLong(TYPESPACE_DELTA_SSD)); typeSpaceDelta.put(QuotaUpdate.StorageType.RAID5, result.getLong(TYPESPACE_DELTA_RAID5)); typeSpaceDelta.put(QuotaUpdate.StorageType.ARCHIVE, result.getLong(TYPESPACE_DELTA_ARCHIVE)); typeSpaceDelta.put(QuotaUpdate.StorageType.DB, result.getLong(TYPESPACE_DELTA_DB)); resultList .add(new QuotaUpdate(id, inodeId, namespaceDelta, diskspaceDelta, typeSpaceDelta)); } } catch (SQLException ex) { throw HopsSQLExceptionHelper.wrap(ex); } finally { if (s != null) { try { s.close(); } catch (SQLException ex) { LOG.warn("Exception when closing the PrepareStatement", ex); } } if (result != null) { try { result.close(); } catch (SQLException ex) { LOG.warn("Exception when closing the REsultSet", ex); } } mysqlConnector.closeSession(); } return resultList; }
Source:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(-34618072, -58436443); System.out.println("\n"); }

Target:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(-34618072, -58436443); }
Source:
protected void handleComments() { try { while (line != null) { String tLine = line.trim(); if (tLine.startsWith(" ")) { if (tLine != null) { tLine = tLine.trim(); } comments.add(++count + line); } } else if (!tLine.startsWith(" line = stripOffComment(tLine); return; } comments.add(++count + line); line = in.readLine(); } } catch (IOException ex) { System.err.println(ex); return; } }

Target:
protected void handleComments() { try { while (line != null) { String tLine = line.trim(); if (tLine.startsWith(" ")) { tLine = in.readLine(); if (tLine != null) { tLine = tLine.trim(); } comments.add(++count + line); } } else if (!tLine.startsWith(" line = stripOffComment(tLine); return; } comments.add(++count + line); line = in.readLine(); } } catch (IOException ex) { System.err.println(ex); return; } }
Source:
public void testResetToLocalBranch() throws Exception { checkoutAndVerify(new String[] { LOCAL_BRANCHES, "master" }, new String[] { LOCAL_BRANCHES, "stable" }); String stable = getTestFileContent(); checkoutAndVerify(new String[] { LOCAL_BRANCHES, "stable" }, new String[] { LOCAL_BRANCHES, "master" }); String master = getTestFileContent(); assertFalse(stable.equals(master)); SWTBotShell resetDialog = openResetDialog(); resetDialog.bot().tree().getTreeItem(LOCAL_BRANCHES).getNode("stable") .select(); resetDialog.bot().radio( UIText.ResetTargetSelectionDialog_ResetTypeHardButton).click(); resetDialog.bot().button(UIText.ResetTargetSelectionDialog_ResetButton) .click(); Job.getJobManager().join(JobFamilies.RESET, null); bot.shell(UIText.ResetTargetSelectionDialog_ResetQuestion).bot() .button(IDialogConstants.YES_LABEL).click(); waitInUI(); String reset = getTestFileContent(); assertEquals("Wrong content after reset", stable, reset); }

Target:
public void testResetToLocalBranch() throws Exception { checkoutAndVerify(new String[] { LOCAL_BRANCHES, "master" }, new String[] { LOCAL_BRANCHES, "stable" }); String stable = getTestFileContent(); checkoutAndVerify(new String[] { LOCAL_BRANCHES, "stable" }, new String[] { LOCAL_BRANCHES, "master" }); String master = getTestFileContent(); assertFalse(stable.equals(master)); SWTBotShell resetDialog = openResetDialog(); resetDialog.bot().tree().getTreeItem(LOCAL_BRANCHES).getNode("stable") .select(); resetDialog.bot().radio( UIText.ResetTargetSelectionDialog_ResetTypeHardButton).click(); resetDialog.bot().button(UIText.ResetTargetSelectionDialog_ResetButton) .click(); bot.shell(UIText.ResetTargetSelectionDialog_ResetQuestion).bot() .button(IDialogConstants.YES_LABEL).click(); Job.getJobManager().join(JobFamilies.RESET, null); String reset = getTestFileContent(); assertEquals("Wrong content after reset", stable, reset); }
Source:
private boolean expiredFromCache(ActiveSession as) { if (as.getLastSeen() == null) { return true; } Timestamp expire = new Timestamp(as.getLastSeen().getTime() + cache.getTimeToLive(MILLISECONDS)); Timestamp now = new Timestamp(now()); return now.after(expire); }

Target:
private boolean expiredFromCache(ActiveSession as) { if (as.getLastSeen() == null) { return true; } Timestamp expireAt = new Timestamp(as.getLastSeen().getTime() + cache.getTimeToLive(MILLISECONDS)); Timestamp now = new Timestamp(now()); return now.after(expireAt); }
Source:
private void checkComments(Map<String, List<Comment>> in) throws BadRequestException { Iterator<Map.Entry<String, List<Comment>>> mapItr = in.entrySet().iterator(); while (mapItr.hasNext()) { Map.Entry<String, List<Comment>> ent = mapItr.next(); String path = ent.getKey(); List<Comment> list = ent.getValue(); if (list == null) { mapItr.remove(); continue; } Iterator<Comment> listItr = list.iterator(); while (listItr.hasNext()) { Comment c = listItr.next(); if (c == null) { listItr.remove(); } else { if (c.line < 0) { throw new BadRequestException(String.format( "negative line number %d not allowed on %s", c.line, path)); } c.message = Strings.emptyToNull(c.message).trim(); if (c.message.isEmpty()) { listItr.remove(); } } } if (list.isEmpty()) { mapItr.remove(); } } }

Target:
private void checkComments(Map<String, List<Comment>> in) throws BadRequestException { Iterator<Map.Entry<String, List<Comment>>> mapItr = in.entrySet().iterator(); while (mapItr.hasNext()) { Map.Entry<String, List<Comment>> ent = mapItr.next(); String path = ent.getKey(); List<Comment> list = ent.getValue(); if (list == null) { mapItr.remove(); continue; } Iterator<Comment> listItr = list.iterator(); while (listItr.hasNext()) { Comment c = listItr.next(); if (c == null) { listItr.remove(); continue; } if (c.line < 0) { throw new BadRequestException(String.format( "negative line number %d not allowed on %s", c.line, path)); } c.message = Strings.emptyToNull(c.message).trim(); if (c.message.isEmpty()) { listItr.remove(); } } if (list.isEmpty()) { mapItr.remove(); } } }
Source:
public ImmutableSet<ModelWithPayload<Container>> resolveOrFetchSeries( Iterable<ModelWithPayload<Item>> itemsWithPayload) throws NitroException { if (Iterables.isEmpty(itemsWithPayload)) { return ImmutableSet.of(); } ImmutableList.Builder items = ImmutableList.builder(); for (ModelWithPayload<Item> itemWithPayload : itemsWithPayload) { items.add(itemWithPayload.getModel()); } Iterable<Episode> episodes = Iterables.filter(items.build(), Episode.class); Multimap<String, Episode> seriesUriMap = toSeriesUriMap(episodes); Set<String> seriesUris = seriesUriMap.keySet(); ResolvedContent resolved = resolver.findByCanonicalUris(seriesUris); Set<String> toFetch = Sets.newHashSet(); for (String seriesUri : seriesUris) { Maybe<Identified> maybeId = resolved.asMap().get(seriesUri); if (!maybeId.hasValue() || Iterables.any(seriesUriMap.get(seriesUri), fullFetchPermitted)) { log.trace("Will fetch series from Nitro", seriesUri); toFetch.add(seriesUri); } } ImmutableSet<ModelWithPayload<Series>> fetched = contentAdapter.fetchSeries(asSeriesPidRefs(toFetch)); ImmutableSet<Container> containers = ImmutableSet.copyOf( Iterables.filter( resolved.getAllResolvedResults(), Container.class )); ImmutableSet<ModelWithPayload<Container>> wrappedContainers = ImmutableSet.copyOf( Iterables.transform( containers, this::wrapResolvedContentWithEmptyPayload )); return mergeContainersWithExisting(wrappedContainers, fetched); }

Target:
public ImmutableSet<ModelWithPayload<Container>> resolveOrFetchSeries( Iterable<ModelWithPayload<Item>> itemsWithPayload) throws NitroException { if (Iterables.isEmpty(itemsWithPayload)) { return ImmutableSet.of(); } Iterable<Episode> episodes = StreamSupport.stream(itemsWithPayload.spliterator(), false) .map(ModelWithPayload::getModel) .filter(Episode.class::isInstance) .map(Episode.class::cast) .collect(MoreCollectors.toImmutableList()); Multimap<String, Episode> seriesUriMap = toSeriesUriMap(episodes); Set<String> seriesUris = seriesUriMap.keySet(); ResolvedContent resolved = resolver.findByCanonicalUris(seriesUris); Set<String> toFetch = Sets.newHashSet(); for (String seriesUri : seriesUris) { Maybe<Identified> maybeId = resolved.asMap().get(seriesUri); if (!maybeId.hasValue() || Iterables.any(seriesUriMap.get(seriesUri), fullFetchPermitted)) { log.trace("Will fetch series from Nitro", seriesUri); toFetch.add(seriesUri); } } ImmutableSet<ModelWithPayload<Series>> fetched = contentAdapter.fetchSeries(asSeriesPidRefs(toFetch)); ImmutableSet<ModelWithPayload<Container>> wrappedContainers = resolved.getAllResolvedResults().stream() .filter(Container.class::isInstance) .map(Container.class::cast) .map(this::wrapResolvedContentWithEmptyPayload) .collect(MoreCollectors.toImmutableSet()); return mergeContainersWithExisting(wrappedContainers, fetched); }
Source:
public void visitToken(final DetailAST ast) { if (!allowClassImports && ast.getType() == TokenTypes.IMPORT) { final DetailAST startingDot = ast.getFirstChild(); logsStarredImportViolation(startingDot); } else if (!allowStaticMemberImports) { final DetailAST startingDot = ast.getFirstChild().getNextSibling(); logsStarredImportViolation(startingDot); } }

Target:
public void visitToken(final DetailAST ast) { if (ast.getType() == TokenTypes.IMPORT) { if (!allowClassImports) { final DetailAST startingDot = ast.getFirstChild(); logsStarredImportViolation(startingDot); } } else if (!allowStaticMemberImports) { final DetailAST startingDot = ast.getFirstChild().getNextSibling(); logsStarredImportViolation(startingDot); } }
Source:
private static String getProxyType(String protocol) { protocol = protocol.trim().toLowerCase(Locale.ENGLISH); String type; if (null == protocol) { throw new IllegalArgumentException("unknown proxy protocol: " + protocol); } else switch (protocol) { case "http": type = IProxyData.HTTP_PROXY_TYPE; break; case "https": type = IProxyData.HTTPS_PROXY_TYPE; break; case "socks4": case "socks_5": type = IProxyData.SOCKS_PROXY_TYPE; break; default: throw new IllegalArgumentException("unknown proxy protocol: " + protocol); } return type; }

Target:
private static String getProxyType(String protocol) { protocol = protocol.trim().toLowerCase(Locale.ENGLISH); String type; if (protocol != null) { throw new IllegalArgumentException("unknown proxy protocol: " + protocol); } else switch (protocol) { case "http": type = IProxyData.HTTP_PROXY_TYPE; break; case "https": type = IProxyData.HTTPS_PROXY_TYPE; break; case "socks4": case "socks_5": type = IProxyData.SOCKS_PROXY_TYPE; break; default: throw new IllegalArgumentException("unknown proxy protocol: " + protocol); } return type; }
Source:
private void setupTestState() throws IOException, StoreException { StoreMetrics metrics = new StoreMetrics(clusterMap.getMetricRegistry()); BlobStore src = new BlobStore(STORE_ID, storeConfig, null, null, DISK_IO_SCHEDULER, StoreTestUtils.DEFAULT_DISK_SPACE_ALLOCATOR, metrics, metrics, srcDir.getAbsolutePath(), STORE_CAPACITY, STORE_KEY_FACTORY, null, null, time); src.start(); try { deletedId = new MockId("deletedId"); addMessage(src, deletedId, Utils.Infinite_Time, false, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM), time.milliseconds()); putId = new MockId("putId"); putData = addMessage(src, putId, Utils.Infinite_Time, false, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM), time.milliseconds()); addMessage(src, deletedId, Utils.Infinite_Time, true, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM), time.milliseconds()); expiredId = new MockId("expiredId"); addMessage(src, expiredId, 0, false, Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM), time.milliseconds()); } finally { src.shutdown(); } }

Target:
private void setupTestState() throws IOException, StoreException { StoreMetrics metrics = new StoreMetrics(clusterMap.getMetricRegistry()); BlobStore src = new BlobStore(STORE_ID, storeConfig, null, null, DISK_IO_SCHEDULER, StoreTestUtils.DEFAULT_DISK_SPACE_ALLOCATOR, metrics, metrics, srcDir.getAbsolutePath(), STORE_CAPACITY, STORE_KEY_FACTORY, null, null, time); src.start(); try { short accountId = Utils.getRandomShort(TestUtils.RANDOM); short containerId = Utils.getRandomShort(TestUtils.RANDOM); deletedId = new MockId("deletedId", accountId, containerId); addMessage(src, deletedId, Utils.Infinite_Time, false, accountId, containerId, time.milliseconds()); putId = new MockId("putId", accountId, containerId); putData = addMessage(src, putId, Utils.Infinite_Time, false, accountId, containerId, time.milliseconds()); addMessage(src, deletedId, Utils.Infinite_Time, true, accountId, containerId, time.milliseconds()); expiredId = new MockId("expiredId", accountId, containerId); addMessage(src, expiredId, 0, false, accountId, containerId, time.milliseconds()); } finally { src.shutdown(); } }
Source:
public boolean test(@Nullable ItemStack stack) { if(stack==null) return false; Optional<IFluidHandlerItem> handler = FluidUtil.getFluidHandler(stack).resolve(); if(!handler.isPresent()) return false; return fluidTagInput.extractFrom(handler.get(), FluidAction.SIMULATE); }

Target:
public boolean test(@Nullable ItemStack stack) { if(stack==null) return false; Optional<IFluidHandlerItem> handler = FluidUtil.getFluidHandler(stack).resolve(); return handler.isPresent()&&fluidTagInput.extractFrom(handler.get(), FluidAction.SIMULATE); }
Source:
public void testConverter() throws IOException { ParquetReader<SimpleRecord> reader = ParquetReader.builder(new SimpleReadSupport(), new Path(this.testFile.getAbsolutePath())).build(); for (SimpleRecord record = reader.read(); record != null; record = reader.read()) { for (SimpleRecord.NameValue value : record.getValues()) { switch(value.getName()) { case INT32_FIELD: Assert.assertEquals(32, value.getValue()); break; case INT64_FIELD: Assert.assertEquals(64L, value.getValue()); break; case FLOAT_FIELD: Assert.assertEquals(1.0f, value.getValue()); break; case DOUBLE_FIELD: Assert.assertEquals(2.0d, value.getValue()); break; case BINARY_FIELD: Assert.assertArrayEquals("foobar".getBytes(), (byte[])value.getValue()); break; case FIXED_LEN_BYTE_ARRAY_FIELD: Assert.assertArrayEquals(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, (byte[])value.getValue()); break; } } } }

Target:
public void testConverter() throws IOException { try ( ParquetReader<SimpleRecord> reader = ParquetReader.builder(new SimpleReadSupport(), new Path(testFile().getAbsolutePath())).build()) { for (SimpleRecord record = reader.read(); record != null; record = reader.read()) { for (SimpleRecord.NameValue value : record.getValues()) { switch(value.getName()) { case INT32_FIELD: Assert.assertEquals(32, value.getValue()); break; case INT64_FIELD: Assert.assertEquals(64L, value.getValue()); break; case FLOAT_FIELD: Assert.assertEquals(1.0f, value.getValue()); break; case DOUBLE_FIELD: Assert.assertEquals(2.0d, value.getValue()); break; case BINARY_FIELD: Assert.assertArrayEquals("foobar".getBytes(), (byte[])value.getValue()); break; case FIXED_LEN_BYTE_ARRAY_FIELD: Assert.assertArrayEquals(new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, (byte[])value.getValue()); break; } } } } }
Source:
private void appendImageLine(final PatchScript script, final SafeHtmlBuilder m) { final String rawBase = GWT.getHostPageBaseURL() + "cat/"; m.openTr(); m.setAttribute("valign", "center"); m.setAttribute("align", "center"); m.openTd(); m.setStyleName(Gerrit.RESOURCES.css().iconCell()); m.closeTd(); appendLineNumber(m, false); if (script.getDisplayMethodA() == DisplayMethod.IMG) { final String url; if (idSideA == null) { url = rawBase + KeyUtil.encode(patchKey.toString()) + "^1"; } else { Patch.Key k = new Patch.Key(idSideA, patchKey.get()); url = rawBase + KeyUtil.encode(k.toString()) + "^0"; } appendLineText(m, DELETE, createImage(url), false, true); } else { appendLineNone(m, DELETE); } if (script.getDisplayMethodB() == DisplayMethod.IMG) { final String url = rawBase + KeyUtil.encode(patchKey.toString()) + "^0"; appendLineText(m, INSERT, createImage(url), false, true); } else { appendLineNone(m, INSERT); } appendLineNumber(m, true); m.closeTr(); }

Target:
private void appendImageLine(final PatchScript script, final SafeHtmlBuilder m) { m.openTr(); m.setAttribute("valign", "center"); m.setAttribute("align", "center"); m.openTd(); m.setStyleName(Gerrit.RESOURCES.css().iconCell()); m.closeTd(); appendLineNumber(m, false); if (script.getDisplayMethodA() == DisplayMethod.IMG) { final String url = getUrlA(); appendLineText(m, DELETE, createImage(url), false, true); } else { appendLineNone(m, DELETE); } if (script.getDisplayMethodB() == DisplayMethod.IMG) { final String url = getUrlB(); appendLineText(m, INSERT, createImage(url), false, true); } else { appendLineNone(m, INSERT); } appendLineNumber(m, true); m.closeTr(); }
Source:
public JSONPropertyWriter dateTimeFormat(DateTimeFormat dateTimeFormat) { JSONPropertyWriter writer = new JSONPropertyWriter(this); writer.dateTimeFormat = dateTimeFormat; return writer; }

Target:
public JSONPropertyWriter dateTimeFormat(DateTimeFormat dateTimeFormat) { this.dateTimeFormat = dateTimeFormat; return this; }
Source:
public void processLintResults(String lintFile, String lintFileSize) { RemoteFileFetcher lintFetcher = new RemoteFileFetcher(workspace, logger, lintFile, lintFileSize); try { String input = lintFetcher.getRemoteFile(); if (input != null && input.length() > 0) { lintResults = new LintResults(); BufferedReader reader = new BufferedReader(new StringReader(input)); String lint; while ((lint = reader.readLine()) != null) { JSONObject json = JSONObject.fromObject(lint); Object line = json.get("line"); Object charPosition = json.get("char"); lintResults.add(new LintResult( (String) json.get("name"), (String) json.get("code"), (String) json.get("severity"), (String) json.get("path"), line == null ? null : (Integer) line, charPosition == null ? null : (Integer) charPosition, (String) json.get("description"))); } } } catch (JSONException e) { e.printStackTrace(logger.getStream()); } catch (InterruptedException e) { e.printStackTrace(logger.getStream()); } catch (IOException e) { e.printStackTrace(logger.getStream()); } }

Target:
public void processLintResults(String lintFile, String lintFileSize) { RemoteFileFetcher lintFetcher = new RemoteFileFetcher(workspace, logger, lintFile, lintFileSize); try { String input = lintFetcher.getRemoteFile(); if (input != null && input.length() > 0) { lintResults = new LintResults(); BufferedReader reader = new BufferedReader(new StringReader(input)); String lint; while ((lint = reader.readLine()) != null) { JSONObject json = JSONObject.fromObject(lint); lintResults.add(LintResult.fromJsonObject(json)); } } } catch (JSONException e) { e.printStackTrace(logger.getStream()); } catch (InterruptedException e) { e.printStackTrace(logger.getStream()); } catch (IOException e) { e.printStackTrace(logger.getStream()); } }
Source:
public void testGetDatasets() throws Exception { final List<DatasetDTO> datasets= createDatasets(Arrays.asList(10090, 10094, 10095)); doReturn(datasets).when(this.studyDatasetService).getDatasets(100, null); this.mockMvc .perform(MockMvcRequestBuilders.get("/crops/{crop}/studies/{studyId}/datasets/list", this.cropName, 100, null) .contentType(this.contentType)) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$", IsCollectionWithSize.hasSize(datasets.size()))); }

Target:
public void testGetDatasets() throws Exception { final List<DatasetDTO> datasets= createDatasets(Arrays.asList(10090, 10094, 10095)); doReturn(datasets).when(this.studyDatasetService).getDatasets(100, null); this.mockMvc .perform(MockMvcRequestBuilders.get("/crops/{crop}/studies/{studyId}/datasets", this.cropName, 100, null) .contentType(this.contentType)) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$", IsCollectionWithSize.hasSize(datasets.size()))); }
Source:
public void setUp() throws Exception { context = OptaplannerPersistenceUtil.setupWithPoolingDataSource(OptaplannerPersistenceUtil.OPTAPLANNER_PERSISTENCE_UNIT_NAME); entityManagerFactory = (EntityManagerFactory) context.get(PersistenceUtil.ENTITY_MANAGER_FACTORY); transactionManager = (TransactionManager) InitialContext.doLookup("java:comp/TransactionManager"); }

Target:
public void setUp() throws Exception { context = PersistenceUtil.setupWithPoolingDataSource("org.optaplanner.persistence.jpa.test"); entityManagerFactory = (EntityManagerFactory) context.get(PersistenceUtil.ENTITY_MANAGER_FACTORY); transactionManager = (TransactionManager) InitialContext.doLookup("java:comp/TransactionManager"); }
Source:
public void addPushApplication(PushApplication pushApp) throws IllegalArgumentException { pushApp.setDeveloper(loginName.get()); final String pushApplicationID = pushApp.getPushApplicationID(); if (findByPushApplicationID(pushApplicationID) != null) { throw new IllegalArgumentException("PushApplicationID exits already: " + pushApplicationID); } else { pushApplicationDao.create(pushApp); } }

Target:
public void addPushApplication(PushApplication pushApp) { final String id = pushApp.getPushApplicationID(); if (findByPushApplicationID(id) != null) { throw new IllegalArgumentException("App ID already exists: " + id); } try { pushApp.setDeveloper(loginName.get()); pushApplicationDao.create(pushApp); pushApplicationDao.flushAndClear(); } catch (RuntimeException e) { throw new RuntimeException("Transaction failed for app with ID: " + id, e); } }
Source:
public List<String> getList(int col) { if (get(col) instanceof List) return ((List<String>) get(col)); String str = getString(col); return str != null ? ListEscapeUtils.toList(str) : null; }

Target:
public List<String> getList(int col) { Object obj = get(col); if (obj == null) return null; else if (obj instanceof List<?>) return (List<String>) obj; else if (obj instanceof String) return ListEscapeUtils.toList((String) obj); else return ListEscapeUtils.toList(obj.toString()); }
Source:
private void refreshIndexDelta() { if (repository.isBare()) return; try { DirCache currentIndex = repository.readDirCache(); DirCache oldIndex = lastIndex; lastIndex = currentIndex; if (oldIndex == null) { refresh(); return; } Set<String> paths = new TreeSet<String>(); TreeWalk walk = new TreeWalk(repository); try { walk.addTree(new DirCacheIterator(oldIndex)); walk.addTree(new DirCacheIterator(currentIndex)); walk.setFilter(TreeFilter.ANY_DIFF); while (walk.next()) { if(walk.isSubtree()) walk.enterSubtree(); else paths.add(walk.getPathString()); } } finally { walk.release(); } if (!paths.isEmpty()) refreshFiles(paths); } catch (IOException ex) { Activator.error(String.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex); scheduleReloadJob("Exception while calculating index delta, doing full reload instead"); } }

Target:
private void refreshIndexDelta() { if (repository.isBare()) return; try { DirCache currentIndex = repository.readDirCache(); DirCache oldIndex = lastIndex; lastIndex = currentIndex; if (oldIndex == null) { refresh(); return; } Set<String> paths = new TreeSet<String>(); TreeWalk walk = new TreeWalk(repository); try { walk.addTree(new DirCacheIterator(oldIndex)); walk.addTree(new DirCacheIterator(currentIndex)); walk.setFilter(TreeFilter.ANY_DIFF); while (walk.next()) { if (walk.isSubtree()) walk.enterSubtree(); else paths.add(walk.getPathString()); } } finally { walk.release(); } if (!paths.isEmpty()) refreshFiles(paths); } catch (IOException ex) { Activator.error(MessageFormat.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex); scheduleReloadJob("Exception while calculating index delta, doing full reload instead"); } }
Source:
private long getExtremeLogEntry(Function<PaxosStateLog<V>, Long> extractor) { lock.readLock().lock(); try { long result = extractor.apply(currentLog); long experimentalResult = extractor.apply(experimentalLog); if (result != experimentalResult) { log.error("Mismatch in getting the extreme log entry between legacy and current implementations." + " Legacy result {}, current result {}.", SafeArg.of("legacy", result), SafeArg.of("current", experimentalResult)); } return result; } finally { lock.readLock().unlock(); } }

Target:
private long getExtremeLogEntry(Function<PaxosStateLog<V>, Long> extractor) { lock.readLock().lock(); try { Long result = extractor.apply(currentLog); Long experimentalResult = safeReadFromExperimental(extractor::apply); if (!Objects.equals(result, experimentalResult)) { log.error("Mismatch in getting the extreme log entry between legacy and current implementations." + " Legacy result {}, current result {}.", SafeArg.of("legacy", result), SafeArg.of("current", experimentalResult)); } return result; } finally { lock.readLock().unlock(); } }
Source:
public OauthGrantAuthenticationResult authenticate(PasswordGrantRequest passwordGrantRequest) { PasswordGrantAuthenticator authenticator = PasswordGrantAuthenticators.forApplication(this, getDataStore()); return authenticator.authenticate(passwordGrantRequest); }

Target:
public OauthGrantAuthenticationResult authenticate(PasswordGrantRequest passwordGrantRequest) { Assert.notNull(passwordGrantRequest, "passwordGrantRequest is required and cannot be null."); PasswordGrantAuthenticator authenticator = PasswordGrantAuthenticators.forApplication(this, getDataStore()); return authenticator.authenticate(passwordGrantRequest); }
Source:
private void loadFromFile() throws IOException { File settingFile = new File(conf.getInterpreterSettingPath()); if (!settingFile.exists()) { return; } FileInputStream fis = new FileInputStream(settingFile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } isr.close(); fis.close(); String json = sb.toString(); InterpreterInfoSaving info = gson.fromJson(json, InterpreterInfoSaving.class); for (String k : info.interpreterSettings.keySet()) { InterpreterSetting setting = info.interpreterSettings.get(k); setting.getOption().setRemote(true); final InterpreterSetting intpSetting = new InterpreterSetting(setting.id(), setting.getName(), setting.getGroup(), setting.getInterpreterInfos(), setting.getProperties(), setting.getDependencies(), setting.getOption()); Thread t = new Thread() { public void run() { try { loadInterpreterDependencies(intpSetting); } catch (RepositoryException e) { logger.error("Error while downloading repos for interpreter group :" + intpSetting.getGroup(), e); } catch (IOException e) { logger.error("Error while downloading repos for interpreter group :" + intpSetting.getGroup(), e); } } }; t.start(); intpSetting.setInterpreterGroupFactory(this); interpreterSettings.put(k, intpSetting); } this.interpreterBindings = info.interpreterBindings; if (info.interpreterRepositories != null) { for (RemoteRepository repo : info.interpreterRepositories) { if (!depResolver.getRepos().contains(repo)) { this.interpreterRepositories.add(repo); } } } }

Target:
private void loadFromFile() throws IOException { File settingFile = new File(conf.getInterpreterSettingPath()); if (!settingFile.exists()) { return; } FileInputStream fis = new FileInputStream(settingFile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } isr.close(); fis.close(); String json = sb.toString(); InterpreterInfoSaving info = gson.fromJson(json, InterpreterInfoSaving.class); for (String k : info.interpreterSettings.keySet()) { InterpreterSetting setting = info.interpreterSettings.get(k); setting.getOption().setRemote(true); setting.setPath(interpreterSettingsRef.get(setting.getGroup()).getPath()); setting.setInterpreterGroupFactory(this); loadInterpreterDependencies(setting); interpreterSettings.put(k, setting); } this.interpreterBindings = info.interpreterBindings; if (info.interpreterRepositories != null) { for (RemoteRepository repo : info.interpreterRepositories) { if (!depResolver.getRepos().contains(repo)) { this.interpreterRepositories.add(repo); } } } }
Source:
public Optional<FlyingData> fill(DataHolder dataHolder, FlyingData manipulator, MergeFunction overlap) { if (supports(dataHolder)) { final FlyingData merged = overlap.merge(checkNotNull(manipulator).copy(), from(dataHolder).get()); manipulator.set(Keys.IS_FLYING, merged.flying().get()); return Optional.of(manipulator); } return Optional.absent(); }

Target:
public Optional<FlyingData> fill(DataHolder dataHolder, FlyingData manipulator, MergeFunction overlap) { if (supports(dataHolder)) { final FlyingData merged = checkNotNull(overlap, "MergeFunction cannot be null!").merge(checkNotNull(manipulator).copy(), from(dataHolder).orNull()); manipulator.set(Keys.IS_FLYING, merged.flying().get()); return Optional.of(manipulator); } return Optional.absent(); }
Source:
public static StatuteType find(String code) { if (StringUtils.isBlank(code)) { return null; } for (StatuteType statuteType : readActiveStatuteTypes()) { if (StringUtils.equals(code, statuteType.getCode())) { return statuteType; } } return null; }

Target:
public static Optional<StatuteType> find(String code) { Predicate<StatuteType> matchesCode = statute -> StringUtils.equals(code, statute.getCode()); return readAll(StatuteType::isActive, matchesCode).findFirst(); }
Source:
private void setPointDescriptionText(String text) { if (fPointDescBrowser != null) { StringBuilder desc = new StringBuilder(); HTMLPrinter.insertPageProlog(desc, 0, TextUtil.getJavaDocStyleSheerURL()); ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color fgcolor = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (fgcolor == null) { fgcolor = JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } Color bgcolor = colorRegistry.get(JFacePreferences.INFORMATION_BACKGROUND_COLOR); if (bgcolor == null) { bgcolor = JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } String tmpDesc = desc.toString(); String fgHex = String.format("text=\"#%s\"", toHexString(fgcolor)); String bgHex = String.format("bgcolor=\"#%s\"", toHexString(bgcolor)); tmpDesc = tmpDesc.replaceAll("text=\"#[0-9a-f]{6}\"", fgHex); tmpDesc = tmpDesc.replaceAll("bgcolor=\"#[0-9a-f]{6}\"", bgHex); desc = new StringBuilder(tmpDesc); desc.append(text); HTMLPrinter.addPageEpilog(desc); fPointDescBrowser.setText(desc.toString()); } else fPointDescription.setText(PDEHTMLHelper.stripTags(text)); }

Target:
private void setPointDescriptionText(String text) { if (fPointDescBrowser != null) { StringBuilder desc = new StringBuilder(); ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color fgcolor = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (fgcolor == null) { fgcolor = JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } Color bgcolor = colorRegistry.get(JFacePreferences.INFORMATION_BACKGROUND_COLOR); if (bgcolor == null) { bgcolor = JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } StringBuilder stylesheet = new StringBuilder(); String line; try (BufferedReader br = new BufferedReader(new InputStreamReader(TextUtil.getJavaDocStyleSheerURL().openStream()))) { while ((line = br.readLine()) != null) { stylesheet.append("\n"); stylesheet.append(line); } } catch (IOException e) { stylesheet.setLength(0); } HTMLPrinter.insertPageProlog(desc, 0, fgcolor.getRGB(), bgcolor.getRGB(), stylesheet.length() > 0 ? stylesheet.substring(1) : ""); desc.append(text); HTMLPrinter.addPageEpilog(desc); fPointDescBrowser.setText(desc.toString()); } else fPointDescription.setText(PDEHTMLHelper.stripTags(text)); }
Source:
private boolean updateParameters() { for (MoveDiskParameters moveDiskParameters : getParameters().getParametersList()) { DiskImage diskImage = getDiskImageDao().getAncestor(moveDiskParameters.getImageId()); if (diskImage == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } List<VM> allVms = getVmDAO().getVmsListForDisk(diskImage.getId()); VM vm = !allVms.isEmpty() ? allVms.get(0) : null; if (vm == null || isVmDown(vm)) { moveParametersList.add(moveDiskParameters); } else if (isVmRunning(vm)) { MultiValueMapUtils.addToMap(vm.getId(), createLiveMigrateDiskParameters(moveDiskParameters, vm.getId()), vmsLiveMigrateParametersMap); } else { addCanDoActionMessage(String.format("$%1$s %2$s", "VmName", vm.getVmName())); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN_OR_UP); } } return true; }

Target:
private boolean updateParameters() { for (MoveDiskParameters moveDiskParameters : getParameters().getParametersList()) { DiskImage diskImage = getDiskImageDao().getAncestor(moveDiskParameters.getImageId()); if (diskImage == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } List<VM> allVms = getVmDAO().getVmsListForDisk(diskImage.getId()); VM vm = !allVms.isEmpty() ? allVms.get(0) : null; if (vm == null || isVmDown(vm)) { moveParametersList.add(moveDiskParameters); } else if (isVmRunning(vm)) { vmsLiveMigrateParametersList.add(createLiveMigrateDiskParameters(moveDiskParameters, vm.getId())); } else { addCanDoActionMessage(String.format("$%1$s %2$s", "VmName", vm.getVmName())); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN_OR_UP); } } return true; }
Source:
boolean isHigherThan(NMSVersion o) { return compareTo(o) > 0; }

Target:
public boolean isHigherThan(NMSVersion o) { return compareTo(o) > 0; }
Source:
public void handlePut(RestRequest restRequest, RestResponseChannel restResponseChannel) { long processingStartTime = System.currentTimeMillis(); long preProcessingTime = 0; handlePrechecks(restRequest, restResponseChannel); restRequest.getMetricsTracker().injectMetrics(frontendMetrics.putBlobMetrics); RestRequestMetrics requestMetrics = restRequest.getSSLSession() != null ? frontendMetrics.putBlobSSLMetrics : frontendMetrics.putBlobMetrics; restRequest.getMetricsTracker().injectMetrics(requestMetrics); try { logger.trace("Handling PUT request - {}", restRequest.getUri()); checkAvailable(); long propsBuildStartTime = System.currentTimeMillis(); BlobProperties blobProperties = RestUtils.buildBlobProperties(restRequest.getArgs()); if (blobProperties.getTimeToLiveInSeconds() + TimeUnit.MILLISECONDS.toSeconds( blobProperties.getCreationTimeInMs()) > Integer.MAX_VALUE) { logger.debug("TTL set to very large value in PUT request with BlobProperties {}", blobProperties); frontendMetrics.ttlTooLargeError.inc(); } byte[] usermetadata = RestUtils.buildUsermetadata(restRequest.getArgs()); frontendMetrics.putBlobPropsBuildTimeInMs.update(System.currentTimeMillis() - propsBuildStartTime); logger.trace("Blob properties of blob being PUTed - {}", blobProperties); PutCallback routerCallback = new PutCallback(restRequest, restResponseChannel, new BlobInfo(blobProperties, usermetadata)); preProcessingTime = System.currentTimeMillis() - processingStartTime; SecurityProcessRequestCallback securityCallback = new SecurityProcessRequestCallback(restRequest, restResponseChannel, blobProperties, usermetadata, routerCallback); securityService.processRequest(restRequest, securityCallback); } catch (Exception e) { submitResponse(restRequest, restResponseChannel, null, e); } finally { frontendMetrics.putPreProcessingTimeInMs.update(preProcessingTime); } }

Target:
public void handlePut(RestRequest restRequest, RestResponseChannel restResponseChannel) { handlePrechecks(restRequest, restResponseChannel); Exception exception = isUp ? new RestServiceException("PUT is not supported", RestServiceErrorCode.UnsupportedHttpMethod) : new RestServiceException("AmbryBlobStorageService unavailable", RestServiceErrorCode.ServiceUnavailable); submitResponse(restRequest, restResponseChannel, null, exception); }
Source:
public void create() { EngineExtensionsManager.getInstance().dump(); AuthenticationProfileRepository.getInstance(); DbUserCacheManager.getInstance().init(); AsyncTaskManager.getInstance().initAsyncTaskManager(); ResourceManager.getInstance().init(); OvfDataUpdater.getInstance().initOvfDataUpdater(); SchedulingManager.getInstance().setMigrationHandler(new MigrationHandler() { @Override public void migrateVM(List<Guid> initialHosts, Guid vmToMigrate) { MigrateVmParameters parameters = new MigrateVmParameters(false, vmToMigrate); parameters.setInitialHosts(new ArrayList<Guid>(initialHosts)); Backend.getInstance().runInternalAction(VdcActionType.MigrateVm, parameters, ExecutionHandler.createInternalJobContext()); } }); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { MacPoolManager.getInstance().initialize(); } }); StoragePoolStatusHandler.init(); GlusterJobsManager.init(); ExternalTrustStoreInitializer.init(); try { log.info("Init VM custom properties utilities"); VmPropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of vm custom properties failed.", e); } try { log.info("Init device custom properties utilities"); DevicePropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of device custom properties failed.", e); } SchedulingManager.getInstance().init(); new DwhHeartBeat().init(); PmHealthCheckManager.getInstance().initialize(); }

Target:
public void create() { EngineExtensionsManager.getInstance(); AuthenticationProfileRepository.getInstance(); DbUserCacheManager.getInstance().init(); AsyncTaskManager.getInstance().initAsyncTaskManager(); ResourceManager.getInstance().init(); OvfDataUpdater.getInstance().initOvfDataUpdater(); SchedulingManager.getInstance().setMigrationHandler(new MigrationHandler() { @Override public void migrateVM(List<Guid> initialHosts, Guid vmToMigrate) { MigrateVmParameters parameters = new MigrateVmParameters(false, vmToMigrate); parameters.setInitialHosts(new ArrayList<Guid>(initialHosts)); Backend.getInstance().runInternalAction(VdcActionType.MigrateVm, parameters, ExecutionHandler.createInternalJobContext()); } }); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { MacPoolManager.getInstance().initialize(); } }); StoragePoolStatusHandler.init(); GlusterJobsManager.init(); ExternalTrustStoreInitializer.init(); try { log.info("Init VM custom properties utilities"); VmPropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of vm custom properties failed.", e); } try { log.info("Init device custom properties utilities"); DevicePropertiesUtils.getInstance().init(); } catch (InitializationException e) { log.error("Initialization of device custom properties failed.", e); } SchedulingManager.getInstance().init(); new DwhHeartBeat().init(); PmHealthCheckManager.getInstance().initialize(); }
Source:
public void onReceiveSystemInfo(RestApi.SystemInfo info) { if (getActivity() == null) return; mDeviceId.setText(info.myID); mDeviceId.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mActivity.getApi().copyDeviceId(mDeviceId.getText().toString()); view.performClick(); return true; } }); mCpuUsage.setText(new DecimalFormat("0.00").format(info.cpuPercent) + "%"); mRamUsage.setText(RestApi.readableFileSize(mActivity, info.sys)); mAnnounceServer.setText(Integer.toString(info.extAnnounceConnected) + "/" + Integer.toString(info.extAnnounceTotal)); if (info.extAnnounceConnected > 1) { mAnnounceServer.setTextColor(getResources().getColor(R.color.text_green)); } else { mAnnounceServer.setTextColor(getResources().getColor(R.color.text_red)); } }

Target:
public void onReceiveSystemInfo(RestApi.SystemInfo info) { if (getActivity() == null) return; mDeviceId.setText(info.myID); mDeviceId.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mActivity.getApi().copyDeviceId(mDeviceId.getText().toString()); view.performClick(); return true; } }); mCpuUsage.setText(new DecimalFormat("0.00").format(info.cpuPercent) + "%"); mRamUsage.setText(RestApi.readableFileSize(mActivity, info.sys)); mAnnounceServer.setText(Integer.toString(info.extAnnounceConnected) + "/" + Integer.toString(info.extAnnounceTotal)); if (info.extAnnounceConnected > 0) { mAnnounceServer.setTextColor(getResources().getColor(R.color.text_green)); } else { mAnnounceServer.setTextColor(getResources().getColor(R.color.text_red)); } }
Source:
public boolean chkAuthorization(String userName, Object conceptCollectionObj, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { IConceptCollection collection; String conceptCollectionId = null; if (conceptCollectionObj instanceof String) { conceptCollectionId = (String) conceptCollectionObj; collection = conceptCollectionManager.getConceptCollection(conceptCollectionId); } else { try { collection = (IConceptCollection) conceptCollectionObj; } catch (ClassCastException cce) { throw new IllegalObjectException(cce); } } String conceptCollectionOwner = collection.getOwner().getUserName(); if (userName.equals(conceptCollectionOwner)) { return true; } if (userRoles.length == 0) { return false; } List<String> roles = Arrays.asList(userRoles); List<IConceptCollectionCollaborator> ccCollaboratorList = conceptCollectionManager .showCollaboratingUsers(conceptCollectionId); if (ccCollaboratorList == null || ccCollaboratorList.isEmpty()) return false; for (IConceptCollectionCollaborator ccCollaborator : ccCollaboratorList) { String collaboratorName = ccCollaborator.getCollaborator().getUserObj().getUserName(); if (userName != null) { if (userName.equals(collaboratorName)) { List<IQuadrigaRole> collaboratorRoles = ccCollaborator.getCollaborator().getCollaboratorRoles(); if (collaboratorRoles != null) { for (IQuadrigaRole collabRole : collaboratorRoles) { String collaboratorRoleId = collabRole.getId(); if (roles != null) { if (roles.contains(collaboratorRoleId)) { return true; } } } } } } } return false; }

Target:
public boolean chkAuthorization(String userName, Object conceptCollectionObj, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { IConceptCollection collection; if (conceptCollectionObj instanceof String) { String conceptCollectionId = (String) conceptCollectionObj; collection = conceptCollectionManager.getConceptCollection(conceptCollectionId); } else { try { collection = (IConceptCollection) conceptCollectionObj; } catch (ClassCastException cce) { throw new IllegalObjectException(cce); } } String conceptCollectionOwner = collection.getOwner().getUserName(); if (userName.equals(conceptCollectionOwner)) { return true; } if (userRoles.length == 0) { return false; } List<String> roles = Arrays.asList(userRoles); List<IConceptCollectionCollaborator> ccCollaboratorList = conceptCollectionManager .showCollaboratingUsers(collection.getConceptCollectionId()); if (ccCollaboratorList == null || ccCollaboratorList.isEmpty()) { return false; } for (IConceptCollectionCollaborator ccCollaborator : ccCollaboratorList) { String collaboratorName = ccCollaborator.getCollaborator().getUserObj().getUserName(); if (userName != null) { if (userName.equals(collaboratorName)) { List<IQuadrigaRole> collaboratorRoles = ccCollaborator.getCollaborator().getCollaboratorRoles(); if (collaboratorRoles != null) { for (IQuadrigaRole collabRole : collaboratorRoles) { String collaboratorRoleId = collabRole.getId(); if (roles != null) { if (roles.contains(collaboratorRoleId)) { return true; } } } } } } } return false; }
Source:
public String controller(@FragmentParam("patientProgram") PatientProgram enrollment, @FragmentParam(value = "encounter", required = false) Encounter encounter, @FragmentParam("showClinicalData") boolean showClinicalData, FragmentModel model) { Map<String, Object> dataPoints = new LinkedHashMap<String, Object>(); dataPoints.put("Enrolled", enrollment.getDateEnrolled()); Obs ancNoObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.ANTENATAL_CASE_NUMBER)); if (ancNoObs != null) { dataPoints.put("ANC No. ", ancNoObs.getValueNumeric()); } Obs lmpObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept("1427AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); Date edd; if (lmpObs != null) { edd = calculateEdd(lmpObs.getValueDate()); if (edd == null) { dataPoints.put("EDD: ", "Unknown (Missing L.M.P.)"); } else { dataPoints.put("EDD: ", edd); } } model.put("dataPoints", dataPoints); return "view/dataPoints"; }

Target:
public String controller(@FragmentParam("patientProgram") PatientProgram enrollment, @FragmentParam(value = "encounter", required = false) Encounter encounter, @FragmentParam("showClinicalData") boolean showClinicalData, FragmentModel model) { Map<String, Object> dataPoints = new LinkedHashMap<String, Object>(); dataPoints.put("Enrolled", enrollment.getDateEnrolled()); Obs ancNoObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.ANTENATAL_CASE_NUMBER)); if (ancNoObs != null) { dataPoints.put("ANC No", ancNoObs.getValueNumeric()); } Obs lmpObs = EmrUtils.firstObsInProgram(enrollment, Dictionary.getConcept(Dictionary.LAST_MONTHLY_PERIOD)); if (lmpObs != null) { dataPoints.put("EDD", CalculationUtils.dateAddDays(lmpObs.getValueDate(), 280)); } model.put("dataPoints", dataPoints); return "view/dataPoints"; }
Source:
public static List<Entity> prepare(String extensionName, String jobName, InputStream configStream, List<URL> urls) throws IOException, FalconException { ClassLoader extensionClassLoader = ExtensionClassLoader.load(urls); if (extensionClassLoader.getResourceAsStream(EXTENSION_BUILDER_INTERFACE_SERVICE_FILE) == null) { throw new FalconCLIException("The jars in the extension build are not packaged with META-INF/services/" + EXTENSION_BUILDER_INTERFACE_SERVICE_FILE); } ExtensionHandler extensionHandler = new ExtensionHandler(); return extensionHandler.getEntities(extensionClassLoader, extensionName, jobName, configStream); }

Target:
public static List<Entity> prepare(String extensionName, String jobName, InputStream configStream, List<URL> urls) throws IOException, FalconException { ClassLoader extensionClassLoader = ExtensionClassLoader.load(urls); if (extensionClassLoader.getResourceAsStream(EXTENSION_BUILDER_INTERFACE_SERVICE_FILE) == null) { throw new FalconCLIException("The extension build time jars do not contain " + EXTENSION_BUILDER_INTERFACE_SERVICE_FILE); } ExtensionHandler extensionHandler = new ExtensionHandler(); return extensionHandler.getEntities(extensionClassLoader, extensionName, jobName, configStream); }