auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testDirValidation() throws Exception { CommandStringBuilder csb = new CommandStringBuilder(CliStrings.DESCRIBE_OFFLINE_DISK_STORE); csb.addOption(CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, DISK_STORE_NAME); csb.addOption(CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, "wrongDiskDir"); String commandString = csb.toString(); gfsh.executeAndAssertThat(commandString).statusIsError() .containsOutput("Could not find disk-dirs: \"wrongDiskDir"); }

Target:
public void testDirValidation() { CommandStringBuilder csb = new CommandStringBuilder(CliStrings.DESCRIBE_OFFLINE_DISK_STORE); csb.addOption(CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, DISK_STORE_NAME); csb.addOption(CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, "wrongDiskDir"); String commandString = csb.toString(); gfsh.executeAndAssertThat(commandString).statusIsError() .containsOutput("Could not find disk-dirs: \"wrongDiskDir"); }
Source:
public void updateSchedulePlanWritesCriteria() { SchedulePlan update = SchedulePlan.create(); update.setGuid(schedulePlan.getGuid()); update.setLabel(schedulePlan.getLabel()); update.setStudyKey(schedulePlan.getStudyKey()); Schedule schedule = TestUtils.getSchedule("My Schedule"); Criteria criteria = TestUtils.createCriteria(100, 200, ALL_OF_GROUPS, NONE_OF_GROUPS); criteria.setKey("scheduleCriteria:"+schedulePlan.getGuid()+":0"); CriteriaScheduleStrategy strategy = new CriteriaScheduleStrategy(); ScheduleCriteria scheduleCriteria = new ScheduleCriteria(schedule, criteria); strategy.getScheduleCriteria().add(scheduleCriteria); update.setStrategy(strategy); ArgumentCaptor<Criteria> criteriaCaptor = ArgumentCaptor.forClass(Criteria.class); SchedulePlan updated = dao.updateSchedulePlan(TEST_STUDY, update); strategy = (CriteriaScheduleStrategy)updated.getStrategy(); strategy.getScheduleCriteria().get(0).getCriteria(); scheduleCriteria = strategy.getScheduleCriteria().get(0); Criteria returnedCriteria = scheduleCriteria.getCriteria(); assertEquals(new Integer(100), returnedCriteria.getMinAppVersion(IOS)); assertEquals(new Integer(200), returnedCriteria.getMaxAppVersion(IOS)); verify(criteriaDao).createOrUpdateCriteria(criteriaCaptor.capture()); Criteria updatedCriteria = criteriaCaptor.getValue(); assertEquals(new Integer(100), updatedCriteria.getMinAppVersion(IOS)); assertEquals(new Integer(200), updatedCriteria.getMaxAppVersion(IOS)); }

Target:
public void updateSchedulePlanWritesCriteria() { mockSchedulePlanQuery(); SchedulePlan update = SchedulePlan.create(); update.setGuid(schedulePlan.getGuid()); update.setLabel(schedulePlan.getLabel()); update.setStudyKey(schedulePlan.getStudyKey()); Schedule schedule = TestUtils.getSchedule("My Schedule"); Criteria criteria = TestUtils.createCriteria(100, 200, ALL_OF_GROUPS, NONE_OF_GROUPS); criteria.setKey("scheduleCriteria:"+schedulePlan.getGuid()+":0"); CriteriaScheduleStrategy strategy = new CriteriaScheduleStrategy(); ScheduleCriteria scheduleCriteria = new ScheduleCriteria(schedule, criteria); strategy.getScheduleCriteria().add(scheduleCriteria); update.setStrategy(strategy); ArgumentCaptor<Criteria> criteriaCaptor = ArgumentCaptor.forClass(Criteria.class); SchedulePlan updated = dao.updateSchedulePlan(TEST_STUDY, update); strategy = (CriteriaScheduleStrategy)updated.getStrategy(); scheduleCriteria = strategy.getScheduleCriteria().get(0); Criteria returnedCriteria = scheduleCriteria.getCriteria(); assertEquals(new Integer(100), returnedCriteria.getMinAppVersion(IOS)); assertEquals(new Integer(200), returnedCriteria.getMaxAppVersion(IOS)); verify(criteriaDao).createOrUpdateCriteria(criteriaCaptor.capture()); Criteria updatedCriteria = criteriaCaptor.getValue(); assertEquals(new Integer(100), updatedCriteria.getMinAppVersion(IOS)); assertEquals(new Integer(200), updatedCriteria.getMaxAppVersion(IOS)); }
Source:
public void testPermissionsForAddingTemplateDedicatedHostNotChanged(){ setupDedicatedHostForVmAndTemplate(true); List<PermissionSubject> permissionCheckSubjects = cmd.getPermissionCheckSubjects(); for(PermissionSubject permissionSubject : permissionCheckSubjects){ assertFalse(ActionGroup.EDIT_ADMIN_TEMPLATE_PROPERTIES.equals(permissionSubject.getActionGroup())); } }

Target:
public void testPermissionsForAddingTemplateDedicatedHostNotChanged(){ setupDedicatedHostForVmAndTemplate(true); List<PermissionSubject> permissionCheckSubjects = cmd.getPermissionCheckSubjects(); for(PermissionSubject permissionSubject : permissionCheckSubjects){ assertFalse(ActionGroup.EDIT_ADMIN_TEMPLATE_PROPERTIES == permissionSubject.getActionGroup()); } }
Source:
private static Limiter<Void> newLimiter() { return DefaultLimiter.newBuilder() .limit(TracingLimitDecorator.wrap(AIMDLimit.newBuilder().initialLimit(1).build())) .build(new SimpleStrategy<>()); }

Target:
private Limiter<Void> newLimiter() { Limiter<Void> limiter = new InstrumentedLimiter(SimpleLimiter.newBuilder() .limit(new RemotingWindowedLimit(VegasLimit.newDefault())) .build(), slowAcquire); return RemotingBlockingLimiter.wrap(limiter, timeout); }
Source:
protected List<Image> execute(ListImagesCmd command) { WebTarget webTarget = getBaseResource().path("/images/json"); webTarget = booleanQueryParam(webTarget, "all", command.hasShowAllEnabled()); if (command.getFilters() != null) webTarget = webTarget.queryParam("filters", urlPathSegmentEscaper().escape(command.getFilters())); LOGGER.trace("GET: {}", webTarget); List<Image> images = webTarget.request().accept(MediaType.APPLICATION_JSON) .get(new TypeReference<List<Image>>() { }).awaitResult(); LOGGER.trace("Response: {}", images); return images; }

