auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testTmfEventRequest() { TmfEventRequest request = new TmfEventRequestStub(ITmfEvent.class); assertEquals("getRequestId", fRequestCount++, request.getRequestId()); assertEquals("getDataType", ITmfEvent.class, request.getDataType()); assertEquals("StartTime", TmfTimestamp.BIG_BANG, request.getRange().getStartTime()); assertEquals("EndTime", TmfTimestamp.BIG_CRUNCH, request.getRange().getEndTime()); assertEquals("getIndex", 0, request.getIndex()); assertEquals("getNbRequestedEvents", TmfEventRequest.ALL_DATA, request.getNbRequested()); assertFalse("isCompleted", request.isCompleted()); assertFalse("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertEquals("getNbRead", 0, request.getNbRead()); }

Target:
public void testTmfEventRequest() { TmfEventRequest request = new TmfEventRequestStub(ITmfEvent.class); assertEquals("getRequestId", fRequestCount++, request.getRequestId()); assertEquals("getDataType", ITmfEvent.class, request.getDataType()); assertEquals("StartTime", TmfTimestamp.BIG_BANG, request.getRange().getStartTime()); assertEquals("EndTime", TmfTimestamp.BIG_CRUNCH, request.getRange().getEndTime()); assertEquals("getRange", TmfTimeRange.ETERNITY, request.getRange()); assertSame("getRange", TmfTimeRange.ETERNITY, request.getRange()); assertEquals("getIndex", 0, request.getIndex()); assertEquals("getNbRequestedEvents", TmfEventRequest.ALL_DATA, request.getNbRequested()); assertFalse("isCompleted", request.isCompleted()); assertFalse("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertEquals("getNbRead", 0, request.getNbRead()); }
Source:
public static void showDialogDeletePermanently(final Activity activity, final Note note) { new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Dialog)) .setTitle(R.string.delete_dialog_title) .setMessage(R.string.delete_dialog_message) .setNegativeButton(R.string.cancel, null) .setPositiveButton( R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (note != null) { note.delete(); if (activity instanceof NotesActivity) { NotesActivity notesActivity = (NotesActivity) activity; if(notesActivity.getNoteListFragment() != null) { notesActivity.getNoteListFragment().updateSelectionAfterTrashAction(); } else { ((NotesActivity) activity).showDetailPlaceholder(); } } else if (activity instanceof NoteEditorActivity) { ((NoteEditorActivity) activity).finish(); } } else { DialogUtils.showDialogWithEmail( activity, activity.getString(R.string.delete_dialog_error_message) ); } } } ) .show(); }

Target:
public static void showDialogDeletePermanently(final Activity activity, final Note note) { new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Dialog)) .setTitle(R.string.delete_dialog_title) .setMessage(R.string.delete_dialog_message) .setNegativeButton(R.string.cancel, null) .setPositiveButton( R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (note != null) { note.delete(); if (activity instanceof NotesActivity) { NotesActivity notesActivity = (NotesActivity) activity; if (notesActivity.getNoteListFragment() != null) { notesActivity.getNoteListFragment().updateSelectionAfterTrashAction(); } else { notesActivity.showDetailPlaceholder(); } } else if (activity instanceof NoteEditorActivity) { ((NoteEditorActivity) activity).finish(); } } else { DialogUtils.showDialogWithEmail( activity, activity.getString(R.string.delete_dialog_error_message) ); } } } ) .show(); }
Source:
private boolean updateRngDevice() { if (!getParameters().isUpdateRngDevice()) { rngDeviceUtils.handleUrandomRandomChange( getParameters().getClusterLevelChangeFromVersion(), getCluster().getCompatibilityVersion(), getVmId(), cloneContextAndDetachFromParent(), true); return true; } VdcQueryReturnValue query = runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); List<VmRngDevice> rngDevs = query.getReturnValue(); VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = runInternalAction(VdcActionType.AddRngDevice, params, cloneContextAndDetachFromParent()); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = runInternalAction(VdcActionType.RemoveRngDevice, params, cloneContextAndDetachFromParent()); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = runInternalAction(VdcActionType.UpdateRngDevice, params, cloneContextAndDetachFromParent()); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { return false; } return true; }

Target:
private boolean updateRngDevice() { if (getParameters().isUpdateRngDevice()) { return regularUpdateRngDevice(); } rngDeviceUtils.handleUrandomRandomChange( getParameters().getClusterLevelChangeFromVersion(), getCluster().getCompatibilityVersion(), getVmId(), cloneContextAndDetachFromParent(), true); return true; }
Source:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { InfinispanConfiguration conf; if (configuration != null) { conf = configuration.copy(); } else { conf = new InfinispanConfiguration(); } String[] confParameters = new String[] {"hosts", "cacheContainerConfiguration", "configurationUri", "cacheContainer"}; if (!Arrays.stream(confParameters).anyMatch(parameters::containsKey) || setCacheFromComponent) { if (cacheContainer == null) { cacheContainer = new DefaultCacheManager(new GlobalConfigurationBuilder().defaultCacheName("default").build(), new org.infinispan.configuration.cache.ConfigurationBuilder().build()); setCacheFromComponent = false; } conf.setCacheContainer(cacheContainer); } else { conf.setCacheContainer(null); } InfinispanEndpoint endpoint = new InfinispanEndpoint(uri, remaining, this, conf); setProperties(endpoint, parameters); return endpoint; }

