auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void registerCacheEventListener(CacheEventListener<? super K, ? super V> listener, EventOrdering ordering, EventFiring firing, EnumSet<EventType> forEventTypes) { boolean doRegister = forEventTypes.contains(EventType.EVICTED) || forEventTypes.contains(EventType.EXPIRED); EventListenerWrapper wrapper = new EventListenerWrapper(listener, firing, ordering, forEventTypes); if(wrapper.config.orderingMode() == EventOrdering.ORDERED) { orderedListenerCount.incrementAndGet(); } if(aSyncListenersSet.contains(wrapper) || syncListenersSet.contains(wrapper)) { throw new IllegalStateException("Cache Event Listener already registered: " + listener); } if (firing == EventFiring.ASYNCHRONOUS) { aSyncListenersSet.add(wrapper); } else { syncListenersSet.add(wrapper); } if (doRegister) { store.enableStoreEventNotifications(storeListener); } }

Target:
public void registerCacheEventListener(CacheEventListener<? super K, ? super V> listener, EventOrdering ordering, EventFiring firing, EnumSet<EventType> forEventTypes) { boolean doRegister = forEventTypes.contains(EventType.EVICTED) || forEventTypes.contains(EventType.EXPIRED); EventListenerWrapper wrapper = new EventListenerWrapper(listener, firing, ordering, forEventTypes); if(wrapper.config.orderingMode() == EventOrdering.ORDERED) { orderedListenerCount.incrementAndGet(); } if(aSyncListenersSet.contains(wrapper) || syncListenersSet.contains(wrapper)) { throw new IllegalStateException("Cache Event Listener already registered: " + listener); } if (firing == EventFiring.ASYNCHRONOUS) { aSyncListenersSet.add(wrapper); } else { syncListenersSet.add(wrapper); } if (doRegister) { store.enableStoreEventNotifications(storeListener); } synchronized (this) { if (eventThreadLocal instanceof NoOpEventThreadLocalImpl) { eventThreadLocal = new EventThreadLocalImpl(); } } }
Source:
public void createControl(Composite parent) { fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT); Dialog.applyDialogFont(fPane); fSourceViewer = new SourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); fSourceViewer.setEditable(false); Control sourceViewerControl= fSourceViewer.getControl(); sourceViewerControl.setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)); IPreferenceStore preferenceStore= EditorsUI.getPreferenceStore(); Color bg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, sourceViewerControl.getDisplay()); Color fg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, sourceViewerControl.getDisplay()); Color selBg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND, sourceViewerControl.getDisplay()); Color selFg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND, sourceViewerControl.getDisplay()); sourceViewerControl.setBackground(bg); sourceViewerControl.setForeground(fg); if (sourceViewerControl instanceof StyledText) { StyledText styledText = (StyledText) sourceViewerControl; styledText.setSelectionBackground(selBg); styledText.setSelectionForeground(selFg); } disposeColors(); fForegroundColor= fg; fBackgroundColor= bg; fSelectionForegroundColor= selFg; fSelectionBackgroundColor= selBg; sourceViewerControl.addDisposeListener(e -> disposeColors()); fPane.setContent(sourceViewerControl); }

Target:
public void createControl(Composite parent) { fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT); Dialog.applyDialogFont(fPane); fSourceViewer = new FileChangeSourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); fPane.setContent(fSourceViewer.getControl()); }
Source:
public static Intent newIntent(Activity activity, EnrolledCoursesResponse courseData, CourseUpgradeResponse courseUpgradeData, String courseComponentId, String lastAccessedId, boolean isVideosMode) { Bundle courseBundle = new Bundle(); courseBundle.putSerializable(EXTRA_COURSE_DATA, courseData); courseBundle.putParcelable(EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData); courseBundle.putString(EXTRA_COURSE_COMPONENT_ID, courseComponentId); final Intent intent = new Intent(activity, CourseOutlineActivity.class); intent.putExtra(EXTRA_BUNDLE, courseBundle); intent.putExtra(EXTRA_LAST_ACCESSED_ID, lastAccessedId); intent.putExtra(EXTRA_IS_VIDEOS_MODE, isVideosMode); return intent; }

Target:
public static Intent newIntent(Activity activity, EnrolledCoursesResponse courseData, CourseUpgradeResponse courseUpgradeData, String courseComponentId, String lastAccessedId, boolean isVideosMode) { final Bundle courseBundle = new Bundle(); courseBundle.putSerializable(EXTRA_COURSE_DATA, courseData); courseBundle.putParcelable(EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData); courseBundle.putString(EXTRA_COURSE_COMPONENT_ID, courseComponentId); final Intent intent = new Intent(activity, CourseOutlineActivity.class); intent.putExtra(EXTRA_BUNDLE, courseBundle); intent.putExtra(EXTRA_LAST_ACCESSED_ID, lastAccessedId); intent.putExtra(EXTRA_IS_VIDEOS_MODE, isVideosMode); return intent; }
Source:
public void setUp() { filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock, null); filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); }

Target:
public void setUp() { filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock); filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); }
Source:
protected void refreshVisuals() { final DDiagramElement diagElement = this.resolveDiagramElement(); if (primaryShape != null) { final boolean firstRegion = isFirstRegionPart(); if (firstRegion && primaryShape.getBorder() instanceof LineBorder || !firstRegion && primaryShape.getBorder() instanceof MarginBorder) { configureBorder(primaryShape); } if (diagElement instanceof DNodeContainer) { final DNodeContainer container = (DNodeContainer) diagElement; if (primaryShape instanceof GradientRoundedRectangle && container.getOwnedStyle() instanceof FlatContainerStyle) { if (((GradientRoundedRectangle) primaryShape).getBackgroundStyle() != ((FlatContainerStyle) container.getOwnedStyle()).getBackgroundStyle()) { ((AbstractDiagramContainerEditPart) this).reInitFigure(); } } } } super.refreshVisuals(); }

