auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static QueryRunner createQueryRunner() throws Exception { DistributedQueryRunner queryRunner = HiveQueryRunner.createQueryRunner(getTables(), ImmutableMap.of(), "sql-standard", ImmutableMap.of("hive.pushdown-filter-enabled", "true"), Optional.empty()); queryRunner.execute(noPushdownFilter(queryRunner.getDefaultSession()), "CREATE TABLE lineitem_ex (linenumber, orderkey, ship_by_air, is_returned, byte_col1, byte_col2) AS " + "SELECT linenumber, " + " orderkey, " + " IF (linenumber % 7 = 0, null, shipmode = 'AIR') AS ship_by_air, " + " IF (linenumber % 5 = 0, null, returnflag = 'R') AS is_returned, " + " IF (linenumber % 8 = 0, null, cast((linenumber) as TINYINT)) AS byte_col1, " + " IF (linenumber % 9 = 0, null, cast((-linenumber) as TINYINT)) AS byte_col2 " + "FROM lineitem"); return queryRunner; }

Target:
private static QueryRunner createQueryRunner() throws Exception { DistributedQueryRunner queryRunner = HiveQueryRunner.createQueryRunner(getTables(), ImmutableMap.of(), "sql-standard", ImmutableMap.of("hive.pushdown-filter-enabled", "true"), Optional.empty()); queryRunner.execute(noPushdownFilter(queryRunner.getDefaultSession()), "CREATE TABLE lineitem_ex (linenumber, orderkey, ship_by_air, is_returned, ship_day, ship_month) AS " + "SELECT linenumber, " + " orderkey, " + " IF (linenumber % 7 = 0, null, shipmode = 'AIR') AS ship_by_air, " + " IF (linenumber % 5 = 0, null, returnflag = 'R') AS is_returned, " + " IF (linenumber % 4 = 0, null, CAST(day(shipdate) AS TINYINT)) AS ship_day, " + " IF (linenumber % 6 = 0, null, CAST(month(shipdate) AS TINYINT)) AS ship_month " + "FROM lineitem"); return queryRunner; }
Source:
public boolean append(ByteBuffer source, int targetChannel, DataType dataType) throws IOException { checkState(!isFinished, "Sort buffer is already finished."); checkState(!isReleased, "Sort buffer is already released."); int totalBytes = source.remaining(); if (totalBytes == 0) { return true; } if (!allocateBuffersForRecord(totalBytes)) { return false; } writeIndex(targetChannel, totalBytes, dataType); writeRecord(source); ++numTotalRecords; numTotalBytes += totalBytes; return true; }

Target:
public boolean append(ByteBuffer source, int targetChannel, DataType dataType) throws IOException { checkArgument(source.hasRemaining(), "Cannot append empty data."); checkState(!isFinished, "Sort buffer is already finished."); checkState(!isReleased, "Sort buffer is already released."); int totalBytes = source.remaining(); if (!allocateBuffersForRecord(totalBytes)) { return false; } writeIndex(targetChannel, totalBytes, dataType); writeRecord(source); ++numTotalRecords; numTotalBytes += totalBytes; return true; }
Source:
public static Locale getLocale(String localeName) { Locale locale; String[] languageAndRegion = localeName.split("_", 2); if (languageAndRegion.length > 1) { locale = new Locale(languageAndRegion[0], languageAndRegion[1]); } else { locale = new Locale(localeName); } return locale; }

Target:
public static Locale getLocale(String localeName) { Locale locale; String[] languageAndRegion = localeName.split("-", 2); if (languageAndRegion.length > 1) { locale = new Locale(languageAndRegion[0], languageAndRegion[1]); } else { locale = new Locale(localeName); } return locale; }
Source:
public NettyPipelineBuilder create( Channel channel, Log log ) throws Exception { ChannelPipeline pipeline = channel.pipeline(); NettyPipelineBuilder builder = NettyPipelineBuilder.with( pipeline, log ); int i = 0; for ( ChannelHandler handler : wrapper.handlersFor( channel ) ) { builder.add( String.format( "%s_%d", wrapper.name(), i ), handler ); } return builder; }

Target:
public NettyPipelineBuilder create( Channel channel, Log log ) throws Exception { ChannelPipeline pipeline = channel.pipeline(); NettyPipelineBuilder builder = NettyPipelineBuilder.with( pipeline, log ); int i = 0; for ( ChannelHandler handler : wrapper.handlersFor( channel ) ) { builder.add( String.format( "%s_%d", wrapper.name(), i ), handler ); i++; } return builder; }
Source:
public void readFromNBT(NBTTagCompound par1nbtTagCompound) { super.readFromNBT(par1nbtTagCompound); inv.readFromNBT(par1nbtTagCompound, "inv"); matrix.readFromNBT(par1nbtTagCompound, "matrix"); placedBy = par1nbtTagCompound.getString("placedBy"); NBTTagList lst = par1nbtTagCompound.getTagList("fuzzyFlags"); if(lst != null) { for(int i = 0; i < 9; i++) { NBTTagCompound comp = (NBTTagCompound) lst.tagAt(i); fuzzyFlags[i].ignore_dmg = comp.getBoolean("ignore_dmg"); fuzzyFlags[i].ignore_nbt = comp.getBoolean("ignore_nbt"); fuzzyFlags[i].use_od = comp.getBoolean("use_od"); fuzzyFlags[i].use_category = comp.getBoolean("use_category"); } } cacheRecipe(); }

Target:
public void readFromNBT(NBTTagCompound par1nbtTagCompound) { super.readFromNBT(par1nbtTagCompound); inv.readFromNBT(par1nbtTagCompound, "inv"); matrix.readFromNBT(par1nbtTagCompound, "matrix"); placedBy = par1nbtTagCompound.getString("placedBy"); if(par1nbtTagCompound.hasKey("fuzzyFlags")) { NBTTagList lst = par1nbtTagCompound.getTagList("fuzzyFlags"); for(int i = 0; i < 9; i++) { NBTTagCompound comp = (NBTTagCompound) lst.tagAt(i); fuzzyFlags[i].ignore_dmg = comp.getBoolean("ignore_dmg"); fuzzyFlags[i].ignore_nbt = comp.getBoolean("ignore_nbt"); fuzzyFlags[i].use_od = comp.getBoolean("use_od"); fuzzyFlags[i].use_category = comp.getBoolean("use_category"); } } cacheRecipe(); }
Source:
public String getString( final Object key ) { return String.valueOf(getDynamicProperties().get( key )); }