Target:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { InfinispanConfiguration conf; if (configuration != null) { conf = configuration.copy(); } else { conf = new InfinispanConfiguration(); } if (!isConfigProvided(parameters, conf) || setCacheFromComponent) { if (cacheContainer == null) { cacheContainer = new DefaultCacheManager(new GlobalConfigurationBuilder().defaultCacheName("default").build(), new org.infinispan.configuration.cache.ConfigurationBuilder().build()); setCacheFromComponent = false; log.debug("Default cacheContainer has been created"); } conf.setCacheContainer(cacheContainer); } else { conf.setCacheContainer(null); } InfinispanEndpoint endpoint = new InfinispanEndpoint(uri, remaining, this, conf); setProperties(endpoint, parameters); return endpoint; }
Source:
public EventProcessorAsyncClient createInstance() { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};" + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; EventProcessorAsyncClient eventProcessorAsyncClient = new EventHubClientBuilder() .connectionString(connectionString) .partitionProcessorFactory((PartitionProcessorImpl::new)) .consumerGroupName("consumer-group") .buildEventProcessorAsyncClient(); END: com.azure.messaging.eventhubs.eventprocessorasyncclient.instantiation return eventProcessorAsyncClient; }

Target:
public EventProcessorAsyncClient createInstance() { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};" + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; EventProcessorAsyncClient eventProcessorAsyncClient = new EventHubClientBuilder() .connectionString(connectionString) .partitionProcessorFactory((PartitionProcessorImpl::new)) .consumerGroupName("consumer-group") .buildEventProcessorAsyncClient(); END: com.azure.messaging.eventhubs.eventprocessorasyncclient.instantiation return eventProcessorAsyncClient; }
Source:
public void deleteExtraDownloadedFiles() { new Thread(new Runnable() { @Override public void run() { final ProfileModel profile = getEnvironment(MainApplication.this).getUserPrefs().getProfile(); final IDatabase db = getEnvironment(MainApplication.this).getDatabase(); if (profile != null) db.getAllVideos(Sha1Util.SHA1(profile.username), new DataCallback<List<VideoModel>>() { @Override public void onResult(List<VideoModel> result) { ArrayList<File> extraFiles = FileUtil.getAllFileFromExternalStorage(MainApplication.this, profile); FileUtil.deleteExtraFilesNotInDatabase(result, extraFiles); } @Override public void onFail(Exception ex) { Log.e(this.getClass().getSimpleName(), "Unable to get to get list of Videos" ); } }); } }).start(); }

Target:
public void deleteExtraDownloadedFiles() { new Thread(new Runnable() { @Override public void run() { final ProfileModel profile = getEnvironment(MainApplication.this).getUserPrefs().getProfile(); final IDatabase db = getEnvironment(MainApplication.this).getDatabase(); if (profile != null) { db.getAllVideos(Sha1Util.SHA1(profile.username), new DataCallback<List<VideoModel>>() { @Override public void onResult(List<VideoModel> result) { ArrayList<File> extraFiles = FileUtil.getAllFileFromExternalStorage(MainApplication.this, profile); FileUtil.deleteExtraFilesNotInDatabase(result, extraFiles); } @Override public void onFail(Exception ex) { Log.e(this.getClass().getSimpleName(), "Unable to get to get list of Videos" ); } }); } } }).start(); }
Source:
public void onError(int error) { if (error == 7) { changeUIStateToRetry(); } }

Target:
public void onError(int error) { if (error == SpeechRecognizer.ERROR_NO_MATCH) { changeUIStateToRetry(); } }
Source:
private void trackQuickActionCompleted(QuickActionTrackPropertyValue type) { Map<String, String> properties = new HashMap<>(1); properties.put("quick_action", type.toString()); AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_QUICK_ACTIONS_QUICKACTION_TOUCH, properties); }

Target:
private void trackQuickActionCompleted(QuickActionTrackPropertyValue type) { Map<String, String> properties = new HashMap<>(1); properties.put("quick_action", type.toString()); AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_QUICK_ACTIONS_QUICKACTION_TOUCHED, properties); AnalyticsTracker.flush(); }
Source:
public Response getCompleteTasks( @QueryParam("n") final Integer maxTaskStatuses, @Context final HttpServletRequest req ) { final Function<String, Task> taskFunction = taskId -> { final Optional<Task> optionalTask = taskStorageQueryAdapter.getTask(taskId); if (!optionalTask.isPresent()) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return optionalTask.get(); }; Function<TaskStatus, Iterable<ResourceAction>> raGenerator = taskStatus -> { final Task task = taskFunction.apply(taskStatus.getId()); return Lists.newArrayList( new ResourceAction( new Resource(task.getDataSource(), ResourceType.DATASOURCE), Action.READ ) ); }; final List<TaskStatus> recentlyFinishedTasks = Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, taskStorageQueryAdapter.getRecentlyFinishedTaskStatuses(maxTaskStatuses), raGenerator, authorizerMapper ) ); final List<TaskStatusPlus> completeTasks = recentlyFinishedTasks .stream() .map(status -> new TaskStatusPlus( status.getId(), taskFunction.apply(status.getId()).getType(), taskStorageQueryAdapter.getCreatedTime(status.getId()), DateTimes.EPOCH, status.getStatusCode(), status.getDuration(), TaskLocation.unknown(), taskStorageQueryAdapter.getTask(status.getId()).get().getDataSource() ) ) .collect(Collectors.toList()); return Response.ok(completeTasks).build(); }