Target:
protected List<Image> execute(ListImagesCmd command) { WebTarget webTarget = getBaseResource().path("/images/json"); webTarget = booleanQueryParam(webTarget, "all", command.hasShowAllEnabled()); if (command.getFilters() != null) { webTarget = webTarget.queryParam("filters", urlPathSegmentEscaper().escape(command.getFilters())); } LOGGER.trace("GET: {}", webTarget); List<Image> images = webTarget.request().accept(MediaType.APPLICATION_JSON) .get(new TypeReference<List<Image>>() { }); LOGGER.trace("Response: {}", images); return images; }
Source:
private void refreshTokenNormal() { setTokenExpire(); try { mAuthContext = new AuthenticationContext(ToDoActivity.this, Constants.AUTHORITY_URL, false); txtSummary.setText("TODO Services sending services..."); getToken(new AuthenticationCallback<AuthenticationResult>() { @Override public void onError(Exception exc) { Log.e(TAG, "refreshTokenNormal error" + exc.getMessage(), exc); Toast.makeText(getApplicationContext(), exc.getMessage(), Toast.LENGTH_LONG) .show(); } @Override public void onSuccess(AuthenticationResult result) { if (result.getAccessToken() != null && !result.getAccessToken().isEmpty() && result.getRefreshToken() != null && !result.getRefreshToken().isEmpty()) { Log.d(TAG, "refreshTokenNormal onSuccess"); } else { Log.d(TAG, "refreshTokenNormal Problem...."); } Toast.makeText(getApplicationContext(), "OnCompleted", Toast.LENGTH_LONG) .show(); txtSummary.setText("TODO Services refreshed"); setLocalToken(result); } }); } catch (Exception e) { Log.e(TAG, "Refresh token normal error", e); Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }

Target:
private void refreshTokenNormal() { setTokenExpire(); try { mAuthContext = new AuthenticationContext(ToDoActivity.this, Constants.AUTHORITY_URL, false); txtSummary.setText("TODO Services sending services..."); getToken(new AuthenticationCallback<AuthenticationResult>() { @Override public void onError(Exception exc) { Log.e(TAG, "refreshTokenNormal error" + exc.getMessage(), exc); Toast.makeText(getApplicationContext(), exc.getMessage(), Toast.LENGTH_LONG) .show(); } @Override public void onSuccess(AuthenticationResult result) { if (isNotEmpty(result.getAccessToken()) && isNotEmpty(result.getRefreshToken())) { Log.d(TAG, "refreshTokenNormal onSuccess"); } else { Log.d(TAG, "refreshTokenNormal Problem...."); } Toast.makeText(getApplicationContext(), "OnCompleted", Toast.LENGTH_LONG) .show(); txtSummary.setText("TODO Services refreshed"); setLocalToken(result); } }); } catch (Exception e) { Log.e(TAG, "Refresh token normal error", e); Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } }
Source:
public synchronized @Nullable PcapOldPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException { SeekableByteChannel fFileChannel = getFileChannel(); if (fFileChannel.size() - fFileChannel.position() == 0) { return null; } if (fFileChannel.size() - fFileChannel.position() < PcapFileValues.PACKET_HEADER_SIZE) { throw new BadPcapFileException("A pcap header is invalid."); } ByteOrder byteOrder = getByteOrder(); ByteBuffer pcapPacketHeader = ByteBuffer.allocate(PcapFileValues.PACKET_HEADER_SIZE); pcapPacketHeader.clear(); pcapPacketHeader.order(byteOrder); fFileChannel.read(pcapPacketHeader); pcapPacketHeader.flip(); pcapPacketHeader.position(PcapFileValues.INCLUDED_LENGTH_POSITION); long includedPacketLength = ConversionHelper.unsignedIntToLong(pcapPacketHeader.getInt()); if (fFileChannel.size() - fFileChannel.position() < includedPacketLength) { throw new BadPcapFileException("A packet header is invalid."); } if (includedPacketLength > Integer.MAX_VALUE) { throw new BadPacketException("Packets that are bigger than 2^31-1 bytes are not supported."); } ByteBuffer pcapPacketData = ByteBuffer.allocate((int) includedPacketLength); pcapPacketData.clear(); fFileChannel.read(pcapPacketData); pcapPacketData.flip(); TreeMap<Long, Long> fFileIndex = getFileIndex(); fFileIndex.put(++currentRank, fFileChannel.position()); setCurrentRank(currentRank); return new PcapOldPacket(this, null, pcapPacketHeader, pcapPacketData, currentRank - 1); }

Target:
public synchronized @Nullable PcapOldPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException { SeekableByteChannel fFileChannel = getFileChannel(); if (fFileChannel.size() - fFileChannel.position() == 0) { return null; } if (fFileChannel.size() - fFileChannel.position() < PcapFileValues.PACKET_HEADER_SIZE) { throw new BadPcapFileException("A pcap header is invalid."); } ByteOrder byteOrder = getByteOrder(); ByteBuffer pcapPacketHeader = ByteBuffer.allocate(PcapFileValues.PACKET_HEADER_SIZE); pcapPacketHeader.clear(); pcapPacketHeader.order(byteOrder); fFileChannel.read(pcapPacketHeader); pcapPacketHeader.flip(); pcapPacketHeader.position(PcapFileValues.INCLUDED_LENGTH_POSITION); long includedPacketLength = ConversionHelper.unsignedIntToLong(pcapPacketHeader.getInt()); if (fFileChannel.size() - fFileChannel.position() < includedPacketLength) { throw new BadPcapFileException("A packet header is invalid."); } if (includedPacketLength > Integer.MAX_VALUE) { throw new BadPacketException("Packets that are bigger than 2^31-1 bytes are not supported."); } ByteBuffer pcapPacketData = ByteBuffer.allocate((int) includedPacketLength); pcapPacketData.clear(); fFileChannel.read(pcapPacketData); pcapPacketData.flip(); TreeMap<Long, Long> fFileIndex = getFileIndex(); setCurrentRank(getCurrentRank()+1); fFileIndex.put(getCurrentRank(), fFileChannel.position()); return new PcapOldPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); }
Source:
public void generatedVersion2ShouldDecodeLegacyFormat() { final LegacySubscriptionInfoSerde info = new LegacySubscriptionInfoSerde( 2, LATEST_SUPPORTED_VERSION, processId, ACTIVE_TASKS, STANDBY_TASKS, "localhost:80", null ); final ByteBuffer buffer = info.encode(); buffer.rewind(); final SubscriptionInfo decoded = SubscriptionInfo.decode(buffer); assertEquals(2, decoded.version()); assertEquals(SubscriptionInfo.UNKNOWN, decoded.latestSupportedVersion()); assertEquals(processId, decoded.processId()); assertEquals(ACTIVE_TASKS, decoded.prevTasks()); assertEquals(STANDBY_TASKS, decoded.standbyTasks()); assertEquals("localhost:80", decoded.userEndPoint()); }