Target:
public String getString( final Object key ) { return (String) getDynamicProperties().get( key ); }
Source:
public void setCurve(final Currency ccy, final YieldAndDiscountCurve curve) { ArgumentChecker.notNull(ccy, "currency"); ArgumentChecker.notNull(curve, "curve"); if (!_discountingCurves.containsKey(ccy)) { _discountingCurves.put(ccy, curve); setAllCurves(); } else { boolean curvesEqual = _discountingCurves.get(ccy).equals(curve); s_logger.debug("Two discounting curves for {}: {}", curvesEqual ? "equal" : "unequal", ccy.getCode(), curve, _discountingCurves.get(ccy)); if (!curvesEqual) { throw new IllegalArgumentException("Currency discounting curve already set: " + ccy.toString()); } } }

Target:
public void setCurve(final Currency ccy, final YieldAndDiscountCurve curve) { ArgumentChecker.notNull(ccy, "currency"); ArgumentChecker.notNull(curve, "curve"); if (!_discountingCurves.containsKey(ccy)) { _discountingCurves.put(ccy, curve); setAllCurves(); } else { boolean curvesEqual = _discountingCurves.get(ccy).equals(curve); s_logger.debug("Two discounting curves for {}: {}", curvesEqual ? "equal" : "unequal", ccy.getCode(), curve, _discountingCurves.get(ccy)); if (!curvesEqual) { throw new IllegalArgumentException("Attempting to replace " + ccy.getCode() + " discounting curve with " + "different curve. existing: " + _discountingCurves.get(ccy) + ", new: " + curve); } } }
Source:
public String getModulesPath() throws IOException, ConfigInvalidException { lazyLoadModulesConfig(); return modulesConfig.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, (pathToName.get(path) != null) ? pathToName.get(path) : path, ConfigConstants.CONFIG_KEY_PATH); }

Target:
public String getModulesPath() throws IOException, ConfigInvalidException { lazyLoadModulesConfig(); return modulesConfig.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, getModuleName(path), ConfigConstants.CONFIG_KEY_PATH); }
Source:
public ChargeEntity transitionChargeState( ChargeEntity charge, ChargeStatus targetChargeState, ZonedDateTime gatewayEventTime ) { ChargeStatus fromChargeState = ChargeStatus.fromString(charge.getStatus()); charge.setStatus(targetChargeState); ChargeEventEntity chargeEventEntity = chargeEventDao.persistChargeEventOf(charge, gatewayEventTime); PaymentGatewayStateTransitions.getInstance() .getEventForTransition(fromChargeState, targetChargeState) .ifPresent(eventType -> { if (shouldEmitPaymentStateTransitionEvents) { PaymentStateTransition transition = new PaymentStateTransition(chargeEventEntity.getId(), eventType); stateTransitionQueue.offer(transition); logger.info("Offered payment state transition to emitter queue [from={}] [to={}] [chargeId={}]", fromChargeState, targetChargeState, chargeEventEntity.getId()); } }); return charge; }

Target:
public ChargeEntity transitionChargeState( ChargeEntity charge, ChargeStatus targetChargeState, ZonedDateTime gatewayEventTime ) { ChargeStatus fromChargeState = ChargeStatus.fromString(charge.getStatus()); charge.setStatus(targetChargeState); ChargeEventEntity chargeEventEntity = chargeEventDao.persistChargeEventOf(charge, gatewayEventTime); PaymentGatewayStateTransitions.getInstance() .getEventForTransition(fromChargeState, targetChargeState) .ifPresent(eventType -> { if (shouldEmitPaymentStateTransitionEvents) { PaymentStateTransition transition = new PaymentStateTransition(chargeEventEntity.getId(), eventType); stateTransitionQueue.offer(transition); logger.info("Offered payment state transition to emitter queue [from={}] [to={}] [chargeEventId={}] [chargeId={}]", fromChargeState, targetChargeState, chargeEventEntity.getId(), charge.getExternalId()); } }); return charge; }
Source:
protected boolean scheduleExecutor( ExecutorDetails exec, TopologyDetails td, Collection<ExecutorDetails> scheduledTasks, Iterable<String> sortedNodes) { WorkerSlot targetSlot = findWorkerForExec(exec, td, sortedNodes); if (targetSlot != null) { RasNode targetNode = idToNode(targetSlot.getNodeId()); targetNode.assignSingleExecutor(targetSlot, exec, td); scheduledTasks.add(exec); LOG.debug( "TASK assigned to Node: avail [ mem: cpu: ] total [ mem: cpu: ] on " + "slot: on Rack: {}", exec, targetNode.getHostname(), targetNode.getAvailableMemoryResources(), targetNode.getAvailableCpuResources(), targetNode.getTotalMemoryResources(), targetNode.getTotalCpuResources(), targetSlot, nodeToRack(targetNode)); return true; } else { String comp = td.getExecutorToComponent().get(exec); NormalizedResourceRequest requestedResources = td.getTotalResources(exec); schedulingFailText = "Not Enough Resources to schedule Task " + exec + " - " + comp + " " + requestedResources; LOG.error(schedulingFailText); return false; } }

