auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getStoreClientConfigString(List<String> storeNames, String coordinatorUrl) { String result = null; try { RestRequestBuilder requestBuilder = new RestRequestBuilder(new URI(coordinatorUrl + URL_SEPARATOR + STORE_CLIENT_CONFIG_OPS + URL_SEPARATOR + Joiner.on(",") .join(storeNames))); String timeoutStr = Long.toString(this.config.getTimeoutConfig() .getOperationTimeout(VoldemortOpCode.GET_OP_CODE)); requestBuilder.setMethod(GET); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, String.valueOf(System.currentTimeMillis())); if(this.routingTypeCode != null) { requestBuilder.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode); } if(this.zoneId != INVALID_ZONE_ID) { requestBuilder.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId)); } RestRequest request = requestBuilder.build(); Future<RestResponse> future = client.restRequest(request); RestResponse response = future.get(); ByteString entity = response.getEntity(); result = entity.asString("UTF-8"); } catch(ExecutionException e) { if(e.getCause() instanceof RestException) { RestException exception = (RestException) e.getCause(); if(logger.isDebugEnabled()) { logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus()); } } else { throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e); } } catch(InterruptedException e) { if(logger.isDebugEnabled()) { logger.debug("Operation interrupted : " + e.getMessage(), e); } throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e); } catch(URISyntaxException e) { throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e); } return result; }

Target:
public String getStoreClientConfigString(List<String> storeNames, String coordinatorUrl) { try { StringBuilder URIStringBuilder = new StringBuilder().append(coordinatorUrl) .append(URL_SEPARATOR) .append(STORE_CLIENT_CONFIG_OPS) .append(URL_SEPARATOR) .append(Joiner.on(",") .join(storeNames)); RestRequestBuilder requestBuilder = new RestRequestBuilder(new URI(URIStringBuilder.toString())); String timeoutStr = Long.toString(this.config.getTimeoutConfig() .getOperationTimeout(VoldemortOpCode.GET_OP_CODE)); requestBuilder.setMethod(requestType.GET.toString()); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr); requestBuilder = setCommonRequestHeader(requestBuilder); RestRequest request = requestBuilder.build(); Future<RestResponse> future = client.restRequest(request); RestResponse response = future.get(); ByteString entity = response.getEntity(); return entity.asString("UTF-8"); } catch(Exception e) { if(e.getCause() instanceof RestException) { return ((RestException) e.getCause()).getResponse().getEntity().asString("UTF-8"); } handleRequestAndResponseException(e); } return null; }
Source:
private List<VendorSupplierDiversity> buildVendorDiversitiesFromPmwFormDropDownLists(PaymentWorksVendor pmwVendor, Map<String, SupplierDiversity> paymentWorksToKfsDiversityMap, List<VendorSupplierDiversity> kfsVendorSupplierDiversities) { if (paymentWorksFormModeService.shouldUseLegacyFormProcessingMode()) { VendorSupplierDiversity minority = createVendorSupplierDiversityForDropDownData(pmwVendor.getMinorityStatus(), pmwVendor.getMbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(minority)) { kfsVendorSupplierDiversities.add(minority); } VendorSupplierDiversity womanOwned = createVendorSupplierDiversityForDropDownData(pmwVendor.getWomanOwned(), pmwVendor.getWbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(womanOwned)) { kfsVendorSupplierDiversities.add(womanOwned); } VendorSupplierDiversity veteran = createVendorSupplierDiversityForDropDownData(pmwVendor.getDisabledVeteran(), pmwVendor.getVeteranCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(veteran)) { kfsVendorSupplierDiversities.add(veteran); } } else if (paymentWorksFormModeService.shouldUseForeignFormProcessingMode()) { LOG.info("buildVendorDiversitiesFromPmwFormDropDownLists, " + PaymentWorksConstants.FOREIGN_FORM_PROCESSING_NOT_IMPLEMENTED_LOG_MESSAGE); } return kfsVendorSupplierDiversities; }

Target:
private List<VendorSupplierDiversity> buildVendorDiversitiesFromPmwFormDropDownLists(PaymentWorksVendor pmwVendor, Map<String, SupplierDiversity> paymentWorksToKfsDiversityMap, List<VendorSupplierDiversity> kfsVendorSupplierDiversities) { VendorSupplierDiversity minority = createVendorSupplierDiversityForDropDownData(pmwVendor.getMinorityStatus(), pmwVendor.getMbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(minority)) { kfsVendorSupplierDiversities.add(minority); } VendorSupplierDiversity womanOwned = createVendorSupplierDiversityForDropDownData(pmwVendor.getWomanOwned(), pmwVendor.getWbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(womanOwned)) { kfsVendorSupplierDiversities.add(womanOwned); } VendorSupplierDiversity veteran = createVendorSupplierDiversityForDropDownData(pmwVendor.getDisabledVeteran(), pmwVendor.getVeteranCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(veteran)) { kfsVendorSupplierDiversities.add(veteran); } return kfsVendorSupplierDiversities; }
Source:
public List<DMNIncludeModel> loadModels(final WorkspaceProject workspaceProject) { return getPaths(workspaceProject) .stream() .map(includeModelFactory::create) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); }

