auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void process() { PerformanceMonitor.startActivity("rendering/ambientOcclusion"); Texture ssaoNoiseTexture = updateNoiseTexture(); GL13.glActiveTexture(GL13.GL_TEXTURE2); glBindTexture(GL11.GL_TEXTURE_2D, ssaoNoiseTexture.getId()); ssaoMaterial.setInt("texNoise", 2, true); ssaoMaterial.setFloat4("ssaoSettings", ssaoStrength, ssaoRad, 0.0f, 0.0f, true); ssaoMaterial.setMatrix4("invProjMatrix", activeCamera.getInverseProjectionMatrix(), true); ssaoMaterial.setMatrix4("projMatrix", activeCamera.getProjectionMatrix(), true); ssaoMaterial.setFloat2("texelSize", 1.0f / outputFboWidth, 1.0f / outputFboHeight, true); ssaoMaterial.setFloat2("noiseTexelSize", NOISE_TEXEL_SIZE, NOISE_TEXEL_SIZE, true); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }

Target:
public void process() { PerformanceMonitor.startActivity("rendering/ambientOcclusion"); ssaoMaterial.setFloat4("ssaoSettings", ssaoStrength, ssaoRad, 0.0f, 0.0f, true); ssaoMaterial.setMatrix4("invProjMatrix", activeCamera.getInverseProjectionMatrix(), true); ssaoMaterial.setMatrix4("projMatrix", activeCamera.getProjectionMatrix(), true); ssaoMaterial.setFloat2("texelSize", 1.0f / outputFboWidth, 1.0f / outputFboHeight, true); ssaoMaterial.setFloat2("noiseTexelSize", NOISE_TEXEL_SIZE, NOISE_TEXEL_SIZE, true); ssaoMaterial.setFloat3("ssaoSamples", ssaoSamples); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }
Source:
private BKHttpServiceProvider(BookieServer bookieServer, AutoRecoveryMain autoRecovery, ServerConfiguration serverConf) throws IOException, KeeperException, InterruptedException, BKException { this.bookieServer = bookieServer; this.autoRecovery = autoRecovery; this.serverConf = serverConf; this.layoutManager = new ZkLayoutManager( ZooKeeperClient.newBuilder() .connectString(serverConf.getZkServers()) .sessionTimeoutMs(serverConf.getZkTimeout()) .build(), serverConf.getZkLedgersRootPath(), ZkUtils.getACLs(serverConf)); this.zk = ZooKeeperClient.newBuilder() .connectString(serverConf.getZkServers()) .sessionTimeoutMs(serverConf.getZkTimeout()) .build(); ClientConfiguration clientConfiguration = new ClientConfiguration(serverConf); clientConfiguration.setZkServers(serverConf.getZkServers()); this.bka = new BookKeeperAdmin(clientConfiguration); this.executor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("BKHttpServiceThread").setDaemon(true).build()); }

Target:
private BKHttpServiceProvider(BookieServer bookieServer, AutoRecoveryMain autoRecovery, ServerConfiguration serverConf) throws IOException, KeeperException, InterruptedException, BKException { this.bookieServer = bookieServer; this.autoRecovery = autoRecovery; this.serverConf = serverConf; this.layoutManager = bookieServer.getBookie().getRegistrationManager().getLayoutManager(); this.zk = ZooKeeperClient.newBuilder() .connectString(serverConf.getZkServers()) .sessionTimeoutMs(serverConf.getZkTimeout()) .build(); ClientConfiguration clientConfiguration = new ClientConfiguration(serverConf); clientConfiguration.setZkServers(serverConf.getZkServers()); this.bka = new BookKeeperAdmin(clientConfiguration); this.executor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("BKHttpServiceThread").setDaemon(true).build()); }
Source:
public static Encoding getDatabaseEncoding(String databaseEncoding) { if ("UTF8".equals(databaseEncoding)) { return UTF8_ENCODING; } String[] candidates = encodings.get(databaseEncoding); if (candidates != null) { for (String candidate : candidates) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Search encoding candidate {0}", candidate); } if (Charset.isSupported(candidate)) { return new Encoding(candidate); } } } if (Charset.isSupported(databaseEncoding)) { return new Encoding(databaseEncoding); } if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "{0} encoding not found, returning default encoding", databaseEncoding); } return DEFAULT_ENCODING; }

Target:
public static Encoding getDatabaseEncoding(String databaseEncoding) { if ("UTF8".equals(databaseEncoding)) { return UTF8_ENCODING; } String[] candidates = encodings.get(databaseEncoding); if (candidates != null) { for (String candidate : candidates) { LOGGER.log(Level.FINEST, "Search encoding candidate {0}", candidate); if (Charset.isSupported(candidate)) { return new Encoding(candidate); } } } if (Charset.isSupported(databaseEncoding)) { return new Encoding(databaseEncoding); } LOGGER.log(Level.FINEST, "{0} encoding not found, returning default encoding", databaseEncoding); return DEFAULT_ENCODING; }
Source:
private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) { dismissLoadingDialog(); OCFile syncedFile = operation.getLocalFile(); if (!result.isSuccess()) { if (result.getCode() == ResultCode.SYNC_CONFLICT) { Intent i = new Intent(this, ConflictsResolveActivity.class); i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile); i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount()); startActivity(i); } } else { if (operation.transferWasRequested()) { } else { Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()), Toast.LENGTH_LONG); msg.show(); } } }

Target:
private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) { dismissLoadingDialog(); OCFile syncedFile = operation.getLocalFile(); if (!result.isSuccess()) { if (result.getCode() == ResultCode.SYNC_CONFLICT) { Intent i = new Intent(this, ConflictsResolveActivity.class); i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile); i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount()); startActivity(i); } } else { if (!operation.transferWasRequested()) { Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()), Toast.LENGTH_LONG); msg.show(); } } }
Source:
public void write(final File idxFile) throws IOException { final LittleEndianOutputStream idxStream = new LittleEndianOutputStream(new BufferedOutputStream(new FileOutputStream(idxFile))); try { write(idxStream); } finally { idxStream.close(); } }