Target:
protected boolean scheduleExecutor( ExecutorDetails exec, TopologyDetails td, Collection<ExecutorDetails> scheduledTasks, Iterable<String> sortedNodes) { WorkerSlot targetSlot = findWorkerForExec(exec, td, sortedNodes); if (targetSlot != null) { RasNode targetNode = idToNode(targetSlot.getNodeId()); targetNode.assignSingleExecutor(targetSlot, exec, td); scheduledTasks.add(exec); LOG.debug( "TASK assigned to Node: avail [ mem: cpu: ] total [ mem: cpu: ] on " + "slot: on Rack: {}", exec, targetNode.getHostname(), targetNode.getAvailableMemoryResources(), targetNode.getAvailableCpuResources(), targetNode.getTotalMemoryResources(), targetNode.getTotalCpuResources(), targetSlot, nodeToRack(targetNode)); return true; } else { String comp = td.getExecutorToComponent().get(exec); NormalizedResourceRequest requestedResources = td.getTotalResources(exec); LOG.warn("Not Enough Resources to schedule Task - {}", exec, comp, requestedResources); return false; } }
Source:
public void whenExceedMaxConsumersNumThen429() throws IOException, InterruptedException, ExecutionException, TimeoutException { final String etName = NakadiTestUtils.createEventType().getName(); final List<CompletableFuture<HttpURLConnection>> connectionFutures = range(0, 8) .mapToObj(x -> createConsumingConnection(etName)) .collect(Collectors.toList()); assertThat("first 5 connections should be accepted", countStatusCode(connectionFutures, HttpStatus.OK.value()), equalTo(5)); assertThat("last 3 connections should be rejected", countStatusCode(connectionFutures, HttpStatus.TOO_MANY_REQUESTS.value()), equalTo(3)); for (final CompletableFuture<HttpURLConnection> conn : connectionFutures) { if (conn.get().getResponseCode() == HttpStatus.OK.value()) { conn.get().disconnect(); break; } } range(0, 15).forEach(value -> NakadiTestUtils.publishEvent(etName, "{\"foo\": \"please, close connection\"}")); Thread.sleep(1000); final List<CompletableFuture<HttpURLConnection>> moreConnectionFutures = range(0, 3) .mapToObj(x -> createConsumingConnection(etName)) .collect(Collectors.toList()); assertThat("one more connection should be accepted", countStatusCode(moreConnectionFutures, HttpStatus.OK.value()), equalTo(1)); assertThat("other 2 connections should be rejected as we had only one new free slot", countStatusCode(moreConnectionFutures, HttpStatus.TOO_MANY_REQUESTS.value()), equalTo(2)); }

Target:
public void whenExceedMaxConsumersNumThen429() throws IOException, InterruptedException, ExecutionException, TimeoutException { final String etName = NakadiTestUtils.createEventType().getName(); final List<CompletableFuture<HttpURLConnection>> connectionFutures = range(0, 8) .mapToObj(x -> createConsumingConnection(etName)) .collect(Collectors.toList()); assertThat("first 5 connections should be accepted", countStatusCode(connectionFutures, HttpStatus.OK.value()), equalTo(5)); assertThat("last 3 connections should be rejected", countStatusCode(connectionFutures, HttpStatus.TOO_MANY_REQUESTS.value()), equalTo(3)); for (final CompletableFuture<HttpURLConnection> conn : connectionFutures) { if (conn.get().getResponseCode() == HttpStatus.OK.value()) { conn.get().disconnect(); break; } } range(0, 15).forEach(value -> NakadiTestUtils.publishEvent(etName, "{\"foo\": \"bar\"}")); Thread.sleep(1000); final List<CompletableFuture<HttpURLConnection>> moreConnectionFutures = range(0, 3) .mapToObj(x -> createConsumingConnection(etName)) .collect(Collectors.toList()); assertThat("one more connection should be accepted", countStatusCode(moreConnectionFutures, HttpStatus.OK.value()), equalTo(1)); assertThat("other 2 connections should be rejected as we had only one new free slot", countStatusCode(moreConnectionFutures, HttpStatus.TOO_MANY_REQUESTS.value()), equalTo(2)); }
Source:
public ListCoercer(TypeManager typeManager, HiveType fromHiveType, HiveType toHiveType, BridgingRecordCursor bridgingRecordCursor) { requireNonNull(typeManager, "typeManage is null"); requireNonNull(fromHiveType, "fromHiveType is null"); requireNonNull(toHiveType, "toHiveType is null"); this.bridgingRecordCursor = requireNonNull(bridgingRecordCursor, "bridgingRecordCursor is null"); this.fromElementHiveType = HiveType.valueOf(((ListTypeInfo) fromHiveType.getTypeInfo()).getListElementTypeInfo().getTypeName()); this.toElementHiveType = HiveType.valueOf(((ListTypeInfo) toHiveType.getTypeInfo()).getListElementTypeInfo().getTypeName()); this.fromElementType = fromElementHiveType.getType(typeManager); this.toElementType = toElementHiveType.getType(typeManager); this.elementCoercer = fromElementHiveType.equals(toElementHiveType) ? null : createCoercer(typeManager, fromElementHiveType, toElementHiveType, bridgingRecordCursor); this.pageBuilder = elementCoercer == null ? null : new PageBuilder(ImmutableList.of(toHiveType.getType(typeManager))); }

Target:
public ListCoercer(TypeManager typeManager, HiveType fromHiveType, HiveType toHiveType, BridgingRecordCursor bridgingRecordCursor) { requireNonNull(typeManager, "typeManage is null"); requireNonNull(fromHiveType, "fromHiveType is null"); requireNonNull(toHiveType, "toHiveType is null"); this.bridgingRecordCursor = requireNonNull(bridgingRecordCursor, "bridgingRecordCursor is null"); HiveType fromElementHiveType = HiveType.valueOf(((ListTypeInfo) fromHiveType.getTypeInfo()).getListElementTypeInfo().getTypeName()); HiveType toElementHiveType = HiveType.valueOf(((ListTypeInfo) toHiveType.getTypeInfo()).getListElementTypeInfo().getTypeName()); this.fromElementType = fromElementHiveType.getType(typeManager); this.toType = toHiveType.getType(typeManager); this.toElementType = toElementHiveType.getType(typeManager); this.elementCoercer = fromElementHiveType.equals(toElementHiveType) ? null : createCoercer(typeManager, fromElementHiveType, toElementHiveType, bridgingRecordCursor); this.pageBuilder = elementCoercer == null ? null : new PageBuilder(ImmutableList.of(toType)); }
Source:
public void makeSortable() { makeSortable(new Comparator<T>() { private LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(T o1, T o2) { String text1 = getValue(o1); String text2 = getValue(o2); if (text1.equals(text2)) { return 0; } else if (RxTxRateRenderer.NO_VALUE.equals(text1) || RxTxRateRenderer.NO_VALUE.equals(text2)) { return RxTxRateRenderer.NO_VALUE.equals(text1) ? -1 : 1; } else if (RxTxRateRenderer.ZERO_VALUE.equals(text1) || RxTxRateRenderer.ZERO_VALUE.equals(text2)) { return RxTxRateRenderer.ZERO_VALUE.equals(text1) ? -1 : 1; } else if (RxTxRateRenderer.SMALL_VALUE.equals(text1) || RxTxRateRenderer.SMALL_VALUE.equals(text2)) { return RxTxRateRenderer.SMALL_VALUE.equals(text1) ? -1 : 1; } else { return lexoNumeric.compare(text1, text2); } } }); }