Target:
protected void refreshVisuals() { if (primaryShape != null) { final boolean firstRegion = isFirstRegionPart(); if (firstRegion && primaryShape.getBorder() instanceof LineBorder || !firstRegion && primaryShape.getBorder() instanceof MarginBorder) { configureBorder(primaryShape); } final DDiagramElement diagElement = this.resolveDiagramElement(); if (diagElement instanceof DNodeContainer) { final DNodeContainer container = (DNodeContainer) diagElement; if (primaryShape instanceof GradientRoundedRectangle && container.getOwnedStyle() instanceof FlatContainerStyle) { if (((GradientRoundedRectangle) primaryShape).getBackgroundStyle() != ((FlatContainerStyle) container.getOwnedStyle()).getBackgroundStyle()) { ((AbstractDiagramContainerEditPart) this).reInitFigure(); } } } } super.refreshVisuals(); }
Source:
private void testConnection(URL url) throws IOException { try { URLConnection connection = (URLConnection) ProxyConfiguration.open(url); connection.setConnectTimeout(20000); connection.connect(); if(connection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + url.toString(), responseCode); } } else { Util.copyStreamAndClose(connection.getInputStream(),new NullOutputStream()); } } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) throw new IOException("Failed to validate the SSL certificate of "+url,e); } }

Target:
private void testConnection(URL url) throws IOException { try { URLConnection connection = (URLConnection) ProxyConfiguration.open(url); if(connection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + url, responseCode); } } else { Util.copyStreamAndClose(connection.getInputStream(),new NullOutputStream()); } } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) throw new IOException("Failed to validate the SSL certificate of "+url,e); } }
Source:
private static List<String> getCompileFilePaths(@NotNull JpsModule module, @NotNull ElixirTarget target, @NotNull CompileContext context, Collection<File> files){ if(JavaBuilderUtil.isCompileJavaIncrementally(context)){ return getCompileFilePathsDefault(module, target); } return ContainerUtil.map(files, new Function<File, String>() { @Override public String fun(File file) { return file.getAbsolutePath(); } }); }

Target:
private static List<String> getCompileFilePaths(@NotNull JpsModule module, @NotNull ElixirTarget target, @NotNull CompileContext context, Collection<File> files){ if(context.getScope().isBuildIncrementally(target.getTargetType())){ return getCompileFilePathsDefault(module, target); } return ContainerUtil.map(files, new Function<File, String>() { @Override public String fun(File file) { return file.getAbsolutePath(); } }); }
Source:
public String getDescription() { StringBuffer sb = new StringBuffer("a union between \""); Joiner joiner = Joiner.on("\", \""); List<String> descriptionList = Lists.transform(vfsList, new Function<VFS, String>() { @Override public String apply(VFS vfs) { return vfs.getDescription(); }}); try { joiner.appendTo(sb, descriptionList); } catch (IOException e) { throw new AssertionError(e); } return sb.append("\"").toString(); }

Target:
public String getDescription() { StringBuilder sb = new StringBuilder("a union between \""); Joiner joiner = Joiner.on("\", \""); List<String> descriptionList = Lists.transform(vfsList, new Function<VFS, String>() { @Override public String apply(VFS vfs) { return vfs.getDescription(); }}); joiner.appendTo(sb, descriptionList); return sb.append("\"").toString(); }
Source:
private void loadImages(final IDockerConnection connection) { final Job loadImagesJob = new Job(DVMessages .getFormattedString("ImagesLoadJob.msg", connection.getUri())) { @Override protected IStatus run(final IProgressMonitor monitor) { connection.getImages(true); return Status.OK_STATUS; } }; loadImagesJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Display.getDefault().asyncExec(() -> { viewer.refresh(); }); } }); loadImagesJob.schedule(); }

Target:
private void loadImages(final IDockerConnection connection) { final Job loadImagesJob = new Job(DVMessages .getFormattedString("ImagesLoadJob.msg", connection.getUri())) { @Override protected IStatus run(final IProgressMonitor monitor) { connection.getImages(true); Display.getDefault().asyncExec(() -> { viewer.refresh(); }); return Status.OK_STATUS; } }; loadImagesJob.schedule(); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + name.hashCode(); result = prime * result + value.hashCode(); return result; }
Source:
public void getVolumeSnapshotSchedule(AsyncQuery aQuery, Guid volumeId) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery asyncQuery) { return source != null ? source : null; } }; Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeSnapshotScheduleByVolumeId, new IdQueryParameters(volumeId), aQuery); }

Target:
public void getVolumeSnapshotSchedule(AsyncQuery aQuery, Guid volumeId) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery asyncQuery) { return source; } }; Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeSnapshotScheduleByVolumeId, new IdQueryParameters(volumeId), aQuery); }
Source:
public void diskSpaceRequirementsTest() throws StoreException { DiskSpaceRequirements requirements = store.getDiskSpaceRequirements(); if (!isLogSegmented) { assertNull("Expected null DiskSpaceRequirements for non segmented log", requirements); return; } assertEquals(SEGMENT_CAPACITY, requirements.getSegmentSizeInBytes()); assertEquals((LOG_CAPACITY / SEGMENT_CAPACITY) - 3, requirements.getSegmentsNeeded()); assertEquals(0, requirements.getSwapSegmentsInUse()); }