Target:
public List<DMNIncludeModel> loadModels(final WorkspaceProject workspaceProject) { return getPaths(workspaceProject) .stream() .map(getPathDMNIncludeModelFunction()) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
public byte[] getBytesUnsafe() { return getBytes(); }

Target:
public byte[] getBytesUnsafe() { return cachedBytes != null ? cachedBytes : getBytes(); }
Source:
private <T extends Connection> void parseConnectionList(Node n, T conTemplate, EList<T> connectionlist) { NodeList childNodes = n.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node connectionNode = childNodes.item(i); if (LibraryElementTags.CONNECTION_ELEMENT.equals(connectionNode.getNodeName())) { T connection = EcoreUtil.copy(conTemplate); connection.setResTypeConnection(false); NamedNodeMap connectionAttributeMap = connectionNode.getAttributes(); Node destinationElement = connectionAttributeMap.getNamedItem(LibraryElementTags.DESTINATION_ATTRIBUTE); if (destinationElement != null) { IInterfaceElement destination = getConnectionEndPoint(destinationElement.getNodeValue()); if (null != destination) { connection.setDestination(destination); } else { Activator.getDefault() .logError("Connection destination not found: " + destinationElement.getNodeValue()); continue; } } Node sourceElement = connectionAttributeMap.getNamedItem(LibraryElementTags.SOURCE_ATTRIBUTE); if (sourceElement != null) { IInterfaceElement source = getConnectionEndPoint(sourceElement.getNodeValue()); if (null != source) { connection.setSource(source); } else { Activator.getDefault().logError("Connection source not found: " + sourceElement.getNodeValue()); continue; } } Node commentElement = connectionAttributeMap.getNamedItem(LibraryElementTags.COMMENT_ATTRIBUTE); if (commentElement != null) { connection.setComment(commentElement.getNodeValue()); } parseConnectionRouting(connectionAttributeMap, connection); connectionlist.add(connection); } } }

Target:
private <T extends Connection> void parseConnectionList(Node n, T conTemplate, EList<T> connectionlist) { NodeList childNodes = n.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node connectionNode = childNodes.item(i); if (LibraryElementTags.CONNECTION_ELEMENT.equals(connectionNode.getNodeName())) { T connection = EcoreUtil.copy(conTemplate); connection.setResTypeConnection(false); NamedNodeMap connectionAttributeMap = connectionNode.getAttributes(); Node destinationElement = connectionAttributeMap.getNamedItem(LibraryElementTags.DESTINATION_ATTRIBUTE); if (destinationElement != null) { IInterfaceElement destination = getConnectionEndPoint(destinationElement.getNodeValue()); if (null != destination) { connection.setDestination(destination); } else { Activator.getDefault() .logError("Connection destination not found: " + destinationElement.getNodeValue()); continue; } } Node sourceElement = connectionAttributeMap.getNamedItem(LibraryElementTags.SOURCE_ATTRIBUTE); if (null != sourceElement) { IInterfaceElement source = getConnectionEndPoint(sourceElement.getNodeValue()); if (null != source) { connection.setSource(source); } else { Activator.getDefault().logError("Connection source not found: " + sourceElement.getNodeValue()); continue; } } Node commentElement = connectionAttributeMap.getNamedItem(LibraryElementTags.COMMENT_ATTRIBUTE); if (null != commentElement) { connection.setComment(commentElement.getNodeValue()); } parseConnectionRouting(connectionAttributeMap, connection); connectionlist.add(connection); } } }
Source:
public void onCreate() { Log.d(TAG, "Service started"); newEpisodesNotification = new NewEpisodesNotification(getApplicationContext()); isRunning = true; handler = new Handler(Looper.getMainLooper()); notificationManager = new DownloadServiceNotification(this); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); downloadCompletionThread.start(); Notification notification = notificationManager.updateNotifications( requester.getNumberOfDownloads(), downloads); startForeground(R.id.notification_downloading, notification); }

Target:
public void onCreate() { Log.d(TAG, "Service started"); isRunning = true; handler = new Handler(Looper.getMainLooper()); notificationManager = new DownloadServiceNotification(this); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); downloadCompletionThread.start(); Notification notification = notificationManager.updateNotifications( requester.getNumberOfDownloads(), downloads); startForeground(R.id.notification_downloading, notification); }
Source:
public ByteBuf getCommandLineBytes() { final int dataItemsSize = dataItems == null ? macro.name().length() : dataItems.length(); final String changedSinceStr = changedSince == null ? "" : changedSince.toString(); final int vanishedSize = isVanished ? SP_VANISHED.length() : 0; final int len = ImapClientConstants.PAD_LEN + changedSinceStr.length() + dataItemsSize + msgNumbers.length() + vanishedSize; final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_FETCH_SP_B : FETCH_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (dataItems != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(dataItems.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); } else { sb.writeBytes(macro.name().getBytes(StandardCharsets.US_ASCII)); } if (changedSince != null) { sb.writeByte(ImapClientConstants.SPACE); sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(CHANGEDSINCE_SP_B); sb.writeBytes(changedSinceStr.getBytes(StandardCharsets.US_ASCII)); if (isVanished) { sb.writeBytes(SP_VANISHED_B); } sb.writeByte(ImapClientConstants.R_PAREN); } sb.writeBytes(CRLF_B); return sb; }