Target:
public void makeSortable() { makeSortable(new Comparator<T>() { private LexoNumericComparator lexoNumeric = new LexoNumericComparator(); @Override public int compare(T o1, T o2) { String text1 = getValue(o1); String text2 = getValue(o2); if (text1.equals(text2)) { return 0; } else if (RxTxRateRenderer.isEmpty(text1) || RxTxRateRenderer.isEmpty(text2)) { return RxTxRateRenderer.isEmpty(text1) ? -1 : 1; } else if (RxTxRateRenderer.isZero(text1) || RxTxRateRenderer.isZero(text2)) { return RxTxRateRenderer.isZero(text1) ? -1 : 1; } else if (RxTxRateRenderer.isSmall(text1) || RxTxRateRenderer.isSmall(text2)) { return RxTxRateRenderer.isSmall(text1) ? -1 : 1; } else { return lexoNumeric.compare(text1, text2); } } }); }
Source:
protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = getConfig(); if (SecurityUtils.isStramWebSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } else { String authType = config.get(SecurityUtils.HADOOP_HTTP_AUTH_PROP); if (!SecurityUtils.HADOOP_HTTP_AUTH_VALUE_SIMPLE.equals(authType)) { LOG.warn("Found but authentication was disabled in Apex.", SecurityUtils.HADOOP_HTTP_AUTH_PROP, authType); config = new Configuration(config); config.set(SecurityUtils.HADOOP_HTTP_AUTH_PROP, SecurityUtils.HADOOP_HTTP_AUTH_VALUE_SIMPLE); config.setBoolean(SecurityUtils.HADOOP_HTTP_AUTH_SIMPLE_ANONYMOUS_ALLOWED_PROP, true); } } addSSLConfigResource(config); WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName() + ":" + webApp.port(); if (ConfigUtils.isSSLEnabled(config)) { appMasterTrackingUrl = "https://" + appMasterTrackingUrl; } LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }

Target:
protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = SecurityUtils.configureWebAppSecurity(getConfig(), dag.getValue(Context.DAGContext.SSL_CONFIG)); WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName() + ":" + webApp.port(); if (ConfigUtils.isSSLEnabled(config)) { appMasterTrackingUrl = "https://" + appMasterTrackingUrl; } LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }
Source:
public String toString() { try { JSONObject object = new JSONObject(); object.put("isHealthy", isHealthy.get()); object.put("isBootstrapping", isBootstrapping.get()); object.put("nodeState", nodeState); object.put("bootstrapTime", DateUtil.formatyyyyMMddHHmm(bootstrapTime)); object.put("isCassandraProcessAlive", isCassandraProcessAlive.get()); object.put("isGossipActive", isGossipActive.get()); object.put("isThriftActive", isThriftActive.get()); object.put("isNativeTransportActive", isNativeTransportActive.get()); object.put("isRequiredDirectoriesExist", isRequiredDirectoriesExist.get()); object.put("isYamlWritten", isYmlWritten.get()); if (backupMetadata != null) object.put("backupStatus", backupMetadata.getJSON()); else object.put("backupStatus", backupMetadata); object.put("restoreStatus", restoreStatus.getJSON()); return object.toString(); }catch (JSONException ex) { logger.error("JSONException during toString representation of InstanceState.", ex); } return null; }

Target:
public String toString() { return GsonJsonSerializer.getGson().toJson(this); }
Source:
public static Pill create(DeviceAccountPair pillAccountPair, Optional<DeviceStatus> pillStatusOptional, final Optional<Color> pillColorOptional) { final Color color = pillColorOptional.isPresent() ? pillColorOptional.get() : DEFAULT_COLOR; if (!pillStatusOptional.isPresent()) { return new Pill(pillAccountPair.internalDeviceId, pillAccountPair.externalDeviceId, null, null, null, State.UNKNOWN, color); } final DeviceStatus pillStatus = pillStatusOptional.get(); final State state = pillStatus.batteryLevel < MIN_IDEAL_BATTERY_LEVEL ? State.LOW_BATTERY : State.NORMAL; return new Pill(pillAccountPair.internalDeviceId, pillAccountPair.externalDeviceId, pillStatus.firmwareVersion, pillStatus.batteryLevel, pillStatus.lastSeen, state, color); }

Target:
public static Pill create(DeviceAccountPair pillAccountPair, Optional<DeviceStatus> pillStatusOptional, final Optional<Color> pillColorOptional) { final Color color = pillColorOptional.isPresent() ? pillColorOptional.get() : DEFAULT_COLOR; if (!pillStatusOptional.isPresent()) { return new Pill(pillAccountPair.internalDeviceId, pillAccountPair.externalDeviceId, Optional.<String>absent(), Optional.<Integer>absent(), Optional.<DateTime>absent(), State.UNKNOWN, color); } final DeviceStatus pillStatus = pillStatusOptional.get(); final State state = pillStatus.batteryLevel < MIN_IDEAL_BATTERY_LEVEL ? State.LOW_BATTERY : State.NORMAL; return new Pill(pillAccountPair.internalDeviceId, pillAccountPair.externalDeviceId, Optional.of(pillStatus.firmwareVersion), Optional.of(pillStatus.batteryLevel), Optional.of(pillStatus.lastSeen), state, color); }
Source:
protected void handleObjectPut(Object object) throws Exception { FeatureTypeInfo featureTypeUpdate = (FeatureTypeInfo) object; String workspace = getAttribute("workspace"); String datastore = getAttribute("datastore"); String featuretype = getAttribute("featuretype"); DataStoreInfo ds = catalog.getDataStoreByName(workspace, datastore); FeatureTypeInfo featureTypeInfo = catalog.getFeatureTypeByDataStore( ds, featuretype ); Map<String, Serializable> parametersCheck = featureTypeInfo.getStore().getConnectionParameters(); CatalogBuilder helper = new CatalogBuilder(catalog); helper.updateFeatureType(featureTypeInfo,featureTypeUpdate); calculateOptionalFields(featureTypeUpdate, featureTypeInfo); catalog.save( featureTypeInfo ); catalog.getResourcePool().clear(featureTypeInfo); Map<String, Serializable> parameters = featureTypeInfo.getStore().getConnectionParameters(); if( parameters.equals(parametersCheck)){ LOGGER.info( "PUT FeatureType" + datastore + "," + featuretype + " updated metadata only"); } else { LOGGER.info( "PUT featureType" + datastore + "," + featuretype + " updated metadata and data access" ); catalog.getResourcePool().clear(featureTypeInfo.getStore()); } }