Target:
public void diskSpaceRequirementsTest() throws Exception { int segmentsAllocated = 3; doDiskSpaceRequirementsTest(segmentsAllocated, 0); File tempFile = File.createTempFile("sample-swap", LogSegmentNameHelper.SUFFIX + BlobStoreCompactor.TEMP_LOG_SEGMENT_NAME_SUFFIX, tempDir); doDiskSpaceRequirementsTest(segmentsAllocated, 1); assertTrue("Could not delete temp file", tempFile.delete()); addCuratedData(SEGMENT_CAPACITY); segmentsAllocated += 1; doDiskSpaceRequirementsTest(segmentsAllocated, 0); File.createTempFile("sample-swap", LogSegmentNameHelper.SUFFIX + BlobStoreCompactor.TEMP_LOG_SEGMENT_NAME_SUFFIX, tempDir).deleteOnExit(); File.createTempFile("sample-swap", LogSegmentNameHelper.SUFFIX + BlobStoreCompactor.TEMP_LOG_SEGMENT_NAME_SUFFIX, tempDir).deleteOnExit(); addCuratedData(SEGMENT_CAPACITY); segmentsAllocated += 1; doDiskSpaceRequirementsTest(segmentsAllocated, 2); }
Source:
public void execute(CommandLine options) throws Exception { super.execute(options); List<String> args = options.getArgList(); Path inputFile = new Path(args.get(0)); Map<String, Long> columnSizes = getColumnSizeInBytes(inputFile); Map<String, Float> columnRatio = getColumnRatio(columnSizes); if (args.size() > 1) { for (String inputColumn : args.subList(1, args.size())) { long size = 0; float ratio = 0; for (String column : columnSizes.keySet()) { if (column.equals(inputColumn) || column.startsWith(inputColumn + ".")) { size += columnSizes.get(column); ratio += columnRatio.get(column); } } Main.out.println(inputColumn + "->" + " Size In Bytes: " + size + " Size In Ratio: " + ratio); } } else { for (String column : columnSizes.keySet()) { Main.out.println(column + "->" + " Size In Bytes: " + columnSizes.get(column) + " Size In Ratio: " + columnRatio.get(column)); } } }

Target:
public void execute(CommandLine options) throws Exception { super.execute(options); List<String> args = options.getArgList(); Path inputFile = new Path(args.get(0)); Map<String, Long> columnSizes = getColumnSizeInBytes(inputFile); Map<String, Float> columnRatio = getColumnRatio(columnSizes); if (args.size() > 1) { for (String inputColumn : args.subList(1, args.size())) { long size = 0; float ratio = 0; for (String column : columnSizes.keySet()) { if (column.equals(inputColumn) || column.startsWith(inputColumn + ".")) { size += columnSizes.get(column); ratio += columnRatio.get(column); } } Main.out.println(inputColumn + "-> Size In Bytes: " + size + " Size In Ratio: " + ratio); } } else { for (String column : columnSizes.keySet()) { Main.out.println(column + "->" + " Size In Bytes: " + columnSizes.get(column) + " Size In Ratio: " + columnRatio.get(column)); } } }
Source:
public void profileChangePassword(WebContext ctx) { U userAccount = getUser().getUserObject(getUserClass()); userAccount = userAccount.getMapper().refreshOrFail(userAccount); assertNotNew(userAccount); if (ctx.ensureSafePOST()) { try { String oldPassword = ctx.get(PARAM_OLD_PASSWORD).asString(); String newPassword = ctx.get(PARAM_NEW_PASSWORD).asString(); String confirmation = ctx.get(PARAM_CONFIRMATION).asString(); validateOldPassword(oldPassword, userAccount); userAccount.getUserAccountData() .getLogin() .verifyPassword(newPassword, confirmation, userAccount.getUserAccountData().getMinPasswordLength()); userAccount.getUserAccountData().getLogin().setCleartextPassword(newPassword); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordChange").causedByCurrentUser().forCurrentUser().log(); showSavedMessage(); ctx.respondWith().redirectToGet("/profile"); return; } catch (Exception e) { auditLog.neutral("AuditLog.passwordChangeFailed").causedByCurrentUser().forCurrentUser().log(); UserContext.handle(e); } } ctx.respondWith().template("/templates/biz/biz/tenants/profile-change-password.html.pasta", userAccount); }

Target:
public void profileChangePassword(WebContext ctx) { U userAccount = getUser().getUserObject(getUserClass()); userAccount = userAccount.getMapper().refreshOrFail(userAccount); assertNotNew(userAccount); if (ctx.ensureSafePOST()) { try { String oldPassword = ctx.get(PARAM_OLD_PASSWORD).asString(); String newPassword = ctx.get(PARAM_NEW_PASSWORD).asString(); String confirmation = ctx.get(PARAM_CONFIRMATION).asString(); validateOldPassword(oldPassword, userAccount); userAccount.getUserAccountData() .getLogin() .verifyPassword(newPassword, confirmation, userAccount.getUserAccountData().getMinPasswordLength()); userAccount.getUserAccountData().getLogin().setCleartextPassword(newPassword); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordChange").causedByCurrentUser().forCurrentUser().log(); showSavedMessage(); ctx.respondWith().redirectToGet("/profile"); return; } catch (Exception e) { auditLog.neutral("AuditLog.passwordChangeFailed").causedByCurrentUser().forCurrentUser().log(); UserContext.handle(e); } } ctx.respondWith().template("/templates/biz/tenants/profile-change-password.html.pasta", userAccount); }
Source:
public void test500DoesNotRetry() { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.<String> of()); assert !retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()).build()); verify(utils, command); }

Target:
public void test500DoesNotRetry() { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.<String> of()); assertFalse(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()).build())); verify(utils, command); }
Source:
void store(Iterable<Event> events) { final Iterable<EEntity> entities = Iterables.transform(events, EventToEEntity.instance()); store(newLinkedList(entities)); }

Target:
void store(Iterable<Event> events) { final Iterable<EEntity> entities = Iterables.transform(events, EventToEEntity.instance()); store(newArrayList(entities)); }
Source:
public static Total of(String total) { notNull(total, "total"); return Total.valueOf(total.toUpperCase()); }