Target:
public Response getCompleteTasks( @QueryParam("n") final Integer maxTaskStatuses, @Context final HttpServletRequest req ) { final Function<String, Task> taskFunction = taskId -> { final Optional<Task> optionalTask = taskStorageQueryAdapter.getTask(taskId); if (!optionalTask.isPresent()) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return optionalTask.get(); }; Function<TaskStatus, Iterable<ResourceAction>> raGenerator = taskStatus -> { final Task task = taskFunction.apply(taskStatus.getId()); return Lists.newArrayList( new ResourceAction( new Resource(task.getDataSource(), ResourceType.DATASOURCE), Action.READ ) ); }; final List<TaskStatus> recentlyFinishedTasks = Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, taskStorageQueryAdapter.getRecentlyFinishedTaskStatuses(maxTaskStatuses), raGenerator, authorizerMapper ) ); final List<TaskStatusPlus> completeTasks = Lists.newArrayList(Iterables.transform( recentlyFinishedTasks, status -> { final Pair<DateTime, String> pair = taskStorageQueryAdapter.getCreatedDateAndDataSource(status.getId()); return new TaskStatusPlus( status.getId(), taskFunction.apply(status.getId()).getType(), pair.lhs, DateTimes.EPOCH, status.getStatusCode(), status.getDuration(), TaskLocation.unknown(), pair.rhs); })); return Response.ok(completeTasks).build(); }
Source:
public int compare(ScanResultValue o1, ScanResultValue o2) { int comparison; if (scanQuery.getResultFormat().equals(ScanQuery.RESULT_FORMAT_LIST)) { comparison = Longs.compare( (Long) ((Map<String, Object>) ((List<Object>) o1.getEvents()).get(0)).get(ColumnHolder.TIME_COLUMN_NAME), (Long) ((Map<String, Object>) ((List<Object>) o2.getEvents()).get(0)).get(ColumnHolder.TIME_COLUMN_NAME) ); } else if (scanQuery.getResultFormat().equals(ScanQuery.RESULT_FORMAT_COMPACTED_LIST)) { int val1TimeColumnIndex = o1.getColumns().indexOf(ColumnHolder.TIME_COLUMN_NAME); int val2TimeColumnIndex = o2.getColumns().indexOf(ColumnHolder.TIME_COLUMN_NAME); List<Object> event1 = (List<Object>) ((List<Object>) o1.getEvents()).get(0); List<Object> event2 = (List<Object>) ((List<Object>) o2.getEvents()).get(0); comparison = Longs.compare( (Long) event1.get(val1TimeColumnIndex), (Long) event2.get(val2TimeColumnIndex) ); } else { throw new UOE("Result format [%s] is not supported", scanQuery.getResultFormat()); } if (scanQuery.getTimeOrder().equals(ScanQuery.TIME_ORDER_DESCENDING)) { return comparison * -1; } return comparison; }

Target:
public int compare(ScanResultValue o1, ScanResultValue o2) { int comparison; comparison = Longs.compare( o1.getFirstEventTimestamp(scanQuery), o2.getFirstEventTimestamp(scanQuery)); if (scanQuery.getTimeOrder().equals(ScanQuery.TimeOrder.DESCENDING)) { return comparison; } return comparison * -1; }
Source:
public static void notifyLocationChanged( final Iterable<Pair<TaskRunnerListener, Executor>> listeners, final String taskId, final TaskLocation location ) { log.info("Task [%s] location changed to [%s].", taskId, location); for (final Pair<TaskRunnerListener, Executor> listener : listeners) { try { listener.rhs.execute( new Runnable() { @Override public void run() { listener.lhs.locationChanged(taskId, location); } } ); } catch (Exception e) { log.warn(e, "Unable to notify listener for task[%s].", taskId); } } }

Target:
public static void notifyLocationChanged( final Iterable<Pair<TaskRunnerListener, Executor>> listeners, final String taskId, final TaskLocation location ) { log.info("Task [%s] location changed to [%s].", taskId, location); for (final Pair<TaskRunnerListener, Executor> listener : listeners) { try { listener.rhs.execute( new Runnable() { @Override public void run() { listener.lhs.locationChanged(taskId, location); } } ); } catch (Exception e) { log.makeAlert(e, "Unable to notify task listener") .addData("taskId", taskId) .addData("taskLocation", location) .addData("listener", listener.toString()) .emit(); } } }
Source:
private void assertCommandWithIdsIssued(String expectedCommand) throws MessagingException, IOException { ArgumentCaptor<String> commandPrefixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> commandSuffixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Set> commandUidsCaptor = ArgumentCaptor.forClass(Set.class); verify(imapConnection, atLeastOnce()).executeCommandWithIdSet( commandPrefixCaptor.capture(), commandSuffixCaptor.capture(), commandUidsCaptor.capture()); List<String> commandPrefixes = commandPrefixCaptor.getAllValues(); List<String> commandSuffixes = commandSuffixCaptor.getAllValues(); List<Set> commandUids = commandUidsCaptor.getAllValues(); for (int i = 0, end = commandPrefixes.size(); i < end; i++) { String command = commandPrefixes.get(i) + " " + ImapUtility.join(",", commandUids.get(i)) + " " + commandSuffixes.get(i); if (command.trim().equals(expectedCommand)) { return; } } fail("Expected IMAP command not issued: " + expectedCommand); }

Target:
private void assertCommandWithIdsIssued(String expectedCommand) throws MessagingException, IOException { ArgumentCaptor<String> commandPrefixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> commandSuffixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Set> commandUidsCaptor = ArgumentCaptor.forClass(Set.class); verify(imapConnection, atLeastOnce()).executeCommandWithIdSet( commandPrefixCaptor.capture(), commandSuffixCaptor.capture(), commandUidsCaptor.capture()); List<String> commandPrefixes = commandPrefixCaptor.getAllValues(); List<String> commandSuffixes = commandSuffixCaptor.getAllValues(); List<Set> commandUids = commandUidsCaptor.getAllValues(); for (int i = 0, end = commandPrefixes.size(); i < end; i++) { String command = commandPrefixes.get(i) + " " + ImapUtility.join(",", commandUids.get(i)) + ((commandSuffixes.get(i).length() == 0) ? "" : " " + commandSuffixes.get(i)); if (command.equals(expectedCommand)) { return; } } fail("Expected IMAP command not issued: " + expectedCommand); }
Source:
private void testSumOverSameGroup(int max, boolean fullGiraphEnv) throws Exception { TestGraphUtils.runTest( TestGraphUtils.chainModifiers( new Small1GraphInit<IntWritable, IntWritable, NullWritable>(), new EachVertexInit<>((vertex) -> vertex.getValue().set(- vertex.getId().get() % max))), (graph) -> { int[] sums = new int[max]; for (int i = 0; i < max; i ++) { sums[i] -= i; } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { sums[vtx.getId().get() % max] += vtx.getId().get(); } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { Assert.assertEquals(sums[vtx.getId().get() % max], vtx.getValue().get()); } }, (GiraphConfiguration conf) -> { BlockUtils.setBlockFactoryClass(conf, MessagesWithoutVerticesBlockFactory.class); TestGraphUtils.USE_FULL_GIRAPH_ENV_IN_TESTS.set(conf, fullGiraphEnv); }); }