Target:
public void write(final File idxFile) throws IOException { try(final LittleEndianOutputStream idxStream = new LittleEndianOutputStream(new BufferedOutputStream(new FileOutputStream(idxFile)))) { write(idxStream); } }
Source:
private Map<String, Object> serializeJetpackProtectAndSsoParams() { Map<String, Object> params = new HashMap<>(); if (mJpSettings.monitorActive != mRemoteJpSettings.monitorActive) { params.put("monitor", mJpSettings.monitorActive); } if (mJpSettings.jetpackProtectEnabled != mRemoteJpSettings.jetpackProtectEnabled) { params.put("protect", mJpSettings.jetpackProtectEnabled); } if (!mJpSettings.whitelistMatches(mRemoteJpSettings.jetpackProtectWhitelist)) { String whitelistArray = mJpSettings.jetpackProtectWhitelist.toString().replace("[", "").replace("]", ""); params.put("jetpack_protect_global_whitelist", whitelistArray); } if (mJpSettings.ssoActive != mRemoteJpSettings.ssoActive) { params.put("sso", mJpSettings.ssoActive); } if (mJpSettings.ssoMatchEmail != mRemoteJpSettings.ssoMatchEmail) { params.put("jetpack_sso_match_by_email", mJpSettings.ssoMatchEmail); } if (mJpSettings.ssoRequireTwoFactor != mRemoteJpSettings.ssoRequireTwoFactor) { params.put("jetpack_sso_require_two_step", mJpSettings.ssoRequireTwoFactor); } return params; }

Target:
private Map<String, Object> serializeJetpackProtectAndSsoParams() { Map<String, Object> params = new HashMap<>(); if (mJpSettings.monitorActive != mRemoteJpSettings.monitorActive) { params.put("monitor", mJpSettings.monitorActive); } if (mJpSettings.jetpackProtectEnabled != mRemoteJpSettings.jetpackProtectEnabled) { params.put("protect", mJpSettings.jetpackProtectEnabled); } if (!mJpSettings.whitelistMatches(mRemoteJpSettings.jetpackProtectWhitelist)) { String whitelistArray = TextUtils.join(",", mJpSettings.jetpackProtectWhitelist); params.put("jetpack_protect_global_whitelist", whitelistArray); } if (mJpSettings.ssoActive != mRemoteJpSettings.ssoActive) { params.put("sso", mJpSettings.ssoActive); } if (mJpSettings.ssoMatchEmail != mRemoteJpSettings.ssoMatchEmail) { params.put("jetpack_sso_match_by_email", mJpSettings.ssoMatchEmail); } if (mJpSettings.ssoRequireTwoFactor != mRemoteJpSettings.ssoRequireTwoFactor) { params.put("jetpack_sso_require_two_step", mJpSettings.ssoRequireTwoFactor); } return params; }
Source:
void fillChunks() { try { PutChunk chunkToFill; if (!isChunkFillComplete()) { do { if (channelReadBuffer == null) { channelReadBuffer = chunkFillerChannel.getNextChunk(0); } if (channelReadBuffer != null) { maybeStopTrackingWaitForChannelDataTime(); chunkToFill = getChunkToFill(); if (chunkToFill == null) { maybeStartTrackingWaitForChunkTime(); break; } else { maybeStopTrackingWaitForChunkTime(); bytesFilledSoFar += chunkToFill.fillFrom(channelReadBuffer); if (chunkToFill.isReady()) { routerCallback.onPollReady(); updateChunkFillerWaitTimeMetrics(); } if (!channelReadBuffer.hasRemaining()) { chunkFillerChannel.resolveOldestChunk(null); channelReadBuffer = null; } } } else { if (getFreeChunk() != null) { maybeStartTrackingWaitForChannelDataTime(); } break; } } while (!isChunkFillComplete()); } if (isChunkFillComplete()) { PutChunk lastChunk = getBuildingChunk(); if (lastChunk != null) { lastChunk.onFillComplete(true); } } } catch (Exception e) { RouterException routerException = e instanceof RouterException ? (RouterException) e : new RouterException("PutOperation fillChunks encountered unexpected error", e, RouterErrorCode.UnexpectedInternalError); routerMetrics.chunkFillerUnexpectedErrorCount.inc(); routerCallback.onPollReady(); setOperationExceptionAndComplete(routerException); } }

Target:
void fillChunks() { try { PutChunk chunkToFill; while (!isChunkFillingDone()) { if (channelReadBuffer == null) { channelReadBuffer = chunkFillerChannel.getNextChunk(0); } if (channelReadBuffer != null) { maybeStopTrackingWaitForChannelDataTime(); chunkToFill = getChunkToFill(); if (chunkToFill == null) { maybeStartTrackingWaitForChunkTime(); break; } else { maybeStopTrackingWaitForChunkTime(); bytesFilledSoFar += chunkToFill.fillFrom(channelReadBuffer); if (chunkToFill.isReady()) { routerCallback.onPollReady(); updateChunkFillerWaitTimeMetrics(); } if (!channelReadBuffer.hasRemaining()) { chunkFillerChannel.resolveOldestChunk(null); channelReadBuffer = null; } } } else { if (getFreeChunk() != null) { maybeStartTrackingWaitForChannelDataTime(); } break; } } if (chunkFillingCompletedSuccessfully) { PutChunk lastChunk = getBuildingChunk(); if (lastChunk != null) { lastChunk.onFillComplete(true); } } } catch (Exception e) { RouterException routerException = e instanceof RouterException ? (RouterException) e : new RouterException("PutOperation fillChunks encountered unexpected error", e, RouterErrorCode.UnexpectedInternalError); routerMetrics.chunkFillerUnexpectedErrorCount.inc(); routerCallback.onPollReady(); setOperationExceptionAndComplete(routerException); } }
Source:
public void updatePhysics(GlowBlock block) { BlockPhysicsEvent event = EventFactory.getInstance() .callEvent(new BlockPhysicsEvent(block, block.getTypeId())); if (event.isCancelled()) { return; } }