Target:
public ByteBuf getCommandLineBytes() { final int dataItemsSize = dataItems == null ? macro.name().length() : dataItems.length(); final String changedSinceStr = changedSince == null ? "" : changedSince.toString(); final int vanishedSize = isVanished ? SP_VANISHED.length() : 0; final int len = ImapClientConstants.PAD_LEN + dataItemsSize + msgNumbers.length() + vanishedSize; final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_FETCH_SP_B : FETCH_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (dataItems != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(dataItems.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); } else { sb.writeBytes(macro.name().getBytes(StandardCharsets.US_ASCII)); } if (changedSince != null) { sb.writeByte(ImapClientConstants.SPACE); sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(CHANGEDSINCE_SP_B); sb.writeBytes(changedSinceStr.getBytes(StandardCharsets.US_ASCII)); if (isVanished) { sb.writeBytes(SP_VANISHED_B); } sb.writeByte(ImapClientConstants.R_PAREN); } sb.writeBytes(CRLF_B); return sb; }
Source:
public void testGenerateTaskManagerResourceIDWithRemoteRpcService() throws Exception { final Configuration configuration = createConfiguration(); final String rpcAddress = "flink"; final int rpcPort = 9090; final String taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, rpcAddress, rpcPort); assertThat(taskManagerResourceID, notNullValue()); assertThat(taskManagerResourceID.substring(0, taskManagerResourceID.length() - 7), equalTo(rpcAddress + ":" + rpcPort)); }

Target:
public void testGenerateTaskManagerResourceIDWithRemoteRpcService() throws Exception { final Configuration configuration = createConfiguration(); final String rpcAddress = "flink"; final int rpcPort = 9090; final String taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, rpcAddress, rpcPort); assertThat(taskManagerResourceID, notNullValue()); assertThat(taskManagerResourceID, containsString(rpcAddress + ":" + rpcPort)); }
Source:
public @NonNull TmfModelResponse<TmfTreeModel<TimeGraphEntryModel>> fetchTree(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { fetchTreeIsComplete = true; long rootId = ENTRY_ID.getAndIncrement(); TraceEntryModel traceEntry = new TraceEntryModel(getTrace(), rootId); entryList = new ArrayList<>(); entryList.add(traceEntry); for (ITmfAnalysisModuleWithStateSystems module : fmodules) { synchronized (fStartedAnalysis) { if (monitor != null) { if (monitor.isCanceled()) { return new TmfModelResponse<>(null, Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } } } waitForInitialization(getTrace(), module); long id = ENTRY_ID.getAndIncrement(); entryList.add(new ModuleEntryModel(id, rootId, module, traceEntry.getStartTime())); for (ITmfStateSystem ss : module.getStateSystems()) { addStateSystem(ss, id); } } Status status = fetchTreeIsComplete ? Status.COMPLETED : Status.RUNNING; String msg = fetchTreeIsComplete ? CommonStatusMessage.COMPLETED : CommonStatusMessage.RUNNING; return new TmfModelResponse<>(new TmfTreeModel<>(Collections.emptyList(), entryList), status, msg); }

Target:
public @NonNull TmfModelResponse<TmfTreeModel<TimeGraphEntryModel>> fetchTree(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { fetchTreeIsComplete = true; long rootId = ENTRY_ID.getAndIncrement(); ITmfTrace trace = getTrace(); TraceEntryModel.Builder traceEntry = new TraceEntryModel.Builder(rootId, trace.getName(), trace.getStartTime().toNanos(), trace); entryList = new ArrayList<>(); moduleEntryModelList = new ArrayList<>(); long traceEnd = traceEntry.getStartTime(); for (ITmfAnalysisModuleWithStateSystems module : fModules) { synchronized (fStartedAnalysis) { if (monitor != null) { if (monitor.isCanceled()) { return new TmfModelResponse<>(null, Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } } } waitForInitialization(getTrace(), module); long id = ENTRY_ID.getAndIncrement(); ModuleEntryModel.Builder moduleEntry = new ModuleEntryModel.Builder(id, module.getName(), traceEntry.getStartTime(), module); long moduleEnd = traceEntry.getStartTime(); for (ITmfStateSystem ss : module.getStateSystems()) { addStateSystem(ss, id); moduleEnd = Long.max(moduleEnd, ss.getCurrentEndTime()); } moduleEntry.setEndTime(moduleEnd); traceEnd = Long.max(traceEnd, moduleEnd); ModuleEntryModel finalModuleEntry = moduleEntry.build(rootId); entryList.add(finalModuleEntry); moduleEntryModelList.add(finalModuleEntry); } traceEntry.setEndTime(traceEnd); TraceEntryModel finalTraceEntry = traceEntry.build(-1); entryList.add(finalTraceEntry); Collections.reverse(entryList); Status status = fetchTreeIsComplete ? Status.COMPLETED : Status.RUNNING; String msg = fetchTreeIsComplete ? CommonStatusMessage.COMPLETED : CommonStatusMessage.RUNNING; return new TmfModelResponse<>(new TmfTreeModel<>(Collections.emptyList(), entryList), status, msg); }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_RESULT_SELECT_CELLTOWERS) { if (resultCode == RESULT_OK) { log.debug("Chosen file: " + data.getDataString()); try { String type = getContentResolver().getType(data.getData()); boolean isGzip = type != null && type.equals("application/octet-stream") && data.getDataString().endsWith(".gz"); InputStream importFile = getContentResolver().openInputStream(data.getData()); importCellTowersData(importFile, isGzip); } catch (FileNotFoundException e) { e.printStackTrace(); log.error("Cannot open file " + data.getDataString(), e); Helpers.msgShort(this, getString(R.string.error_importing_celltowers_data)); } } } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_RESULT_SELECT_CELLTOWERS) { if (resultCode == RESULT_OK) { log.debug("Chosen file: " + data.getDataString()); importCellTowersData(data.getData()); } } }
Source:
public AccountGroupCollection(Collection<AccountGroup> groups) { this.groups = groups; }

Target:
public AccountGroupCollection(Collection<AccountGroup> groups) { this.groups = Collections.unmodifiableCollection(groups); }
Source:
public void waitForInitialRemoteData_readOnlyTrue_throwsIfWrongServerSchema() { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.logIn(credentials, Constants.AUTH_URL); final SyncConfiguration configNew = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .waitForInitialRemoteData() .readOnly() .schema(StringOnly.class) .build(); assertFalse(configNew.realmExists()); Realm realm = null; try { realm = Realm.getInstance(configNew); fail(); } catch (RealmMigrationNeededException ignored) { } finally { if (realm != null) { realm.close(); } user.logOut(); } }

Target:
public void waitForInitialRemoteData_readOnlyTrue_throwsIfWrongServerSchema() { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.logIn(credentials, Constants.AUTH_URL); final SyncConfiguration configNew = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .waitForInitialRemoteData() .readOnly() .schema(StringOnly.class) .build(); assertFalse(configNew.realmExists()); Realm realm = null; try { realm = Realm.getInstance(configNew); fail(); } catch (RealmMigrationNeededException ignore) { } finally { if (realm != null) { realm.close(); } user.logOut(); } }
Source:
protected String buildGroupBySQL(List<String> aggregateFunctions) { String groupedColSql = Joiner.on(",").join(mGroupedColumns); String selectFuncSql = convertAggregateFunctionsToSql(aggregateFunctions.get(0)); for (int i = 1; i < aggregateFunctions.size(); i++) { selectFuncSql += "," + convertAggregateFunctionsToSql(aggregateFunctions.get(i)); } String sqlCmd = String.format("SELECT %s , %s FROM %s GROUP BY %s", selectFuncSql, groupedColSql, "{1}", groupedColSql); return sqlCmd; }

Target:
protected String buildGroupBySQL(List<String> aggregateFunctions) throws DDFException { String groupedColSql = Joiner.on(",").join(mGroupedColumns); List<String> aggregationFuncSql = new ArrayList<String>(); for(String aggFunc: aggregateFunctions) { aggregationFuncSql.add(convertAggregateFunctionsToSql(aggFunc)); } String selectFuncSql = Joiner.on(",").join(aggregationFuncSql); return String.format("SELECT %s , %s FROM %s GROUP BY %s", selectFuncSql, groupedColSql, "{1}", groupedColSql); }
Source:
public ItemStack[] getRemainingItems(InventoryCrafting inv) { return ForgeHooks.defaultRecipeGetRemainingItems(inv); }

Target:
public ItemStack[] getRemainingItems(InventoryCrafting inv) { ItemStack[] ret = new ItemStack[inv.getSizeInventory()]; for (int i = 0; i < ret.length; i++) { if (drains[i] != 0) { ret[i] = inv.getStackInSlot(i); if (isEmpty(ret[i])) continue; ret[i] = setSize(ret[i].copy(), 1); if (drains[i] > 0) { ret[i].getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null).drain(drains[i], true); } else { IFluidContainerItem fluidContainerItem = (IFluidContainerItem) ret[i].getItem(); fluidContainerItem.drain(ret[i], -drains[i], true); } ret[i] = makeSafe(ret[i]);; } else { ret[i] = ForgeHooks.getContainerItem(inv.getStackInSlot(i)); } } return ret; }
Source:
public void testCommitId() { try { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { e.printStackTrace(); } assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); }

