auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onNext(final AggregationMessage aggregationMessage) { final String workerId = aggregationMessage.getSourceId().toString(); final String localState = codec.decode(aggregationMessage.getData().array()); final String globalState = globalStateMachine.getCurrentState(); switch (globalState) { case STATE_INIT: break; case STATE_RUN: if (localState.equals(STATE_INIT)) { sendResponseMessage(workerId, new byte[0]); return; } break; case STATE_CLEANUP: default: throw new RuntimeException("Invalid state"); } blockedWorkerIds.add(workerId); LOG.log(Level.FINE, "Receive a synchronization message from {0}. {1} messages have been received out of {2}.", new Object[]{workerId, blockedWorkerIds.size(), numWorkersToSync}); tryReleaseWorkers(); }

Target:
public void onNext(final AggregationMessage aggregationMessage) { final String workerId = aggregationMessage.getSourceId().toString(); final String localState = codec.decode(aggregationMessage.getData().array()); final String globalState = globalStateMachine.getCurrentState(); switch (globalState) { case STATE_INIT: if (!localState.equals(STATE_INIT)) { throw new RuntimeException("Individual workers cannot overtake the global state"); } break; case STATE_RUN: if (localState.equals(STATE_INIT)) { sendResponseMessage(workerId, EMPTY_DATA); return; } else if (!localState.equals(STATE_RUN)) { throw new RuntimeException("Individual workers cannot overtake the global state"); } break; case STATE_CLEANUP: throw new RuntimeException("Workers never call the global barrier in STATE_CLEANUP state"); default: throw new RuntimeException("Invalid state"); } blockWorker(workerId); }
Source:
public HttpMessage setProtocolVersion(HttpVersion version) { ObjectUtil.checkNotNull(version, "version"); this.version = version; return this; }

Target:
public HttpMessage setProtocolVersion(HttpVersion version) { this.version = ObjectUtil.checkNotNull(version, "version"); return this; }
Source:
private void validate() { assertThat(localSegment, Objects::nonNull, () -> new AxonConfigurationException("The localSegment may not be null")); assertThat(channel, Objects::nonNull, () -> new AxonConfigurationException("JChannel may not be null")); assertThat(clusterName, Objects::nonNull, () -> new AxonConfigurationException("The clusterName may not be null")); assertThat(serializer, Objects::nonNull, () -> new AxonConfigurationException("Serializer may not be null")); assertThat(routingStrategy, Objects::nonNull, () -> new AxonConfigurationException("RoutingStrategy may not be null")); assertThat(consistentHashChangeListener, Objects::nonNull, () -> new AxonConfigurationException("ConsistentHashChangeListener may not be null")); }

Target:
protected void validate() { assertNonNull(localSegment, "The localSegment is a hard requirement and should be provided"); assertNonNull(channel, "The JChannel is a hard requirement and should be provided"); assertClusterName(clusterName, "The clusterName is a hard requirement and should be provided"); assertNonNull(serializer, "The Serializer is a hard requirement and should be provided"); assertNonNull(routingStrategy, "The RoutingStrategy is a hard requirement and should be provided"); assertNonNull(consistentHashChangeListener, "The ConsistentHashChangeListener is a hard requirement and should be provided"); }
Source:
private Object unwrapBinary(Object obj, BinaryReaderHandles hnds) { if (obj instanceof BinaryObjectImpl) { BinaryObjectImpl obj0 = (BinaryObjectImpl)obj; return marsh.deserialize(BinaryHeapInputStream.create(obj0.array(), obj0.start()), hnds); } else if (obj instanceof BinaryObject ) return ((BinaryObject)obj).deserialize(); else if (BinaryUtils.knownCollection(obj)) return unwrapCollection((Collection<Objects>)obj, hnds); else if (BinaryUtils.knownMap(obj)) return unwrapMap((Map<Object, Object>)obj, hnds); else if (obj instanceof Object[]) return unwrapArray((Object[])obj, hnds); else return obj; }

Target:
private Object unwrapBinary(Object obj, BinaryReaderHandles hnds) { if (obj instanceof BinaryObjectImpl) { BinaryObjectImpl obj0 = (BinaryObjectImpl)obj; return marsh.deserialize(BinaryHeapInputStream.create(obj0.array(), obj0.start()), hnds); } else if (obj instanceof BinaryObject) return ((BinaryObject)obj).deserialize(); else if (BinaryUtils.knownCollection(obj)) return unwrapCollection((Collection<Object>)obj, hnds); else if (BinaryUtils.knownMap(obj)) return unwrapMap((Map<Object, Object>)obj, hnds); else if (obj instanceof Object[]) return unwrapArray((Object[])obj, hnds); else return obj; }
Source:
public void put(String handle, LocalDateTime lastUsed) { storageLock.lock(); try { if (_storage == null) { throw new RuntimeException(EXCEPTION_STORAGE); } if (lastUsed == null) { _storage.put(LAST_USED.getKey(handle), (String) null); } else { String gsonStr = gson.toJson(lastUsed); _storage.put(LAST_USED.getKey(handle), gsonStr); } } finally { storageLock.unlock(); } }

Target:
public void put(String handle, LocalDateTime lastUsed) { storageLock.lock(); try { if (storage == null) { throw new IllegalStateException(EXCEPTION_STORAGE); } if (lastUsed == null) { storage.put(LAST_USED.getKey(handle), (String) null); } else { String gsonStr = gson.toJson(lastUsed); storage.put(LAST_USED.getKey(handle), gsonStr); } } finally { storageLock.unlock(); } }
Source:
public ArrayList<LinkInfo> getRemoteGoToLinks() throws IOException { if (remoteGoToLinks == null) { loadAndPreflightPdf(); remoteGoToLinks = parseForLinks(PDActionRemoteGoTo.SUB_TYPE); } return remoteGoToLinks; }