Target:
public final void updatePhysics(GlowBlock block) { BlockPhysicsEvent event = EventFactory.getInstance() .callEvent(new BlockPhysicsEvent(block, block.getTypeId())); if (!event.isCancelled()) { updatePhysicsAfterEvent(block); } }
Source:
public String getDeviceId() { Log.d(LOG_TAG, "getDeviceId(): return 0"); return "0"; }

Target:
public String getDeviceId() { return getMeid(); }
Source:
protected boolean itemInListExistsLowerCase(List<String> lines, String item) { for (String line : lines) { String lowLine = line.toLowerCase(); if (lowLine.contains(item)) { return true; } } return false; }

Target:
public boolean itemInListExistsLowerCase(List<String> lines, String item) { for (String line : lines) { String lowLine = line.toLowerCase(); if (lowLine.contains(item)) { return true; } } return false; }
Source:
public static LibraryDilution to(DilutionDto from) { LibraryDilution to = new LibraryDilution(); to.setName(from.getName()); to.setIdentificationBarcode(from.getIdentificationBarcode()); to.setConcentration(from.getConcentration()); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { to.setCreationDate(df.parse(from.getCreationDate())); } catch (ParseException e) { } return to; }

Target:
public static LibraryDilution to(DilutionDto from) { LibraryDilution to = new LibraryDilution(); to.setId(from.getId()); to.setName(from.getName()); to.setIdentificationBarcode(from.getIdentificationBarcode()); to.setConcentration(from.getConcentration()); to.setLibrary(to(from.getLibrary())); if (!isStringEmptyOrNull(from.getDilutionUserName())) { to.setDilutionCreator(from.getDilutionUserName()); } DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { to.setCreationDate(df.parse(from.getCreationDate())); } catch (ParseException e) { } return to; }
Source:
private Object[] parseCsv(String value) { assert StringUtils.isNotEmpty(value); String[] values = value.split(keyDelimiter); Object[] arr = new Object[fields.size()]; assert values.length == arr.length; try { for (int i = 0; i < arr.length; i++) { arr[i] = values[i] == null ? "" : values[i]; } } catch (Exception e) { throw new RuntimeException(e); } return arr; }

Target:
private Object[] parseCsv(String value) { assert StringUtils.isNotEmpty(value); String[] values = value.split(keyDelimiter); Object[] arr = new Object[fields.size()]; assert values.length == arr.length; for (int i = 0; i < arr.length; i++) { arr[i] = values[i] == null ? "" : values[i]; } return arr; }
Source:
public Block apply(Block block) { if (elementCoercer == null) { return block; } BlockBuilder blockBuilder = toType.createBlockBuilder(new BlockBuilderStatus(), block.getPositionCount()); ColumnarArray arrayBlock = ColumnarArray.toColumnarArray(block); Block elementsBlock = elementCoercer.apply(arrayBlock.getElementsBlock()); for (int i = 0; i < arrayBlock.getPositionCount(); i++) { if (arrayBlock.isNull(i)) { blockBuilder.appendNull(); continue; } int offset = arrayBlock.getOffset(i); int elementSize = arrayBlock.getLength(i); BlockBuilder singleArrayBuilder = blockBuilder.beginBlockEntry(); for (int j = 0; j < elementSize; j++) { if (elementsBlock.isNull(offset + j)) { singleArrayBuilder.appendNull(); } else { elementsBlock.writePositionTo(offset + j, singleArrayBuilder); singleArrayBuilder.closeEntry(); } } blockBuilder.closeEntry(); } return blockBuilder.build(); }

Target:
public Block apply(Block block) { if (elementCoercer == null) { return block; } ColumnarArray arrayBlock = toColumnarArray(block); Block elementsBlock = elementCoercer.apply(arrayBlock.getElementsBlock()); boolean[] valueIsNull = new boolean[arrayBlock.getPositionCount()]; int[] offsets = new int[arrayBlock.getPositionCount() + 1]; for (int i = 0; i < arrayBlock.getPositionCount(); i++) { valueIsNull[i] = arrayBlock.isNull(i); offsets[i + 1] = offsets[i] + arrayBlock.getLength(i); } return new ArrayBlock(arrayBlock.getPositionCount(), valueIsNull, offsets, elementsBlock); }
Source:
private File getTestBundleRoot() { URL url = getClass().getResource(BUNDLE_ROOT); URI uri = null; try { uri = url.toURI(); } catch (URISyntaxException e) { e.printStackTrace(); return null; } return new File(uri); }

Target:
private File getTestBundleRoot() throws Exception { return new File(getClass().getResource(BUNDLE_ROOT).toURI()); }
Source:
public InputStream getContents() throws CoreException { if (exists) { try { File file = path.toFile(); timestamp = file.lastModified(); if (Files.isSymbolicLink(file.toPath())) { String symLink = FileUtils.readSymLink(file); return new ByteArrayInputStream(symLink.getBytes()); } return new FileInputStream(file); } catch (IOException e) { Activator.error(e.getMessage(), e); } } return null; }

Target:
public InputStream getContents() throws CoreException { if (exists) { try { File file = path.toFile(); timestamp = file.lastModified(); if (Files.isSymbolicLink(file.toPath())) { String symLink = FileUtils.readSymLink(file); return new ByteArrayInputStream(Constants.encode(symLink)); } return new FileInputStream(file); } catch (IOException | UnsupportedOperationException e) { Activator.error(e.getMessage(), e); } } return null; }
Source:
public MaterializedViewSupervisor( TaskMaster taskMaster, TaskStorage taskStorage, MetadataSupervisorManager metadataSupervisorManager, SQLMetadataSegmentManager segmentManager, IndexerMetadataStorageCoordinator metadataStorageCoordinator, MaterializedViewTaskConfig config, MaterializedViewSupervisorSpec spec ) { this.taskMaster = taskMaster; this.taskStorage = taskStorage; this.metadataStorageCoordinator = metadataStorageCoordinator; this.segmentManager = segmentManager; this.metadataSupervisorManager = metadataSupervisorManager; this.config = config; this.spec = spec; this.dataSource = spec.getDataSourceName(); this.supervisorId = StringUtils.format("MaterializedViewSupervisor-%s", dataSource); this.maxTaskCount = spec.getContext().containsKey("maxTaskCount") ? Integer.parseInt(String.valueOf(spec.getContext().get("maxTaskCount"))) : MAX_TASK_COUNT; }