Target:
public void generatedVersion2ShouldDecodeLegacyFormat() { final LegacySubscriptionInfoSerde info = new LegacySubscriptionInfoSerde( 2, LATEST_SUPPORTED_VERSION, processId, ACTIVE_TASKS, STANDBY_TASKS, "localhost:80" ); final ByteBuffer buffer = info.encode(); buffer.rewind(); final SubscriptionInfo decoded = SubscriptionInfo.decode(buffer); assertEquals(2, decoded.version()); assertEquals(SubscriptionInfo.UNKNOWN, decoded.latestSupportedVersion()); assertEquals(processId, decoded.processId()); assertEquals(ACTIVE_TASKS, decoded.prevTasks()); assertEquals(STANDBY_TASKS, decoded.standbyTasks()); assertEquals("localhost:80", decoded.userEndPoint()); }
Source:
private void initialize(final PluginManager pm, final Plugin essPlugin) { getLogger().log(Level.INFO, "Continuing to enable Protect."); ess = new EssentialsConnect(essPlugin, this); final EssentialsProtectBlockListener blockListener = new EssentialsProtectBlockListener(this); pm.registerEvents(blockListener, this); final EssentialsProtectEntityListener entityListener = new EssentialsProtectEntityListener(this); pm.registerEvents(entityListener, this); if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_13_2_R01)) { final EssentialsProtectEntityListener_1_13_R1 entityListener1_13_2_r1 = new EssentialsProtectEntityListener_1_13_R1(this); pm.registerEvents(entityListener1_13_2_r1, this); } if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_14_R01)) { final EssentialsProtectEntityListener_1_14_R1 entityListener_1_14_r1 = new EssentialsProtectEntityListener_1_14_R1(this); pm.registerEvents(entityListener_1_14_r1, this); } if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_16_1_R01)) { final EssentialsProtectBlockListener_1_16_R1 blockListener_1_16_r1 = new EssentialsProtectBlockListener_1_16_R1(this); pm.registerEvents(blockListener_1_16_r1, this); } final EssentialsProtectWeatherListener weatherListener = new EssentialsProtectWeatherListener(this); pm.registerEvents(weatherListener, this); }

Target:
private void initialize(final PluginManager pm, final Plugin essPlugin) { getLogger().log(Level.INFO, "Continuing to enable Protect."); ess = new EssentialsConnect(essPlugin, this); final EssentialsProtectBlockListener blockListener = new EssentialsProtectBlockListener(this); pm.registerEvents(blockListener, this); final EssentialsProtectEntityListener entityListener = new EssentialsProtectEntityListener(this); pm.registerEvents(entityListener, this); if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_13_2_R01)) { final EssentialsProtectEntityListener_1_13_2_R1 entityListener_1_13_2_r1 = new EssentialsProtectEntityListener_1_13_2_R1(this); pm.registerEvents(entityListener_1_13_2_r1, this); } if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_14_R01)) { final EssentialsProtectEntityListener_1_14_R1 entityListener_1_14_r1 = new EssentialsProtectEntityListener_1_14_R1(this); pm.registerEvents(entityListener_1_14_r1, this); } if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_16_1_R01)) { final EssentialsProtectBlockListener_1_16_R1 blockListener_1_16_r1 = new EssentialsProtectBlockListener_1_16_R1(this); pm.registerEvents(blockListener_1_16_r1, this); } final EssentialsProtectWeatherListener weatherListener = new EssentialsProtectWeatherListener(this); pm.registerEvents(weatherListener, this); }
Source:
public String getAuthHeaderNullable(@Nullable AuthHeader value) { return value == null ? "" : value.toString(); }

Target:
public String getAuthHeaderNullable(@Nullable AuthHeader value) { return value == null ? "[no value]" : value.toString(); }
Source:
public void testOnChat() throws Exception { instance.chatButton.pseudoClassStateChanged(PseudoClass.getPseudoClass("highlighted"), true); instance.onChat(new ActionEvent(instance.chatButton, Event.NULL_SOURCE_TARGET)); assertThat(instance.chatButton.getPseudoClassStates().contains(PseudoClass.getPseudoClass("highlighted")), is(false)); }

Target:
public void testOnChat() throws Exception { instance.chatButton.pseudoClassStateChanged(HIGHLIGHTED, true); instance.onChat(new ActionEvent(instance.chatButton, Event.NULL_SOURCE_TARGET)); assertThat(instance.chatButton.getPseudoClassStates().contains(HIGHLIGHTED), is(false)); }
Source:
private static void assertNumberOfThreadsReasonable(int startingThreads, int threadCount, boolean nonLeaderDown) { int threadLimit = startingThreads + 1000; if (nonLeaderDown) { if (threadCount > threadLimit) { System.out.println("hello"); } assertThat(threadCount) .as("should not additionally spin up too many threads after a non-leader failed") .isLessThanOrEqualTo(threadLimit); } else { assertThat(threadCount) .as("should not additionally spin up too many threads in the absence of failures") .isLessThanOrEqualTo(threadLimit); } }