Target:
public static Total of(String total) { notNull(total, "total"); try { return Total.valueOf(total.toUpperCase()); } catch (IllegalArgumentException e) { throw new UnsupportedOperationException( format("Unknown value for Grid's total: \"%s\", supported values are: [%s]", total, StringUtils.arrayToCommaDelimitedString(Total.values())), e); } }
Source:
public void testTimestampMicrosConversion() throws Exception { TimestampMicrosConversion conversion = new TimestampMicrosConversion(); long instant = May_28_2015_21_46_53_221.getTimeInMillis() * 1000 + 843; Timestamp May_28_2015_21_46_53_221_843_ts = Timestamp.newBuilder().setSeconds(1432849613L).setNanos(221843000) .build(); Assert.assertEquals("Known timestamp should be correct", May_28_2015_21_46_53_221_843_ts, conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); try { conversion.toLong(May_28_2015_21_46_53_221_843_ts, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); Assert.fail("Should not convert DateTime to long"); } catch (UnsupportedOperationException e) { } try { conversion.fromLong((long) -1.0, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); } catch (IllegalArgumentException e) { } }

Target:
public void testTimestampMicrosConversion() { TimestampMicrosConversion conversion = new TimestampMicrosConversion(); Timestamp May_28_2015_21_46_53_221_843_ts = Timestamp.newBuilder().setSeconds(1432849613L).setNanos(221843000) .build(); Timestamp Jan_2_1900_3_4_5_678_901_ts = Timestamp.newBuilder().setSeconds(-2208891355L).setNanos(678901000).build(); long instant = May_28_2015_21_46_53_221.getTimeInMillis() * 1000 + 843; Timestamp tsFromInstant = conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); long roundTrip = conversion.toLong(tsFromInstant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); Assert.assertEquals("Round-trip conversion should work", instant, roundTrip); Assert.assertEquals("Known timestamp should be correct", May_28_2015_21_46_53_221_843_ts, conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); Assert.assertEquals("Known timestamp should be correct", instant, (long) conversion .toLong(May_28_2015_21_46_53_221_843_ts, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); instant = Jan_2_1900_3_4_5_678.getTimeInMillis() * 1000 + 901; tsFromInstant = conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); roundTrip = conversion.toLong(tsFromInstant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); Assert.assertEquals("Round-trip conversion should work", instant, roundTrip); Assert.assertEquals("Known timestamp should be correct", Jan_2_1900_3_4_5_678_901_ts, conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); Assert.assertEquals("Known timestamp should be correct", instant, (long) conversion.toLong(Jan_2_1900_3_4_5_678_901_ts, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); }
Source:
public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof DefaultOrganization)) { return false; } final DefaultOrganization otherOrg = (DefaultOrganization) other; return Objects.equal(_name, otherOrg._name); }

Target:
public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof DefaultOrganization)) { return false; } final DefaultOrganization otherOrg = (DefaultOrganization) other; return Objects.equal(_id, otherOrg._id); }
Source:
public boolean killOperation(UUID uuid, String userId) throws StandardException { RunningOperation op = operations.get(uuid); if (op == null) return false; Activation activation = op.getOperation().getActivation(); String databaseOwner = activation.getLanguageConnectionContext().getDataDictionary().getAuthorizationDatabaseOwner(); String runningUserId = activation.getLanguageConnectionContext().getCurrentUserId(activation); String groupuser = activation.getLanguageConnectionContext().getCurrentGroupUser(activation); if (!userId.equals(databaseOwner) && !userId.equals(runningUserId)) { if (groupuser != null) { if (!groupuser.equals(databaseOwner) && !groupuser.equals(runningUserId)) throw StandardException.newException(SQLState.AUTH_NO_PERMISSION_FOR_KILLING_OPERATION, userId, uuid.toString()); } else throw StandardException.newException(SQLState.AUTH_NO_PERMISSION_FOR_KILLING_OPERATION, userId, uuid.toString()); } unregisterOperation(uuid); op.getOperation().kill(); op.getThread().interrupt(); ResultSet rs=activation.getResultSet(); rs.close(); return true; }

Target:
public boolean killOperation(UUID uuid, String userId) throws StandardException { RunningOperation op = operations.get(uuid); if (op == null) return false; Activation activation = op.getOperation().getActivation(); String databaseOwner = activation.getLanguageConnectionContext().getDataDictionary().getAuthorizationDatabaseOwner(); String runningUserId = activation.getLanguageConnectionContext().getCurrentUserId(activation); String groupuser = activation.getLanguageConnectionContext().getCurrentGroupUser(activation); if (!userId.equals(databaseOwner) && !userId.equals(runningUserId)) { if (groupuser != null) { if (!groupuser.equals(databaseOwner) && !groupuser.equals(runningUserId)) throw StandardException.newException(SQLState.AUTH_NO_PERMISSION_FOR_KILLING_OPERATION, userId, uuid.toString()); } else throw StandardException.newException(SQLState.AUTH_NO_PERMISSION_FOR_KILLING_OPERATION, userId, uuid.toString()); } unregisterOperation(uuid); op.getOperation().kill(); op.getThread().interrupt(); ResultSet rs=activation.getResultSet(); if (rs!=null && !rs.isClosed()) { rs.close(); } return true; }
Source:
public List<ActivityMetadata> metadataForAnnouncements(@RequestParam final Long start, @RequestParam final Long end) throws JsonParseException, IOException, ValidationException { Date startDate = new Date(start); Date endDate = new Date(end); validateActivityDatesAndDateRange(start, end); return activityMetadataManager.getActivityMetadataByConcept( ActivityConcept.ANNOUNCEMENT, startDate, endDate); }