Target:
public void testCommitId() throws IOException { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); }
Source:
public Mono<Void> runAsync() { try { throw new IllegalArgumentException(); } catch (Exception ex) { } return Mono.empty(); }

Target:
public Mono<Void> runAsync() { return Mono.error(new IllegalArgumentException()); }
Source:
public static void updateGoogleUserData(String token, User user) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); try { Oauth2 oauth2; oauth2 = new Oauth2.Builder(GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), credential) .setApplicationName("").build(); Userinfoplus userinfoplus = oauth2.userinfo().get().execute(); updateUserFromGoogleUserinfoplus(userinfoplus, user); } catch (GeneralSecurityException | IOException e) { throw new CustomWebApplicationException("Could not get Google profile.", HttpStatus.SC_BAD_REQUEST); } }

Target:
public static void updateGoogleUserData(String token, User user) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); try { Oauth2 oauth2; oauth2 = new Oauth2.Builder(GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), credential) .setApplicationName("").build(); Userinfoplus userinfoplus = oauth2.userinfo().get().execute(); updateUserFromGoogleUserinfoplus(userinfoplus, user); } catch (GeneralSecurityException | IOException e) { throw new CustomWebApplicationException("Could not get Google profile of " + user.getUsername() + ".", HttpStatus.SC_BAD_REQUEST); } }
Source:
public FxSwapTrade trade(LocalDate valuationDate, MarketData marketData) { FxRate fxNearRate = marketData.getValue(fxNearKey); double rate = fxNearRate.fxRate(fxNearKey.getPair()); double fxPts = marketData.getValue(fxPtsKey); return template.toTrade(valuationDate, BuySell.BUY, 1d, rate, fxPts); }

Target:
public FxSwapTrade trade(LocalDate valuationDate, MarketData marketData) { FxRate fxNearRate = marketData.getValue(fxNearKey); double rate = fxNearRate.fxRate(template.getCurrencyPair()); double fxPts = marketData.getValue(fxPtsKey); return template.toTrade(valuationDate, BuySell.BUY, 1d, rate, fxPts); }
Source:
public DefaultDiffEngine() { this.diffProcessor = new DiffBuilder(); }