Target:
private static void assertNumberOfThreadsReasonable(int startingThreads, int threadCount, boolean nonLeaderDown) { int threadLimit = startingThreads + 1000; if (nonLeaderDown) { assertThat(threadCount) .as("should not additionally spin up too many threads after a non-leader failed") .isLessThanOrEqualTo(threadLimit); } else { assertThat(threadCount) .as("should not additionally spin up too many threads in the absence of failures") .isLessThanOrEqualTo(threadLimit); } }
Source:
public void binderDied() { if (DBG) { Slog.d(TAG, "Binder is dead - unregister " + mPackageName); } Iterator<IBinder> list_iterator = mBleApps.keySet().iterator(); while (list_iterator.hasNext()) { IBinder token = list_iterator.next(); ClientDeathRecipient deathRec = mBleApps.get(token); if (deathRec.equals(this)) { if (DBG) { Slog.d(TAG, "Remove this BLE app " + mPackageName); } mBleApps.remove(token); break; } } if (isBleAppPresent()) { return; } if (DBG) { Slog.d(TAG, "Disabling LE only mode after application crash"); } try { mBluetoothLock.readLock().lock(); if (mBluetooth != null && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) { mEnable = false; mBluetooth.onBrEdrDown(); } } catch (RemoteException e) { Slog.e(TAG, "Unable to call onBrEdrDown", e); } finally { mBluetoothLock.readLock().unlock(); } }

Target:
public void binderDied() { if (DBG) { Slog.d(TAG, "Binder is dead - unregister " + mPackageName); } for (Map.Entry<IBinder, ClientDeathRecipient> entry : mBleApps.entrySet()) { IBinder token = entry.getKey(); ClientDeathRecipient deathRec = entry.getValue(); if (deathRec.equals(this)) { if (DBG) { Slog.d(TAG, "Remove this BLE app " + mPackageName); } mBleApps.remove(token); break; } } if (isBleAppPresent()) { return; } if (DBG) { Slog.d(TAG, "Disabling LE only mode after application crash"); } try { mBluetoothLock.readLock().lock(); if (mBluetooth != null && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) { mEnable = false; mBluetooth.onBrEdrDown(); } } catch (RemoteException e) { Slog.e(TAG, "Unable to call onBrEdrDown", e); } finally { mBluetoothLock.readLock().unlock(); } }
Source:
public void initializeDataSource() { fRootEntry = null; CounterAnalysis module = null; ITmfTrace trace = getTrace(); if (trace != null) { module = TmfTraceUtils.getAnalysisModuleOfClass(trace, CounterAnalysis.class, CounterAnalysis.ID); } if (trace != null && module != null) { module.schedule(); module.waitForInitialization(); ITmfStateSystem stateSystem = module.getStateSystem(); if (stateSystem != null) { fRootEntry = new TmfTreeViewerEntry(trace.getName()); TmfTreeViewerEntry rootBranch = new TmfTreeViewerEntry(getTrace().getName()); fRootEntry.getChildren().add(rootBranch); addTreeViewerBranch(stateSystem, rootBranch, CounterAnalysis.GROUPED_COUNTER_ASPECTS_ATTRIB); addTreeViewerBranch(stateSystem, rootBranch, CounterAnalysis.UNGROUPED_COUNTER_ASPECTS_ATTRIB); } } }

Target:
public void initializeDataSource() { fRootEntry = null; CounterAnalysis module = null; ITmfTrace trace = getTrace(); if (trace != null) { module = TmfTraceUtils.getAnalysisModuleOfClass(trace, CounterAnalysis.class, CounterAnalysis.ID); if (module != null) { module.schedule(); module.waitForInitialization(); ITmfStateSystem stateSystem = module.getStateSystem(); if (stateSystem != null) { fRootEntry = new TmfTreeViewerEntry(trace.getName()); TmfTreeViewerEntry rootBranch = new TmfTreeViewerEntry(getTrace().getName()); fRootEntry.getChildren().add(rootBranch); addTreeViewerBranch(stateSystem, rootBranch, CounterAnalysis.GROUPED_COUNTER_ASPECTS_ATTRIB); addTreeViewerBranch(stateSystem, rootBranch, CounterAnalysis.UNGROUPED_COUNTER_ASPECTS_ATTRIB); } } } }
Source:
public String toString() { return "BigtableConnectionBuilder(project=" + this.project + ", instance=" + this.instance + ", profile=" + (this.profile != null ? this.profile : "null") + ", credentials=" + this.credentials + ")"; }

Target:
public String toString() { return "BigtableConnectionBuilder(project=" + this.project + ", instance=" + this.instance + ", profile=" + this.profile + ", credentials=" + this.credentials + ")"; }
Source:
private Notification updateNotifications() { String contentTitle = getString(R.string.download_notification_title); int numDownloads = requester.getNumberOfDownloads(); String downloadsLeft = (numDownloads > 0) ? getResources().getQuantityString(R.plurals.downloads_left, numDownloads, numDownloads) : getString(R.string.downloads_processing); if (notificationCompatBuilder != null) { List<String> lines = new ArrayList<>(downloads.size()); StringBuilder line = new StringBuilder("\u2022 "); for (Downloader downloader : downloads) { final DownloadRequest request = downloader.getDownloadRequest(); switch (request.getFeedfileType()) { case Feed.FEEDFILETYPE_FEED: if (request.getTitle() != null) { line.append(request.getTitle()); } break; case FeedMedia.FEEDFILETYPE_FEEDMEDIA: if (request.getTitle() != null) { line.append(request.getTitle()) .append(" (") .append(request.getProgressPercent()) .append("%)"); } break; default: line.append("Unknown: ").append(request.getFeedfileType()); } lines.add(line.toString()); } String bigText = StringUtils.join(lines, '\n'); notificationCompatBuilder.setContentTitle(contentTitle); notificationCompatBuilder.setContentText(downloadsLeft); notificationCompatBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText)); return notificationCompatBuilder.build(); } return null; }

Target:
private Notification updateNotifications() { if (notificationCompatBuilder == null) { return null; } String contentTitle = getString(R.string.download_notification_title); int numDownloads = requester.getNumberOfDownloads(); String downloadsLeft = (numDownloads > 0) ? getResources().getQuantityString(R.plurals.downloads_left, numDownloads, numDownloads) : getString(R.string.downloads_processing); String bigText = compileNotificationString(downloads); notificationCompatBuilder.setContentTitle(contentTitle); notificationCompatBuilder.setContentText(downloadsLeft); notificationCompatBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText)); return notificationCompatBuilder.build(); }
Source:
public synchronized void documentAboutToBeChanged(DocumentEvent event) { TextChangingEvent changingEvent; if (!isFixedWidth()) { changingEvent = new TextChangingEvent(this); changingEvent.start = event.getOffset(); changingEvent.newText = event.getText() == null ? "" : event.getText(); changingEvent.replaceCharCount = event.getLength(); changingEvent.newCharCount = changingEvent.newText.length(); try { changingEvent.replaceLineCount = document.getNumberOfLines(event.getOffset(), event.getLength()) - 1; } catch (BadLocationException e) { ConsolePlugin.log(e); } changingEvent.newLineCount = document.computeNumberOfLines(changingEvent.newText); } else { try { changingEvent = generateTextChangingEvent(event); } catch (BadLocationException e) { ConsolePlugin.log(e); changingEvent = new TextChangingEvent(this); } } for (TextChangeListener listener : textChangeListeners) { listener.textChanging(changingEvent); } if (ASSERT) { updatePredicition(changingEvent); } }