Target:
public List<ActivityMetadata> metadataForAnnouncements(@RequestParam final Long start, @RequestParam final Long end) throws JsonParseException, IOException, ValidationException { Date startDate = new Date(start); Date endDate = new Date(end); validateActivityDatesAndDateRange(start, end); return activityMetadataManager.getAnnouncementActivityMetadata(startDate, endDate); }
Source:
public void onEvent(final Event event, final Object source, final Object data) { Patient patient = ((PatientEvent) event).getPatient(); XWikiContext context = contextProvider.get(); XWiki wiki = context.getWiki(); try { XWikiDocument doc = wiki.getDocument(patient.getDocument(), context); if (isNew(doc, context)) { wiki.deleteDocument(doc, true, context); EntityReference defaultReference = new EntityReference(wiki.getDefaultPage(context), EntityType.DOCUMENT, new EntityReference(wiki.getDefaultSpace(context), EntityType.SPACE)); defaultReference = currentResolver.resolve(defaultReference, EntityType.DOCUMENT); String url = wiki.getURL(new DocumentReference(defaultReference), "view", context); if (context.getResponse().isCommitted()) { context.getResponse().setHeader("Location", url); context.getResponse().flushBuffer(); } else { context.getResponse().sendRedirect(url); } } } catch (XWikiException ex) { logger.error("Could not delete patient. {}", ex.getMessage()); } catch (IOException ex) { logger.error("Could not redirect user appropriately. {}", ex.getMessage()); } }

Target:
public void onEvent(final Event event, final Object source, final Object data) { Patient patient = ((PatientEvent) event).getPatient(); XWikiContext context = contextProvider.get(); XWiki wiki = context.getWiki(); try { XWikiDocument doc = wiki.getDocument(patient.getDocument(), context); if (isNew(doc, context)) { wiki.deleteDocument(doc, true, context); EntityReference defaultReference = new EntityReference(wiki.getDefaultPage(context), EntityType.DOCUMENT, new EntityReference(wiki.getDefaultSpace(context), EntityType.SPACE)); defaultReference = currentResolver.resolve(defaultReference, EntityType.DOCUMENT); String url = wiki.getURL(new DocumentReference(defaultReference), "view", context); context.getResponse().sendRedirect(url); } } catch (XWikiException ex) { logger.error("Could not delete patient. {}", ex.getMessage()); } catch (IOException ex) { logger.error("Could not redirect user appropriately. {}", ex.getMessage()); } }
Source:
public boolean canCreate(ReviewDb db, RevWalk rw, RevObject object) { if (!canWrite()) { return false; } boolean owner; boolean admin; switch (getCurrentUser().getAccessPath()) { case REST_API: case JSON_RPC: owner = isOwner(); admin = getCurrentUser().getCapabilities().canAdministrateServer(); break; default: owner = false; admin = false; } if (object instanceof RevCommit) { if (admin || (owner && !isBlocked(Permission.CREATE))) { return true; } else if (!canPerform(Permission.CREATE)) { return false; } boolean isMerged = isMergedIntoBranchOrTag(db, rw, (RevCommit) object); return isMerged || canUpdate(); } else if (object instanceof RevTag) { final RevTag tag = (RevTag) object; try { rw.parseBody(tag); } catch (IOException e) { return false; } final PersonIdent tagger = tag.getTaggerIdent(); if (tagger != null) { boolean valid; if (getCurrentUser().isIdentifiedUser()) { final IdentifiedUser user = (IdentifiedUser) getCurrentUser(); final String addr = tagger.getEmailAddress(); valid = user.getEmailAddresses().contains(addr); } else { valid = false; } if (!valid && !owner && !canForgeCommitter()) { return false; } } if (tag.getFullMessage().contains("-----BEGIN PGP SIGNATURE-----\n")) { return owner || canPerform(Permission.PUSH_SIGNED_TAG); } else { return owner || canPerform(Permission.PUSH_TAG); } } else { return false; } }

Target:
public boolean canCreate(ReviewDb db, RevWalk rw, RevObject object) { if (!canWrite()) { return false; } boolean owner; boolean admin; switch (getCurrentUser().getAccessPath()) { case REST_API: case JSON_RPC: owner = isOwner(); admin = getCurrentUser().getCapabilities().canAdministrateServer(); break; default: owner = false; admin = false; } if (object instanceof RevCommit) { if (admin || (owner && !isBlocked(Permission.CREATE))) { return true; } else if (!canPerform(Permission.CREATE)) { return false; } else if (canUpdate()) { return true; } else if (isMergedIntoBranchOrTag(db, rw, (RevCommit) object)) { return true; } return false; } else if (object instanceof RevTag) { final RevTag tag = (RevTag) object; try { rw.parseBody(tag); } catch (IOException e) { return false; } final PersonIdent tagger = tag.getTaggerIdent(); if (tagger != null) { boolean valid; if (getCurrentUser().isIdentifiedUser()) { final IdentifiedUser user = (IdentifiedUser) getCurrentUser(); final String addr = tagger.getEmailAddress(); valid = user.getEmailAddresses().contains(addr); } else { valid = false; } if (!valid && !owner && !canForgeCommitter()) { return false; } } if (tag.getFullMessage().contains("-----BEGIN PGP SIGNATURE-----\n")) { return owner || canPerform(Permission.PUSH_SIGNED_TAG); } else { return owner || canPerform(Permission.PUSH_TAG); } } else { return false; } }
Source:
private static List<org.eclipse.jetty.client.api.Request> getRequestForDestination(Destination destination) { PoolingHttpDestination poolingHttpDestination = (PoolingHttpDestination) destination; Queue<HttpExchange> httpExchanges = poolingHttpDestination.getHttpExchanges(); List<org.eclipse.jetty.client.api.Request> requests = httpExchanges.stream() .map(HttpExchange::getRequest) .collect(Collectors.toList()); ((DuplexConnectionPool) poolingHttpDestination.getConnectionPool()).getActiveConnections().stream() .filter(HttpConnectionOverHTTP.class::isInstance) .map(HttpConnectionOverHTTP.class::cast) .map(connection -> connection.getHttpChannel().getHttpExchange()) .filter(Objects::nonNull) .forEach(exchange -> requests.add(exchange.getRequest())); return requests.stream() .filter(Objects::nonNull) .collect(Collectors.toList()); }