Target:
public DefaultDiffEngine() { this(new DiffBuilder()); }
Source:
protected boolean validate() { if (getParameters() == null || getParameters().getAgent() == null || getParameters().getAgent().getIp() == null || getParameters().getAgent().getHostId() == null || getParameters().getAgent().getPassword() == null || getParameters().getAgent().getType() == null || getParameters().getAgent().getUser() == null) { return failValidation(EngineMessage.VDS_ADD_FENCE_AGENT_MANDATORY_PARAMETERS_MISSING); } Guid vdsId = getParameters().getAgent().getHostId(); VDS vds = vdsDao.get(vdsId); Guid vdsClusterId = vds.getClusterId(); Cluster cluster = clusterDao.get(vdsClusterId); String clusterCompatibilityVersion = cluster.getCompatibilityVersion().toString(); if (!FenceConfigHelper.getValidFenceAgentTypes(clusterCompatibilityVersion) .contains(getParameters().getAgent().getType())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_AGENT_NOT_SUPPORTED); } return super.validate(); }

Target:
protected boolean validate() { if (getParameters() != null || getParameters().getAgent() != null || getParameters().getAgent().getHostId() != null || getParameters().getAgent().getType() != null) { Guid vdsId = getParameters().getAgent().getHostId(); VDS vds = vdsDao.get(vdsId); Guid vdsClusterId = vds.getClusterId(); Cluster cluster = clusterDao.get(vdsClusterId); String clusterCompatibilityVersion = cluster.getCompatibilityVersion().toString(); if (!FenceConfigHelper.getValidFenceAgentTypes(clusterCompatibilityVersion) .contains(getParameters().getAgent().getType())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_AGENT_NOT_SUPPORTED); } } return super.validate(); }
Source:
private void markThisMessageAsRead(Message message) { try { int mID = message.getID(); if (!startedFromFilter && zulipApp.getPointer() < mID) { zulipApp.syncPointer(mID); } boolean isMessageRead = false; if (message.getMessageRead() != null) { isMessageRead = message.getMessageRead(); } if (!isMessageRead) { try { updateBuilder.where().eq(Message.ID_FIELD, message.getID()); updateBuilder.updateColumnValue(Message.MESSAGE_READ_FIELD, true); updateBuilder.update(); } catch (SQLException e) { ZLog.logException(e); } } zulipApp.markMessageAsRead(message); } catch (NullPointerException e) { Log.w("scrolling", "Could not find a location to scroll to!"); } }

Target:
private void markThisMessageAsRead(Message message) { try { int mID = message.getID(); if (zulipApp.getPointer() < mID) { zulipApp.syncPointer(mID); } boolean isMessageRead = false; if (message.getMessageRead() != null) { isMessageRead = message.getMessageRead(); } if (!isMessageRead) { try { updateBuilder.where().eq(Message.ID_FIELD, message.getID()); updateBuilder.updateColumnValue(Message.MESSAGE_READ_FIELD, true); updateBuilder.update(); } catch (SQLException e) { ZLog.logException(e); } } zulipApp.markMessageAsRead(message); } catch (NullPointerException e) { Log.w("scrolling", "Could not find a location to scroll to!"); } }
Source:
public IArtifactRepository read(URL location, InputStream input, IProgressMonitor monitor) throws ProvisionException { BufferedInputStream bufferedInput = null; try { try { bufferedInput = new BufferedInputStream(input); Parser repositoryParser = new Parser(Activator.getContext(), Activator.ID); repositoryParser.parse(input); IStatus result = repositoryParser.getStatus(); switch (result.getSeverity()) { case IStatus.CANCEL: throw new OperationCanceledException(); case IStatus.ERROR: throw new ProvisionException(result); case IStatus.WARNING: case IStatus.INFO: LogHelper.log(result); break; default: break; } SimpleArtifactRepository repository = repositoryParser.getRepository(); if (repository == null) throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, Messages.io_parseError, null)); return repository; } finally { if (bufferedInput != null) bufferedInput.close(); } } catch (IOException ioe) { String msg = NLS.bind(Messages.io_failedRead, location); throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, ioe)); } }