Target:
private void testSumOverSameGroup(int max, boolean fullGiraphEnv) throws Exception { Int2IntFunction f = (id) -> id % max - 1; TestGraphUtils.runTest( TestGraphUtils.chainModifiers( new Small1GraphInit<IntWritable, IntWritable, NullWritable>(), new EachVertexInit<>((vertex) -> vertex.getValue().set(f.apply(vertex.getId().get())))), (graph) -> { Int2IntOpenHashMap sums = new Int2IntOpenHashMap(); for (int i = 0; i < max; i ++) { sums.addTo(f.apply(i), f.apply(i) + 1); } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { sums.addTo(f.apply(vtx.getId().get()), vtx.getId().get() + 1); } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { Assert.assertEquals(sums.get(f.apply(vtx.getId().get())), vtx.getValue().get()); } Assert.assertNull(graph.getVertex(-1)); }, (GiraphConfiguration conf) -> { BlockUtils.setBlockFactoryClass(conf, MessagesWithoutVerticesBlockFactory.class); TestGraphUtils.USE_FULL_GIRAPH_ENV_IN_TESTS.set(conf, fullGiraphEnv); }); }
Source:
public void init(Path configPath, Supplier<String> nodeName, Supplier<NodeContext> nodeContext) throws UncheckedNomadException { requireNonNull(configPath); requireNonNull(nodeName); requireNonNull(nodeContext); this.configurationManager = new NomadConfigurationManager(configPath, parameterSubstitutor); this.configurationManager.createDirectories(); DynamicConfigEventServiceImpl eventService = new DynamicConfigEventServiceImpl(); this.eventRegistrationService = eventService; this.eventFiringService = eventService; try { this.nomadServer = nomadServerFactory.createServer(getConfigurationManager(), null, nodeName.get(), getEventFiringService()); } catch (SanskritException | NomadException e) { throw new UncheckedNomadException("Exception initializing Nomad Server: " + e.getMessage(), e); } DynamicConfigServiceImpl dynamicConfigService = new DynamicConfigServiceImpl(nodeContext.get(), licenseService, this, objectMapperFactory); DynamicConfigListener auditListener = new AuditListener(); this.dynamicConfigService = new AuditService(dynamicConfigService, auditListener); this.topologyService = dynamicConfigService; getEventRegistrationService().register(dynamicConfigService); getEventRegistrationService().register(auditListener); LOGGER.info("Bootstrapped nomad system with root: {}", parameterSubstitutor.substitute(configPath.toString())); }

Target:
public void init(Path configPath, Supplier<String> nodeName, Supplier<NodeContext> nodeContext) throws UncheckedNomadException { requireNonNull(configPath); requireNonNull(nodeName); requireNonNull(nodeContext); this.configurationManager = new NomadConfigurationManager(configPath, parameterSubstitutor); this.configurationManager.createDirectories(); DynamicConfigEventServiceImpl eventService = new DynamicConfigEventServiceImpl(); this.eventRegistrationService = eventService; this.eventFiringService = eventService; try { this.nomadServer = nomadServerFactory.createServer(getConfigurationManager(), null, nodeName.get(), getEventFiringService()); } catch (SanskritException | NomadException e) { throw new UncheckedNomadException("Exception initializing Nomad Server: " + e.getMessage(), e); } DynamicConfigServiceImpl dynamicConfigService = new DynamicConfigServiceImpl(nodeContext.get(), licenseService, this, objectMapperFactory); this.dynamicConfigService = new AuditService(dynamicConfigService); this.topologyService = dynamicConfigService; getEventRegistrationService().register(dynamicConfigService); getEventRegistrationService().register(new AuditListener()); LOGGER.info("Bootstrapped nomad system with root: {}", parameterSubstitutor.substitute(configPath.toString())); }
Source:
public TaskStatus run(final TaskToolbox toolbox) throws Exception { try { if (useLegacy) { return runInternalLegacy(toolbox); } else { return runInternal(toolbox); } } catch (Exception e) { log.error(e, "Encountered exception while running task."); Map<String, Object> context = Maps.newHashMap(); List<String> savedParseExceptionMessages = IndexTask.getMessagesFromSavedParseExceptions(savedParseExceptions); if (savedParseExceptionMessages != null) { context.put("unparseableEvents", savedParseExceptionMessages); } return TaskStatus.failure( getId(), getTaskCompletionMetrics(), e.getMessage(), getTaskCompletionContext() ); } }

Target:
public TaskStatus run(final TaskToolbox toolbox) throws Exception { try { if (useLegacy) { return runInternalLegacy(toolbox); } else { return runInternal(toolbox); } } catch (Exception e) { log.error(e, "Encountered exception while running task."); errorMsg = Throwables.getStackTraceAsString(e); toolbox.getTaskReportFileWriter().write(getTaskCompletionReports()); return TaskStatus.failure( getId(), errorMsg ); } }
Source:
public void testInterfacesHierarchy() { Rule a = new NoOpRule(Pattern.matchByClass(A.class)); Rule b = new NoOpRule(Pattern.matchByClass(B.class)); Rule ab = new NoOpRule(Pattern.matchByClass(AB.class)); MatchingEngine matchingEngine = MatchingEngine.builder() .register(a) .register(b) .register(ab) .build(); assertEquals( matchingEngine.getCandidates(new A() {}).collect(toList()), ImmutableList.of(a)); assertEquals( matchingEngine.getCandidates(new B() {}).collect(toList()), ImmutableList.of(b)); assertEquals( matchingEngine.getCandidates(new AB()).collect(toList()), ImmutableList.of(ab, a, b)); }