Target:
public List<LinkInfo> getRemoteGoToLinks() throws IOException { if (remoteGoToLinks == null) { loadAndPreflightPdf(); remoteGoToLinks = parseForLinks(PDActionRemoteGoTo.SUB_TYPE); } return remoteGoToLinks; }
Source:
private void breakModifies(ProgressMonitor pm) throws IOException { if (breakScore <= 0) return; ArrayList<DiffEntry> newEntries = new ArrayList<DiffEntry>(entries.size()); pm.beginTask(JGitText.get().renamesBreakingModifies, entries.size()); for (int i = 0; i < entries.size(); i++) { DiffEntry e = entries.get(i); if (e.getChangeType() == ChangeType.MODIFY) { final int score = calculateModifyScore(e); if (score < breakScore) { List<DiffEntry> tmp = DiffEntry.breakModify(e); DiffEntry del = tmp.get(0); del.score = score; deleted.add(del); added.add(tmp.get(1)); } else { newEntries.add(e); } } pm.update(1); } entries = newEntries; }

Target:
private void breakModifies(ProgressMonitor pm) throws IOException { if (breakScore <= 0) return; ArrayList<DiffEntry> newEntries = new ArrayList<DiffEntry>(entries.size()); pm.beginTask(JGitText.get().renamesBreakingModifies, entries.size()); for (int i = 0; i < entries.size(); i++) { DiffEntry e = entries.get(i); if (e.getChangeType() == ChangeType.MODIFY) { final int score = calculateModifyScore(e); if (score < breakScore) { List<DiffEntry> tmp = DiffEntry.breakModify(e); DiffEntry del = tmp.get(0); del.score = score; deleted.add(del); added.add(tmp.get(1)); } else { newEntries.add(e); } } else { newEntries.add(e); } pm.update(1); } entries = newEntries; }
Source:
public void sendJsonMessage(String json) throws OperationFailedException { try { assertConnected(); org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); msg.setType(org.jivesoftware.smack.packet.Message.Type.groupchat); msg.addExtension(new JsonMessageExtension(json)); MessageEventManager. addNotificationsRequests(msg, true, false, false, true); multiUserChat.sendMessage(msg); } catch (NotConnectedException | InterruptedException ex){ throw new OperationFailedException( "Failed to send JSON message " + json , OperationFailedException.GENERAL_ERROR , ex); } }

Target:
public void sendJsonMessage(String json) throws OperationFailedException { org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); msg.addExtension(new JsonMessageExtension(json)); sendMessage(msg); }
Source:
public static void placeSteamOven(World world, BlockPos pos, List<ItemStack> input, List<ItemStack> output) { MultiBlockPattern pattern = TileSteamOven.patterns.get(0); Map<Character, IBlockState> blockMapping = new HashMap<Character, IBlockState>(); IBlockState base = RailcraftBlocks.getBlockMachineAlpha().getDefaultState(); IBlockState steamOven = base.withProperty(MachineProxyAlpha.VARIANT, EnumMachineAlpha.STEAM_OVEN); blockMapping.put('B', steamOven); TileEntity tile = pattern.placeStructure(world, pos, blockMapping); if (tile instanceof TileSteamOven) { TileSteamOven master = (TileSteamOven) tile; for (int slot = 0; slot < 9; slot++) { if (input != null && slot < input.size()) master.inv.setInventorySlotContents(TileSteamOven.SLOT_INPUT + slot, input.get(slot)); if (output != null && slot < output.size()) master.inv.setInventorySlotContents(TileSteamOven.SLOT_OUTPUT + slot, output.get(slot)); } } }

Target:
public static void placeSteamOven(World world, BlockPos pos, List<ItemStack> input, List<ItemStack> output) { MultiBlockPattern pattern = TileSteamOven.patterns.get(0); Map<Character, IBlockState> blockMapping = new HashMap<Character, IBlockState>(); blockMapping.put('B', EnumMachineAlpha.STEAM_OVEN.getState()); TileEntity tile = pattern.placeStructure(world, pos, blockMapping); if (tile instanceof TileSteamOven) { TileSteamOven master = (TileSteamOven) tile; for (int slot = 0; slot < 9; slot++) { if (input != null && slot < input.size()) master.inv.setInventorySlotContents(TileSteamOven.SLOT_INPUT + slot, input.get(slot)); if (output != null && slot < output.size()) master.inv.setInventorySlotContents(TileSteamOven.SLOT_OUTPUT + slot, output.get(slot)); } } }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof ErrorPage) { ErrorPage other = (ErrorPage) obj; boolean rtn = true; rtn = ObjectUtils.nullSafeEquals(getExceptionName(), other.getExceptionName()); rtn = rtn && ObjectUtils.nullSafeEquals(this.path, other.path); rtn = rtn && this.status == other.status; return rtn; } return false; }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof ErrorPage) { ErrorPage other = (ErrorPage) obj; boolean rtn = ObjectUtils.nullSafeEquals(getExceptionName(), other.getExceptionName()); rtn = rtn && ObjectUtils.nullSafeEquals(this.path, other.path); rtn = rtn && this.status == other.status; return rtn; } return false; }
Source:
protected boolean shouldNotFilter(HttpServletRequest request) { final HttpSession session = request.getSession(false); if (session != null && !session.isNew()) { log.debug("User has a session: {}", request.getRemoteUser(), session.getId()); log.debug("Max inactive interval: {}", session.getMaxInactiveInterval()); final Instant ctime = Instant.ofEpochMilli(session.getCreationTime()); final Instant atime = Instant.ofEpochMilli(session.getLastAccessedTime()); log.debug("Session creation time: {}, last access time: {}", ctime, atime); return true; } else { log.debug("User does not have a session", request.getRemoteUser()); } return REST_API_SERVLET_PATH.equalsIgnoreCase(request.getServletPath()); }

Target:
protected boolean shouldNotFilter(HttpServletRequest request) { final HttpSession session = request.getSession(false); if (session != null && !session.isNew()) { log.debug("User has a session: {}", request.getRemoteUser(), session.getId()); log.debug("Max inactive interval: {}", session.getMaxInactiveInterval()); if (log.isDebugEnabled()) { final Instant ctime = Instant.ofEpochMilli(session.getCreationTime()); final Instant atime = Instant.ofEpochMilli(session.getLastAccessedTime()); log.debug("Session creation time: {}, last access time: {}", ctime, atime); } return true; } else { log.debug("User does not have a session", request.getRemoteUser()); } return REST_API_SERVLET_PATH.equalsIgnoreCase(request.getServletPath()); }
Source:
private VolumeType getType() { if (!getStorageDomain().getStorageType().isOpenStackDomain() && getParameters().getVolumeFormat() == VolumeFormat.RAW) { return VolumeType.Preallocated; } return VolumeType.Sparse; }