Target:
public IArtifactRepository read(URL location, InputStream input, IProgressMonitor monitor) throws ProvisionException { BufferedInputStream bufferedInput = null; try { try { bufferedInput = new BufferedInputStream(input); Parser repositoryParser = new Parser(Activator.getContext(), Activator.ID); repositoryParser.parse(input); IStatus result = repositoryParser.getStatus(); switch (result.getSeverity()) { case IStatus.CANCEL: throw new OperationCanceledException(); case IStatus.ERROR: throw new ProvisionException(result); case IStatus.WARNING: case IStatus.INFO: LogHelper.log(result); break; case IStatus.OK: break; default: throw new IllegalStateException("Not valid value for serverity: " + result.getSeverity()); } SimpleArtifactRepository repository = repositoryParser.getRepository(); if (repository == null) throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, Messages.io_parseError, null)); return repository; } finally { if (bufferedInput != null) bufferedInput.close(); } } catch (IOException ioe) { String msg = NLS.bind(Messages.io_failedRead, location); throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, ioe)); } }
Source:
public LogReplicationEntry resend() { LogReplicationEntry ack = null; boolean force = false; log.info("processAcks and pendingMessage size {}", pendingCompletableFutureForAcks.keySet(), pendingMessages.getSize()); if (pendingMessages.isEmpty()) { return null; } try { ack = processAcks(); } catch (Exception e) { log.warn("Caught a timeout exception ", e); force = true; } for (int i = 0; i < pendingMessages.getSize(); i++) { LogReplicationPendingEntry entry = pendingMessages.getList().get(i); if (entry.timeout(msgTimer) || force) { if (errorOnMsgTimeout && entry.retry >= maxRetry) { log.warn("Entry of type has been resent max times for timer {}.", entry.getData().getMetadata().getTimestamp(), entry.getData().getMetadata().getMessageMetadataType(), maxRetry, msgTimer); throw new LogEntrySyncTimeoutException("timeout"); } entry.retry(); log.info("Resend message {}", entry.getData().getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(entry.getData()); addCFToAcked(entry.getData(), cf); } else { log.info("Skip resending message with timer ", entry.getData().getMetadata(), msgTimer); } } return ack; }

Target:
public LogReplicationEntry resend() { LogReplicationEntry ack = null; boolean force = false; log.debug("processAcks and pendingMessage size {}", pendingCompletableFutureForAcks.keySet(), pendingMessages.getSize()); if (pendingMessages.isEmpty()) { return null; } try { ack = processAcks(); } catch (TimeoutException e) { log.warn("Caught a timeout exception ", e); force = true; } catch (ExecutionException | InterruptedException e ) { log.warn("Caught an exception.", e); } for (int i = 0; i < pendingMessages.getSize(); i++) { LogReplicationPendingEntry entry = pendingMessages.getList().get(i); if (entry.timeout(msgTimer) || force) { if (errorOnMsgTimeout && entry.retry >= maxRetry) { log.warn("Entry of type has been resent max times for timer {}.", entry.getData().getMetadata().getTimestamp(), entry.getData().getMetadata().getMessageMetadataType(), maxRetry, msgTimer); throw new LogEntrySyncTimeoutException("timeout"); } entry.retry(); log.debug("Resend message {}", entry.getData().getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(entry.getData()); addCFToAcked(entry.getData(), cf); } else { log.info("Skip resending message with timer ", entry.getData().getMetadata(), msgTimer); } } return ack; }
Source:
public Void visitVariable(VariableTree node, Void p) { warnAboutTypeAnnotationsTooEarly(node, node.getModifiers()); Pair<Tree, AnnotatedTypeMirror> preAssCtxt = visitorState.getAssignmentContext(); visitorState.setAssignmentContext( Pair.of((Tree) node, atypeFactory.getAnnotatedType(node))); try { if (atypeFactory.getDependentTypesHelper() != null) { if (getCurrentPath().getParentPath() != null && getCurrentPath().getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) { atypeFactory .getDependentTypesHelper() .checkType(visitorState.getAssignmentContext().second, node); } else { atypeFactory .getDependentTypesHelper() .checkType(atypeFactory.getAnnotatedTypeLhs(node), node); } } if (node.getInitializer() != null) { commonAssignmentCheck(node, node.getInitializer(), "assignment.type.incompatible"); } else { validateTypeOf(node); } return super.visitVariable(node, p); } finally { visitorState.setAssignmentContext(preAssCtxt); } }

Target:
public Void visitVariable(VariableTree node, Void p) { warnAboutTypeAnnotationsTooEarly(node, node.getModifiers()); Pair<Tree, AnnotatedTypeMirror> preAssCtxt = visitorState.getAssignmentContext(); AnnotatedTypeMirror variableType; if (getCurrentPath().getParentPath() != null && getCurrentPath().getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) { variableType = atypeFactory.getAnnotatedType(node); } else { variableType = atypeFactory.getAnnotatedTypeLhs(node); } visitorState.setAssignmentContext(Pair.of(node, variableType)); try { if (atypeFactory.getDependentTypesHelper() != null) { atypeFactory.getDependentTypesHelper().checkType(variableType, node); } if (node.getInitializer() != null) { commonAssignmentCheck(node, node.getInitializer(), "assignment.type.incompatible"); } else { validateTypeOf(node); } return super.visitVariable(node, p); } finally { visitorState.setAssignmentContext(preAssCtxt); } }
Source:
public RqWithoutHeader(final Request req, final CharSequence name) { super( new Request() { @Override @SuppressWarnings("unchecked") public Iterable<String> head() throws IOException { final String prefix = String.format( "%s:", name.toString().toLowerCase(Locale.ENGLISH) ); return new Concat<String>( req.head(), Collections.EMPTY_LIST, new Condition.LowerCase(prefix) ); } @Override public InputStream body() throws IOException { return req.body(); } } ); }

Target:
public RqWithoutHeader(final Request req, final CharSequence name) { super( new Request() { @Override public Iterable<String> head() throws IOException { final String prefix = String.format( "%s:", name.toString().toLowerCase(Locale.ENGLISH) ); return new Select<String>( req.head(), new Condition<String>() { @Override public boolean fits(final String header) { return !header.toLowerCase(Locale.ENGLISH) .startsWith(prefix); } } ); } @Override public InputStream body() throws IOException { return req.body(); } } ); }
Source:
public static String getVideoPath(Context context, DownloadEntry video) { String filepath = null; if (video.filepath != null && video.filepath.length() > 0) { if (video.isDownloaded()) { File f = new File(video.filepath); if (f.exists()) { filepath = video.filepath; } } } else { DownloadEntry de = (DownloadEntry) DatabaseFactory.getInstance(DatabaseFactory.TYPE_DATABASE_NATIVE) .getIVideoModelByVideoUrl( video.url, null); if (de != null) { if (de.filepath != null) { File f = new File(de.filepath); if (f.exists()) { filepath = de.filepath; } } } } if (TextUtils.isEmpty(filepath)) { filepath = video.getBestEncodingUrl(context); } return filepath; }

Target:
public static String getVideoPath(Context context, DownloadEntry video) { String filepath = null; if (video.filepath != null && video.filepath.length() > 0) { if (video.isDownloaded()) { final File f = new File(video.filepath); if (f.exists()) { filepath = video.filepath; } } } else { final DownloadEntry de = (DownloadEntry) DatabaseFactory.getInstance(DatabaseFactory.TYPE_DATABASE_NATIVE) .getIVideoModelByVideoUrl( video.url, null); if (de != null) { if (de.filepath != null) { final File f = new File(de.filepath); if (f.exists()) { filepath = de.filepath; } } } } if (TextUtils.isEmpty(filepath)) { filepath = video.getBestEncodingUrl(context); } return filepath; }
Source:
private boolean hasExcessiveAverageLineLength(File file) { long nbLines = 0; long nbCharacters = 0; HeaderCommentDetector detector = new HeaderCommentDetector(); try (BufferedReader reader = getReader(file)) { nbCharacters = reader.lines() .filter(line -> !detector.isLineInHeaderComment(line)) .mapToLong(line -> line.length()) .sum(); } catch (IOException e) { handleException(e, file); } try (BufferedReader reader = getReader(file)) { nbLines = reader.lines().count(); } catch (IOException e) { handleException(e, file); } nbLines -= detector.getNumberOfLinesInHeaderComment(); int averageLineLength = nbLines > 0 ? (int) (nbCharacters / nbLines) : -1; return averageLineLength > averageLineLengthThreshold; }

Target:
private boolean hasExcessiveAverageLineLength(File file) { int averageLineLength = new AverageLineLengthCalculator(file, encoding).getAverageLineLength(); return averageLineLength > averageLineLengthThreshold; }
Source:
public void cancel() { if (addLogicalImageTask != null) { thread.interrupt(); addLogicalImageTask.cancelTask(); } }

Target:
public void cancel() { if (addLogicalImageTask != null) { addLogicalImageTask.cancelTask(); } }
Source:
public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchParentChildGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), getConfig().getNameSubstitutionStrategy(), authorizations); }