Target:
public synchronized void documentAboutToBeChanged(DocumentEvent event) { TextChangingEvent changingEvent; if (!isFixedWidth()) { changingEvent = new TextChangingEvent(this); changingEvent.start = event.getOffset(); changingEvent.newText = event.getText() == null ? "" : event.getText(); changingEvent.replaceCharCount = event.getLength(); changingEvent.newCharCount = changingEvent.newText.length(); try { changingEvent.replaceLineCount = document.getNumberOfLines(event.getOffset(), event.getLength()) - 1; } catch (BadLocationException e) { log(e); } changingEvent.newLineCount = document.computeNumberOfLines(changingEvent.newText); } else { try { changingEvent = generateTextChangingEvent(event); } catch (BadLocationException e) { log(e); changingEvent = new TextChangingEvent(this); } } for (TextChangeListener listener : textChangeListeners) { listener.textChanging(changingEvent); } if (ASSERT) { updatePrediction(changingEvent); } }
Source:
public File getStatsFile(VariantSource source) { return new File( Paths.get(jobOptions.getPipelineOptions().getString(JobParametersNames.OUTPUT_DIR_STATISTICS)) .resolve(VariantStorageManager.buildFilename(source)) + STATS_FILE_POSTFIX ); }

Target:
private File getStatsFile(VariantSource source) { return new File( Paths.get(jobOptions.getPipelineOptions().getString(JobParametersNames.OUTPUT_DIR_STATISTICS)) .resolve(VariantStorageManager.buildFilename(source)) + STATS_FILE_SUFFIX ); }
Source:
public static boolean isPluginInstalled(final String shortName) { Jenkins instance = Jenkins.getInstance(); if (instance != null) { return instance.getPlugin(shortName) != null; } return true; }

Target:
public static boolean isPluginInstalled(final String shortName) { Jenkins instance = Jenkins.getInstance(); if (instance == null) { throw new IllegalStateException("Jenkins has not been started, or was already shut down"); } return instance.getPlugin(shortName) != null; }
Source:
public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { String user = uri.getUser(); final String pass = uri.getPass(); String host = uri.getHost(); int port = uri.getPort(); try { if (config == null) config = OpenSshConfig.get(fs); final OpenSshConfig.Host hc = config.lookup(host); host = hc.getHostName(); if (port <= 0) port = hc.getPort(); if (user == null) user = hc.getUser(); Session session = createSession(credentialsProvider, fs, user, pass, host, port, hc); while (!session.isConnected()) { try { session.connect(tms); } catch (JSchException e) { session.disconnect(); session = null; if (credentialsProvider != null && e.getCause() == null && e.getMessage().equals("Auth fail")) { credentialsProvider.reset(uri); session = createSession(credentialsProvider, fs, user, pass, host, port, hc); } else { throw e; } } } return new JschSession(session, uri); } catch (JSchException je) { final Throwable c = je.getCause(); if (c instanceof UnknownHostException) throw new TransportException(uri, JGitText.get().unknownHost); if (c instanceof ConnectException) throw new TransportException(uri, c.getMessage()); throw new TransportException(uri, je.getMessage(), je); } }

Target:
public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { String user = uri.getUser(); final String pass = uri.getPass(); String host = uri.getHost(); int port = uri.getPort(); try { if (config == null) config = OpenSshConfig.get(fs); final OpenSshConfig.Host hc = config.lookup(host); host = hc.getHostName(); if (port <= 0) port = hc.getPort(); if (user == null) user = hc.getUser(); Session session = createSession(credentialsProvider, fs, user, pass, host, port, hc); int retries = 0; while (!session.isConnected() && retries < 3) { try { retries++; session.connect(tms); } catch (JSchException e) { session.disconnect(); session = null; if (credentialsProvider != null && e.getCause() == null && e.getMessage().equals("Auth fail")) { credentialsProvider.reset(uri); session = createSession(credentialsProvider, fs, user, pass, host, port, hc); } else { throw e; } } } return new JschSession(session, uri); } catch (JSchException je) { final Throwable c = je.getCause(); if (c instanceof UnknownHostException) throw new TransportException(uri, JGitText.get().unknownHost); if (c instanceof ConnectException) throw new TransportException(uri, c.getMessage()); throw new TransportException(uri, je.getMessage(), je); } }
Source:
private void checkOtherType(Object o, String expectedResult) throws QueryEvaluationException, InterruptedException { add("wd:Q888", "p:P999", o); StringBuilder query = uris().prefixes(Ontology.prefix(new StringBuilder())); query.append("SELECT ?item ?itemLabel WHERE {\n" + " wd:Q888 p:P999 ?item .\n" + " SERVICE ontology:label {\n" + " bd:serviceParam ontology:language \"en\".\n" + " }\n" + "}"); TupleQueryResult result = query(query.toString()); assertTrue(result.hasNext()); BindingSet resultSet = result.next(); assertThat(resultSet, binds("itemLabel", expectedResult, null)); closeStore(); }