Target:
public MaterializedViewSupervisor( TaskMaster taskMaster, TaskStorage taskStorage, MetadataSupervisorManager metadataSupervisorManager, SQLMetadataSegmentManager segmentManager, IndexerMetadataStorageCoordinator metadataStorageCoordinator, MaterializedViewTaskConfig config, MaterializedViewSupervisorSpec spec ) { this.taskMaster = taskMaster; this.taskStorage = taskStorage; this.metadataStorageCoordinator = metadataStorageCoordinator; this.segmentManager = segmentManager; this.metadataSupervisorManager = metadataSupervisorManager; this.config = config; this.spec = spec; this.dataSource = spec.getDataSourceName(); this.supervisorId = StringUtils.format("MaterializedViewSupervisor-%s", dataSource); this.maxTaskCount = spec.getContext().containsKey("maxTaskCount") ? Integer.parseInt(String.valueOf(spec.getContext().get("maxTaskCount"))) : DEFAULT_MAX_TASK_COUNT; this.minDataLagMs = spec.getContext().containsKey("minDataLagMs") ? Long.parseLong(String.valueOf(spec.getContext().get("minDataLagMs"))) : DEFAULT_MIN_DATA_LAG_MS; }
Source:
protected boolean isInEndState() { if (status == LRAStatus.Cancelling && allFinished(heuristicList, failedList)) { status = LRAStatus.Cancelled; } else if (status == LRAStatus.Closing && allFinished(heuristicList, failedList)) { status = LRAStatus.Closed; } switch (status) { case FailedToCancel: case FailedToClose: case Closed: case Cancelled: return true; default: return false; } }

Target:
protected boolean isInEndState() { if (status == LRAStatus.Cancelling && allFinished(heuristicList, failedList)) { status = LRAStatus.Cancelled; } else if (status == LRAStatus.Closing && allFinished(heuristicList, failedList)) { status = LRAStatus.Closed; } return isFinished(); }
Source:
private ResponseEntity<?> postEventInternal(final String eventTypeName, final String eventsAsString, final NativeWebRequest nativeWebRequest, final EventTypeMetrics eventTypeMetrics, final Client client) { final long startingNanos = System.nanoTime(); try { final JSONArray eventsAsJsonObjects = new JSONArray(eventsAsString); final int eventCount = eventsAsJsonObjects.length(); final int size = eventsAsString.getBytes().length; eventTypeMetrics.reportSizing(eventCount, size); final ThrottleResult result = throttlingService.mark(client.getId(), eventTypeName, size, eventCount); return result.isThrottled() ? rateLimitHeaders(ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS), result).build() : response(publisher.publish(eventsAsJsonObjects, eventTypeName, client), result); } catch (final JSONException e) { LOG.debug("Problem parsing event", e); return processJSONException(e, nativeWebRequest); } catch (final NoSuchEventTypeException e) { LOG.debug("Event type not found.", e); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.debug("Failed to publish batch", e); return create(e.asProblem(), nativeWebRequest); } finally { eventTypeMetrics.updateTiming(startingNanos, System.nanoTime()); } }

Target:
private ResponseEntity<?> postEventInternal(final String eventTypeName, final String eventsAsString, final NativeWebRequest nativeWebRequest, final EventTypeMetrics eventTypeMetrics, final Client client) { final long startingNanos = System.nanoTime(); try { final JSONArray eventsAsJsonObjects = new JSONArray(eventsAsString); final int eventCount = eventsAsJsonObjects.length(); final int size = eventsAsString.getBytes().length; eventTypeMetrics.reportSizing(eventCount, size); final ThrottleResult result = throttlingService.mark(client.getId(), eventTypeName, size); return result.isThrottled() ? rateLimitHeaders(ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS), result).build() : response(publisher.publish(eventsAsJsonObjects, eventTypeName, client), result); } catch (final JSONException e) { LOG.debug("Problem parsing event", e); return processJSONException(e, nativeWebRequest); } catch (final NoSuchEventTypeException e) { LOG.debug("Event type not found.", e); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.debug("Failed to publish batch", e); return create(e.asProblem(), nativeWebRequest); } finally { eventTypeMetrics.updateTiming(startingNanos, System.nanoTime()); } }
Source:
public String run( ReportInfo ri ) { StringBuilder sb = new StringBuilder(); sb.append("Generated: ").append( new Date().toString() ).append("\n"); sb.append("From - Till: ").append( new SimpleDateFormat("MM/dd/yyyy").format(ri.from().getTime()) ).append(" - ").append( new SimpleDateFormat("MM/dd/yyyy").format(ri.till().getTime()) ).append("\n"); sb.append("Url: ").append( ConfigurationManager.getProperty("dspace.url") ).append("\n"); sb.append("\n"); for (String[] ss : new String[][] { new String[] { ConfigurationManager.getProperty("assetstore.dir"), "Assetstore size: ", }, new String[] { ConfigurationManager.getProperty("search.dir"), "Search dir size: ", }, new String[] { ConfigurationManager.getProperty("log.dir"), "Log dir size: ", }, }) { try { File dir = new File(ss[0]); if (dir.exists()) { long dir_size = FileUtils.sizeOfDirectory(dir); sb.append(String.format("%s: %s\n", ss[1], FileUtils.byteCountToDisplaySize(dir_size)) ); } else { sb.append(String.format("Directory [%s] does not exist!\n", ss[0])); } }catch(Exception e) { error(e, "directory - " + ss[0]); } } return sb.toString(); }