Target:
public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchParentChildGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), this.nameSubstitutionStrategy, authorizations); }
Source:
public int getItemCount() { switch (wiFiDirectActivity.mState) { case send: return 3; case submit: return 2; } return 1; }

Target:
public int getItemCount() { switch (wiFiDirectActivity.mState) { case send: return 3; case submit: return 2; case receive: return 1; } return 0; }
Source:
public boolean isValidPartitionKeyProperty() { return !((this.partitionKeyExpression != null) && (this.partitionKeyExtractorClass != null)); }

Target:
public boolean isValidPartitionKeyProperty() { return (this.partitionKeyExpression == null) || (this.partitionKeyExtractorClass == null); }
Source:
Mono<Response<RecognizeLinkedEntitiesResult>> recognizeLinkedEntitiesWithResponse(String text, String language, Context context) { return recognizeBatchLinkedEntitiesWithResponse( Arrays.asList(new TextDocumentInput(Integer.toString(0), text, language)), null, context) .flatMap(response -> { Iterator<RecognizeLinkedEntitiesResult> responseItem = response.getValue().iterator(); return Mono.just(new SimpleResponse<>(response, responseItem.next())); }); }

Target:
Mono<Response<RecognizeLinkedEntitiesResult>> recognizeLinkedEntitiesWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return recognizeBatchLinkedEntitiesWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); }
Source:
public void testGroupByOneColumnWithLiterallyFalseFilter() throws Exception { testQuery( "SELECT COUNT(*), MAX(cnt) FROM druid.foo WHERE 1 = 0 GROUP BY dim1", CalciteTests.REGULAR_USER_AUTH_RESULT, ImmutableList.of(), ImmutableList.of() ); }

Target:
public void testGroupByOneColumnWithLiterallyFalseFilter() throws Exception { testQuery( "SELECT COUNT(*), MAX(cnt) FROM druid.foo WHERE 1 = 0 GROUP BY dim1", ImmutableList.of(), ImmutableList.of() ); }
Source:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock("Activate host")) { executionHandler.updateSpecificActionJobCompleted(vds.getId(), ActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(() -> { List<Network> networks = networkDao.getAllForCluster(vds.getClusterId()); networkClusterHelper.setStatus(vds.getClusterId(), networks); return null; }); if (vds.getClusterSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); startVDOService(vds); } } } }