Target:
private VolumeType getType() { if ((getStorageDomain().getStorageType().isBlockDomain() || getStorageDomain().getStorageType().isFileDomain()) && getParameters().getVolumeFormat() == VolumeFormat.RAW) { return VolumeType.Preallocated; } return VolumeType.Sparse; }
Source:
private void addVersionAndBranchTags(String remotePath, CVSTag[] tags) { TagCacheEntry entry = getTagCacheEntryFor(remotePath, true); entry.accessed(); for (int i = 0; i < tags.length; i++) { if (tags[i].getType() != CVSTag.DATE) { if (!getAllKnownTagsForParents(entry).contains(tags[i])) { removeTagFromChildrenCacheEntries(entry, tags[i], false); entry.tags.add(tags[i]); } } } }

Target:
private void addVersionAndBranchTags(String remotePath, CVSTag[] tags) { String name = getCachePathFor(remotePath); TagCacheEntry entry = (TagCacheEntry)versionAndBranchTags.get(name); if (entry == null) { entry = new TagCacheEntry(); versionAndBranchTags.put(name, entry); } else { entry.accessed(); } for (int i = 0; i < tags.length; i++) { if(tags[i].getType() != CVSTag.DATE){ entry.tags.add(tags[i]); } } }
Source:
public QueryResponse getSpecies() throws IOException { Properties properties = new Properties(); properties.load(DBAdaptorConnector.class.getResourceAsStream("/eva.properties")); return setQueryResponse(archiveEvaproDbAdaptor.getSpecies(properties.getProperty("eva.version"), true)); }

Target:
public QueryResponse getSpecies() { return setQueryResponse(archiveEvaproDbAdaptor.getSpecies(properties.getProperty("eva.version"), true)); }
Source:
void messageConsumptionCycle() { while (!killed) { long incrementedClock = 0; UpdateMessage message = null; if (!internalMessageQueue.isEmpty()) message = internalMessageQueue.removeFirst(); else synchronized (externalMessageLock) { if (!externalMessageQueue.isEmpty()) { message = takeExternalMessage(); } else { incrementedClock = ++clock; } } if (message == null) { localUpdateTermination(incrementedClock); while (message == null) { synchronized (externalMessageLock) { while (externalMessageQueue.isEmpty()) { try { externalMessageLock.wait(); } catch (InterruptedException e) { if (killed) return; } } message = takeExternalMessage(); } } } message.receiver.update(message.direction, message.updateElement, null); } }

Target:
void messageConsumptionCycle() { while (!killed) { long incrementedClock = 0; UpdateMessage message = null; if (!internalMessageQueue.isEmpty()) message = internalMessageQueue.removeFirst(); else synchronized (externalMessageLock) { if (!externalMessageQueue.isEmpty()) { message = takeExternalMessage(); } else { incrementedClock = ++clock; } } if (message == null) { localUpdateTermination(incrementedClock); while (message == null) { synchronized (externalMessageLock) { while (externalMessageQueue.isEmpty()) { try { externalMessageLock.wait(); } catch (InterruptedException e) { if (killed) return; } } message = takeExternalMessage(); } } } message.receiver.update(message.direction, message.updateElement, DifferentialTimestamp.ZERO); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || o.getClass() != getClass()) { return false; } PeriodBroadcastDistributionRule that = (PeriodBroadcastDistributionRule) o; if (!Objects.equals(period, that.period)) { return false; } if (!Objects.equals(includeFuture, that.includeFuture)) { return false; } return Objects.equals(colocatedDataSources, that.colocatedDataSources); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || o.getClass() != getClass()) { return false; } PeriodBroadcastDistributionRule that = (PeriodBroadcastDistributionRule) o; if (!Objects.equals(period, that.period)) { return false; } if (includeFuture != that.includeFuture) { return false; } return Objects.equals(colocatedDataSources, that.colocatedDataSources); }
Source:
protected HttpClient createHttpClient() throws Error { int port = getPort(); Lookup<AuthSchemeProvider> authSchemeProvider = null; CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(getHost(), port, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME); if (user != null && user.length() > 0) { credsProvider.setCredentials( authScope, new UsernamePasswordCredentials(user, password) ); } else if (kerberos) { authSchemeProvider = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)) .build(); credsProvider.setCredentials( authScope, new Credentials() { @Override public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } } ); } RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setConnectTimeout(timeout) .build(); HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setConnectionManager(new BasicHttpClientConnectionManager(createConnectionSocketFactoryRegistry())) .setDefaultRequestConfig(globalConfig) .setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeProvider); if (!compress) { clientBuilder.disableContentCompression(); } return new HttpClient45(clientBuilder.build()); }

Target:
protected HttpClient createHttpClient() { int port = getPort(); Lookup<AuthSchemeProvider> authSchemeProvider = null; CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(getHost(), port, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME); if (user != null && user.length() > 0) { credsProvider.setCredentials( authScope, new UsernamePasswordCredentials(user, password) ); } else if (kerberos) { authSchemeProvider = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)) .build(); credsProvider.setCredentials( authScope, new Credentials() { @Override public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } } ); } RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setConnectTimeout(timeout) .build(); HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setConnectionManager(new BasicHttpClientConnectionManager(createConnectionSocketFactoryRegistry())) .setDefaultRequestConfig(globalConfig) .setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeProvider); if (!compress) { clientBuilder.disableContentCompression(); } return new HttpClient45(clientBuilder.build()); }
Source:
public void bindPubSubProducer(String name, MessageChannel moduleOutputChannel, Properties properties) { validateProducerProperties(name, properties, SUPPORTED_PUBSUB_PRODUCER_PROPERTIES); RabbitPropertiesAccessor accessor = new RabbitPropertiesAccessor(properties); String exchangeName = applyPrefix(accessor.getPrefix(this.defaultPrefix), name); declareExchangeIfNotPresent(new FanoutExchange(exchangeName)); AmqpOutboundEndpoint endpoint = new AmqpOutboundEndpoint(determineRabbitTemplate(accessor)); endpoint.setExchangeName(exchangeName); endpoint.setRoutingKey(name); configureOutboundHandler(endpoint, accessor); doRegisterProducer(name, moduleOutputChannel, endpoint, accessor); }