Target:
private void checkOtherType(Object o, String expectedResult) throws QueryEvaluationException { add("wd:Q888", "p:P999", o); StringBuilder query = uris().prefixes(Ontology.prefix(new StringBuilder())); query.append("SELECT ?item ?itemLabel WHERE {\n" + " wd:Q888 p:P999 ?item .\n" + " SERVICE ontology:label {\n" + " bd:serviceParam ontology:language \"en\".\n" + " }\n" + "}"); TupleQueryResult result = query(query.toString()); assertTrue(result.hasNext()); BindingSet resultSet = result.next(); assertThat(resultSet, binds("itemLabel", expectedResult, null)); closeStore(); }
Source:
public void prepare(final StorableProperties properties) { ExecutorCompletionService completionService = new ExecutorCompletionService<>(threadPool); int counter = 0; for (final PrepareContractionHierarchies prepare : getPreparations()) { LOGGER.info((++counter) + "/" + getPreparations().size() + " calling CH prepare.doWork for " + prepare.getWeighting() + " ... (" + Helper.getMemInfo() + ")"); final String name = AbstractWeighting.weightingToFileName(prepare.getWeighting()); completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { String errorKey = CH.PREPARE + "error." + name; try { Thread.currentThread().setName(name); properties.put(errorKey, "CH preparation incomplete"); prepare.doWork(); properties.remove(errorKey); properties.put(CH.PREPARE + "date." + name, Helper.createFormatter().format(new Date())); } catch (Exception ex) { LOGGER.error("Problem while CH preparation " + name, ex); properties.put(errorKey, ex.getMessage()); throw ex; } return null; } }); } threadPool.shutdown(); try { for (int i = 0; i < getPreparations().size(); i++) { completionService.take().get(); } } catch (Exception e) { threadPool.shutdownNow(); throw new RuntimeException(e); } }

Target:
public void prepare(final StorableProperties properties) { ExecutorCompletionService completionService = new ExecutorCompletionService<>(threadPool); int counter = 0; for (final PrepareContractionHierarchies prepare : getPreparations()) { LOGGER.info((++counter) + "/" + getPreparations().size() + " calling CH prepare.doWork for " + prepare.getWeighting() + " ... (" + Helper.getMemInfo() + ")"); final String name = AbstractWeighting.weightingToFileName(prepare.getWeighting()); completionService.submit(new Runnable() { @Override public void run() { String errorKey = CH.PREPARE + "error." + name; try { Thread.currentThread().setName(name); properties.put(errorKey, "CH preparation incomplete"); prepare.doWork(); properties.remove(errorKey); properties.put(CH.PREPARE + "date." + name, Helper.createFormatter().format(new Date())); } catch (Exception ex) { LOGGER.error("Problem while CH preparation " + name, ex); properties.put(errorKey, ex.getMessage()); throw ex; } } }, name); } threadPool.shutdown(); try { for (int i = 0; i < getPreparations().size(); i++) { completionService.take().get(); } } catch (Exception e) { threadPool.shutdownNow(); throw new RuntimeException(e); } }
Source:
public void testScrollBarViewDoesNotShowButtonWhenLimitedSpace() { ViewGroup.LayoutParams params = mScrollBarView.getLayoutParams(); params.height = 0; try { mActivityRule.runOnUiThread(() -> mScrollBarView.requestLayout()); } catch (Throwable throwable) { throwable.printStackTrace(); throw new RuntimeException(throwable); } onView(withId(R.id.page_up)).check(matches(not(isDisplayed()))); onView(withId(R.id.scrollbar_thumb)).check(matches(not(isDisplayed()))); onView(withId(R.id.alpha_jump)).check(matches(not(isDisplayed()))); }