Target:
protected void executeCommand() { final VDS vds = getVds(); try (EngineLock monitoringLock = acquireMonitorLock("Activate host")) { executionHandler.updateSpecificActionJobCompleted(vds.getId(), ActionType.MaintenanceVds, false); setSucceeded(setVdsStatus(VDSStatus.Unassigned).getSucceeded()); if (getSucceeded()) { TransactionSupport.executeInNewTransaction(() -> { List<Network> networks = networkDao.getAllForCluster(vds.getClusterId()); networkClusterHelper.setStatus(vds.getClusterId(), networks); return null; }); if (vds.getClusterSupportsGlusterService()) { runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vds.getId(), Arrays.asList("glusterd"), "restart")); boolean isRunning = isVDORunning(vds); if (!isRunning) { log.info("VDO service is down in host : '{}' , starting VDO service", vds.getId()); startVDOService(vds); } } } } }
Source:
public ResponseEntity postEvent(@PathVariable final String eventTypeName, @RequestBody final String event, final NativeWebRequest nativeWebRequest) { LOG.trace("Received event for event type {}", event, eventTypeName); try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); try { final Timer successfullyPublishedTimer = metricRegistry.timer(metricNameFor(eventTypeName, SUCCESS_METRIC_NAME)); final Timer.Context successfullyPublishedTimerContext = successfullyPublishedTimer.time(); final JSONObject eventAsJson = parseJson(event); validateSchema(eventAsJson, eventType); String partitionId = applyPartitioningStrategy(eventType, eventAsJson); topicRepository.postEvent(eventTypeName, partitionId, event); successfullyPublishedTimerContext.stop(); return status(HttpStatus.CREATED).build(); } catch (Exception e) { metricRegistry.counter(metricNameFor(eventTypeName, FAILED_METRIC_NAME)).inc(); throw e; } } catch (NoSuchEventTypeException e) { LOG.debug("Could not process event.", e); return create(e.asProblem(), nativeWebRequest); } catch (final EventValidationException e) { LOG.debug("Event validation error: {}", e.getValidationError().getMessage()); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("error posting to partition", e); return create(e.asProblem(), nativeWebRequest); } }

Target:
public ResponseEntity postEvent(@PathVariable final String eventTypeName, @RequestBody final String event, final NativeWebRequest nativeWebRequest) { LOG.trace("Received event for event type {}", event, eventTypeName); try { final long startingTime = System.nanoTime(); final EventType eventType = eventTypeRepository.findByName(eventTypeName); return doWithMetrics(eventTypeName, startingTime, () -> { final JSONObject eventAsJson = parseJson(event); validateSchema(eventAsJson, eventType); String partitionId = applyPartitioningStrategy(eventType, eventAsJson); topicRepository.postEvent(eventTypeName, partitionId, event); return status(HttpStatus.CREATED).build(); }); } catch (NoSuchEventTypeException e) { LOG.debug("Could not process event.", e); return create(e.asProblem(), nativeWebRequest); } catch (final EventValidationException e) { LOG.debug("Event validation error: {}", e.getValidationError().getMessage()); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.error("error posting to partition", e); return create(e.asProblem(), nativeWebRequest); } }
Source:
protected void postAddNetwork(Guid providerId, String externalId) { ExternalSubnet externalSubnet = getParameters().getExternalSubnet(); if (externalSubnet != null) { AddExternalSubnetParameters subnetParameters = new AddExternalSubnetParameters( externalSubnet, providerId, externalId); getBackend().runInternalAction( ActionType.AddSubnetToProvider, subnetParameters); } }

Target:
protected void postAddNetwork(Guid providerId, String externalId) { ExternalSubnet externalSubnet = getParameters().getExternalSubnet(); if (externalSubnet != null) { AddExternalSubnetParameters subnetParameters = new AddExternalSubnetParameters( externalSubnet, providerId, externalId); getBackend().runInternalMultipleActions( ActionType.AddSubnetToProvider, Arrays.asList(subnetParameters)); } }
Source:
public void testEventTypeFilter() throws Exception { getMockEndpoint("mock:direct:fulltext.filter").expectedMessageCount(0); createContext(ENHANCEMENT_ROUTE); Map<String, Object> headers = createEvent(FILE_ID, EVENT_TYPES); headers.put(EVENT_TYPE, "ResourceDeletion"); template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); }

Target:
public void testEventTypeFilter() throws Exception { getMockEndpoint("mock:direct:fulltext.filter").expectedMessageCount(0); createContext(ENHANCEMENT_ROUTE); Map<String, Object> headers = createEvent(FILE_ID); headers.put(EVENT_TYPE, "ResourceDeletion"); template.sendBodyAndHeaders("", headers); assertMockEndpointsSatisfied(); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); navigationController = new HomepageFragmentController(getSupportFragmentManager(), R.id.container); navigationController.loadHomeInitially(); bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetBehavior.setPeekHeight(0); bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset == 0) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } bottomNavigation.onAddSheetSlideOffset(slideOffset); } }); bottomNavigation.setListener(this); PreferencesManager preferencesManager = new PreferencesManager(this); preferencesManager.increaseNumAppOpens(); if (preferencesManager.getNumAppOpens() == NUM_APP_OPENS_FOR_RATING_ASK) { showPleaseRateDialog(); } importFromCsv.setText(preferencesManager.isOnFreeVersion() ? getString(R.string.import_from_csv_file_premium) : getString(R.string.import_from_csv_file)); createListDialog = new CreateListDialog(this, this); dataSource = new DataSource(this); paymentManager = new PaymentManager(this, this); paymentManager.setUpAndCheckForPremium(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); navigationController = new HomepageFragmentController(getSupportFragmentManager(), R.id.container); navigationController.loadHomeInitially(); bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); bottomSheetBehavior.setPeekHeight(0); bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { if (slideOffset == 0) { bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); } bottomNavigation.onAddSheetSlideOffset(slideOffset); } }); bottomNavigation.setListener(this); preferencesManager = new PreferencesManager(this); preferencesManager.increaseNumAppOpens(); if (preferencesManager.getNumAppOpens() == NUM_APP_OPENS_FOR_RATING_ASK) { showPleaseRateDialog(); } createListDialog = new CreateListDialog(this, this); dataSource = new DataSource(this); paymentManager = new PaymentManager(this, this); paymentManager.setUpAndCheckForPremium(); }