Target:
protected void handleObjectPut(Object object) throws Exception { FeatureTypeInfo featureTypeUpdate = (FeatureTypeInfo) object; String workspace = getAttribute("workspace"); String datastore = getAttribute("datastore"); String featuretype = getAttribute("featuretype"); DataStoreInfo ds = catalog.getDataStoreByName(workspace, datastore); FeatureTypeInfo featureTypeInfo = catalog.getFeatureTypeByDataStore( ds, featuretype ); Map<String, Serializable> parametersCheck = featureTypeInfo.getStore().getConnectionParameters(); CatalogBuilder helper = new CatalogBuilder(catalog); helper.updateFeatureType(featureTypeInfo,featureTypeUpdate); calculateOptionalFields(featureTypeUpdate, featureTypeInfo); catalog.save( featureTypeInfo ); catalog.getResourcePool().clear(featureTypeInfo); Map<String, Serializable> parameters = featureTypeInfo.getStore().getConnectionParameters(); MetadataMap mdm = featureTypeInfo.getMetadata(); boolean virtual = mdm != null && mdm.containsKey(FeatureTypeInfo.JDBC_VIRTUAL_TABLE); if( !virtual && parameters.equals(parametersCheck)){ LOGGER.info( "PUT FeatureType" + datastore + "," + featuretype + " updated metadata only"); } else { LOGGER.info( "PUT featureType" + datastore + "," + featuretype + " updated metadata and data access" ); catalog.getResourcePool().clear(featureTypeInfo.getStore()); } }
Source:
public Building(double x, double y, int team, int localTeam) { super(x, y, team, localTeam); setStartHealth(20); disableMobHealthRegen(true); disableBuildingHealthRegen(false); freezeTime = 10; spawnTime = TurnSynchronizer.synchedRandom.nextInt(SPAWN_INTERVAL); }

Target:
public Building(double x, double y, int team, int localTeam) { super(x, y, team, localTeam); setStartHealth(20); healthRegen = false; healthRegenB = true; freezeTime = 10; spawnTime = TurnSynchronizer.synchedRandom.nextInt(SPAWN_INTERVAL); }
Source:
public void testCollectorFailureDoesNotResultInTwoErrorEmissions() { try { final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() { @Override public void accept(Throwable t) { list.add(t); } }); final RuntimeException e1 = new RuntimeException(); final RuntimeException e2 = new RuntimeException(); TestSubscriber<List<Integer>> ts = TestSubscriber.create(); new Flowable<Integer>() { @Override protected void subscribeActual(final Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { if (n > 0) { s.onNext(1); s.onError(e2); } } @Override public void cancel() { } }); } }.collect( new Callable<List<Integer>>() { @Override public List<Integer> call() { return new ArrayList<Integer>(); } }, new BiConsumer<List<Integer>, Integer>() { @Override public void accept(List<Integer> t1, Integer t2) { throw e1; } }) .subscribe(ts); ts.assertError(e1); ts.assertNotComplete(); assertEquals(Arrays.asList(e2), list); } finally { RxJavaPlugins.reset(); } }

Target:
public void testCollectorFailureDoesNotResultInTwoErrorEmissions() { try { final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); RxJavaPlugins.setErrorHandler(addToList(list)); final RuntimeException e1 = new RuntimeException(); final RuntimeException e2 = new RuntimeException(); Burst.items(1).error(e2) .collect(callableListCreator(), biConsumerThrows(e1)) .test() .assertError(e1) .assertNotComplete(); assertEquals(Arrays.asList(e2), list); } finally { RxJavaPlugins.reset(); } }
Source:
void serializeMessageInfoList(ByteBuffer outputBuffer) { outputBuffer.putInt(messageInfoList == null ? 0 : messageInfoList.size()); if (messageInfoList != null) { for (MessageInfo messageInfo : messageInfoList) { outputBuffer.put(messageInfo.getStoreKey().toBytes()); outputBuffer.putLong(messageInfo.getSize()); outputBuffer.putLong(messageInfo.getExpirationTimeInMs()); outputBuffer.put(messageInfo.isDeleted() ? DELETED : (byte) ~DELETED); switch (version) { case VERSION_1: break; case VERSION_2: Long crc = messageInfo.getCrc(); if (crc != null) { outputBuffer.put(CRC_PRESENT); outputBuffer.putLong(crc); } else { outputBuffer.put((byte) ~CRC_PRESENT); } break; case VERSION_3: crc = messageInfo.getCrc(); if (crc != null) { outputBuffer.put(CRC_PRESENT); outputBuffer.putLong(crc); } else { outputBuffer.put((byte) ~CRC_PRESENT); } outputBuffer.putShort(messageInfo.getAccountId()); outputBuffer.putShort(messageInfo.getContainerId()); outputBuffer.putLong(messageInfo.getOperationTimeMs()); break; default: throw new IllegalArgumentException("Unknown version in MessageInfoList " + version); } } } }