Target:
public void testInterfacesHierarchy() { Rule a = new NoOpRule(Pattern.typeOf(A.class)); Rule b = new NoOpRule(Pattern.typeOf(B.class)); Rule ab = new NoOpRule(Pattern.typeOf(AB.class)); MatchingEngine matchingEngine = MatchingEngine.builder() .register(a) .register(b) .register(ab) .build(); assertEquals( matchingEngine.getCandidates(new A() {}).collect(toList()), ImmutableList.of(a)); assertEquals( matchingEngine.getCandidates(new B() {}).collect(toList()), ImmutableList.of(b)); assertEquals( matchingEngine.getCandidates(new AB()).collect(toList()), ImmutableList.of(ab, a, b)); }
Source:
private Credential getCredentialFromFlow(GoogleAuthorizationCodeFlow flow) throws IOException { return new AuthorizationCodeInstalledApp( flow, new LocalServerReceiver()).authorize("user"); }

Target:
private Credential getCredentialFromFlow(GoogleAuthorizationCodeFlow flow) throws IOException { return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(username); }
Source:
@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof VoltLogicalCalc && call.rel(1) instanceof VoltLogicalTableScan) { VoltLogicalCalc calc = call.rel(0); VoltLogicalTableScan tableScan = call.rel(1); RelDistributionUtils.checkedFallBack(! RelDistributionUtils.isCalcScanSP(tableScan, calc)); } else { RelNode child = call.rel(1); RelDistribution childDist = child.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { SingleRel node = call.rel(0); call.transformTo(node.copy(node.getTraitSet().replace(childDist), node.getInputs())); } } }

Target:
@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof VoltLogicalCalc && call.rel(1) instanceof VoltLogicalTableScan) { VoltLogicalCalc calc = call.rel(0); VoltLogicalTableScan tableScan = call.rel(1); final Pair<Boolean, RexNode> r = RelDistributionUtils.isCalcScanSP(tableScan, calc); final RelDistribution tableDist = tableScan.getTable().getDistribution() .with(r.getSecond(), r.getFirst()); call.transformTo(calc.copy(calc.getTraitSet().replace(tableDist), calc.getInputs())); } else { RelNode child = call.rel(1); RelDistribution childDist = child.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { SingleRel node = call.rel(0); call.transformTo(node.copy(node.getTraitSet().replace(childDist), node.getInputs())); } } }
Source:
public List<MarketDataFunction<?, ?>> marketDataFunctions() { return ImmutableList.of( DiscountCurveMarketDataFunction.INSTANCE, new RateIndexCurveMarketDataFunction(), DiscountFactorsMarketDataFunction.INSTANCE, new CurveGroupMarketDataFunction(RootFinderConfig.defaults()), new ParRatesMarketDataFunction()); }

Target:
public List<MarketDataFunction<?, ?>> marketDataFunctions() { return ImmutableList.of( new DiscountCurveMarketDataFunction(), new RateIndexCurveMarketDataFunction(), new DiscountFactorsMarketDataFunction(), new CurveGroupMarketDataFunction(RootFinderConfig.defaults()), new ParRatesMarketDataFunction()); }
Source:
private static List<File> getCardFolders() { File cardsDirectory = new File(SC_PATH); List<File> cardFolders = new ArrayList<>(); for (File card : Objects.requireNonNull(cardsDirectory.listFiles())) { if (card.getName().startsWith(CARD_FOLDER) && card.isDirectory()) { cardFolders.add(card); } } return cardFolders; }

Target:
private static List<File> getCardFolders() { File cardsDirectory = new File(SC_PATH); List<File> cardFolders = new ArrayList<>(); File[] allContents = cardsDirectory.listFiles(); if (allContents != null) { for (File card : allContents) { if (card.getName().startsWith(CARD_FOLDER) && card.isDirectory()) { cardFolders.add(card); } } } else { LOG.warn("Warning: No Audio Cards Found !"); } return cardFolders; }
Source:
public Page getPageByMappingKey(String mappingKey) throws PageNotFoundException { try { final SPageMapping sPageMapping = pageMappingService.get(mappingKey); return convertToPage(pageService.getPage(sPageMapping.getId())); } catch (final SBonitaReadException e) { throw new PageNotFoundException(e); } catch (final SObjectNotFoundException e) { throw new PageNotFoundException(mappingKey, PageAttribute.MAPPING_KEY); } }

Target:
public Page getPageByMappingKey(String mappingKey) throws PageNotFoundException { try { final SPageMapping sPageMapping = pageMappingService.get(mappingKey); return convertToPage(pageService.getPage(sPageMapping.getId())); } catch (final SBonitaReadException e) { throw new RetrieveException(String.format("Failed to retrieve a page mapping for %s", mappingKey)); } catch (final SObjectNotFoundException e) { throw new PageNotFoundException(e); } }
Source:
public void before() throws Exception { sourceTopic = SOURCE_TOPIC + "-" + testName.getMethodName(); CLUSTER.createTopic(sourceTopic); STREAMS_CONFIG.put(StreamsConfig.APPLICATION_ID_CONFIG, "ktable-restore-from-source-" + testName.getMethodName()); final KTable<String, String> kTable = streamsBuilder.table(sourceTopic, Materialized.as("store")); kTable.toStream().foreach(readKeyValues::put); expectedInitialResultsMap = createExpectedResultsMap("a", "b", "c"); expectedResultsWithDataWrittenDuringRestoreMap = createExpectedResultsMap("a", "b", "c", "d", "f", "g", "h"); }