Target:
public String run( ReportInfo ri ) { StringBuilder sb = new StringBuilder(); sb.append("Generated: ").append( new Date().toString() ).append("\n"); sb.append("From - Till: ").append( new SimpleDateFormat("yyyy-MM-dd").format(ri.from().getTime()) ).append(" - ").append( new SimpleDateFormat("yyyy-MM-dd").format(ri.till().getTime()) ).append("\n"); sb.append("Url: ").append( ConfigurationManager.getProperty("dspace.url") ).append("\n"); sb.append("\n"); DSBitStoreService localStore = new DSpace().getServiceManager().getServicesByType(DSBitStoreService.class).get(0); for (String[] ss : new String[][] { new String[] { localStore.getBaseDir().toString(), "Assetstore size", }, new String[] { ConfigurationManager.getProperty("search.dir"), "Search dir size", }, new String[] { ConfigurationManager.getProperty("log.dir"), "Log dir size", }, }) { try { File dir = new File(ss[0]); if (dir.exists()) { long dir_size = FileUtils.sizeOfDirectory(dir); sb.append(String.format("%-20s: %s\n", ss[1], FileUtils.byteCountToDisplaySize(dir_size)) ); } else { sb.append(String.format("Directory [%s] does not exist!\n", ss[0])); } }catch(Exception e) { error(e, "directory - " + ss[0]); } } return sb.toString(); }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String searchQueryExtra = null; String searchUrl = null; if (savedInstanceState != null) { searchUrl = savedInstanceState.getString(INSTANCE_CURRENT_DISCOVER_URL, null); } if (getArguments() != null && searchUrl == null) { searchQueryExtra = getArguments().getString(Router.EXTRA_SEARCH_QUERY); } if (searchQueryExtra != null) { initSearch(searchQueryExtra); } else { loadUrl(searchUrl == null ? getInitialUrl() : searchUrl); } if (shouldShowSubjectDiscovery()) { initSubjects(); } if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String searchQueryExtra = null; String searchUrl = null; if (savedInstanceState != null) { searchUrl = savedInstanceState.getString(INSTANCE_CURRENT_DISCOVER_URL, null); } if (searchUrl == null && getArguments() != null) { searchQueryExtra = getArguments().getString(Router.EXTRA_SEARCH_QUERY); } if (searchQueryExtra != null) { initSearch(searchQueryExtra); } else { loadUrl(searchUrl == null ? getInitialUrl() : searchUrl); } if (shouldShowSubjectDiscovery()) { initSubjects(); } if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } }
Source:
public static void deleteAllUsers(final String userpoolId) { ListUsersResult listUsersResult; do { ListUsersRequest listUsersRequest = new ListUsersRequest() .withUserPoolId(userpoolId) .withLimit(60); listUsersResult = getUserpoolLL().listUsers(listUsersRequest); for (UserType user : listUsersResult.getUsers()) { if (USERNAME.equals(user.getUsername()) || "bimin".equals(user.getUsername()) || "roskumr@amazon.com".equals(user.getUsername())) { continue; } boolean retryConfirmSignUp = false; do { try { Log.d(TAG, "deleteAllUsers: " + user.getUsername()); getUserpoolLL().adminDeleteUser(new AdminDeleteUserRequest().withUsername(user.getUsername()).withUserPoolId(userpoolId)); } catch (UserNotConfirmedException e) { if (!retryConfirmSignUp) { AdminConfirmSignUpRequest adminConfirmSignUpRequest = new AdminConfirmSignUpRequest(); adminConfirmSignUpRequest.withUsername(user.getUsername()).withUserPoolId(userpoolId); getUserpoolLL().adminConfirmSignUp(adminConfirmSignUpRequest); retryConfirmSignUp = true; try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } } else { retryConfirmSignUp = false; } } catch (Exception e) { Log.e(TAG, "deleteAllUsers: Some error trying to delete user", e); } } while (retryConfirmSignUp); } } while (listUsersResult.getPaginationToken() != null); }

Target:
public static void deleteAllUsers(final String userpoolId) { ListUsersResult listUsersResult; do { ListUsersRequest listUsersRequest = new ListUsersRequest() .withUserPoolId(userpoolId) .withLimit(60); listUsersResult = getUserpoolLL().listUsers(listUsersRequest); for (UserType user : listUsersResult.getUsers()) { if (USERNAME.equals(user.getUsername()) || "bimin".equals(user.getUsername()) || "customAuthTestUser".equals(user.getUsername())) { continue; } boolean retryConfirmSignUp = false; do { try { Log.d(TAG, "deleteAllUsers: " + user.getUsername()); getUserpoolLL().adminDeleteUser(new AdminDeleteUserRequest().withUsername(user.getUsername()).withUserPoolId(userpoolId)); } catch (UserNotConfirmedException e) { if (!retryConfirmSignUp) { AdminConfirmSignUpRequest adminConfirmSignUpRequest = new AdminConfirmSignUpRequest(); adminConfirmSignUpRequest.withUsername(user.getUsername()).withUserPoolId(userpoolId); getUserpoolLL().adminConfirmSignUp(adminConfirmSignUpRequest); retryConfirmSignUp = true; try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } } else { retryConfirmSignUp = false; } } catch (Exception e) { Log.e(TAG, "deleteAllUsers: Some error trying to delete user", e); } } while (retryConfirmSignUp); } } while (listUsersResult.getPaginationToken() != null); }
Source:
public static void cleanup() { if (scs_kafka_test_embedded != null) { System.setProperty("SCS_KAFKA_TEST_EMBEDDED", scs_kafka_test_embedded); } else { System.clearProperty("SCS_KAFKA_TEST_EMBEDDED"); } }

Target:
public static void cleanup() { System.clearProperty("SCS_KAFKA_TEST_EMBEDDED"); }
Source:
public static String getFormattedFileName(Artifact artifact) { StringBuilder destFileName = buildMainFileName(artifact); String extension = new DefaultArtifactHandler(artifact.getType()).getExtension(); destFileName.append(extension); return destFileName.toString(); }

Target:
public static String getFormattedFileName(Artifact artifact) { String destFileName = buildMainFileName(artifact); String extension = new DefaultArtifactHandler(artifact.getType()).getExtension(); return destFileName + "." + extension; }
Source:
public void put( Locator locator, String key, String value ) throws IOException { Timer.Context ctx = Instrumentation.getWriteTimerContext( CassandraModel.CF_METRICS_METADATA_NAME ); Session session = DatastaxIO.getSession(); try { Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME ) .value( KEY, locator.toString() ) .value( COLUMN1, key ) .value( VALUE, serDes.serialize( value ) ); insert.setConsistencyLevel( ConsistencyLevel.ONE ); ResultSet result = session.execute( insert ); LOG.debug( "result.size=" + result.all().size() ); } finally { ctx.stop(); } }