Target:
void serializeMessageInfoList(ByteBuffer outputBuffer) { outputBuffer.putInt(messageInfoList == null ? 0 : messageInfoList.size()); if (messageInfoList != null) { for (MessageInfo messageInfo : messageInfoList) { outputBuffer.put(messageInfo.getStoreKey().toBytes()); outputBuffer.putLong(messageInfo.getSize()); outputBuffer.putLong(messageInfo.getExpirationTimeInMs()); outputBuffer.put(messageInfo.isDeleted() ? DELETED : (byte) ~DELETED); switch (version) { case VERSION_1: break; case VERSION_2: { Long crc = messageInfo.getCrc(); if (crc != null) { outputBuffer.put(CRC_PRESENT); outputBuffer.putLong(crc); } else { outputBuffer.put((byte) ~CRC_PRESENT); } } break; case VERSION_3: { Long crc = messageInfo.getCrc(); if (crc != null) { outputBuffer.put(CRC_PRESENT); outputBuffer.putLong(crc); } else { outputBuffer.put((byte) ~CRC_PRESENT); } outputBuffer.putShort(messageInfo.getAccountId()); outputBuffer.putShort(messageInfo.getContainerId()); outputBuffer.putLong(messageInfo.getOperationTimeMs()); } break; default: throw new IllegalArgumentException("Unknown version in MessageInfoList " + version); } } } }
Source:
public ApplicationStatus status(StreamApplication app) { try { boolean finished = false; boolean unsuccessfulFinish = false; ExecutionPlan plan = getExecutionPlan(app); for (JobConfig jobConfig : plan.getJobConfigs()) { JobRunner runner = new JobRunner(jobConfig); JobStatus status = runner.status(); log.debug("Status is for job {}", new Object[]{status, jobConfig.getName()}); switch (status) { case Running: return ApplicationStatus.running(); case UnsuccessfulFinish: unsuccessfulFinish = true; case SuccessfulFinish: finished = true; break; default: } } if (unsuccessfulFinish) { return ApplicationStatus.unsuccessfulFinish(null); } else if (finished) { return ApplicationStatus.successfulFinish(); } return ApplicationStatus.new_(); } catch (Throwable t) { throw new SamzaException("Failed to get status for application", t); } }

Target:
public ApplicationStatus status(StreamApplication app) { try { boolean hasNewJobs = false; boolean hasRunningJobs = false; ApplicationStatus unsuccessfulFinishStatus = null; ExecutionPlan plan = getExecutionPlan(app); for (JobConfig jobConfig : plan.getJobConfigs()) { JobRunner runner = new JobRunner(jobConfig); ApplicationStatus status = runner.status(); log.debug("Status is for job {}", new Object[]{status, jobConfig.getName()}); switch (status.getStatusCode()) { case New: hasNewJobs = true; break; case Running: hasRunningJobs = true; break; case UnsuccessfulFinish: unsuccessfulFinishStatus = status; break; case SuccessfulFinish: break; default: } } if (hasNewJobs) { return ApplicationStatus.New; } else if (hasRunningJobs) { return ApplicationStatus.Running; } else if (unsuccessfulFinishStatus != null) { return unsuccessfulFinishStatus; } else { return ApplicationStatus.SuccessfulFinish; } } catch (Throwable t) { throw new SamzaException("Failed to get status for application", t); } }
Source:
protected void executeQueryCommand() { Set<GlusterVolumeEntity> eligibleVolumes = new HashSet<GlusterVolumeEntity>(); Guid masterVolumeId = getParameters().getId(); GlusterVolumeEntity masterVolume = getGlusterVolumeDao().getById(masterVolumeId); List<GlusterVolumeEntity> allGlusterVolumesWithMasterCompatibleVersion = getAllGlusterVolumesWithMasterCompatibleVersion(masterVolumeId); CheckEligibilityOfVolumesForGeoRepSessionCreationQuery<CheckGlusterVolumeGeoRepEligibilityParameters> eligibilityQuery = new CheckEligibilityOfVolumesForGeoRepSessionCreationQuery<CheckGlusterVolumeGeoRepEligibilityParameters>(new CheckGlusterVolumeGeoRepEligibilityParameters(masterVolumeId, null)); List<Guid> sessionSlavesIds = eligibilityQuery.prepareSessionMap(getGeoRepDao().getAllSessions()); for(GlusterVolumeEntity currentVolume : allGlusterVolumesWithMasterCompatibleVersion) { List<GEO_REP_NON_ELIGIBILITY_REASON> nonEligibilityResons = eligibilityQuery.processVolumesInCurrentCluster(masterVolume, currentVolume, sessionSlavesIds); if(nonEligibilityResons == null || nonEligibilityResons.size() == 0) { eligibleVolumes.add(currentVolume); } } getQueryReturnValue().setReturnValue(eligibleVolumes); }

Target:
protected void executeQueryCommand() { Set<GlusterVolumeEntity> eligibleVolumes = new HashSet<GlusterVolumeEntity>(); Guid masterVolumeId = getParameters().getId(); GlusterVolumeEntity masterVolume = getGlusterVolumeDao().getById(masterVolumeId); List<GlusterVolumeEntity> allGlusterVolumesWithMasterCompatibleVersion = getAllGlusterVolumesWithMasterCompatibleVersion(masterVolumeId); for(GlusterVolumeEntity currentVolume : allGlusterVolumesWithMasterCompatibleVersion) { List<GlusterGeoRepNonEligibilityReason> nonEligibilityResons = getGeoRepUtilInstance().getNonEligibilityReasons(masterVolume, currentVolume); if(nonEligibilityResons == null || nonEligibilityResons.size() == 0) { eligibleVolumes.add(currentVolume); } } getQueryReturnValue().setReturnValue(eligibleVolumes); }
Source:
private void validateConfigOptions(ReadableConfig config) { String jdbcUrl = config.get(URL); final Optional<JdbcDialect> dialect = JdbcDialects.get(jdbcUrl); checkState(dialect.isPresent(), "Cannot handle such jdbc url: " + jdbcUrl); checkAllOrNone(config, new ConfigOption[]{ USERNAME, PASSWORD }); checkAllOrNone(config, new ConfigOption[]{ SCAN_PARTITION_COLUMN, SCAN_PARTITION_NUM, SCAN_PARTITION_LOWER_BOUND, SCAN_PARTITION_UPPER_BOUND }); if (config.getOptional(SCAN_PARTITION_LOWER_BOUND).isPresent() && config.getOptional(SCAN_PARTITION_UPPER_BOUND).isPresent()) { long lowerBound = config.get(SCAN_PARTITION_LOWER_BOUND); long upperBound = config.get(SCAN_PARTITION_UPPER_BOUND); if (lowerBound > upperBound) { throw new IllegalArgumentException(String.format( "'%s'='%s' must not be larger than '%s'='%s'.", SCAN_PARTITION_LOWER_BOUND.key(), lowerBound, SCAN_PARTITION_UPPER_BOUND.key(), upperBound)); } } checkAllOrNone(config, new ConfigOption[]{ LOOKUP_CACHE_MAX_ROWS, LOOKUP_CACHE_TTL }); if (config.get(LOOKUP_MAX_RETRIES) <= 0) { throw new IllegalArgumentException("The 'lookup.max-retries' should be greater than 0."); } if (config.get(SINK_MAX_RETRIES) <= 0) { throw new IllegalArgumentException("The 'sink.max-retries' should be greater than 0."); } }