Target:
private static List<org.eclipse.jetty.client.api.Request> getRequestForDestination(Destination destination) { PoolingHttpDestination poolingHttpDestination = (PoolingHttpDestination) destination; Queue<HttpExchange> httpExchanges = poolingHttpDestination.getHttpExchanges(); List<org.eclipse.jetty.client.api.Request> requests = httpExchanges.stream() .map(HttpExchange::getRequest) .collect(Collectors.toList()); ((DuplexConnectionPool) poolingHttpDestination.getConnectionPool()).getActiveConnections().stream() .filter(HttpConnectionOverHTTP.class::isInstance) .map(HttpConnectionOverHTTP.class::cast) .map(connection -> connection.getHttpChannel().getHttpExchange()) .filter(Objects::nonNull) .forEach(exchange -> requests.add(exchange.getRequest())); return requests.stream() .filter(Objects::nonNull) .collect(toImmutableList()); }
Source:
private static boolean sameRelCollectionNoOrderConsidered( List<MutableRel> list0, List<MutableRel> list1) { if (list0.size() == list1.size()) { for (MutableRel rel: list0) { int index = list1.indexOf(rel); if (index == -1) { return false; } else { list1.remove(index); } } return true; } return false; }

Target:
private static boolean sameRelCollectionNoOrderConsidered( List<MutableRel> list0, List<MutableRel> list1) { if (list0.size() != list1.size()) { return false; } for (MutableRel rel: list0) { int index = list1.indexOf(rel); if (index == -1) { return false; } else { list1.remove(index); } } return true; }
Source:
private static int lastIndexOfTrim(byte[] raw, char ch, int pos) { while (pos >= 0 && raw[pos] == ' ') { pos--; } while (pos >= 0 && raw[pos] != ch) { pos--; } return pos; }

Target:
private static int lastIndexOfTrim(byte[] raw, char ch, int pos) { while (pos >= 0 && raw[pos] == ' ') pos--; while (pos >= 0 && raw[pos] != ch) pos--; return pos; }
Source:
private void appendMediaFileAndSavePost(MediaFile mediaFile, String imageUrl, ImageLoader imageLoader) { mEditorFragment.appendMediaFile(mediaFile, imageUrl, mImageLoader); if (updatePostObject()) { savePostToDb(); } }

Target:
private void appendMediaFileAndSavePost(MediaFile mediaFile, String imageUrl, ImageLoader imageLoader) { mEditorFragment.appendMediaFile(mediaFile, imageUrl, mImageLoader); savePostAsync(null); }
Source:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } Integer position = ref.position(); if (position == null) { position = ordinal.intValue(); } ordinal++; return new ColumnContext(tableInfo, ref, position); }

Target:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } Integer position = ref.position(); if (position == null) { position = ordinal; } ordinal++; return new ColumnContext(tableInfo, ref, position); }
Source:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { boolean ret = super.executeAnalysis(monitor); Map<String, SegmentStoreStatistics> segments = getPerSegmentTypeStats(); if(ret && segments != null) { fModel = new SegmentStoreStatisticsDataModel("System Call", segments); } return ret; }

Target:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { boolean ret = super.executeAnalysis(monitor); Map<String, SegmentStoreStatistics> segments = getPerSegmentTypeStats(); if(ret && segments != null) { fModel = new SegmentStoreStatisticsDataModel(nullToEmptyString(Messages.SystemCallLatencyStatisticsAnalysisModule_SystemCall)); } return ret; }
Source:
public void registerLocalProviderInstance(Object provider, Map<Class<?>, Integer> contracts) { for (Object registered : getLocalProviderInstances()) { if (registered == provider) { LOG.info("Provider already registered " + provider.getClass().getName()); return; } } localProviderInstances.add(provider); configurationWrapper.registerLocalContract(provider.getClass(), contracts); }

Target:
public void registerLocalProviderInstance(Object provider, Map<Class<?>, Integer> contracts) { for (Object registered : getLocalProviderInstances()) { if (registered == provider) { LOG.infov("Provider already registered {0}", provider.getClass().getName()); return; } } localProviderInstances.add(provider); configurationWrapper.registerLocalContract(provider.getClass(), contracts); }
Source:
public void theGetProfileGenericDataRequestIsReceived(final Map<String, String> settings) throws Throwable { ProfileGenericDataRequest request = new ProfileGenericDataRequestBuilder() .withDeviceidentification(getString(settings, "DeviceIdentification", "TEST1024000000001")) .withObisCode(this.fillObisCode(settings)).withBeginDate(this.fillDate(settings, "beginDate")) .withEndDate(this.fillDate(settings, "endDate")).build(); ProfileGenericDataAsyncResponse asyncResponse = this.client.requestProfileGenericData(request); assertTrue(asyncResponse != null); Helpers.saveAsyncResponse(asyncResponse); }

Target:
public void theGetProfileGenericDataRequestIsReceived(final Map<String, String> settings) throws Throwable { ProfileGenericDataRequest request = new ProfileGenericDataRequestBuilder() .withDeviceidentification(getString(settings, "DeviceIdentification", "TEST1024000000001")) .withObisCode(this.fillObisCode(settings)).withBeginDate(this.fillDate(settings, "beginDate")) .withEndDate(this.fillDate(settings, "endDate")).build(); ProfileGenericDataAsyncResponse asyncResponse = this.client.requestProfileGenericData(request); assertNotNull(asyncResponse); Helpers.saveAsyncResponse(asyncResponse); }
Source:
public int getRackId() { if (rackId == null) { throw new IllegalStateException("rackId not defined for the data node " + hostname + ":" + port); } return rackId; }