Target:
public void testScrollBarViewDoesNotShowButtonWhenLimitedSpace() { ViewGroup.LayoutParams params = mScrollBarView.getLayoutParams(); params.height = 0; requestScrollBarLayout(); onView(withId(R.id.page_up)).check(matches(not(isDisplayed()))); onView(withId(R.id.scrollbar_thumb)).check(matches(not(isDisplayed()))); onView(withId(R.id.alpha_jump)).check(matches(not(isDisplayed()))); }
Source:
protected List<TmfTreeDataModel> getTree(ITmfStateSystem ss, TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<TmfTreeDataModel> nodes = new ArrayList<>(); long traceId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); nodes.add(new TmfTreeDataModel(traceId, -1, getTrace().getName())); String readName = Objects.requireNonNull(Messages.DisksIODataProvider_read); String writeName = Objects.requireNonNull(Messages.DisksIODataProvider_write); for (Integer diskQuark : ss.getQuarks(Attributes.DISKS, "*")) { String diskName = getDiskName(ss, diskQuark); long diskId = getId(diskQuark); nodes.add(new TmfTreeDataModel(diskId, traceId, diskName)); int readQuark = ss.optQuarkRelative(diskQuark, Attributes.SECTORS_READ); if (readQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { nodes.add(new TmfTreeDataModel(getId(readQuark), diskId, readName)); } int writeQuark = ss.optQuarkRelative(diskQuark, Attributes.SECTORS_WRITTEN); if (writeQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { nodes.add(new TmfTreeDataModel(getId(writeQuark), diskId, writeName)); } } return nodes; }

Target:
protected List<TmfTreeDataModel> getTree(ITmfStateSystem ss, TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<TmfTreeDataModel> nodes = new ArrayList<>(); long rootId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); nodes.add(new TmfTreeDataModel(rootId, -1, getTrace().getName())); String readName = Objects.requireNonNull(Messages.DisksIODataProvider_read); String writeName = Objects.requireNonNull(Messages.DisksIODataProvider_write); for (Integer diskQuark : ss.getQuarks(Attributes.DISKS, "*")) { String diskName = getDiskName(ss, diskQuark); long diskId = getId(diskQuark); nodes.add(new TmfTreeDataModel(diskId, rootId, diskName)); int readQuark = ss.optQuarkRelative(diskQuark, Attributes.SECTORS_READ); if (readQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { nodes.add(new TmfTreeDataModel(getId(readQuark), diskId, readName)); } int writeQuark = ss.optQuarkRelative(diskQuark, Attributes.SECTORS_WRITTEN); if (writeQuark != ITmfStateSystem.INVALID_ATTRIBUTE) { nodes.add(new TmfTreeDataModel(getId(writeQuark), diskId, writeName)); } } return nodes; }
Source:
public void secondNodeMustRejectJoinOnThirdNode() throws Exception { IgniteEx node1 = node(NODE_1) .start(); node1.cluster().baselineAutoAdjustTimeout(1); IgniteEx node2 = node(NODE_2) .withRegion(REGION_2, PERSISTENCE) .start(); assertThrowsContainsMessage(() -> node(NODE_3).withRegion(REGION_2, MEMORY).start(), IgniteSpiException.class, "Failed to join node (Incompatible data region configuration [region=" + REGION_2 ); }

Target:
public void secondNodeMustRejectJoinOnThirdNode() throws Exception { IgniteEx node1 = node(NODE_1) .start(); node1.cluster().baselineAutoAdjustTimeout(1); node(NODE_2) .withRegion(REGION_2, PERSISTENCE) .start(); assertThrowsContainsMessage(() -> node(NODE_3).withRegion(REGION_2, MEMORY).start(), IgniteSpiException.class, "Failed to join node (Incompatible data region configuration [region=" + REGION_2 ); }
Source:
public String[] getText() { return text; }

Target:
public String[] getText() { return texts; }
Source:
public ArrayBufferInput(byte[] arr, int offset, int length) { this.buffer = MessageBuffer.wrap(checkNotNull(arr, "input array is null")).slice(offset, length); checkArgument(length <= arr.length); this.length = length; }

Target:
public ArrayBufferInput(byte[] arr, int offset, int length) { checkArgument(offset + length <= arr.length); this.buffer = MessageBuffer.wrap(checkNotNull(arr, "input array is null")).slice(offset, length); }
Source:
public void freeMacs(List<String> macs) { log.info("MacPoolManager::freeMacs - entered"); mLocObj.writeLock().lock(); try { if (!mInitialized) { logInitializationError("Failed to free macs."); } for (String mac : macs) { internalFreeMac(mac); } } finally { mLocObj.writeLock().unlock(); } }

Target:
public void freeMacs(List<String> macs) { log.info("MacPoolManager::freeMacs - entered"); mLocObj.writeLock().lock(); try { if (!mInitialized) { logInitializationError("Failed to free MAC addresses."); } for (String mac : macs) { internalFreeMac(mac); } } finally { mLocObj.writeLock().unlock(); } }
Source:
public ResultHolder getType(@Nullable HaxeGenericResolver resolver) { if (resolver != null) { ResultHolder resolved = resolver.resolve(getType(null).getType().toStringWithoutConstant()); if (resolved != null) return resolved; } return HaxeTypeResolver.getTypeFromTypeTag(getTypeTagPsi(), this.getContextElement()); }

Target:
public ResultHolder getType(@Nullable HaxeGenericResolver resolver) { if (resolver != null) { ResultHolder typeResult = getType(null); ResultHolder resolved = resolver.resolve(typeResult.getType().toStringWithoutConstant()); if (resolved != null) return resolved; } return HaxeTypeResolver.getTypeFromTypeTag(getTypeTagPsi(), this.getContextElement()); }
Source:
public void setContextLimit(Short value) throws IllegalArgumentException { if (value < 1) { throw new IllegalArgumentException("`value' is not positive"); } contextLimit = value; }

Target:
public void setContextLimit(Short value) throws IllegalArgumentException { if (value < 1) { throw new IllegalArgumentException("value is not positive"); } contextLimit = value; }
Source:
protected void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, int code, Exception e) { try { if (code == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { LOG.error("Exception occurred during processing request: {}", e.getMessage(), e); request.setAttribute("javax.servlet.error.exception", e); request.setAttribute("javax.servlet.jsp.jspException", e); } response.sendError(code, e.getMessage()); } catch (IOException e1) { LOG.warn("Unable to send error response, code: {}! (IOException): {}", code, e1.toString()); } catch (IllegalStateException ise) { LOG.warn("Unable to send error response, code: {}! isCommited: {}. (IllegalStateException): {}", code, response.isCommitted(), ise.toString()); } }

Target:
protected void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, int code, Exception e) { try { if (code == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { LOG.error("Exception occurred during processing request: {}", e.getMessage(), e); request.setAttribute("javax.servlet.error.exception", e); request.setAttribute("javax.servlet.jsp.jspException", e); } response.sendError(code, e.getMessage()); } catch (IOException e1) { LOG.warn("Unable to send error response, code: {};", code, e1); } catch (IllegalStateException ise) { LOG.warn("Unable to send error response, code: {}; isCommited: {};", code, response.isCommitted(), ise); } }
Source:
Object nonTxnFindObject(KeyInfo keyInfo, boolean isCreate, boolean generateCallbacks, Object localValue, boolean disableCopyOnRead, boolean preferCD, ClientProxyMembershipID requestingClient, EntryEventImpl clientEvent, boolean returnTombstones) throws TimeoutException, CacheLoaderException { @Retained Object result; result = optimizedGetObject(keyInfo, isCreate, generateCallbacks, localValue, disableCopyOnRead, preferCD, requestingClient, clientEvent, returnTombstones); return result; }

Target:
Object nonTxnFindObject(KeyInfo keyInfo, boolean isCreate, boolean generateCallbacks, Object localValue, boolean disableCopyOnRead, boolean preferCD, ClientProxyMembershipID requestingClient, EntryEventImpl clientEvent, boolean returnTombstones) throws TimeoutException, CacheLoaderException { @Retained Object result = optimizedGetObject(keyInfo, isCreate, generateCallbacks, localValue, disableCopyOnRead, preferCD, requestingClient, clientEvent, returnTombstones); return result; }
Source:
public synchronized ITmfTimestamp readEnd() { try { Long pos = fFile.length() - 1; while (pos > 0) { while (pos > 0) { fFile.seek(pos - 1); if (fFile.read() == '\n') { break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos--; } } catch (IOException e) { return null; } return null; }

Target:
public synchronized ITmfTimestamp readEnd() { try { Long pos = fFile.length() - 1; while (pos > 0) { while (pos > 0) { fFile.seek(pos - 1); if (fFile.read() == '\n') { break; } pos--; } ITmfLocation location = new TmfLongLocation(pos); ITmfContext context = seekEvent(location); ITmfEvent event = parseEvent(context); context.dispose(); if (event != null) { return event.getTimestamp(); } pos--; } } catch (IOException e) { Activator.logError("Error seeking last event. File: " + getPath(), e); } return null; }
Source:
public JavaStubGenerator(final File outputPath) { this(outputPath, false, false, "utf-8"); }

Target:
public JavaStubGenerator(final File outputPath) { this(outputPath, false, false, Charset.defaultCharset().name()); }
Source:
private double cumulativeProbability(double x) { try { NormalDistribution normDist = new NormalDistribution(); return normDist.cumulativeProbability(x); } catch (Exception ex) { return Double.NaN; } }

Target:
private double cumulativeProbability(double x) { try { NormalDistribution normDist = new NormalDistribution(); return normDist.cumulativeProbability(x); } catch (IllegalArgumentException ex) { return Double.NaN; } }
Source:
private void printStackTrace(StackTraceElement[] trace) { boolean dumpOnErrors = getOptions().containsKey("dumpOnErrors") && getBooleanOption("dumpOnErrors", true); if (dumpOnErrors) { String msg = new String(); for (StackTraceElement elem : trace) { msg = msg + "\tat " + elem + "\n"; } message(Diagnostic.Kind.NOTE, msg); } }

Target:
private void printStackTrace(StackTraceElement[] trace) { if (hasOption("dumpOnErrors")) { StringBuilder msg = new StringBuilder(); for (StackTraceElement elem : trace) { msg.append("\tat " + elem + "\n"); } message(Diagnostic.Kind.NOTE, msg.toString()); } }
Source:
private void handleUncommittedChanges(final Repository repository, final List<String> files, Shell shell) { CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.AbstractRebaseCommandHandler_cleanupDialog_title, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, files); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { final PullOperationUI parentOperation = this; final PullOperationUI pullOperationUI = new PullOperationUI( Collections.singleton(repository)); tasksToWaitFor.incrementAndGet(); pullOperationUI.start(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { parentOperation.results.putAll(pullOperationUI.results); int missing = parentOperation.tasksToWaitFor.decrementAndGet(); if (missing == 0) parentOperation.showResults(); } }); } }

Target:
private void handleUncommittedChanges(final Repository repository, final List<String> files, Shell shell) { String dialogTitle = NLS.bind( UIText.AbstractRebaseCommandHandler_cleanupDialog_title, Activator.getDefault().getRepositoryUtil() .getRepositoryName(repository)); CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, dialogTitle, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, files); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { final PullOperationUI parentOperation = this; final PullOperationUI pullOperationUI = new PullOperationUI( Collections.singleton(repository)); tasksToWaitFor.incrementAndGet(); pullOperationUI.start(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { parentOperation.results.putAll(pullOperationUI.results); int missing = parentOperation.tasksToWaitFor.decrementAndGet(); if (missing == 0) parentOperation.showResults(); } }); } }
Source:
public void registerHook(JenkinsRule r) throws Exception { File hgDir = new File(sampleRepo, ".hg"); File hook = new File(hgDir, "hook.py"); FileUtils.write(hook, "import requests\n" + "\n" + "def commit(ui, repo, node, **kwargs):\n" + " ui.warn('Notify Commit hook response: %s\\n' % requests.post('" +r.getURL() +"mercurial/notifyCommit', data={\"url\":\"" +fileUrl() +"\",\"branch\":repo[node].branch(),\"changesetId\":node}))\n" + " pass"); FileUtils.write(new File(hgDir, "hgrc"), "[hooks]\n" + "commit.jenkins = python:"+hook.getAbsolutePath()+":commit"); }