Target:
public void put( Locator locator, String key, String value ) throws IOException { Timer.Context ctx = Instrumentation.getWriteTimerContext( CassandraModel.CF_METRICS_METADATA_NAME ); Session session = DatastaxIO.getSession(); try { Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME ) .value( KEY, locator.toString() ) .value( COLUMN1, key ) .value( VALUE, serDes.serialize( value ) ); insert.setConsistencyLevel( ConsistencyLevel.ONE ); ResultSet result = session.execute( insert ); LOG.trace( "result.size=" + result.all().size() ); } finally { ctx.stop(); } }
Source:
protected void parseCurrencyPairsFromJsonObject(int requestId, JSONObject jsonObject, List<CurrencyPairInfo> pairs) throws Exception { final JSONArray data = jsonObject.getJSONArray("data"); for(int i=0; i< data.length(); ++i) { String symbol = data.getJSONObject(i).getString("symbol"); String[] currencies = symbol.split("-"); if(currencies.length!=2) continue; String currencyBase = currencies[0].toUpperCase(Locale.ENGLISH); String currencyCounter = currencies[1].toUpperCase(Locale.ENGLISH); pairs.add(new CurrencyPairInfo(currencyBase, currencyCounter, symbol)); } }

Target:
protected void parseCurrencyPairsFromJsonObject(int requestId, JSONObject jsonObject, List<CurrencyPairInfo> pairs) throws Exception { final JSONArray data = jsonObject.getJSONArray("data"); for(int i=0; i< data.length(); ++i) { final JSONObject pairJsonObject = data.getJSONObject(i); pairs.add(new CurrencyPairInfo( pairJsonObject.getString("coinType"), pairJsonObject.getString("coinTypePair"), pairJsonObject.getString("symbol") )); } }
Source:
public void truncateTable(TableName tableName, boolean preserveSplits) throws IOException { HTableDescriptor tableDescriptor = getTableDescriptor(tableName); LOG.info("Deleting table %s", tableName); deleteTable(tableName); LOG.info("Creating table %s", tableName); createTable(tableDescriptor); }

Target:
public void truncateTable(TableName tableName, boolean preserveSplits) throws IOException { byte[][] splitKeys = null; if (preserveSplits) { splitKeys = getSplits(tableName); } HTableDescriptor tableDescriptor = getTableDescriptor(tableName); LOG.info("Deleting table %s for truncation.", tableName); deleteTable(tableName); LOG.info("Recreating table %s for truncation", tableName); createTable(tableDescriptor, splitKeys); }
Source:
public void setupContext() { super.setupContext(); NodeMetadata node = null; try { node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group))); } catch (RunNodesException e) { e.printStackTrace(); } String resourceid = String.format("/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s", IdReference.extractResourceGroup(node.getProviderId()), IdReference.extractName(node.getProviderId())); location = view.getComputeService().templateBuilder().build().getLocation().getId(); view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null); metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceid); }

Target:
public void setupContext() { super.setupContext(); NodeMetadata node = null; try { node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group))); } catch (RunNodesException e) { fail(); } String resourceId = String.format("/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s", IdReference.extractResourceGroup(node.getProviderId()), IdReference.extractName(node.getProviderId())); location = view.getComputeService().templateBuilder().build().getLocation().getId(); view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null); metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceId); }
Source:
public void testParquetTupleDomainPrimitiveArray() { HiveColumnHandle columnHandle = new HiveColumnHandle("my_array", HiveType.valueOf("array<int>"), parseTypeSignature(StandardTypes.ARRAY), 0, REGULAR, Optional.empty()); TupleDomain<HiveColumnHandle> domain = withColumnDomains(ImmutableMap.of(columnHandle, Domain.notNull(new ArrayType(INTEGER)))); MessageType fileSchema = new MessageType("hive_schema", new GroupType(OPTIONAL, "my_array", new GroupType(REPEATED, "bag", new PrimitiveType(OPTIONAL, INT32, "array_element")))); Map<Type, HiveColumnHandle> typeColumns = new HashMap<>(); typeColumns.put(getParquetType(columnHandle, fileSchema, true), columnHandle); Map<List<String>, RichColumnDescriptor> descriptorsByPath = getDescriptors(fileSchema, fileSchema, typeColumns); TupleDomain<ColumnDescriptor> tupleDomain = getParquetTupleDomain(descriptorsByPath, domain); assertTrue(tupleDomain.getDomains().get().isEmpty()); }

Target:
public void testParquetTupleDomainPrimitiveArray() { HiveColumnHandle columnHandle = new HiveColumnHandle("my_array", HiveType.valueOf("array<int>"), parseTypeSignature(StandardTypes.ARRAY), 0, REGULAR, Optional.empty()); TupleDomain<HiveColumnHandle> domain = withColumnDomains(ImmutableMap.of(columnHandle, Domain.notNull(new ArrayType(INTEGER)))); MessageType fileSchema = new MessageType("hive_schema", new GroupType(OPTIONAL, "my_array", new GroupType(REPEATED, "bag", new PrimitiveType(OPTIONAL, INT32, "array_element")))); Map<Type, HiveColumnHandle> typeColumns = ImmutableMap.of(getParquetType(columnHandle, fileSchema, true), columnHandle); Map<List<String>, RichColumnDescriptor> descriptorsByPath = getDescriptors(fileSchema, fileSchema, typeColumns); TupleDomain<ColumnDescriptor> tupleDomain = getParquetTupleDomain(descriptorsByPath, domain); assertTrue(tupleDomain.getDomains().get().isEmpty()); }
Source:
public void editFilenamelNonFileObjTest() { when(repoObjLoader.getRepositoryObject(any(PID.class))).thenReturn(workObj); doThrow(new IllegalArgumentException()).when(aclService) .assertHasAccess(anyString(), eq(pid), any(AccessGroupSet.class), eq(Permission.editDescription)); try { service.editLabel(agent, pid, "label"); } catch (Exception e) { assertEquals(e.getCause().getClass(), IllegalArgumentException.class); } }