Target:
public long getRackId() { return rackId; }
Source:
protected void runImpl() throws IOException, Failure { if (!projectControl.canPerformPackAction(receiveGroup)) { throw new Failure(1, "fatal: receive-pack not permitted on this server"); } final ReceiveCommits receive = factory.create(projectControl, repo); ReceiveCommits.Capable r = receive.canUpload(); if (r != ReceiveCommits.Capable.OK) { throw new UnloggedFailure(1, "\nfatal: " + r.getMessage()); } verifyProjectVisible("reviewer", reviewerId); verifyProjectVisible("CC", ccId); receive.addReviewers(reviewerId); receive.addExtraCC(ccId); final ReceivePack rp = receive.getReceivePack(); rp.setRefLogIdent(currentUser.newRefLogIdent()); rp.setTimeout(config.getTimeout()); try { rp.receive(in, out, err); } catch (InterruptedIOException err) { throw new Failure(128, "fatal: client IO read/write timeout", err); } }

Target:
protected void runImpl() throws IOException, Failure { if (!projectControl.canRunReceivePack()) { throw new Failure(1, "fatal: receive-pack not permitted on this server"); } final ReceiveCommits receive = factory.create(projectControl, repo); ReceiveCommits.Capable r = receive.canUpload(); if (r != ReceiveCommits.Capable.OK) { throw new UnloggedFailure(1, "\nfatal: " + r.getMessage()); } verifyProjectVisible("reviewer", reviewerId); verifyProjectVisible("CC", ccId); receive.addReviewers(reviewerId); receive.addExtraCC(ccId); final ReceivePack rp = receive.getReceivePack(); rp.setRefLogIdent(currentUser.newRefLogIdent()); rp.setTimeout(config.getTimeout()); try { rp.receive(in, out, err); } catch (InterruptedIOException err) { throw new Failure(128, "fatal: client IO read/write timeout", err); } }
Source:
public void changesSubscriptionBout() throws Exception { final String alias = "maxi"; final Aliases aliases = new DyBase().user(new URN("urn:test:1890")).aliases(); aliases.add(alias); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.subscribe(false); Assert.assertFalse(bout.subscription()); }

Target:
public void changesSubscriptionBout() throws Exception { final String alias = "maxi"; final Aliases aliases = new DyBase().user(new URN("urn:test:1890")).aliases(); aliases.add(alias); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.subscribe(false); MatcherAssert.assertThat( bout.subscription(), Matchers.equalTo(false) ); }
Source:
private void reconcile() { if (highestContiguousMsgId == -1L && nonContiguousMsgIds.size() > 100) { Long min = Collections.min(nonContiguousMsgIds); LOGGER.info("Setting highestContiguousMsgId to from -1", min); highestContiguousMsgId = min; } nonContiguousMsgIds.removeIf(x -> x <= highestContiguousMsgId); List<Long> contiguousMsgIds = new ArrayList<>(); for (long msgId : (Iterable<Long>) () -> LongStream.iterate(highestContiguousMsgId + 1, id -> id + 1).iterator()) { if (!nonContiguousMsgIds.contains(msgId)) { break; } contiguousMsgIds.add(msgId); }; if (contiguousMsgIds.isEmpty()) { return; } highestContiguousMsgId = contiguousMsgIds.get(contiguousMsgIds.size() - 1); nonContiguousMsgIds.removeAll(contiguousMsgIds); }

Target:
private void reconcile() { if (highestContiguousMsgId == -1L && nonContiguousMsgIds.size() > 100) { Long min = nonContiguousMsgIds.first(); LOGGER.info("Setting highestContiguousMsgId to from -1", min); highestContiguousMsgId = min; } for (long msgId : nonContiguousMsgIds) { if (msgId <= highestContiguousMsgId) { nonContiguousMsgIds.remove(msgId); } else if (msgId > highestContiguousMsgId + 1) { break; } else { nonContiguousMsgIds.remove(msgId); highestContiguousMsgId = msgId; } } }
Source:
public boolean isOpen() { synchronized(portLock) { return isOpen; } }

Target:
public boolean isOpen() { return isOpen; }
Source:
private MediaType requestedContent(WebRequest request) { List<MediaType> mediaTypes = new ArrayList<>(); try { mediaTypes.addAll(contentNegotiationManager.resolveMediaTypes((NativeWebRequest) request)); } catch (HttpMediaTypeNotAcceptableException e1) { logger.error("Reuqested invalid content-type [{}]", request.getHeader(HttpHeaders.ACCEPT)); mediaTypes.add(MediaType.APPLICATION_JSON); } MediaType result = mediaTypes.stream() .reduce(null, this::reduceByPriority); return Optional.ofNullable(result).orElse(MediaType.APPLICATION_JSON); }

Target:
private MediaType requestedContent(WebRequest request) { List<MediaType> mediaTypes = new ArrayList<>(); try { mediaTypes.addAll(contentNegotiationManager.resolveMediaTypes((NativeWebRequest) request)); } catch (HttpMediaTypeNotAcceptableException e1) { logger.error("Requested invalid content-type [{}]", request.getHeader(HttpHeaders.ACCEPT), e1); mediaTypes.add(MediaType.APPLICATION_JSON); } MediaType result = mediaTypes.stream() .reduce(null, this::reduceByPriority); return Optional.ofNullable(result).orElse(MediaType.APPLICATION_JSON); }
Source:
public LogToJSONDataConverter(Configuration config) { this.logger = Logging.getLogger(getClass()); jsonProducer = ProcessingUtilsFactory.getPrinter(config); logParser = ProcessingUtilsFactory.getLogParser(config); if (config.containsKey(ProcessingUtilsFactory.CUSTOM_FIELDS_KEY)) { fields = config.readList(ProcessingUtilsFactory.CUSTOM_FIELDS_KEY, String.class); } }