Target:
public void registerHook(JenkinsRule r) throws Exception { File hgDir = new File(sampleRepo, ".hg"); File hook = new File(hgDir, "hook.py"); FileUtils.write(hook, "import urllib\n" + "import urllib2\n" + "\n" + "def commit(ui, repo, node, **kwargs):\n" + " data = {\n" + " 'url': '" + fileUrl() + "',\n" + " 'branch': repo[node].branch(),\n" + " 'changesetId': node,\n" + " }\n" + " req = urllib2.Request('" + r.getURL() + "mercurial/notifyCommit')\n" + " rsp = urllib2.urlopen(req, urllib.urlencode(data))\n" + " ui.warn('Notify Commit hook response: %s\\n' % rsp.read())\n" + " pass\n"); FileUtils.write(new File(hgDir, "hgrc"), "[hooks]\n" + "commit.jenkins = python:"+hook.getAbsolutePath()+":commit"); }
Source:
private void setupCarbonMessage(ChannelHandlerContext ctx) { if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestReceiving(cMsg); } cMsg.setProperty(Constants.PORT, ((InetSocketAddress) ctx.channel().remoteAddress()).getPort()); cMsg.setProperty(Constants.HOST, ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); cMsg.setProperty(Constants.TO, this.uri); cMsg.setProperty(Constants.SRC_HANDLER, this); cMsg.setProperty(org.wso2.carbon.messaging.Constants.LISTENER_PORT, ((InetSocketAddress) ctx.channel().localAddress()).getPort()); cMsg.setProperty(Constants.IS_SECURED_CONNECTION, isSecured); cMsg.setProperty(Constants.LOCAL_ADDRESS, ctx.channel().localAddress()); cMsg.setProperty(Constants.LOCAL_NAME, ((InetSocketAddress) ctx.channel().localAddress()).getHostName()); cMsg.setProperty(Constants.REMOTE_ADDRESS, ctx.channel().remoteAddress()); cMsg.setProperty(Constants.REMOTE_HOST, ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); cMsg.setProperty(Constants.REMOTE_PORT, ((InetSocketAddress) ctx.channel().remoteAddress()).getPort()); cMsg.setProperty(Constants.CHANNEL_ID, channelId); cMsg.setProperty(Constants.PROTOCOL, Constants.WEBSOCKET_PROTOCOL); cMsg.setProperty(Constants.IS_WEBSOCKET_SERVER, true); cMsg.setProperty(Constants.WEBSOCKET_SERVER_SESSION, serverSession); cMsg.setProperty(Constants.WEBSOCKET_CLIENT_SESSIONS_LIST, clientSessions); }

Target:
private void setupCarbonMessage(ChannelHandlerContext ctx) { if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestReceiving(cMsg); } cMsg.setProperty(Constants.TO, this.uri); cMsg.setProperty(Constants.SRC_HANDLER, this); cMsg.setProperty(org.wso2.carbon.messaging.Constants.LISTENER_PORT, ((InetSocketAddress) ctx.channel().localAddress()).getPort()); cMsg.setProperty(Constants.IS_SECURED_CONNECTION, isSecured); cMsg.setProperty(Constants.LOCAL_ADDRESS, ctx.channel().localAddress()); cMsg.setProperty(Constants.LOCAL_NAME, ((InetSocketAddress) ctx.channel().localAddress()).getHostName()); cMsg.setProperty(Constants.CHANNEL_ID, channelId); cMsg.setProperty(Constants.PROTOCOL, Constants.WEBSOCKET_PROTOCOL); cMsg.setProperty(Constants.IS_WEBSOCKET_SERVER, true); cMsg.setProperty(Constants.WEBSOCKET_SERVER_SESSION, serverSession); cMsg.setProperty(Constants.WEBSOCKET_CLIENT_SESSIONS_LIST, clientSessions); }