Target:
public void editFilenamelNonFileObjTest() { when(repoObjLoader.getRepositoryObject(any(PID.class))).thenReturn(workObj); try { service.editLabel(agent, pid, "label"); } catch (Exception e) { assertEquals(e.getCause().getClass(), IllegalArgumentException.class); } }
Source:
private void removeAllStores(JSONArray args, CallbackContext callbackContext) throws JSONException { List<String> userDatabaseNames = SmartStoreSDKManager.getInstance().getUserStoresPrefixList(); for(String storeName : userDatabaseNames) { SmartStoreSDKManager.getInstance().removeSmartStore(storeName,UserAccountManager.getInstance().getCurrentUser(),UserAccountManager.getInstance().getCurrentUser().getCommunityId()); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }

Target:
private void removeAllStores(JSONArray args, CallbackContext callbackContext) throws JSONException { SmartStoreSDKManager.getInstance().removeAllUserStores(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }
Source:
public StaticMethodInformation(String name, String[] parameterTypes, String returnType, String declaringClass) { this.name = name; this.parameterTypes = parameterTypes.clone(); this.returnType = returnType; this.declaringClass = declaringClass; StringBuilder builder = new StringBuilder("("); for (String p : this.parameterTypes) { builder.append(p); } builder.append(')'); builder.append(returnType); descriptor = builder.toString(); this.modifiers = AccessFlag.PUBLIC; }

Target:
public StaticMethodInformation(String name, String[] parameterTypes, String returnType, String declaringClass) { this.name = name; this.parameterTypes = parameterTypes; this.returnType = returnType; this.declaringClass = declaringClass; StringBuilder builder = new StringBuilder("("); for (String p : this.parameterTypes) { builder.append(p); } builder.append(')'); builder.append(returnType); descriptor = builder.toString(); this.modifiers = AccessFlag.PUBLIC; }
Source:
public Result updateElementRevision(String id, String revisionString) { UserSession session = getAuthenticatedSession(DEVELOPER); Long revision = BridgeUtils.getLongOrDefault(revisionString, 0L); AppConfigElement element = parseJson(request(), AppConfigElement.class); element.setId(id); element.setRevision(revision); VersionHolder holder = service.updateElementRevision(session.getStudyIdentifier(), element); return okResult(holder); }

Target:
public Result updateElementRevision(String id, String revisionString) { UserSession session = getAuthenticatedSession(DEVELOPER); Long revision = BridgeUtils.getLongOrDefault(revisionString, null); if (revision == null) { throw new BadRequestException("Revision is not a valid revision number"); } AppConfigElement element = parseJson(request(), AppConfigElement.class); element.setId(id); element.setRevision(revision); VersionHolder holder = service.updateElementRevision(session.getStudyIdentifier(), element); return okResult(holder); }
Source:
private boolean checkForHypervisorIdUpdate(Consumer existing, ConsumerDTO incoming) { HypervisorIdDTO incomingId = incoming.getHypervisorId(); if (incomingId != null) { HypervisorId existingId = existing.getHypervisorId(); if (incomingId.getHypervisorId() == null || incomingId.getHypervisorId().isEmpty()) { existing.setHypervisorId(null); } else { if (existingId != null) { if (existingId.getHypervisorId() != null && !existingId.getHypervisorId().equals(incomingId.getHypervisorId())) { existingId.setHypervisorId(incomingId.getHypervisorId()); Owner owner = ownerCurator.findOwnerById(existing.getOwnerId()); existingId.setOwner(owner); } else { return false; } } else { Owner owner = ownerCurator.findOwnerById(existing.getOwnerId()); if (isUsedByOwner(incomingId, owner)) { throw new BadRequestException(i18n.tr( "Problem updating unit {0}. Hypervisor id: {1} is already used.", incoming, incomingId.getHypervisorId())); } HypervisorId hypervisorId = new HypervisorId(incomingId.getHypervisorId()); hypervisorId.setOwner(owner); existing.setHypervisorId(hypervisorId); } } return true; } return false; }

Target:
private boolean checkForHypervisorIdUpdate(Consumer existing, ConsumerDTO incoming) { HypervisorIdDTO incomingId = incoming.getHypervisorId(); if (incomingId != null) { HypervisorId existingId = existing.getHypervisorId(); if (incomingId.getHypervisorId() == null || incomingId.getHypervisorId().isEmpty()) { existing.setHypervisorId(null); } else { Owner owner = ownerCurator.findOwnerById(existing.getOwnerId()); if (isUsedByOwner(incomingId, owner)) { throw new BadRequestException(i18n.tr( "Problem updating unit {0}. Hypervisor id: {1} is already used.", incoming, incomingId.getHypervisorId())); } if (existingId != null) { if (existingId.getHypervisorId() != null && !existingId.getHypervisorId().equals(incomingId.getHypervisorId())) { existingId.setHypervisorId(incomingId.getHypervisorId()); existingId.setOwner(owner); } else { return false; } } else { HypervisorId hypervisorId = new HypervisorId(incomingId.getHypervisorId()); hypervisorId.setOwner(owner); existing.setHypervisorId(hypervisorId); } } return true; } return false; }
Source:
public boolean isPanelValid() { return true; }

Target:
public boolean isPanelValid() { configPanel.clearErrorText(); String selectedFilePath = configPanel.getSelectedFilePath(); if(selectedFilePath.isEmpty()) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_noPathSelected()); return false; } File selectedFile = new File(selectedFilePath); Path selectedPath = selectedFile.toPath(); if (!Files.isReadable(selectedPath)) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_notReadable()); return false; } try { if (!XRYFolder.isXRYFolder(selectedPath)) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_notXRYFolder()); return false; } } catch (IOException ex) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_ioError()); logger.log(Level.WARNING, "[XRY DSP] I/O exception encountered trying to test the XRY folder.", ex); return false; } return true; }
Source:
public void finish() { IConsumerAggregator aggregator = fXAggregator; if (aggregator != null) { fSeries.stream().map(s -> s.getXConsumer()).forEach(aggregator::accept); } aggregator = fYAggregator; if (aggregator != null) { fSeries.stream().map(s -> s.getYConsumer()).forEach(aggregator::accept); } }

Target:
public void finish() { IConsumerAggregator aggregatorX = fXAggregator; if (aggregatorX != null) { fSeries.forEach(s -> aggregatorX.accept(s.getXConsumer())); } IConsumerAggregator aggregatorY = fYAggregator; if (aggregatorY != null) { fSeries.forEach(s -> aggregatorY.accept(s.getYConsumer())); } }
Source:
private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context).withName("Community").build(); String token = getAuthToken(asUser.getEmail(), password); new MetadataPatchSuite().runWith(getClient(token), "/api/core/communities/" + parentCommunity.getID(), expectedStatus); }

Target:
private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context).withName("Community").build(); context.restoreAuthSystemState(); String token = getAuthToken(asUser.getEmail(), password); new MetadataPatchSuite().runWith(getClient(token), "/api/core/communities/" + parentCommunity.getID(), expectedStatus); }
Source:
public void validate(final List<LotDepositDto> lotDepositDtos){ errors = new MapBindingResult(new HashMap<String, String>(), LotGeneratorInputDto.class.getName()); if (lotDepositDtos == null) { errors.reject("lot.deposit.input.null", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } lotDepositDtos.forEach((LotDepositDto lotDepositDto) ->{ inventoryCommonValidator.validateTransactionNotes(lotDepositDto.getNotes(), errors); if(lotDepositDto.getAmount() == null || lotDepositDto.getAmount() <= 0){ errors.reject("lot.amount.invalid", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }); }

Target:
public void validate(final List<LotDepositDto> lotDepositDtos){ errors = new MapBindingResult(new HashMap<String, String>(), LotGeneratorInputDto.class.getName()); BaseValidator.checkNotEmpty(lotDepositDtos,"lot.deposit.input.null"); lotDepositDtos.forEach((LotDepositDto lotDepositDto) ->{ inventoryCommonValidator.validateTransactionNotes(lotDepositDto.getNotes(), errors); if(lotDepositDto.getAmount() == null || lotDepositDto.getAmount() <= 0){ errors.reject("lot.amount.invalid", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }); }
Source:
public Token<OzoneTokenIdentifier> getDelegationToken(Text renewer) throws IOException { Token<OzoneTokenIdentifier> token = ozoneManagerClient.getDelegationToken(renewer); if (token != null) { token.setService(dtService); LOG.debug("Created token for dtService {}", token, dtService); } else { LOG.debug("Cannot get ozone delegation token from for service {}", renewer, dtService); } return token; }

Target:
public Token<OzoneTokenIdentifier> getDelegationToken(Text renewer) throws IOException { Token<OzoneTokenIdentifier> token = ozoneManagerClient.getDelegationToken(renewer); if (token != null) { token.setService(dtService); LOG.debug("Created token for dtService {}", token, dtService); } else { LOG.debug("Cannot get ozone delegation token for renewer to access " + "service {}", renewer, dtService); } return token; }
Source:
private void sendTakeMastershipEvent(long uso) { Pair<Mailbox, ImmutableList<Long>> p = m_ackMailboxRefs.get(); Mailbox mbx = p.getFirst(); if (mbx != null && p.getSecond().size() > 0 && m_newLeaderHostId != null) { final int msgLen = 1 + 4 + 4 + m_signatureBytes.length + 8; ByteBuffer buf = ByteBuffer.allocate(msgLen); buf.put(ExportManager.TAKE_MASTERSHIP); buf.putInt(m_partitionId); buf.putInt(m_signatureBytes.length); buf.put(m_signatureBytes); buf.putLong(uso); BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array()); for(Long siteId: p.getSecond()) { if (CoreUtils.getHostIdFromHSId(siteId) != m_newLeaderHostId) { continue; } mbx.send(siteId, bpm); if (exportLog.isDebugEnabled()) { exportLog.debug("Partition " + m_partitionId + " mailbox hsid (" + CoreUtils.hsIdToString(mbx.getHSId()) + ") send TAKE_MASTERSHIP message to " + CoreUtils.hsIdToString(siteId)); } } m_usoToDrain = -1L; m_newLeaderHostId = null; } }

Target:
private void sendTakeMastershipEvent(long uso) { Pair<Mailbox, ImmutableList<Long>> p = m_ackMailboxRefs.get(); Mailbox mbx = p.getFirst(); if (mbx != null && p.getSecond().size() > 0 && m_newLeaderHostId != null) { final int msgLen = 1 + 4 + 4 + m_signatureBytes.length + 8; ByteBuffer buf = ByteBuffer.allocate(msgLen); buf.put(ExportManager.TAKE_MASTERSHIP); buf.putInt(m_partitionId); buf.putInt(m_signatureBytes.length); buf.put(m_signatureBytes); buf.putLong(uso); BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array()); for(Long siteId: p.getSecond()) { if (CoreUtils.getHostIdFromHSId(siteId) == m_newLeaderHostId) { mbx.send(siteId, bpm); if (exportLog.isDebugEnabled()) { exportLog.debug("Partition " + m_partitionId + " mailbox hsid (" + CoreUtils.hsIdToString(mbx.getHSId()) + ") send TAKE_MASTERSHIP message to " + CoreUtils.hsIdToString(siteId)); } break; } } m_usoToDrain = -1L; m_newLeaderHostId = null; } }
Source:
public String getRequestSpecificParams() { StringWriter writer = new StringWriter(); writer.write("/json?indicator="); writer.write(getIndicator()); for (String year : getYears()) { if (!year.isEmpty()) { writer.write("&years="); writer.write(year); } } if (!getGender().isEmpty()) { writer.write("&genders="); writer.write(getGender()); } return writer.toString(); }

Target:
public String getRequestSpecificParams() { Map<String, String> params = new HashMap<>(); params.put("indicator", getIndicator()); params.put("genders", getGender()); String url = IOHelper.constructUrl("/json", params); Map<String, String[]> years = new HashMap<>(); years.put("years", getYears()); return url + "&" + IOHelper.getParamsMultiValue(years); }