Target:
public LogToJSONDataConverter(Configuration config) { jsonProducer = ProcessingUtilsFactory.getPrinter(config); logParser = ProcessingUtilsFactory.getLogParser(config); if (config.containsKey(ProcessingUtilsFactory.CUSTOM_FIELDS_KEY)) { fields = config.readList(ProcessingUtilsFactory.CUSTOM_FIELDS_KEY, String.class); } }
Source:
public void readRecoveredState(ExecutorService executor, ChannelStateReader reader) throws IOException { internalRequestPartitions(() -> executor.submit(() -> { for (InputChannel inputChannel : inputChannels.values()) { if (inputChannel instanceof RemoteInputChannel) { try { ((RemoteInputChannel) inputChannel).readRecoveredState(reader); } catch (Throwable t) { inputChannel.setError(t); return; } } } for (InputChannel inputChannel : inputChannels.values()) { try { inputChannel.requestSubpartition(consumedSubpartitionIndex); } catch (Throwable t) { inputChannel.setError(t); return; } } })); }

Target:
public CompletableFuture<?> readRecoveredState(ExecutorService executor, ChannelStateReader reader) { List<CompletableFuture<?>> futures = getStateConsumedFuture(); executor.submit(() -> { Collection<InputChannel> channels; synchronized (requestLock) { channels = inputChannels.values(); } internalReadRecoveredState(reader, channels); }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }
Source:
boolean isA2dpPlaying(BluetoothDevice device) { enforceCallingOrSelfPermission( BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission"); if (mA2dpSinkStreamHandler == null) return false; return mA2dpSinkStreamHandler.isPlaying(); }

Target:
boolean isA2dpPlaying(BluetoothDevice device) { enforceCallingOrSelfPermission( BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission"); synchronized (mStreamHandlerLock) { if (mA2dpSinkStreamHandler == null) return false; return mA2dpSinkStreamHandler.isPlaying(); } }
Source:
private void checkForIssue(ExpressionTree tree) { MethodInvocationTree nestedTree = extractMethodInvocation(tree); if (nestedTree != null && NEGATIVE_METHODS.anyMatch(nestedTree)) { addIssue(nestedTree, "Use the original value instead."); } }

Target:
private void checkForIssue(ExpressionTree tree) { if (tree.is(Tree.Kind.MEMBER_SELECT)) { Symbol identifierSymbol = ((MemberSelectExpressionTree) tree).identifier().symbol(); Type ownerType = identifierSymbol.owner().type(); if ("MIN_VALUE".equals(identifierSymbol.name()) && (ownerType.is("java.lang.Integer") || ownerType.is("java.lang.Long"))) { addIssue(tree, "Use the original value instead."); } } else { MethodInvocationTree nestedTree = extractMethodInvocation(tree); if (nestedTree != null && NEGATIVE_METHODS.anyMatch(nestedTree)) { addIssue(nestedTree, "Use the original value instead."); } } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_coursedetail_tab); if (savedInstanceState != null) { selectedTab = savedInstanceState.getInt(TAB_ID); } setApplyPrevTransitionOnRestart(true); bundle = getIntent().getBundleExtra(Router.EXTRA_BUNDLE); offlineBar = findViewById(R.id.offline_bar); if (!(NetworkUtil.isConnected(this))) { AppConstants.offline_flag = true; invalidateOptionsMenu(); if(offlineBar!=null){ offlineBar.setVisibility(View.VISIBLE); } } try{ EnrolledCoursesResponse courseData = (EnrolledCoursesResponse) bundle .getSerializable(Router.EXTRA_ENROLLMENT); if ( courseData == null ){ String courseId = bundle.getString(Router.EXTRA_COURSE_ID); if (!TextUtils.isEmpty(courseId)){ SegmentFactory.getInstance().trackNotificationTapped(courseId); NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nMgr.cancelAll(); Api api = new Api(this); courseData = api.getCourseById(courseId); if (courseData != null && courseData.getCourse() != null ) { bundle.putSerializable(Router.EXTRA_ENROLLMENT, courseData); selectedTab = courseInfoTabIndex; } } } if ( courseData != null ) { activityTitle = courseData.getCourse().getName(); try{ segIO.screenViewsTracking(courseData.getCourse().getName()); }catch(Exception e){ logger.error(e); } } else { Router.getInstance().showMyCourses(this); finish(); } }catch(Exception ex){ logger.error(ex); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_coursedetail_tab); if (savedInstanceState != null) { selectedTab = savedInstanceState.getInt(TAB_ID); } setApplyPrevTransitionOnRestart(true); bundle = getIntent().getBundleExtra(Router.EXTRA_BUNDLE); offlineBar = findViewById(R.id.offline_bar); if (!(NetworkUtil.isConnected(this))) { AppConstants.offline_flag = true; invalidateOptionsMenu(); if(offlineBar!=null){ offlineBar.setVisibility(View.VISIBLE); } } try{ EnrolledCoursesResponse courseData = (EnrolledCoursesResponse) bundle .getSerializable(Router.EXTRA_ENROLLMENT); if ( courseData == null ){ String courseId = bundle.getString(Router.EXTRA_COURSE_ID); if (!TextUtils.isEmpty(courseId)){ SegmentFactory.getInstance().trackNotificationTapped(courseId); Api api = new Api(this); courseData = api.getCourseById(courseId); if (courseData != null && courseData.getCourse() != null ) { bundle.putSerializable(Router.EXTRA_ENROLLMENT, courseData); selectedTab = courseInfoTabIndex; } } } if ( courseData != null ) { activityTitle = courseData.getCourse().getName(); try{ segIO.screenViewsTracking(courseData.getCourse().getName()); }catch(Exception e){ logger.error(e); } } else { Router.getInstance().showMyCourses(this); finish(); } }catch(Exception ex){ logger.error(ex); } }