Target:
private void validateConfigOptions(ReadableConfig config) { String jdbcUrl = config.get(URL); final Optional<JdbcDialect> dialect = JdbcDialects.get(jdbcUrl); checkState(dialect.isPresent(), "Cannot handle such jdbc url: " + jdbcUrl); checkAllOrNone(config, new ConfigOption[]{ USERNAME, PASSWORD }); checkAllOrNone(config, new ConfigOption[]{ SCAN_PARTITION_COLUMN, SCAN_PARTITION_NUM, SCAN_PARTITION_LOWER_BOUND, SCAN_PARTITION_UPPER_BOUND }); if (config.getOptional(SCAN_PARTITION_LOWER_BOUND).isPresent() && config.getOptional(SCAN_PARTITION_UPPER_BOUND).isPresent()) { long lowerBound = config.get(SCAN_PARTITION_LOWER_BOUND); long upperBound = config.get(SCAN_PARTITION_UPPER_BOUND); if (lowerBound > upperBound) { throw new IllegalArgumentException(String.format( "'%s'='%s' must not be larger than '%s'='%s'.", SCAN_PARTITION_LOWER_BOUND.key(), lowerBound, SCAN_PARTITION_UPPER_BOUND.key(), upperBound)); } } checkAllOrNone(config, new ConfigOption[]{ LOOKUP_CACHE_MAX_ROWS, LOOKUP_CACHE_TTL }); if (config.get(LOOKUP_MAX_RETRIES) < 0) { throw new IllegalArgumentException(String.format( "The value of '%s' option shouldn't be negative, but is %s.", LOOKUP_MAX_RETRIES.key(), config.get(LOOKUP_MAX_RETRIES))); } if (config.get(SINK_MAX_RETRIES) < 0) { throw new IllegalArgumentException(String.format( "The value of '%s' option shouldn't be negative, but is %s.", SINK_MAX_RETRIES.key(), config.get(SINK_MAX_RETRIES))); } }
Source:
public ResourceBundle getResourcesBundle() { List<ResourceBundle> bundleList = getBundle(RESOURCES_KEY, LocaleFilter.DEFAULT_LOCALE); if (bundleList.size() >= 1) { return bundleList.get(0); } if (dummyResourceBundle == null) { log.warn("Branding theme " + this.getPath() + " is missing its resources.properties file. " + "Check branding.properties resources key. Check that the file referred to in " + "resources key exists."); dummyResourceBundle = new ListResourceBundle() { @Override protected Object[][] getContents() { return new Object[0][0]; } }; } return dummyResourceBundle; }

Target:
public ResourceBundle getResourcesBundle() { List<ResourceBundle> bundleList = getBundle(RESOURCES_KEY, LocaleFilter.DEFAULT_LOCALE); if (bundleList.size() >= 1) { return bundleList.get(0); } throw new MissingResourceException("can't load resources bundle", null, null); }
Source:
public void setup() throws Exception { storeKeyToMockStoreMap.clear(); helixNotifier = new HelixNotifier(getMockHelixStore(storeConfig)); helixNotifier2 = new HelixNotifier(getMockHelixStore(storeConfig)); resetReferenceTopicsAndMessages(); resetListeners(); deleteStoreIfExists(); }

Target:
public void setup() throws Exception { deleteStoreIfExists(); storeKeyToMockStoreMap.clear(); helixNotifier = new HelixNotifier(getMockHelixStore(storeConfig)); resetReferenceTopicsAndMessages(); resetListeners(); }
Source:
public static <T> T adapt(Object sourceObject, Class<T> adapter) { try { if (PlatformUiUtil.isNeonOrLater()) { Bundle bundle = Platform.getBundle("org.eclipse.platform"); Class<?> clazz = bundle.loadClass("org.eclipse.core.runtime.Adapters"); Method adaptMethod = clazz.getMethod("adapt", new Class[] { Object.class, Class.class }); Object result = adaptMethod.invoke(clazz, sourceObject, adapter); return (T) result; } else { Bundle bundle = Platform.getBundle("org.eclipse.ui.workbench"); Class<?> clazz = bundle.loadClass("org.eclipse.ui.internal.util.Util"); Method adaptMethod = clazz.getMethod("getAdapter", new Class[] { Object.class, Class.class }); Object result = adaptMethod.invoke(clazz, sourceObject, adapter); return (T) result; } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }

Target:
public static <T> T adapt(Object sourceObject, Class<T> adapter) { try { if (PlatformUiUtil.isNeonOrLater()) { Bundle bundle = Platform.getBundle("org.eclipse.platform"); Class<?> clazz = bundle.loadClass("org.eclipse.core.runtime.Adapters"); Method adaptMethod = clazz.getMethod("adapt", new Class[] { Object.class, Class.class }); Object result = adaptMethod.invoke(clazz, sourceObject, adapter); return (T) result; } else { Bundle bundle = Platform.getBundle("org.eclipse.ui.workbench"); Class<?> clazz = bundle.loadClass("org.eclipse.ui.internal.util.Util"); Method adaptMethod = clazz.getMethod("getAdapter", new Class[] { Object.class, Class.class }); Object result = adaptMethod.invoke(clazz, sourceObject, adapter); return (T) result; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, RepositoriesUiPlugin.ID_PLUGIN, "Could not adapt", e)); } return null; }
Source:
private void createTable(Connection conn, String table) throws SQLException { String ddl = "create table if not exists " + table + "( " + TRACE.columnName + " bigint not null, " + PARENT.columnName + " bigint not null, " + SPAN.columnName + " bigint not null, " + DESCRIPTION.columnName + " varchar, " + START.columnName + " bigint, " + END.columnName + " bigint, " + HOSTNAME.columnName + " varchar, " + TAG_COUNT + " smallint, " + ANNOTATION_COUNT + " smallint" + " CONSTRAINT pk PRIMARY KEY (" + TRACE.columnName + ", " + PARENT.columnName + ", " + SPAN.columnName + "))\n" + PhoenixDatabaseMetaData.TRANSACTIONAL + "=" + Boolean.FALSE; ; PreparedStatement stmt = conn.prepareStatement(ddl); stmt.execute(); this.table = table; }