Target:
public void before() throws Exception { sourceTopic = SOURCE_TOPIC + "-" + testName.getMethodName(); CLUSTER.createTopic(sourceTopic); STREAMS_CONFIG.put(StreamsConfig.APPLICATION_ID_CONFIG, IntegrationTestUtils.safeUniqueTestName(getClass(), testName)); final KTable<String, String> kTable = streamsBuilder.table(sourceTopic, Materialized.as("store")); kTable.toStream().foreach(readKeyValues::put); expectedInitialResultsMap = createExpectedResultsMap("a", "b", "c"); expectedResultsWithDataWrittenDuringRestoreMap = createExpectedResultsMap("a", "b", "c", "d", "f", "g", "h"); }
Source:
public List<Part> getProgress(File stateDir, String objectId) throws IOException { log.debug("Loading local progress for from {}", objectId, stateDir.toString()); ObjectSpecification spec = loadSpecification(stateDir, objectId); log.debug("Completed loading local object specification (meta file)"); for (Part part : spec.getParts()) { log.debug("Checking md5 for part {}", part.getPartNumber()); if (isCompleted(stateDir, objectId, part)) { Part completedPart = loadPart(stateDir, objectId, getPartName(part)); part.setMd5(completedPart.getMd5()); } } return spec.getParts(); }

Target:
public ObjectSpecification getProgress(File stateDir, String objectId) throws IOException { log.debug("Loading local progress for from {}", objectId, stateDir.toString()); ObjectSpecification spec = loadSpecification(stateDir, objectId); log.debug("Completed loading local object specification (meta file)"); for (Part part : spec.getParts()) { log.debug("Checking md5 for part {}", part.getPartNumber()); if (isCompleted(stateDir, objectId, part)) { Part completedPart = loadPart(stateDir, objectId, getPartName(part)); part.setMd5(completedPart.getMd5()); } } return spec; }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { Timber.d(data!=null?data.toString():""); super.onActivityResult(requestCode, resultCode, data); controller.handleActivityResult(this, requestCode, resultCode, data); }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { Timber.d(data!=null?data.toString():"onActivityResult data is null"); super.onActivityResult(requestCode, resultCode, data); controller.handleActivityResult(this, requestCode, resultCode, data); }
Source:
private void explode() throws IOException { destDir.mkdirs(); File explodeTime = new File(destDir,".timestamp2"); if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified()) return; Project p = new Project(); if (destDir.exists()) { Delete d = new Delete(); d.setProject(p); if (destDir.isDirectory()) d.setDir(destDir); else d.setFile(destDir); d.execute(); } Expand e = new Expand(); e.setProject(p); e.setTaskType("unzip"); e.setSrc(archive); e.setDest(destDir); e.execute(); if (new File(destDir,"WEB-INF/classes").exists()) { throw new IOException("Core override plugin cannot have WEB-INF/classes: "+destDir); } new FileOutputStream(explodeTime).close(); explodeTime.setLastModified(archive.lastModified()); }

Target:
private void explode() throws IOException { destDir.mkdirs(); File explodeTime = new File(destDir,".timestamp2"); if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified()) return; if (destDir.exists()) { if (destDir.isDirectory()) Files.walk(destDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); else destDir.delete(); } destDir.mkdirs(); try (JarFile jar = new JarFile(archive)) { Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(destDir + File.separator + file.getName()); if (file.isDirectory()) { f.mkdir(); continue; } try (InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f)) { while (is.available() > 0) { fos.write(is.read()); } } } } new FileOutputStream(explodeTime).close(); explodeTime.setLastModified(archive.lastModified()); }
Source:
public void testSuccceedForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(false)); assertTrue( "checkDisksNotInBackupStorage() succeed to run since there are no disks which are on a backup storage domain", command.checkDisksInBackupStorage()); }

Target:
public void testSuccceedForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(false)); assertFalse( "checkDisksNotInBackupStorage() succeed to run since there are no disks which are on a backup storage domain", command.checkDisksInBackupStorage()); }
Source:
HttpUnsuccessfulResponseHandler getHttpUnsuccessfulResponseHandler(Message message) { return (request, response, supportsRetry) -> { String redirectLocation = response.getHeaders().getLocation(); if (isRedirect(request, response, redirectLocation)) { String method = (String) message.get(Message.HTTP_REQUEST_METHOD); HttpContent content = null; if (!isRedirectable(method)) { try (TemporaryFileBackedOutputStream tfbos = new TemporaryFileBackedOutputStream()) { message.setContent(OutputStream.class, tfbos); BodyWriter bodyWriter = new BodyWriter(); bodyWriter.handleMessage(message); ByteSource byteSource = tfbos.asByteSource(); content = new InputStreamContent(method, byteSource.openStream()) .setLength(byteSource.size()); } } request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation))); request.setRequestMethod(method); request.setContent(content); request.getHeaders().setAuthorization((String) null); request.getHeaders().setIfMatch(null); request.getHeaders().setIfNoneMatch(null); request.getHeaders().setIfModifiedSince(null); request.getHeaders().setIfUnmodifiedSince(null); request.getHeaders().setIfRange(null); request .getHeaders() .setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0)); Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS); headers.forEach((key, value) -> request.getHeaders().set(key, value)); return true; } return false; }; }

Target:
HttpUnsuccessfulResponseHandler getHttpUnsuccessfulResponseHandler(Message message) { return (request, response, supportsRetry) -> { String redirectLocation = response.getHeaders().getLocation(); if (isRedirect(request, response, redirectLocation)) { String method = (String) message.get(Message.HTTP_REQUEST_METHOD); HttpContent content = null; if (!isRedirectable(method)) { try (TemporaryFileBackedOutputStream tfbos = new TemporaryFileBackedOutputStream()) { message.setContent(OutputStream.class, tfbos); BodyWriter bodyWriter = new BodyWriter(); bodyWriter.handleMessage(message); ByteSource byteSource = tfbos.asByteSource(); content = new InputStreamContent( (String) message.get(Message.CONTENT_TYPE), byteSource.openStream()) .setLength(byteSource.size()); } } request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation))); request.setRequestMethod(method); request.setContent(content); request.getHeaders().setAuthorization((String) null); request.getHeaders().setIfMatch(null); request.getHeaders().setIfNoneMatch(null); request.getHeaders().setIfModifiedSince(null); request.getHeaders().setIfUnmodifiedSince(null); request.getHeaders().setIfRange(null); request .getHeaders() .setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0)); Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS); headers.forEach((key, value) -> request.getHeaders().set(key, value)); return true; } return false; }; }
Source:
public List<OskariLayer> cleanupLayerReferences(int layerId) throws ActionException { List<OskariLayer> layers = mapLayerService.findAll(); for (OskariLayer layer : layers) { JSONObject options = layer.getOptions(); try { if (options != null && options.has("timeseries")) { JSONObject timeseriesOptions = options.getJSONObject("timeseries"); JSONObject timeseriesMetadata = timeseriesOptions.optJSONObject("metadata"); if (timeseriesMetadata == null) { continue; } Integer metadataLayerId = timeseriesMetadata.getInt("layer"); if (metadataLayerId == layerId) { options.remove("timeseries"); layer.setOptions(options); mapLayerService.update(layer); } } } catch (JSONException e) { throw new ActionException("Cannot parse layer metadata options for layer: " + layer.getName() + ", id: " + layer.getId()); } } return layers; }

Target:
public List<OskariLayer> cleanupLayerReferences(int layerId) throws ActionException { Set<OskariLayer> layers = LayerAdminHelper.getTimeseriesReferencedLayers(layerId, mapLayerService.findAll()); for (OskariLayer layer : layers) { JSONObject options = layer.getOptions(); options.remove("timeseries"); layer.setOptions(options); mapLayerService.update(layer); } return new ArrayList<>(layers); }
Source:
private IEMFCompareConfiguration createConfiguration(boolean leftEditable, boolean rightEditable) { CompareConfiguration cc = new CompareConfiguration(); cc.setProperty("MIRRORED", Boolean.TRUE); cc.setLeftEditable(leftEditable); cc.setRightEditable(rightEditable); EMFCompareConfiguration emfCC = new EMFCompareConfiguration(cc); emfCC.setEditingDomain(editingDomain); return emfCC; }

Target:
private IEMFCompareConfiguration createConfiguration(boolean leftEditable, boolean rightEditable) { CompareConfiguration cc = new CompareConfiguration(); cc.setProperty(EMFCompareConfiguration.MIRRORED, Boolean.TRUE); cc.setLeftEditable(leftEditable); cc.setRightEditable(rightEditable); EMFCompareConfiguration emfCC = new EMFCompareConfiguration(cc); emfCC.setEditingDomain(editingDomain); return emfCC; }
Source:
public String disableExtension(String extensionName, String currentUser) { validateExtensionName(extensionName); try { return ExtensionStore.get().disableExtension(extensionName, currentUser); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }

Target:
public String disableExtension(String extensionName, String currentUser) { validateExtensionName(extensionName); try { return ExtensionStore.get().updateExtensionStatus(extensionName, currentUser, ExtensionStatus.DISABLED); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
public void run() { if (!CentralRepository.isEnabled()) return; if (Case.Events.valueOf(event.getPropertyName()) == Case.Events.CONTENT_TAG_ADDED) { handleTagAdded((ContentTagAddedEvent) event); } else { handleTagDeleted((ContentTagDeletedEvent) event); } }

Target:
public void run() { if (!CentralRepository.isEnabled()) { return; } Case.Events curEventType = Case.Events.valueOf(event.getPropertyName()); if (curEventType == Case.Events.CONTENT_TAG_ADDED && event instanceof ContentTagAddedEvent) { handleTagAdded((ContentTagAddedEvent) event); } else if (curEventType == Case.Events.CONTENT_TAG_DELETED && event instanceof ContentTagDeletedEvent) { handleTagDeleted((ContentTagDeletedEvent) event); } else { LOGGER.log(Level.WARNING, String.format("Received an event %s of type %s and was expecting either CONTENT_TAG_ADDED or CONTENT_TAG_DELETED.", event, curEventType)); } }
Source:
protected void sendDatastreamProducerRecord(DatastreamProducerRecord datastreamProducerRecord, TopicPartition srcTopicPartition, int numBytes, SendCallback sendCallback) { _producer.send(datastreamProducerRecord, ((metadata, exception) -> { if (exception != null) { _logger.warn("Detect exception being throw from callback for src partition: while sending producer " + "record, metadata: {}, exception: ", srcTopicPartition, metadata, exception); rewindAndPausePartitionOnException(srcTopicPartition, exception); } else { _consumerMetrics.updateBytesProcessedRate(numBytes); } if (sendCallback != null) { sendCallback.onCompletion(metadata, exception); } })); }

Target:
protected void sendDatastreamProducerRecord(DatastreamProducerRecord datastreamProducerRecord, TopicPartition srcTopicPartition, int numBytes, SendCallback sendCallback) { _producer.send(datastreamProducerRecord, ((metadata, exception) -> { if (exception != null) { String msg = String.format("Detect exception being thrown from callback for src partition: %s while " + "sending, metadata: %s , exception: ", srcTopicPartition, metadata); _logger.warn(msg, exception); rewindAndPausePartitionOnException(srcTopicPartition, exception); } else { _consumerMetrics.updateBytesProcessedRate(numBytes); } if (sendCallback != null) { sendCallback.onCompletion(metadata, exception); } })); }
Source:
String getSignedUrl(RestRequest restRequest) throws RestServiceException; boolean isRequestSigned(RestRequest restRequest); void verifySignedRequest(RestRequest restRequest, Callback<Void> callback); default Future<Void> verifySignedRequest(RestRequest restRequest) { FutureResult<Void> futureResult = new FutureResult<>(); verifySignedRequest(restRequest, futureResult::done); return futureResult; }

Target:
String getSignedUrl(RestRequest restRequest) throws RestServiceException; boolean isRequestSigned(RestRequest restRequest); void verifySignedRequest(RestRequest restRequest) throws RestServiceException; default void verifySignedRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; try { verifySignedRequest(restRequest); } catch (Exception e) { exception = e; } finally { callback.onCompletion(null, exception); } }
Source:
public void testSanity() throws Exception { List<Range<Double>> ranges = Arrays.asList( Range.create(0d, true, 10d, false), Range.create(10d, true, 20d, true)); StreamingSampleStats s1 = new StreamingSampleStats(); s1.setStatistic(Statistic.MEAN); s1.addRange(ranges.get(0)); s1.offer(10d); StreamingSampleStats s2 = new StreamingSampleStats(); s2.setStatistic(Statistic.MEAN); s2.addRange(ranges.get(0)); s2.offer(10d); StreamingSampleStats[] stats = new StreamingSampleStats[] {s1,s2}; ClassificationStats classStats = new FeatureClassStats.Results(ranges, stats); ClassificationStatsPPIO ppio = new ClassificationStatsPPIO(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ppio.encode(classStats, bout); System.out.println(new String(bout.toByteArray())); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(bout.toByteArray())); assertEquals("Results", doc.getDocumentElement().getNodeName()); XMLAssert.assertXpathExists("/Results/Class[@lowerBound='0.0']", doc); XMLAssert.assertXpathExists("/Results/Class[@lowerBound='10.0']", doc); }

Target:
public void testSanity() throws Exception { List<Range<Double>> ranges = Arrays.asList( Range.create(0d, true, 10d, false), Range.create(10d, true, 20d, true)); StreamingSampleStats s1 = new StreamingSampleStats(); s1.setStatistic(Statistic.MEAN); s1.addRange(ranges.get(0)); s1.offer(10d); StreamingSampleStats s2 = new StreamingSampleStats(); s2.setStatistic(Statistic.MEAN); s2.addRange(ranges.get(0)); s2.offer(10d); StreamingSampleStats[] stats = new StreamingSampleStats[] {s1,s2}; ClassificationStats classStats = new FeatureClassStats.Results(ranges, stats); ClassificationStatsPPIO ppio = new ClassificationStatsPPIO(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ppio.encode(classStats, bout); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(bout.toByteArray())); assertEquals("Results", doc.getDocumentElement().getNodeName()); XMLAssert.assertXpathExists("/Results/Class[@lowerBound='0.0']", doc); XMLAssert.assertXpathExists("/Results/Class[@lowerBound='10.0']", doc); }
Source:
protected void onPostExecute(Boolean result) { String media_message=media.getDisplayTitle(); String title_resource = context.getResources().getString(R.string.nominating_for_deletion); String success_resource = context.getResources().getString(R.string.success); String message_resource = context.getResources().getString(R.string.message,media_message); String failed_resource = context.getResources().getString(R.string.failed); String could_not_request_deletion_resource = context.getResources().getString(R.string.could_not_request_deletion); String message; String title = title_resource; if (result){ title += ":"+success_resource; message = message_resource; } else { title += ":"+failed_resource; message = could_not_request_deletion_resource; } notificationBuilder.setDefaults(DEFAULT_ALL) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setSmallIcon(R.drawable.ic_launcher) .setProgress(0,0,false) .setOngoing(false) .setPriority(PRIORITY_HIGH); String urlForDelete = BuildConfig.COMMONS_URL + "/wiki/Commons:Deletion_requests/File:" + media.getFilename(); Intent browserIntent = new Intent(Intent.ACTION_VIEW , Uri.parse(urlForDelete)); PendingIntent pendingIntent = PendingIntent.getActivity(context , 1 , browserIntent , PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.setContentIntent(pendingIntent); notificationManager.notify(NOTIFICATION_DELETE, notificationBuilder.build()); }

Target:
protected void onPostExecute(Boolean result) { String mediaMessage=media.getDisplayTitle(); String fullColon=":"; String titleResource = context.getResources().getString(R.string.nominating_for_deletion); String successResource = context.getResources().getString(R.string.success,titleResource,fullColon); String messageResource = context.getResources().getString(R.string.message,mediaMessage); String failedResource = context.getResources().getString(R.string.failed,titleResource,fullColon); String couldRequest_deletion_resource = context.getResources().getString(R.string.could_not_request_deletion); String message; String title; if (result){ title = successResource; message = messageResource; } else { title = failedResource; message = couldRequest_deletion_resource; } notificationBuilder.setDefaults(DEFAULT_ALL) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setSmallIcon(R.drawable.ic_launcher) .setProgress(0,0,false) .setOngoing(false) .setPriority(PRIORITY_HIGH); String urlForDelete = BuildConfig.COMMONS_URL + "/wiki/Commons:Deletion_requests/File:" + media.getFilename(); Intent browserIntent = new Intent(Intent.ACTION_VIEW , Uri.parse(urlForDelete)); PendingIntent pendingIntent = PendingIntent.getActivity(context , 1 , browserIntent , PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.setContentIntent(pendingIntent); notificationManager.notify(NOTIFICATION_DELETE, notificationBuilder.build()); }