Target:
public void bindPubSubProducer(String name, MessageChannel moduleOutputChannel, Properties properties) { validateProducerProperties(name, properties, SUPPORTED_PUBSUB_PRODUCER_PROPERTIES); RabbitPropertiesAccessor accessor = new RabbitPropertiesAccessor(properties); String exchangeName = applyPrefix(accessor.getPrefix(this.defaultPrefix), name); declareExchangeIfNotPresent(new TopicExchange(exchangeName)); AmqpOutboundEndpoint endpoint = new AmqpOutboundEndpoint(determineRabbitTemplate(accessor)); endpoint.setExchangeName(exchangeName); endpoint.setRoutingKey(name); configureOutboundHandler(endpoint, accessor); doRegisterProducer(name, moduleOutputChannel, endpoint, accessor); }
Source:
private List<KeyRange> getRegionRowKeyRanges() throws SQLException { List<HRegionLocation> regionLocations = getRegionBoundaries(scanGrouper); List<KeyRange> regionKeyRanges = Lists.newArrayListWithExpectedSize(regionLocations.size()); for(HRegionLocation regionLocation : regionLocations){ HRegionInfo regionInfo = regionLocation.getRegionInfo(); KeyRange range = KeyRange.getKeyRange(regionInfo.getStartKey(), true, regionInfo.getEndKey(), false); regionKeyRanges.add(range); } return regionKeyRanges; }

Target:
private List<KeyRange> getRegionRowKeyRanges() throws SQLException { List<HRegionLocation> regionLocations = getRegionBoundaries(scanGrouper); List<KeyRange> regionKeyRanges = Lists.newArrayListWithCapacity(regionLocations.size()); for (int i = 0; i < regionLocations.size(); i++) { HRegionLocation regionLocation = regionLocations.get(i); HRegionInfo regionInfo = regionLocation.getRegionInfo(); byte[] startKey = regionInfo.getStartKey(); byte[] endKey = regionInfo.getEndKey(); KeyRange range = KeyRange.getKeyRange(startKey, endKey); regionKeyRanges.add(range); } return regionKeyRanges; }
Source:
public void handleDelete(ActionParameters params) throws ActionException { final User user = params.getUser(); final long id = ConversionHelper.getLong(params.getRequiredParam(PARAM_ID), -1); if (!service.canModifyCategory(user, id)) { throw new ActionDeniedException("Tried to delete category: " + id); } try { layerService.delete(new long {id}); } catch (ServiceException e) { LOG.warn(e); throw new ActionException("Failed to delete layers"); } AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", id) .deleted(AuditLog.ResourceType.MYPLACES_LAYER); JSONObject response = new JSONObject(); JSONHelper.putValue(response, KEY_SUCCESS, true); ResponseHelper.writeResponse(params, response); }

Target:
public void handleDelete(ActionParameters params) throws ActionException { final User user = params.getUser(); final long id = params.getRequiredParamLong(PARAM_ID); if (!service.canModifyCategory(user, id)) { throw new ActionDeniedException("Tried to delete category: " + id); } try { layerService.delete(new long {id}); } catch (ServiceException e) { LOG.warn(e); throw new ActionException("Failed to delete layers"); } AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", id) .deleted(AuditLog.ResourceType.MYPLACES_LAYER); JSONObject response = new JSONObject(); JSONHelper.putValue(response, KEY_SUCCESS, true); ResponseHelper.writeResponse(params, response); }
Source:
private Set<LoadBalancer> createLoadBalancers(StackV4Request source, Stack stack) { Set<LoadBalancer> loadBalancers = new HashSet<>(); Set<TargetGroup> targetGroups = new HashSet<>(); if (StackType.DATALAKE.equals(source.getType())) { LOGGER.info("Setting up load balancers for stack {}", source.getName()); Set<String> knoxGatewayGroupNames = loadBalancerConfigService.getKnoxGatewayGroups(stack); Set<InstanceGroup> knoxGatewayGroups = stack.getInstanceGroups().stream() .filter(ig -> knoxGatewayGroupNames.contains(ig.getGroupName())) .collect(Collectors.toSet()); if (!knoxGatewayGroups.isEmpty()) { LOGGER.info("Knox gateway instance found; enabling Knox load balancer configuration."); TargetGroup targetGroup = new TargetGroup(); targetGroup.setType(TargetGroupType.KNOX.name()); targetGroup.setInstanceGroups(knoxGatewayGroups); targetGroups.add(targetGroup); knoxGatewayGroups.forEach(ig -> ig.addTargetGroup(targetGroup)); } } if (!targetGroups.isEmpty()) { LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setStack(stack); loadBalancer.setType(LoadBalancerType.PRIVATE.name()); loadBalancer.setTargetGroups(targetGroups); targetGroups.forEach(tg -> tg.setLoadBalancer(loadBalancer)); loadBalancers.add(loadBalancer); } return loadBalancers; }

Target:
private Set<LoadBalancer> createLoadBalancers(StackV4Request source, Stack stack) { Set<LoadBalancer> loadBalancers = new HashSet<>(); Set<TargetGroup> targetGroups = new HashSet<>(); if (StackType.DATALAKE.equals(source.getType()) && entitlementService.datalakeLoadBalancerEnabled(ThreadBasedUserCrnProvider.getUserCrn(), ThreadBasedUserCrnProvider.getAccountId())) { LOGGER.info("Setting up load balancers for stack {}", source.getName()); Set<String> knoxGatewayGroupNames = loadBalancerConfigService.getKnoxGatewayGroups(stack); Set<InstanceGroup> knoxGatewayGroups = stack.getInstanceGroups().stream() .filter(ig -> knoxGatewayGroupNames.contains(ig.getGroupName())) .collect(Collectors.toSet()); if (!knoxGatewayGroups.isEmpty()) { LOGGER.info("Knox gateway instance found; enabling Knox load balancer configuration."); TargetGroup targetGroup = new TargetGroup(); targetGroup.setType(TargetGroupType.KNOX); targetGroup.setInstanceGroups(knoxGatewayGroups); targetGroups.add(targetGroup); knoxGatewayGroups.forEach(ig -> ig.addTargetGroup(targetGroup)); } } if (!targetGroups.isEmpty()) { LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setStack(stack); loadBalancer.setType(LoadBalancerType.PRIVATE); loadBalancer.setTargetGroups(targetGroups); targetGroups.forEach(tg -> tg.setLoadBalancer(loadBalancer)); loadBalancers.add(loadBalancer); } return loadBalancers; }
Source:
public static void sendGeoIntent(@NonNull Activity activity, @NonNull Location location, String placeName) { String geoStr = "geo:0,0?q=" + location.getLatitude() + "," + location.getLongitude(); if (!TextUtils.isEmpty(placeName)) { geoStr += "(" + placeName +")"; } try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr))); } catch (ActivityNotFoundException e) { FeedbackUtil.showMessage(activity, R.string.error_no_maps_app); } }

Target:
public static void sendGeoIntent(@NonNull Activity activity, @NonNull Location location, String placeName) { String geoStr = "geo:0,0?q=" + location.getLatitude() + "," + location.getLongitude(); if (!TextUtils.isEmpty(placeName)) { geoStr += "(" + placeName + ")"; } try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Uri.encode(geoStr)))); } catch (ActivityNotFoundException e) { FeedbackUtil.showMessage(activity, R.string.error_no_maps_app); } }
Source:
protected void delete(Context context, Integer id) throws AuthorizeException { try { MetadataSchema metadataSchema = metadataSchemaService.find(context, id); if (metadataSchema == null) { throw new ResourceNotFoundException("metadata schema with id: " + id + " not found"); } metadataSchemaService.delete(context, metadataSchema); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
protected void delete(Context context, Integer id) throws AuthorizeException { try { MetadataSchema metadataSchema = metadataSchemaService.find(context, id); if (metadataSchema == null) { throw new ResourceNotFoundException("metadata schema with id: " + id + " not found"); } metadataSchemaService.delete(context, metadataSchema); } catch (SQLException e) { throw new RuntimeException( "error while trying to delete " + MetadataSchemaRest.NAME + " with id: " + id, e ); } }
Source:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResults equivToTelescopeResults ) { DefaultScoredCandidates.Builder<T> candidates = DefaultScoredCandidates.fromSource("Alias"); desc.startStage("Resolving aliases:"); EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName("Alias Equivalence Generator"); for (Alias alias : content.getAliases()) { desc.appendText(alias.toString()); } desc.finishStage(); Set<T> resolvedContentForAliases = content.getAliases().parallelStream() .filter(alias -> namespaceToMatch == null || alias.getNamespace().equals(namespaceToMatch)) .map(this::getLookupEntries) .flatMap(MoreStreams::stream) .map(this::getResolvedContent) .map(ResolvedContent::getAllResolvedResults) .flatMap(MoreStreams::stream) .filter(cls::isInstance) .map(cls::cast) .collect(MoreCollectors.toImmutableSet()); for (T identified : resolvedContentForAliases) { if (java.util.Objects.equals(content.getId(), identified.getId())) { continue; } if (identified.isActivelyPublished()) { candidates.addEquivalent(identified, Score.nullScore()); desc.appendText("Resolved %s", identified.getCanonicalUri()); } } equivToTelescopeResults.addGeneratorResult(generatorComponent); return candidates.build(); }

Target:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResults equivToTelescopeResults ) { DefaultScoredCandidates.Builder<T> candidates = DefaultScoredCandidates.fromSource("Alias"); desc.startStage("Resolving aliases:"); EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName("Alias Equivalence Generator"); for (Alias alias : content.getAliases()) { desc.appendText(alias.toString()); } desc.finishStage(); Set<T> resolvedContentForAliases = content.getAliases().parallelStream() .filter(alias -> namespaceToMatch == null || alias.getNamespace().equals(namespaceToMatch)) .map(this::getLookupEntries) .flatMap(MoreStreams::stream) .map(this::getResolvedContent) .map(ResolvedContent::getAllResolvedResults) .flatMap(MoreStreams::stream) .filter(cls::isInstance) .map(cls::cast) .collect(MoreCollectors.toImmutableSet()); for (T identified : resolvedContentForAliases) { if (java.util.Objects.equals(content.getId(), identified.getId())) { continue; } if (identified.isActivelyPublished()) { candidates.addEquivalent(identified, Score.nullScore()); desc.appendText("Found potential candidate in %s", identified.getCanonicalUri()); } } equivToTelescopeResults.addGeneratorResult(generatorComponent); return candidates.build(); }
Source:
private void updateQcowCompat() { if (getImage().getVolumeFormat().equals(VolumeFormat.COW)) { getImage().setQcowCompat(QcowCompat.QCOW2_V2); if (FeatureSupported.qcowCompatSupported(getStoragePool().getCompatibilityVersion())) { QemuImageInfo qemuImageInfo = ImagesHandler.getQemuImageInfoFromVdsm(getStoragePool().getId(), getStorageDomainId(), getImage().getImage().getDiskId(), getImage().getImageId(), false); if (qemuImageInfo != null) { getImage().setQcowCompat(qemuImageInfo.getQcowCompat()); } imageDao.update(getImage().getImage()); } } }

Target:
private void updateQcowCompat() { if (getImage().getVolumeFormat().equals(VolumeFormat.COW)) { getImage().setQcowCompat(QcowCompat.QCOW2_V2); if (FeatureSupported.qcowCompatSupported(getStoragePool().getCompatibilityVersion())) { QemuImageInfo qemuImageInfo = ImagesHandler.getQemuImageInfoFromVdsm(getStoragePool().getId(), getStorageDomainId(), getImage().getImage().getDiskId(), getImage().getImageId(), false); if (qemuImageInfo != null) { getImage().setQcowCompat(qemuImageInfo.getQcowCompat()); } } imageDao.update(getImage().getImage()); } }
Source:
public void testNotEnoughForMultipleDiskAndDomainsFirstDomainFails() { ArrayList<DiskImage> imagesDisks = mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID, 4); imagesDisks.addAll(mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID2, 4)); doReturn(imagesDisks).when(cmd).getSourceImages(); mockStorageDomainDAOGetForStoragePool(15, STORAGE_DOMAIN_ID); mockStorageDomainDAOGetForStoragePool(22, STORAGE_DOMAIN_ID2); assertFalse("Validation should fail. First domain should not have enough free space for request.", cmd.isEnoughSpaceToMergeSnapshots()); }

Target:
public void testNotEnoughForMultipleDiskAndDomainsFirstDomainFails() { List<DiskImage> imagesDisks = mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID, IMAGE_ACTUAL_SIZE_GB); imagesDisks.addAll(mockMultipleSourceImagesForDomain(4, STORAGE_DOMAIN_ID2, IMAGE_ACTUAL_SIZE_GB)); doReturn(imagesDisks).when(cmd).getSourceImages(); mockStorageDomainDAOGetForStoragePool(15, STORAGE_DOMAIN_ID); mockStorageDomainDAOGetForStoragePool(22, STORAGE_DOMAIN_ID2); assertFalse("Validation should fail. First domain should not have enough free space for request.", cmd.isEnoughSpaceToMergeSnapshots()); }
Source:
private boolean executeOnce(final int thisTryNumber, final int totalTriesIntended) { final Connection sshConnection = new Connection(parent.host, parent.port); try { sshConnection.connect(null, sshTimeoutMillis, 0, sshTimeoutMillis); LOGGER.info("SSH port is open on {}:{}", parent.host, parent.port); return true; } catch (IOException e) { LOGGER.error("Failed to connect to {}:{} (try {}/{}) - {}", parent.host, parent.port, thisTryNumber, totalTriesIntended, e.getMessage()); return false; } finally { sshConnection.close(); } }

Target:
private boolean executeOnce(final int thisTryNumber, final int totalTriesIntended) { final Connection sshConnection = new Connection(parent.host, parent.port); try { sshConnection.connect(null, sshTimeoutMillis, sshTimeoutMillis, sshTimeoutMillis); LOGGER.info("SSH port is open on {}:{}", parent.host, parent.port); return true; } catch (IOException e) { LOGGER.error("Failed to connect to {}:{} (try {}/{}) - {}", parent.host, parent.port, thisTryNumber, totalTriesIntended, e.getMessage()); return false; } finally { sshConnection.close(); } }
Source:
private OnHeapValueHolder<V> invalidateInGetorComputeIfAbsent(MapWrapper<K, V> map, final K key, final ValueHolder<V> value, final Fault<V> fault, final long now) { final AtomicReference<OnHeapValueHolder<V>> toInvalidate = new AtomicReference<OnHeapValueHolder<V>>(); map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, final OnHeapValueHolder<V> mappedValue) { if(mappedValue.equals(fault)) { try { toInvalidate.set(cloneValueHolder(key, value, now, Duration.ZERO, true)); } catch (LimitExceededException ex) { throw new AssertionError("Should have already been thrown."); } invalidationListener.onInvalidation(key, toInvalidate.get()); return null; } return mappedValue; } }); return toInvalidate.get(); }

Target:
private OnHeapValueHolder<V> invalidateInGetorComputeIfAbsent(MapWrapper<K, V> map, final K key, final ValueHolder<V> value, final Fault<V> fault, final long now) { final AtomicReference<OnHeapValueHolder<V>> toInvalidate = new AtomicReference<OnHeapValueHolder<V>>(); map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, final OnHeapValueHolder<V> mappedValue) { if(mappedValue.equals(fault)) { try { toInvalidate.set(cloneValueHolder(key, value, now, Duration.ZERO, false)); } catch (LimitExceededException ex) { throw new AssertionError("Sizing is not expected to happen."); } invalidationListener.onInvalidation(key, toInvalidate.get()); return null; } return mappedValue; } }); return toInvalidate.get(); }
Source:
public String toResponse() { if (selectionSet instanceof String) { return String.format( "\"%s\":%s", getName(), getSelectionSet().toString().equals("") ? "{\"edges\":[]}" : getSelectionSet().toString() ); } else if (selectionSet instanceof Number) { return String.format( "\"%s\":%s", getName(), getSelectionSet().toString().equals("") ? "{\"edges\":[]}" : getSelectionSet().toString() ); } else { return String.format("\"%s\":%s", getName(), ((SelectionSet) getSelectionSet()).toResponse()); } }

Target:
public String toResponse() { if (selectionSet instanceof String || selectionSet instanceof Number) { return String.format( "\"%s\":%s", getName(), getSelectionSet().toString().equals("") ? "{\"edges\":[]}" : getSelectionSet().toString() ); } else { return String.format("\"%s\":%s", getName(), ((SelectionSet) getSelectionSet()).toResponse()); } }
Source:
public <A extends Annotation> ConstraintValidator<A, ?> getInitializedValidator(Type validatedValueType, ConstraintDescriptorImpl<A> descriptor, ConstraintValidatorFactory constraintFactory) { Contracts.assertNotNull( validatedValueType ); Contracts.assertNotNull( descriptor ); Contracts.assertNotNull( constraintFactory ); final CacheKey key = new CacheKey( descriptor.getAnnotation(), validatedValueType, constraintFactory ); if ( constraintValidatorCache.containsKey( key ) ) { @SuppressWarnings("unchecked") ConstraintValidator<A, ?> constraintValidator = (ConstraintValidator<A, ?>) constraintValidatorCache.get( key ); if ( DUMMY_CONSTRAINT_VALIDATOR.equals( constraintValidator ) ) { return null; } else { log.tracef( "Constraint validator %s found in cache.", constraintValidator ); return constraintValidator; } } ConstraintValidatorDescriptor<A> validatorTypeDescriptor = findMatchingValidatorClass( descriptor, validatedValueType ); ConstraintValidator<A, ?> constraintValidator = createAndInitializeValidator( constraintFactory, validatorTypeDescriptor, descriptor ); if ( constraintValidator == null ) { putInitializedValidator( validatedValueType, descriptor.getAnnotation(), constraintFactory, DUMMY_CONSTRAINT_VALIDATOR ); return null; } else { putInitializedValidator( validatedValueType, descriptor.getAnnotation(), constraintFactory, constraintValidator ); return constraintValidator; } }

Target:
public <A extends Annotation> ConstraintValidator<A, ?> getInitializedValidator(Type validatedValueType, ConstraintDescriptorImpl<A> descriptor, ConstraintValidatorFactory constraintFactory) { Contracts.assertNotNull( validatedValueType ); Contracts.assertNotNull( descriptor ); Contracts.assertNotNull( constraintFactory ); final CacheKey key = new CacheKey( descriptor.getAnnotation(), validatedValueType, constraintFactory ); if ( constraintValidatorCache.containsKey( key ) ) { @SuppressWarnings("unchecked") ConstraintValidator<A, ?> constraintValidator = (ConstraintValidator<A, ?>) constraintValidatorCache.get( key ); if ( DUMMY_CONSTRAINT_VALIDATOR.equals( constraintValidator ) ) { return null; } else { log.tracef( "Constraint validator %s found in cache.", constraintValidator ); return constraintValidator; } } ConstraintValidatorDescriptor<A> validatorDescriptor = findMatchingValidatorDescriptor( descriptor, validatedValueType ); ConstraintValidator<A, ?> constraintValidator = createAndInitializeValidator( constraintFactory, validatorDescriptor, descriptor ); if ( constraintValidator == null ) { putInitializedValidator( validatedValueType, descriptor.getAnnotation(), constraintFactory, DUMMY_CONSTRAINT_VALIDATOR ); return null; } else { putInitializedValidator( validatedValueType, descriptor.getAnnotation(), constraintFactory, constraintValidator ); return constraintValidator; } }
Source:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { e.printStackTrace(); } return null; }

Target:
private static JAXBContext initOnmsEventParameterContext() { try { return JAXBContext.newInstance(EventParms.class); } catch (JAXBException e) { throw new RuntimeException(e); } }
Source:
public RemoteCounterManagerTest() { testImpl = new CounterManagerImplTest(this::allTestCounterManagers, this::log, this::cacheManager); }

Target:
public RemoteCounterManagerTest() { strategy = new CounterManagerImplTestStrategy(this::allTestCounterManagers, this::log, this::cacheManager); }
Source:
private void tallyAlignmentRecords(final SAMRecord s1, final SAMRecord s2) { if (!s1.getReadName().equals(s2.getReadName())) { throw new PicardException("Read names do not match: " + s1.getReadName() + " : " + s2.getReadName()); } catalogDuplicateDifferences(s1, s2); final AlignmentComparison comp = compareAlignmentRecords(s1, s2); switch (comp) { case UNMAPPED_BOTH: ++comparisonMetric.unmappedBoth; break; case UNMAPPED_LEFT: ++comparisonMetric.unmappedLeft; break; case UNMAPPED_RIGHT: ++comparisonMetric.unmappedRight; break; case MAPPINGS_DIFFER: ++comparisonMetric.mappingsDiffer; break; case MAPPINGS_MATCH: ++comparisonMetric.mappingsMatch; break; default: throw new PicardException("Unhandled comparison type: " + comp); } }

Target:
private void tallyAlignmentRecords(final SAMRecord s1, final SAMRecord s2) { if (!s1.getReadName().equals(s2.getReadName())) { throw new PicardException("Read names do not match: " + s1.getReadName() + " : " + s2.getReadName()); } catalogDuplicateDifferences(s1, s2); final AlignmentComparison comp = compareAlignmentRecords(s1, s2); comparisonMetric.updateMetric(comp); }
Source:
private Message.Builder getMessageBuilder(Class<?> clazz) { try { assert supports(clazz); Method method = methodCache.get(clazz); if (method == null) { method = clazz.getMethod("newBuilder"); methodCache.put(clazz, method); } return (Message.Builder) method.invoke(clazz); } catch (Exception ex) { throw new MessageConversionException( "Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex); } }

Target:
private Message.Builder getMessageBuilder(Class<?> clazz) { try { Method method = methodCache.get(clazz); if (method == null) { method = clazz.getMethod("newBuilder"); methodCache.put(clazz, method); } return (Message.Builder) method.invoke(clazz); } catch (Exception ex) { throw new MessageConversionException( "Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex); } }
Source:
static String base64(byte[] data) { byte[] encodedData = Base64.getEncoder().encode(data); return new String(encodedData, StandardCharsets.UTF_8); }

Target:
static String base64(byte[] data) { return Base64.getEncoder().encodeToString(data); }
Source:
public void onAdd(SolApplication solApplication) { IniReader reader = new IniReader(Const.SAVE_FILE_NAME, null); String saveMajorVersion = reader.getString("version", "").split("\\.")[0]; String gameMajorVersion = Const.VERSION.split("\\.")[0]; continueControl.setEnabled(SaveManager.hasPrevShip("prevShip.ini") && saveMajorVersion.equals(gameMajorVersion)); }

Target:
public void onAdd(SolApplication solApplication) { continueControl.setEnabled(SaveManager.hasPreviousCompatibleShip()); }
Source:
public boolean execute(int retries, MapOperation mapOperation, ILogger logger) { RecordStore recordStore = mapOperation.recordStore; if (recordStore == null) { return false; } if (recordStore.getInMemoryFormat() != NATIVE || recordStore.getEvictionPolicy() == NONE) { return false; } MapContainer mapContainer = recordStore.getMapContainer(); Evictor evictor = mapContainer.getEvictor(); for (int i = 0; i < retries; i++) { if (logger.isFineEnabled()) { logger.fine(format( "Applying forced eviction on current RecordStore (map %s, partitionId: %d)!", mapOperation.getName(), mapOperation.getPartitionId() )); } try { evictor.forceEvict(recordStore); mapOperation.runInternal(); return true; } catch (NativeOutOfMemoryError e) { ignore(e); } } return false; }

Target:
public boolean execute(int retries, MapOperation mapOperation, ILogger logger) { if (doesNotHaveRecordStore(mapOperation)) { return false; } RecordStore recordStore = mapOperation.recordStore; if (!nativeFormatWithEvictionPolicy(recordStore)) { return false; } MapContainer mapContainer = recordStore.getMapContainer(); Evictor evictor = mapContainer.getEvictor(); for (int i = 0; i < retries; i++) { if (logger.isFineEnabled()) { logger.fine(format( "Applying forced eviction on current RecordStore (map %s, partitionId: %d)!", mapOperation.getName(), mapOperation.getPartitionId() )); } try { evictor.forceEvict(recordStore); mapOperation.runInternal(); return true; } catch (NativeOutOfMemoryError e) { ignore(e); } } return false; }
Source:
public void onFailure(Throwable caught) { if (hasResponse()) { GWT.log("HTTP " + getResponse().getStatusCode() + ": " + getResponse().getStatusText()); } Message message = new Message(translateCauses(caught), MessageStyle.ERROR); DisplayMessageEvent.fire(hasHandlers, message); }

Target:
public void onFailure(Throwable caught) { Message message = new Message(translateCauses(caught), MessageStyle.ERROR); DisplayMessageEvent.fire(hasHandlers, message); }
Source:
public void stop() { coapServer.stop(); if (clientRegistry instanceof Stoppable) { ((Stoppable) clientRegistry).stop(); } if (securityRegistry instanceof Stoppable) { ((Stoppable) securityRegistry).stop(); } if (observationRegistry instanceof Stoppable) { ((Stoppable) observationRegistry).stop(); } LOG.info("LW-M2M server stopped"); }

Target:
public void stop() { coapServer.stop(); if (clientRegistry instanceof Stoppable) { ((Stoppable) clientRegistry).stop(); } if (securityRegistry instanceof Stoppable) { ((Stoppable) securityRegistry).stop(); } if (observationRegistry instanceof Stoppable) { ((Stoppable) observationRegistry).stop(); } if (queueRequestSender instanceof Stoppable) { ((Stoppable) queueRequestSender).stop(); } LOG.info("LW-M2M server stopped"); }
Source:
public void setLogFilePermission(String fileName) throws IOException { File file = new File(logRootDir, fileName).getCanonicalFile(); boolean runAsUser = ObjectReader.getBoolean(stormConf.get(SUPERVISOR_RUN_WORKER_AS_USER), false); File parent = new File(logRootDir, fileName).getParentFile(); Optional<File> mdFile = (parent == null) ? Optional.empty() : getMetadataFileForWorkerLogDir(parent); Optional<String> topoOwner = mdFile.isPresent() ? Optional.of(getTopologyOwnerFromMetadataFile(mdFile.get().getCanonicalPath())) : Optional.empty(); if (runAsUser && topoOwner.isPresent() && file.exists() && !Files.isReadable(file.toPath())) { LOG.debug("Setting permissions on file with topo-owner {}", fileName, topoOwner); try { ClientSupervisorUtils.processLauncherAndWait(stormConf, topoOwner.get(), Lists.newArrayList("blob", file.getCanonicalPath()), null, "setup group read permissions for file: " + fileName); } catch (IOException e) { ExceptionMeters.NUM_PERMISSION_EXCEPTIONS.mark(); throw e; } } }

Target:
public void setLogFilePermission(String fileName) throws IOException { File file = new File(logRootDir, fileName).getCanonicalFile(); boolean runAsUser = ObjectReader.getBoolean(stormConf.get(SUPERVISOR_RUN_WORKER_AS_USER), false); File parent = new File(logRootDir, fileName).getParentFile(); Optional<File> mdFile = (parent == null) ? Optional.empty() : getMetadataFileForWorkerLogDir(parent); Optional<String> topoOwner = mdFile.isPresent() ? Optional.of(getTopologyOwnerFromMetadataFile(mdFile.get().getCanonicalPath())) : Optional.empty(); if (runAsUser && topoOwner.isPresent() && file.exists() && !Files.isReadable(file.toPath())) { LOG.debug("Setting permissions on file with topo-owner {}", fileName, topoOwner); try { ClientSupervisorUtils.processLauncherAndWait(stormConf, topoOwner.get(), Lists.newArrayList("blob", file.getCanonicalPath()), null, "setup group read permissions for file: " + fileName); } catch (IOException e) { ExceptionMeters.NUM_SET_PERMISSION_EXCEPTIONS.mark(); throw e; } } }
Source:
private void estimateCommandsMachineName( Devfile devfile, Tool tool, KubernetesList recipeObjects) { List<Command> toolsCommands = devfile .getCommands() .stream() .filter(c -> c.getActions().get(0).getTool().equals(tool.getName())) .collect(toList()); if (toolsCommands.isEmpty()) { return; } List<Pod> pods = recipeObjects .getItems() .stream() .filter(hasMetadata -> hasMetadata instanceof Pod) .map(hasMetadata -> (Pod) hasMetadata) .collect(toList()); if (pods.size() != 1) { return; } Pod pod = pods.get(0); List<Container> containers = pod.getSpec().getContainers(); if (containers.size() != 1) { return; } Container container = containers.get(0); String machineName = Names.machineName(pod, container); toolsCommands.forEach(c -> c.getAttributes().put(MACHINE_NAME_ATTRIBUTE, machineName)); }

Target:
private void estimateCommandsMachineName( Devfile devfile, Tool tool, KubernetesList recipeObjects) { List<Command> toolsCommands = devfile .getCommands() .stream() .filter(c -> c.getActions().get(0).getTool().equals(tool.getName())) .collect(toList()); if (toolsCommands.isEmpty()) { return; } List<Pod> pods = recipeObjects .getItems() .stream() .filter(hasMetadata -> hasMetadata instanceof Pod) .map(hasMetadata -> (Pod) hasMetadata) .collect(toList()); Pod pod; if (pods.size() != 1 || (pod = pods.get(0)).getSpec().getContainers().isEmpty()) { return; } String machineName = Names.machineName(pod, pod.getSpec().getContainers().get(0)); toolsCommands.forEach(c -> c.getAttributes().put(MACHINE_NAME_ATTRIBUTE, machineName)); }
Source:
private String encrypt(String value) { try { return getStorageHelper().encrypt(mContext, value); } catch (GeneralSecurityException | IOException e) { Logger.e(TAG, "Encryption failure", "", ADALError.ENCRYPTION_FAILED, e); } return null; }

Target:
private String encrypt(String value) { try { return getStorageHelper().encrypt(value); } catch (GeneralSecurityException | IOException e) { Logger.e(TAG, "Encryption failure", "", ADALError.ENCRYPTION_FAILED, e); } return null; }
Source:
public String getBackupIdentifier() { return Const.SystemParams.ACCOUNT_ATTRIBUTES_BACKUP_LOG_MSG + this.googleId; }

Target:
public String getBackupIdentifier() { return ACCOUNT_ATTRIBUTES_BACKUP_LOG_MSG + this.googleId; }