Target:
private void createTable(Connection conn, String table) throws SQLException { String ddl = "create table if not exists " + table + "( " + TRACE.columnName + " bigint not null, " + PARENT.columnName + " bigint not null, " + SPAN.columnName + " bigint not null, " + DESCRIPTION.columnName + " varchar, " + START.columnName + " bigint, " + END.columnName + " bigint, " + HOSTNAME.columnName + " varchar, " + TAG_COUNT + " smallint, " + ANNOTATION_COUNT + " smallint" + " CONSTRAINT pk PRIMARY KEY (" + TRACE.columnName + ", " + PARENT.columnName + ", " + SPAN.columnName + "))\n"; PreparedStatement stmt = conn.prepareStatement(ddl); stmt.execute(); this.table = table; }
Source:
public String getRealm() { String realmString = ""; final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (OAuth2Authentication.class.equals(authentication.getClass())) { final Object details = ((OAuth2Authentication) authentication).getUserAuthentication().getDetails(); if (details instanceof Map) { final Map<String, Object> map = (Map<String, Object>) details; final Object realm = map.get("realm"); if (realm != null && realm instanceof String) { realmString = (String) realm; } } } return realmString; }

Target:
public String getRealm() { try { return Optional.of(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .map(authentication -> (OAuth2Authentication) authentication) .map(OAuth2Authentication::getUserAuthentication) .map(Authentication::getDetails) .map(details -> (Map) details) .map(details -> details.get("realm")) .map(realm -> (String) realm) .orElse(""); } catch (final ClassCastException e) { return ""; } }
Source:
protected void onStart() { super.onStart(); mUserEnterTimeMillis = SystemClock.elapsedRealtime(); mUserActions = MetricsWriter.USER_ACTION_NONE; mMetricsWriter.writeMetricsForEnter(); ShortcutViewUtils.Config prevConfig = mShortcutViewConfig; mShortcutViewConfig = new ShortcutViewUtils.Config(this, prevConfig); if (mShortcutViewConfig.isEnabled() != prevConfig.isEnabled() || mSupportsDarkText != isDarkTextSupported()) { recreate(); return; } if (mShortcutViewConfig.isEnabled()) { updateLocationAndEccInfo(); } else { mColorExtractor.addOnColorsChangedListener(this); } }

Target:
protected void onStart() { super.onStart(); mUserEnterTimeMillis = SystemClock.elapsedRealtime(); mUserActions = MetricsWriter.USER_ACTION_NONE; mMetricsWriter.writeMetricsForEnter(); boolean isEnabledPreviously = mShortcutViewConfig.isEnabled(); mShortcutViewConfig.refresh(this); if (mShortcutViewConfig.isEnabled() != isEnabledPreviously || mSupportsDarkText != isDarkTextSupported()) { recreate(); return; } if (mShortcutViewConfig.isEnabled()) { updateLocationAndEccInfo(); } else { mColorExtractor.addOnColorsChangedListener(this); } }
Source:
public String currentAuthorizationHeader() { if (token == null) { synchronized (lock) { try { token = renewAuthorizationHeader(null).get(); } catch (InterruptedException | ExecutionException e) { log.error("Failed to complete crtauth handshake."); throw Throwables.propagate(e); } } } return token; }

Target:
public String currentAuthorizationHeader() { return tokenRef.get(); }
Source:
public HostUpgradeManagerResult checkForUpdates(final VDS host) { try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(host.getHostName()) .checkMode(true) .enableLogging(false) .playbook(AnsibleConstants.HOST_UPGRADE_PLAYBOOK); AnsibleReturnValue ansibleReturnValue = new AnsibleExecutor().runCommand( command, new Pair<>("ANSIBLE_STDOUT_CALLBACK", "hostupgradeplugin") ); if (ansibleReturnValue.getAnsibleReturnCode() != AnsibleReturnCode.OK) { log.error("Failed to run check-update of host '{}'.", host.getName()); throw new RuntimeException("Failed to run check-update of host '{}'."); } boolean updatesAvailable = Boolean.valueOf(ansibleReturnValue.getStdout()); HostUpgradeManagerResult hostUpgradeManagerResult = new HostUpgradeManagerResult(); hostUpgradeManagerResult.setUpdatesAvailable(updatesAvailable); if (updatesAvailable) { AuditLogable auditLog = new AuditLogableImpl(); auditLog.setVdsId(host.getId()); auditLog.setVdsName(host.getName()); auditLogDirector.log(auditLog, AuditLogType.HOST_UPDATES_ARE_AVAILABLE); } return hostUpgradeManagerResult; } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
public HostUpgradeManagerResult checkForUpdates(final VDS host) { try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(host.getHostName()) .checkMode(true) .enableLogging(false) .playbook(AnsibleConstants.HOST_UPGRADE_PLAYBOOK); AnsibleReturnValue ansibleReturnValue = new AnsibleExecutor().runCommand( command, new Pair<>("ANSIBLE_STDOUT_CALLBACK", AnsibleConstants.HOST_UPGRADE_CALLBACK_PLUGIN) ); if (ansibleReturnValue.getAnsibleReturnCode() != AnsibleReturnCode.OK) { log.error("Failed to run check-update of host '{}'.", host.getName()); throw new RuntimeException("Failed to run check-update of host '{}'."); } List<String> availablePackages = JsonHelper.jsonToList(ansibleReturnValue.getStdout()); boolean updatesAvailable = !availablePackages.isEmpty(); HostUpgradeManagerResult hostUpgradeManagerResult = new HostUpgradeManagerResult(); hostUpgradeManagerResult.setUpdatesAvailable(updatesAvailable); if (updatesAvailable) { hostUpgradeManagerResult.setAvailablePackages(availablePackages); log.info("There are available packages ({}) for host '{}'", StringUtils.join(availablePackages, ", "), host.getName()); AuditLogable auditLog = new AuditLogableImpl(); auditLog.setVdsId(host.getId()); auditLog.setVdsName(host.getName()); auditLogDirector.log(auditLog, AuditLogType.HOST_UPDATES_ARE_AVAILABLE); } return hostUpgradeManagerResult; } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } }