auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") final EnumMap<Qualifier, String> qualifiers) throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> pair : qualifiers .entrySet()) { params.put(pair.getKey().getQualifier(), pair.getValue()); } params.put("sort", sort.getSort()); params.put("direction", direction.getOrder()); return this.iterate(params); }

Target:
public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") final EnumMap<Qualifier, String> qualifiers) throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> pair : qualifiers .entrySet()) { params.put(pair.getKey().identifier(), pair.getValue()); } params.put("sort", sort.identifier()); params.put("direction", direction.identifier()); return this.iterate(params); }
Source:
public String toString() { StringJoiner joiner = new StringJoiner(", ", "Worldpay authorisation response (", ")"); if (StringUtils.isNotBlank(getTransactionId())) { joiner.add("orderCode: " + getTransactionId()); } if (StringUtils.isNotBlank(getLastEvent())) { joiner.add("lastEvent: "+ getLastEvent()); } if (StringUtils.isNotBlank(getRefusedReturnCode())) { joiner.add("ISO8583ReturnCode code: " + getRefusedReturnCode()); } if (StringUtils.isNotBlank(getRefusedReturnCodeDescription())) { joiner.add("ISO8583ReturnCode description: " + getRefusedReturnCodeDescription()); } if (StringUtils.isNotBlank(issuerUrl)) { joiner.add("issuerURL: " + issuerUrl); } if (StringUtils.isNotBlank(paRequest)) { joiner.add("issuerURL: " + paRequest); } if (StringUtils.isNotBlank(getErrorCode())) { joiner.add("error code: " + getErrorCode()); } if (StringUtils.isNotBlank(getErrorMessage())) { joiner.add("error: " + getErrorMessage()); } return joiner.toString(); }

Target:
public String toString() { StringJoiner joiner = new StringJoiner(", ", "Worldpay authorisation response (", ")"); if (StringUtils.isNotBlank(getTransactionId())) { joiner.add("orderCode: " + getTransactionId()); } if (StringUtils.isNotBlank(getLastEvent())) { joiner.add("lastEvent: "+ getLastEvent()); } if (StringUtils.isNotBlank(getRefusedReturnCode())) { joiner.add("ISO8583ReturnCode code: " + getRefusedReturnCode()); } if (StringUtils.isNotBlank(getRefusedReturnCodeDescription())) { joiner.add("ISO8583ReturnCode description: " + getRefusedReturnCodeDescription()); } if (StringUtils.isNotBlank(issuerUrl)) { joiner.add("issuerURL: " + issuerUrl); } if (StringUtils.isNotBlank(paRequest)) { joiner.add("paRequest: " + paRequest); } if (StringUtils.isNotBlank(getErrorCode())) { joiner.add("error code: " + getErrorCode()); } if (StringUtils.isNotBlank(getErrorMessage())) { joiner.add("error: " + getErrorMessage()); } return joiner.toString(); }
Source:
public void clickShareButton() { waitForElementByElement(shareButton); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("$('a.share-button.secondary').click()"); waitForElementByElement(moreInfoThumbnail); PageObjectLogging.log("clickShareButton", "share button is clicked", true); }

Target:
public void clickShareButton() { waitForElementByElement(shareButton); shareButton.click(); waitForElementByElement(moreInfoThumbnail); PageObjectLogging.log("clickShareButton", "share button is clicked", true); }
Source:
private List<RemoteReplicaInfo> createRemoteReplicaInfos(List<? extends ReplicaId> peerReplicas, ReplicaId replicaId) { List<RemoteReplicaInfo> remoteReplicaInfos = new ArrayList<>(); PartitionId partition = replicaId.getPartitionId(); Store store = storeManager.getStore(partition); try { for (ReplicaId remoteReplica : peerReplicas) { FindToken findToken = this.tokenHelper.getFindTokenFactoryFromReplicaType(remoteReplica.getReplicaType()).getNewFindToken(); RemoteReplicaInfo remoteReplicaInfo = null; remoteReplicaInfo = new RemoteReplicaInfo(remoteReplica, replicaId, store, findToken, TimeUnit.SECONDS.toMillis(storeConfig.storeDataFlushIntervalSeconds) * Replication_Delay_Multiplier, SystemTime.getInstance(), remoteReplica.getDataNodeId().getPortToConnectTo(), storeKeyConverterFactory.getStoreKeyConverter()); replicationMetrics.addMetricsForRemoteReplicaInfo(remoteReplicaInfo, trackPerPartitionLagInMetric); remoteReplicaInfos.add(remoteReplicaInfo); } if (replicationConfig.replicationTrackPerPartitionLagFromRemote) { replicationMetrics.addLagMetricForPartition(partition); } } catch (Exception e) { logger.error("Encountered exception instantiating RemoteReplicaInfos", e); } return remoteReplicaInfos; }

Target:
private List<RemoteReplicaInfo> createRemoteReplicaInfos(List<? extends ReplicaId> peerReplicas, ReplicaId replicaId) { List<RemoteReplicaInfo> remoteReplicaInfos = new ArrayList<>(); PartitionId partition = replicaId.getPartitionId(); Store store = storeManager.getStore(partition); for (ReplicaId remoteReplica : peerReplicas) { FindToken findToken = this.tokenHelper.getFindTokenFactoryFromReplicaType(remoteReplica.getReplicaType()).getNewFindToken(); RemoteReplicaInfo remoteReplicaInfo = new RemoteReplicaInfo(remoteReplica, replicaId, store, findToken, TimeUnit.SECONDS.toMillis(storeConfig.storeDataFlushIntervalSeconds) * Replication_Delay_Multiplier, SystemTime.getInstance(), remoteReplica.getDataNodeId().getPortToConnectTo()); replicationMetrics.addMetricsForRemoteReplicaInfo(remoteReplicaInfo, trackPerPartitionLagInMetric); remoteReplicaInfos.add(remoteReplicaInfo); } if (replicationConfig.replicationTrackPerPartitionLagFromRemote) { replicationMetrics.addLagMetricForPartition(partition); } return remoteReplicaInfos; }
Source:
private RedisQueueOutboundChannelAdapter createProducerEndpoint(String name, ProducerProperties properties) { String partitionKeyExtractorClass = properties.getPartitionKeyExtractorClass(); String partitionKeyExpression = properties.getPartitionKeyExpression(); RedisQueueOutboundChannelAdapter queue; if (partitionKeyExpression == null && !StringUtils.hasText(partitionKeyExtractorClass)) { queue = new RedisQueueOutboundChannelAdapter(name, this.connectionFactory); } else { queue = new RedisQueueOutboundChannelAdapter( parser.parseExpression(buildPartitionRoutingExpression(name)), this.connectionFactory); } queue.setIntegrationEvaluationContext(this.evaluationContext); queue.setBeanFactory(this.getBeanFactory()); queue.afterPropertiesSet(); return queue; }

Target:
private RedisQueueOutboundChannelAdapter createProducerEndpoint(String name, ProducerProperties properties) { RedisQueueOutboundChannelAdapter queue; if (!properties.isPartitioned()) { queue = new RedisQueueOutboundChannelAdapter(name, this.connectionFactory); } else { queue = new RedisQueueOutboundChannelAdapter( parser.parseExpression(buildPartitionRoutingExpression(name)), this.connectionFactory); } queue.setIntegrationEvaluationContext(this.evaluationContext); queue.setBeanFactory(this.getBeanFactory()); queue.afterPropertiesSet(); return queue; }
Source:
public void updateDominantLocks( String path, UnlockStatus unlockStatus ) throws PartylineException { if ( !unlockStatus.dominanceChanged ) { return; } TransactionManager transactionManager = metadataCache.getAdvancedCache().getTransactionManager(); try { transactionManager.begin(); FileMeta meta = metadataCache.get( path ); if ( unlockStatus.dominantLockLevel == null ) { meta.removeLock( this.nodeKey ); } else { meta.addLock( this.nodeKey, unlockStatus.dominantLockLevel ); } metadataCache.put( path, meta ); } catch ( NotSupportedException | SystemException e ) { try { transactionManager.rollback(); } catch ( SystemException ex ) { throw new PartylineException( "There was a problem with a transaction rollback involving " + path ); } throw new PartylineException( "There was a problem with a transaction begin involving " + path ); } finally { try { transactionManager.commit(); } catch ( RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException e ) { throw new PartylineException( "There was a problem with a transaction commit involving " + path ); } } }

Target:
public void updateDominantLocks( String path, UnlockStatus unlockStatus ) throws PartylineException { if ( !unlockStatus.isDominanceChanged() ) { return; } TransactionManager transactionManager = metadataCache.getAdvancedCache().getTransactionManager(); try { transactionManager.begin(); FileMeta meta = metadataCache.get( path ); if ( unlockStatus.getDominantLockLevel() == null ) { meta.removeLock( this.nodeKey ); } else { meta.setLock( this.nodeKey, unlockStatus.getDominantLockLevel() ); } metadataCache.put( path, meta ); } catch ( NotSupportedException | SystemException e ) { try { transactionManager.rollback(); throw new PartylineException( "Failed to begin transaction. Rolling back. Path: " + path, e ); } catch ( SystemException e1 ) { LoggerFactory.getLogger( getClass().getName() ) .error( "System Exception during transaction rollback involving path: " + path, e1 ); } } finally { try { transactionManager.commit(); } catch ( RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException e ) { LoggerFactory.getLogger( getClass().getName() ) .error( "Exception during transaction commit involving path: " + path, e ); } } }
Source:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { LOG.trace("Exception caught in channel processing.", e.getCause()); if (!exceptionRaised.get()) { exceptionRaised.set(true); if (methodInfo != null) { methodInfo.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getCause()); methodInfo = null; } else { ChannelFuture future = Channels.future(ctx.getChannel()); future.addListener(ChannelFutureListener.CLOSE); Throwable cause = e.getCause(); if (cause instanceof HandlerException) { Channels.write(ctx, future, ((HandlerException) cause).createFailureResponse()); } else { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); Channels.write(ctx, future, response); } } } }

Target:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { String exceptionMessage = "Exception caught in channel processing."; Throwable cause = e.getCause(); if (!exceptionRaised.get()) { exceptionRaised.set(true); if (methodInfo != null) { LOG.error(exceptionMessage, cause); methodInfo.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, cause); methodInfo = null; } else { ChannelFuture future = Channels.future(ctx.getChannel()); future.addListener(ChannelFutureListener.CLOSE); if (cause instanceof HandlerException) { HttpResponse response = ((HandlerException) cause).createFailureResponse(); if (isUserError(response)) { LOG.trace(exceptionMessage, cause); } else { LOG.error(exceptionMessage, cause); } Channels.write(ctx, future, response); } else { LOG.error(exceptionMessage, cause); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); Channels.write(ctx, future, response); } } } else { LOG.trace(exceptionMessage, cause); } }
Source:
public Http2Client(HttpClient client) { this.client = Util.checkNotNull(client, "HttpClient must be not null"); }

Target:
public Http2Client(HttpClient client) { this.client = Util.checkNotNull(client, "HttpClient must not be null"); }
Source:
public boolean testAndSetValue(Integer position, Object value) { if (frame[position] == null) { frame[position] = value; return true; } else { return frame[position].equals(value); } }

Target:
public boolean testAndSetValue(Integer position, Object value) { Preconditions.checkElementIndex(position, frame.length); if (frame[position] == null) { frame[position] = value; return true; } else { return frame[position].equals(value); } }
Source:
private List<SatelMessage> getRefreshCommands() { logger.debug("Gathering refresh commands from all items"); List<SatelMessage> commands = new ArrayList<SatelMessage>(); for (SatelBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { logger.trace("Getting refresh command from item: {}", itemName); SatelBindingConfig itemConfig = provider.getItemConfig(itemName); SatelMessage message = itemConfig.buildRefreshMessage(this.satelModule.getIntegraType()); if (message != null && !commands.contains(message)) { commands.add(message); } } } return commands; }

Target:
private List<SatelMessage> getRefreshCommands() { logger.trace("Gathering refresh commands from all items"); List<SatelMessage> commands = new ArrayList<SatelMessage>(); for (SatelBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { logger.trace("Getting refresh command from item: {}", itemName); SatelBindingConfig itemConfig = provider.getItemConfig(itemName); SatelMessage message = itemConfig.buildRefreshMessage(this.satelModule.getIntegraType()); if (message != null && !commands.contains(message)) { commands.add(message); } } } return commands; }
Source:
private String interpolateString(String value) { Pattern pattern = Pattern.compile(PATTERN); Matcher matcher = pattern.matcher(value); while (matcher.find()) { String name = matcher.group(1); String replace = System.getenv(name); if (replace == null) { replace = System.getProperty(name, ""); } Pattern subPattern = Pattern.compile(Pattern.quote(matcher.group(0))); value = subPattern.matcher(value).replaceAll(replace); } return value; }

Target:
private String interpolateString(String value) { value = interpolate(value, sysPattern, name -> System.getProperty(name, "")); value = interpolate(value, envPattern, name -> System.getenv(name)); return value; }
Source:
public void run() { Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND); while (true) { try { IdWeakReference<?> remove = (IdWeakReference<?>) referenceQueue.remove(); handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL_GC, remove.requestId, 0)); } catch (InterruptedException e) { break; } catch (final Exception e) { handler.post(new Runnable() { @Override public void run() { new RuntimeException(e); } }); } } }

Target:
public void run() { Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND); while (true) { try { RequestWeakReference<?> remove = (RequestWeakReference<?>) referenceQueue.remove(); handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL_GC, remove.request)); } catch (final Exception e) { handler.post(new Runnable() { @Override public void run() { throw new RuntimeException(e); } }); break; } } }
Source:
public void test() throws Exception { String rawInput = getResource(TEST_DOC); String expected = getResource(CONVERTED_HTML); String input = NormalizeHtml.convertToNormalizedHTML(rawInput); input = bodyOnly(input); expected = bodyOnly(expected); input = input.replaceAll("br /", "br"); input = input.replaceAll("\r", ""); expected = expected.replaceAll("\r", ""); Assert.assertEquals("Converted HTML does not equal expected", expected, input); input = rawInput.replaceAll("BODY", "body"); input = bodyOnly(input); input = NormalizeHtml.wrapAndNormalizeHTML(input, false, false, false); input = bodyOnly(input); input = input.replaceAll("\r", ""); input = input.replaceAll("br /", "br"); Assert.assertEquals("Converted body only HTML does not equal expected", expected, input); }

Target:
public void test() throws Exception { String rawInput = getResource(TEST_DOC); String expected = getResource(CONVERTED_HTML); String input = NormalizeHtml.convertToNormalizedHTML(rawInput); input = bodyOnly(input); expected = bodyOnly(expected); expected = expected.replaceAll("\r", ""); Assert.assertEquals("Converted HTML does not equal expected", expected, input); input = rawInput.replaceAll("BODY", "body"); input = bodyOnly(input); input = NormalizeHtml.wrapAndNormalizeHTML(input, false, false, false); input = bodyOnly(input); input = input.replaceAll("\r", ""); Assert.assertEquals("Converted body only HTML does not equal expected", expected, input); }
Source:
public int getNumThreads() { int numThreadsConfigured = getNumThreadsConfigured(); if (numThreadsConfigured != DEFAULT_NUM_THREADS) { return numThreadsConfigured; } else { return Runtime.getRuntime().availableProcessors() - 1; } }

Target:
public int getNumThreads() { int numThreadsConfigured = getNumThreadsConfigured(); if (numThreadsConfigured != DEFAULT_NUM_THREADS) { return numThreadsConfigured; } else { return Math.max(Runtime.getRuntime().availableProcessors() - 1, 1); } }
Source:
public void runAtDriver(RuntimeContainer container) { try { connect(container); } catch (IOException e) { LOGGER.error("Coudln't connect to MarkLogic", e); } }

Target:
public void runAtDriver(RuntimeContainer container) { try { connect(container); } catch (IOException e) { ErrorCode errorCode; String message; if (e.getCause() instanceof FailedRequestException) { errorCode = new DefaultErrorCode(403, ERROR_KEY); message = "Invalid credentials."; } else { errorCode = new DefaultErrorCode(400,ERROR_KEY); message = "Cannot connect to MarkLogic database. Check your database connectivity."; } throw new ComponentException(errorCode, e, new ExceptionContextBuilder().put(ERROR_KEY, message).build()); } }
Source:
public List<String> getStringList(String name) { if (!containsKey(name)) { return Collections.emptyList(); } String v = getString(name); return Arrays.stream(StringUtils.split(v, ',')).map(String::trim).collect(Collectors.toList()); }

Target:
public List<String> getStringList(String name) { String v = getString(name); return Arrays.stream(StringUtils.split(v, ',')).map(String::trim).collect(Collectors.toList()); }
Source:
public static boolean useNewBottomContent(WikipediaApp app) { final int hexBase = 16; return Integer.parseInt(app.getAppInstallID().substring(app.getAppInstallID().length() - 1), hexBase) % 2 == 0; }

Target:
public static boolean useNewBottomContent(WikipediaApp app) { if (app.getReleaseType() == WikipediaApp.RELEASE_PROD) { return false; } final int hexBase = 16; return Integer.parseInt(app.getAppInstallID().substring(app.getAppInstallID().length() - 1), hexBase) % 2 == 0; }
Source:
public void addResourceRole(PerunSession sess, Group group, Role role, Resource resource) throws InternalErrorException, AlreadyAdminException { if (!role.equals(Role.RESOURCESELFSERVICE)) { throw new IllegalArgumentException("Role "+role+" cannot be set on VO"); } try { jdbc.update("insert into authz (role_id, resource_id, authorized_group_id) values ((select id from roles where name=?), ?, ?)", role.getRoleName(), resource.getId(), group.getId()); } catch (DataIntegrityViolationException e) { throw new AlreadyAdminException("Group id=" + group.getId() + " is already "+role+" of resource " + resource, e, group, resource, role); } catch (RuntimeException e) { throw new InternalErrorException(e); } }

Target:
public void addResourceRole(PerunSession sess, Group group, Role role, Resource resource) throws InternalErrorException, AlreadyAdminException { if (!role.equals(Role.RESOURCESELFSERVICE)) { throw new IllegalArgumentException("Role "+role+" cannot be set on resource."); } try { jdbc.update("insert into authz (role_id, resource_id, authorized_group_id) values ((select id from roles where name=?), ?, ?)", role.getRoleName(), resource.getId(), group.getId()); } catch (DataIntegrityViolationException e) { throw new AlreadyAdminException("Group id=" + group.getId() + " is already "+role+" in resource " + resource, e, group, resource, role); } catch (RuntimeException e) { throw new InternalErrorException(e); } }
Source:
public static boolean isValid(String acc) { boolean looksLikeSRA = false; File f = new File(acc); if (f.isFile()) { byte[] buffer = new byte[8]; byte[] signature1 = "NCBI.sra".getBytes(); byte[] signature2 = "NCBInenc".getBytes(); try (InputStream is = new FileInputStream(f)) { int numRead = is.read(buffer); looksLikeSRA = numRead == buffer.length && (Arrays.equals(buffer, signature1) || Arrays.equals(buffer, signature2)); } catch (IOException e) { looksLikeSRA = false; } } else if (f.exists()) { looksLikeSRA = false; } else { looksLikeSRA = acc.toUpperCase().matches ( "^[SED]RR[0-9]{6,9}$" ); } if (!looksLikeSRA) return false; ExceptionInInitializerError initError = checkIfInitialized(); if (initError != null) { if (noLibraryDownload && initError instanceof LibraryLoadError) { throw new LinkageError( "Failed to load SRA native libraries and auto-download is disabled. " + "Please set property samjdk.sra_libraries_download=true to enable auto-download of native libraries", initError ); } else { throw initError; } } return NGS.isValid(acc); }

Target:
public static boolean isValid(String acc) { boolean looksLikeSRA = false; File f = new File(acc); if (f.isFile()) { byte[] buffer = new byte[8]; byte[] signature1 = "NCBI.sra".getBytes(); byte[] signature2 = "NCBInenc".getBytes(); try (InputStream is = new FileInputStream(f)) { int numRead = is.read(buffer); looksLikeSRA = numRead == buffer.length && (Arrays.equals(buffer, signature1) || Arrays.equals(buffer, signature2)); } catch (IOException e) { looksLikeSRA = false; } } else if (f.exists()) { looksLikeSRA = false; } else { looksLikeSRA = acc.toUpperCase().matches ( "^[SED]RR[0-9]{6,9}$" ); } if (!looksLikeSRA) return false; final ExceptionInInitializerError initError = checkIfInitialized(); if (initError != null) { if (noLibraryDownload && initError instanceof LibraryLoadError) { throw new LinkageError( "Failed to load SRA native libraries and auto-download is disabled. " + "Please re-run with JVM argument -Dsamjdk.sra_libraries_download=true to enable auto-download of native libraries", initError ); } else { throw initError; } } return NGS.isValid(acc); }
Source:
public void setUseBulkWriteOperations(final boolean useBulkWriteOperations) { LOG.warning("Setting useBulkWriteOperations has no value functionally or performance-wise."); }

Target:
public void setUseBulkWriteOperations(final boolean useBulkWriteOperations) { }
Source:
public boolean cast(final MagicSpell spell) { if (!ctx.game.tab(Game.Tab.MAGIC)) { return false; } final Component c = component(spell); return c.visible() && c.click(spell.book() == Book.ARCEUUS ? "Reanimate" : "Cast"); }

Target:
public boolean cast(final MagicSpell spell) { if (!ctx.game.tab(Game.Tab.MAGIC)) { return false; } final Component c = component(spell); return c.visible() && c.click(cmd -> cmd.action.equals("Cast") || cmd.action.equals("Reanimate") || cmd.action.equals("Resurrect")); }
Source:
public LogFileConfiguration(@NonNull String directory) { if (directory == null) { throw new IllegalArgumentException("directory cannot be null"); } this.directory = directory; readonly = false; }

Target:
public LogFileConfiguration(@NonNull String directory) { Preconditions.checkArgNotNull(directory, "directory"); this.directory = directory; readonly = false; }
Source:
void perform() { I id = aggregate.getId(); int eventCount = storage.readEventCountAfterLastSnapshot(id); UncommittedEvents uncommittedEvents = aggregate.getUncommittedEvents(); for (Event event : uncommittedEvents.list()) { eventCount = writeEvent(event, eventCount); } commit(eventCount); }

Target:
void perform() { UncommittedEvents uncommittedEvents = aggregate.getUncommittedEvents(); List<Event> eventsToStore = uncommittedEvents.list(); writeEvents(eventsToStore); }
Source:
public void applyLimit(long limit) { if (limit > Integer.MAX_VALUE) { throw new TableException( String.format("The maximum limit value is %d for jdbc connector. Get %d.", Integer.MAX_VALUE, limit)); } this.limit = Math.toIntExact(limit); }

Target:
public void applyLimit(long limit) { this.limit = limit; }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { Set<String> runtimeNames = domainRoot ? AffectedDeploymentOverlay.listAllLinks(context, context.getCurrentAddressValue()) : AffectedDeploymentOverlay.listLinks(context, context.getCurrentAddress()); if(operation.hasDefined(RUNTIME_NAMES_DEFINITION.getName())) { Set<String> requiredRuntimeNames = new HashSet<>(RUNTIME_NAMES_DEFINITION.unwrap(context, operation)); if(!runtimeNames.containsAll(requiredRuntimeNames)) { throw new OperationFailedException("WTF are you trying to do !!!!!"); } runtimeNames = requiredRuntimeNames; } if (domainRoot) { AffectedDeploymentOverlay.redeployLinksAndTransformOperationForDomain(context, AffectedDeploymentOverlay.listServerGroupsReferencingOverlay(context, context.getCurrentAddressValue()), runtimeNames); } else { AffectedDeploymentOverlay.redeployLinksAndTransformOperationForServerGroup(context, context.getCurrentAddress().getParent(), runtimeNames); } }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { Set<String> runtimeNames = domainRoot ? AffectedDeploymentOverlay.listAllLinks(context, context.getCurrentAddressValue()) : AffectedDeploymentOverlay.listLinks(context, context.getCurrentAddress()); if(operation.hasDefined(RUNTIME_NAMES_DEFINITION.getName())) { Set<String> requiredRuntimeNames = new HashSet<>(RUNTIME_NAMES_DEFINITION.unwrap(context, operation)); Set<String> unaffectedDeployments = AffectedDeploymentOverlay.checkRequiredNames(requiredRuntimeNames, runtimeNames); if(!unaffectedDeployments.isEmpty() && !isRedeployAfterRemoval(operation)) { throw DomainControllerLogger.ROOT_LOGGER.redeployingUnaffactedDeployments(unaffectedDeployments); } runtimeNames = requiredRuntimeNames; } ModelNode removeOperation = null; if(isRedeployAfterRemoval(operation)) { removeOperation = Operations.createRemoveOperation(context.getCurrentAddress().append(DEPLOYMENT, runtimeNames.iterator().next()).toModelNode()); } if (domainRoot) { AffectedDeploymentOverlay.redeployLinksAndTransformOperationForDomain(context, runtimeNames, removeOperation); } else { AffectedDeploymentOverlay.redeployLinksAndTransformOperation(context, removeOperation, context.getCurrentAddress().getParent(), runtimeNames); } }
Source:
List<DatanodeDetails> filterViableNodes( List<DatanodeDetails> excludedNodes, int nodesRequired) throws SCMException { List<DatanodeDetails> healthyNodes = nodeManager.getNodes(HddsProtos.NodeState.HEALTHY); if (excludedNodes != null) { healthyNodes.removeAll(excludedNodes); } String msg; if (healthyNodes.size() == 0) { msg = "No healthy node found to allocate container."; LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes .FAILED_TO_FIND_HEALTHY_NODES); } if (healthyNodes.size() < nodesRequired) { msg = String.format("Not enough healthy nodes to allocate container. %d " + " datanodes required. Found %d", nodesRequired, healthyNodes.size()); LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes.FAILED_TO_FIND_SUITABLE_NODE); } List<DatanodeDetails> healthyList = healthyNodes.stream().filter(d -> meetCriteria(d, heavyNodeCriteria)).collect(Collectors.toList()); if (healthyList.size() < nodesRequired) { msg = String.format("Unable to find enough nodes that meet " + "the criteria that cannot engage in more than %d pipelines." + " Nodes required: %d Found: %d", heavyNodeCriteria, nodesRequired, healthyList.size()); LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes.FAILED_TO_FIND_NODES_WITH_SPACE); } return healthyList; }

Target:
List<DatanodeDetails> filterViableNodes( List<DatanodeDetails> excludedNodes, int nodesRequired) throws SCMException { List<DatanodeDetails> healthyNodes = nodeManager.getNodes(HddsProtos.NodeState.HEALTHY); if (excludedNodes != null) { healthyNodes.removeAll(excludedNodes); } String msg; if (healthyNodes.size() == 0) { msg = "No healthy node found to allocate pipeline."; LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes .FAILED_TO_FIND_HEALTHY_NODES); } if (healthyNodes.size() < nodesRequired) { msg = String.format("Not enough healthy nodes to allocate pipeline. %d " + " datanodes required. Found %d", nodesRequired, healthyNodes.size()); LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes.FAILED_TO_FIND_SUITABLE_NODE); } List<DatanodeDetails> healthyList = healthyNodes.stream().filter(d -> meetCriteria(d, heavyNodeCriteria)).collect(Collectors.toList()); if (healthyList.size() < nodesRequired) { msg = String.format("Unable to find enough nodes that meet " + "the criteria that cannot engage in more than %d pipelines." + " Nodes required: %d Found: %d", heavyNodeCriteria, nodesRequired, healthyList.size()); LOG.error(msg); throw new SCMException(msg, SCMException.ResultCodes.FAILED_TO_FIND_SUITABLE_NODE); } return healthyList; }
Source:
public long getTimeUntilNextRun() { long timeUntilNextRun = (packetTransformer instanceof RecurringRunnable) ? ((RecurringRunnable) packetTransformer) .getTimeUntilNextRun() : -1; return timeUntilNextRun; }

Target:
public long getTimeUntilNextRun() { long timeUntilNextRun = (packetTransformer instanceof RecurringRunnable) ? ((RecurringRunnable) packetTransformer) .getTimeUntilNextRun() : defaultTimeUntilNextRunMs; return timeUntilNextRun; }
Source:
public <V> V getService(Class<V> serviceClass, String filter) { ServiceReference<V> serviceRef = getServiceReference(serviceClass, filter); if (serviceRef == null) { return null; } @SuppressWarnings("unchecked") V service = (V)fServices.get(serviceRef); if (service == null) { if (fServices.containsKey(serviceRef) == false) { service = fBundleContext.getService(serviceRef); fServices.put(serviceRef, service); } } return service; }

Target:
public <V> V getService(Class<V> serviceClass, String filter) { ServiceReference<V> serviceRef = getServiceReference(serviceClass, filter); if (serviceRef == null) { return null; } @SuppressWarnings("unchecked") V service = (V)fServices.get(serviceRef); if (service == null) { if (!fServices.containsKey(serviceRef)) { service = fBundleContext.getService(serviceRef); fServices.put(serviceRef, service); } } return service; }
Source:
public void test_setUrl_remote_with_post() { secondsToWaitTillFail = 35; String url = "<LINK_0>"; assumeTrue("Skipping test due to bad internet connection", checkInternet(url)); testLog.append("checkInternet() passed"); String expectedTitle = "Bug List"; Runnable browserSetFunc = () -> { testLog.append("Setting Browser url to:" + url); boolean opSuccess = browser.setUrl( url + "?bug_severity=enhancement&bug_status=NEW&email1=rgrunber&emailassigned_to1=1&emailtype1=substring", null, null); assertTrue("Expecting setUrl() to return true", opSuccess); }; validateTitleChanged(expectedTitle, browserSetFunc); System.out.println(browser.getText()); int numChars = browser.getText().length(); assertTrue("Response data contained " + numChars + " chars.", numChars > 10000); }

Target:
public void test_setUrl_remote_with_post() { assumeFalse(webkit1SkipMsg(), isWebkit1); secondsToWaitTillFail = 35; String url = "<LINK_0>"; assumeTrue("Skipping test due to bad internet connection", checkInternet(url)); testLog.append("checkInternet() passed"); String expectedTitle = "Bug List"; Runnable browserSetFunc = () -> { testLog.append("Setting Browser url to:" + url); boolean opSuccess = browser.setUrl( url + "?bug_severity=enhancement&bug_status=NEW&email1=rgrunber&emailassigned_to1=1&emailtype1=substring", null, null); assertTrue("Expecting setUrl() to return true", opSuccess); }; validateTitleChanged(expectedTitle, browserSetFunc); int numChars = browser.getText().length(); assertTrue("Response data contained " + numChars + " chars.", numChars > 10000); }
Source:
public AbstractAuthenticationToken convert(Jwt jwt) { OAuth2AccessToken accessToken = new OAuth2AccessToken( OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt()); AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt); Collection<GrantedAuthority> authorities = token.getAuthorities(); JWTClaimsSet.Builder builder = new Builder(); for (Entry<String, Object> entry : jwt.getClaims().entrySet()) { builder.claim(entry.getKey(), entry.getValue()); } JWTClaimsSet jwtClaimsSet = builder.build(); JWSObject jwsObject = null; try { jwsObject = JWSObject.parse(accessToken.getTokenValue()); } catch (ParseException e) { LOGGER.error( e.getMessage() + ". When create an instance of JWSObject, an exception is resolved on the token."); } UserPrincipal userPrincipal = new UserPrincipal(accessToken.getTokenValue(), jwsObject, jwtClaimsSet); return new PreAuthenticatedAuthenticationToken(userPrincipal, null, authorities); }

Target:
public AbstractAuthenticationToken convert(Jwt jwt) { OAuth2AccessToken accessToken = new OAuth2AccessToken( OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt()); Collection<GrantedAuthority> authorities = extractAuthorities(jwt); AzureOAuth2AuthenticatedPrincipal principal = new AzureOAuth2AuthenticatedPrincipal( jwt.getHeaders(), jwt.getClaims(), authorities, jwt.getTokenValue()); return new BearerTokenAuthentication(principal, accessToken, authorities); }
Source:
private boolean useGlobalModelCache() { return !Boolean.parseBoolean( System.getProperty( DISABLE_GLOBAL_MODEL_CACHE_SYSTEM_PROPERTY ) ); }

Target:
private boolean useGlobalModelCache() { return !Boolean.getBoolean( DISABLE_GLOBAL_MODEL_CACHE_SYSTEM_PROPERTY ); }
Source:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return OffsetTime.parse(defaultStr, DateTimeFormatter.ofPattern("HH:mm:ss[.SSS]x")); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default LocalDateTime value: " + defaultStr, e); } }

Target:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return OffsetTime.parse(defaultStr, new DateTimeFormatterBuilder() .appendPattern("HH:mm:ss") .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true) .appendPattern("x") .toFormatter()); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default OffsetTime value: " + defaultStr, e); } }
Source:
public static int divideRoundUp(int dividend, int divisor) { Preconditions.checkArgument(dividend >= 0, "Negative dividend is not supported."); Preconditions.checkArgument(divisor > 0, "Negative or zero divisor is not supported."); if (dividend == 0) { return 0; } return (dividend - 1) / divisor + 1; }

Target:
public static int divideRoundUp(int dividend, int divisor) { Preconditions.checkArgument(dividend >= 0, "Negative dividend is not supported."); Preconditions.checkArgument(divisor > 0, "Negative or zero divisor is not supported."); return dividend == 0 ? 0 : (dividend - 1) / divisor + 1; }
Source:
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) { try { return executeLogin(request, response); } catch (InvalidTokenException e) { log.info("Unable to login: " + e.getMessage()); ((HttpServletResponse)response).setStatus(HttpStatus.SC_UNAUTHORIZED); } catch (Exception e) { ((HttpServletResponse)response).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); log.error(e.getMessage(), e); } return false; }

Target:
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { try { return executeLogin(request, response); } catch (InvalidTokenException e) { log.info("Unable to login: " + e.getMessage()); WebUtils.toHttp(response).setStatus(HttpStatus.SC_UNAUTHORIZED); return false; } catch (Exception e) { log.error(e.getMessage(), e); throw e; } }
Source:
public void constructContextObject() { final String key1 = "Key1"; final String value1 = "first-value"; Context emptyContext = Context.NONE; Context keyValueContext = new Context(key1, value1); END: com.azure.core.util.context#object-object }

Target:
public void constructContextObject() { Context emptyContext = Context.NONE; final String userParentSpan = "user-parent-span"; Context keyValueContext = new Context(OPENCENSUS_SPAN_KEY, userParentSpan); END: com.azure.core.util.context#object-object }
Source:
public void testVersioningNotImplemented_exactRef() throws IOException { assertFalse(refdir.hasVersioning()); Ref exactRef = refdir.exactRef(HEAD); assertNotNull(exactRef); exactRef.getUpdateIndex(); }

Target:
public void testVersioningNotImplemented_exactRef() throws IOException { assertFalse(refdir.hasVersioning()); Ref ref = refdir.exactRef(HEAD); assertNotNull(ref); ref.getUpdateIndex(); }
Source:
private WriteResponse unpublishOldContent( HttpServletRequest request, HttpServletResponse response ) { String source = request.getParameter(SOURCE); ImmutableList<String> validUris = ImmutableList.copyOf( Arrays.asList( request.getParameter(VALID_URIS) .split(",") ) ); Publisher publisher = Publisher.fromKey(source).requireValue(); WriteResponse writeResponse = validateApiKey(request, response, publisher); if (writeResponse != null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return writeResponse; } if (oldContentDeactivator.deactivateOldContent(publisher, validUris, 50)) { response.setStatus(HttpServletResponse.SC_OK); } return null; }

Target:
private WriteResponse unpublishOldContent( HttpServletRequest request, HttpServletResponse response ) { String source = request.getParameter(SOURCE_PARAMETER); ImmutableList<String> validUris = ImmutableList.copyOf( request.getParameter(VALID_URIS_PARAMETER) .split(",") ); Publisher publisher = Publisher.fromKey(source).requireValue(); Optional<AtlasErrorSummary> apiKeyErrorSummary = validateApiKey( request, response, publisher ); if (apiKeyErrorSummary.isPresent()) { return error(request, response, apiKeyErrorSummary.get()); } if (oldContentDeactivator.deactivateOldContent(publisher, validUris, 50)) { response.setStatus(HttpServletResponse.SC_OK); } return null; }
Source:
public Type getType() { return Type.INDEX; }

Target:
public String getType() { return "index_hadoop"; }
Source:
public KubernetesTenancyProvider() { String kubernetesMasterUrl = System.getenv(KUBERNETES_MASTER_ENV_VAR_NAME); if (kubernetesMasterUrl == null || kubernetesMasterUrl.isEmpty()) { kubernetesMasterUrl = System.getProperty(KUBERNETES_MASTER_SYS_PROPERTY_NAME); } kubernetesClient = new DefaultKubernetesClient(kubernetesMasterUrl); logger.info("Kubernetes tenancy provider initialized"); logger.info("Kubernetes master URL: {}", kubernetesMasterUrl); }

Target:
public KubernetesTenancyProvider() { String kubernetesMasterUrl = System.getenv(KUBERNETES_MASTER_ENV_VAR_NAME); if (kubernetesMasterUrl == null || kubernetesMasterUrl.isEmpty()) { kubernetesMasterUrl = System.getProperty(KUBERNETES_MASTER_SYS_PROPERTY_NAME); } if (kubernetesMasterUrl == null || kubernetesMasterUrl.isEmpty()) { throw new DeploymentEnvironmentException("Kubernetes master URL not found, set environment variable " + KUBERNETES_MASTER_ENV_VAR_NAME + " or system property " + KUBERNETES_MASTER_SYS_PROPERTY_NAME + "."); } kubernetesClient = new DefaultKubernetesClient(kubernetesMasterUrl); logger.info("Kubernetes tenancy provider initialized"); logger.info("Kubernetes master URL: {}", kubernetesMasterUrl); }
Source:
public static Tuple generateTestTuple(String source, String index, String type, String id) { TopologyBuilder builder = new TopologyBuilder(); GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(), new Config(), new CustomIndexArray<String>(0,1), new HashMap<>(), new HashMap<>(), "") { @Override public Fields getComponentOutputFields(String componentId, String streamId) { return new Fields("source", "index", "type", "id"); } }; return new TupleImpl(topologyContext, new Values(source, index, type, id), source, 1, ""); }

Target:
public static Tuple generateTestTuple(String source, String index, String type, String id) { TopologyBuilder builder = new TopologyBuilder(); GeneralTopologyContext topologyContext = new GeneralTopologyContext(builder.createTopology(), new Config(), new CustomIndexArray<String>(0,0), new HashMap<>(), new HashMap<>(), "") { @Override public Fields getComponentOutputFields(String componentId, String streamId) { return new Fields("source", "index", "type", "id"); } }; return new TupleImpl(topologyContext, new Values(source, index, type, id), source, 1, ""); }
Source:
ValueRange rangeAlignedWeekOfMonth() { return ValueRange.of(1, InternationalFixedChronology.WEEKS_IN_MONTH); }

Target:
ValueRange rangeAlignedWeekOfMonth() { return this.month > 0 ? WEEK_OF_MONTH_RANGE : EMPTY_RANGE; }
Source:
private boolean validateCpuChange(VDSGroup oldGroup) { VDSGroup vdsGroup = getVdsGroup(); String oldCpuName = oldGroup.getcpu_name(); String cpuName = vdsGroup.getcpu_name(); if (oldCpuName == null && cpuName == null) { return true; } Version compatVersion = vdsGroup.getcompatibility_version(); if (!CpuFlagsManagerHandler.CheckIfCpusExist(cpuName, compatVersion)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CPU_NOT_FOUND); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__CLUSTER); return false; } if (!StringHelper.isNullOrEmpty(oldCpuName)) { return true; } boolean isSameManufacturer = CpuFlagsManagerHandler.CheckIfCpusSameManufacture(oldCpuName, cpuName, compatVersion); int vdsNum = DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getVdsGroup().getId()) .size(); if (!isSameManufacturer && vdsNum > 0) { addCanDoActionMessage(VdcBllMessages.VDS_GROUP_CANNOT_UPDATE_CPU_ILLEGAL); return false; } return true; }

Target:
private boolean validateCpuChange(VDSGroup oldGroup) { VDSGroup vdsGroup = getVdsGroup(); String oldCpuName = oldGroup.getcpu_name(); String cpuName = vdsGroup.getcpu_name(); if (oldCpuName == null && cpuName == null) { return true; } Version compatVersion = vdsGroup.getcompatibility_version(); if (!CpuFlagsManagerHandler.CheckIfCpusExist(cpuName, compatVersion)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CPU_NOT_FOUND); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__CLUSTER); return false; } if (StringHelper.isNullOrEmpty(oldCpuName)) { return true; } boolean isSameManufacturer = CpuFlagsManagerHandler.CheckIfCpusSameManufacture(oldCpuName, cpuName, compatVersion); int vdsNum = DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getVdsGroup().getId()) .size(); if (!isSameManufacturer && vdsNum > 0) { addCanDoActionMessage(VdcBllMessages.VDS_GROUP_CANNOT_UPDATE_CPU_ILLEGAL); return false; } return true; }
Source:
protected IDiagramWorkbenchPart getDiagramWorkbenchPart() { IDiagramWorkbenchPart diagramPart = null; IEditorPart editorPart = partReference.getEditor(false); if (editorPart instanceof IDiagramWorkbenchPart) { diagramPart = (IDiagramWorkbenchPart) editorPart; } else if (editorPart != null) { diagramPart = editorPart.getAdapter(IDiagramWorkbenchPart.class); } return diagramPart; }

Target:
protected IDiagramWorkbenchPart getDiagramWorkbenchPart() { IDiagramWorkbenchPart diagramPart = null; IEditorPart editorPart = partReference.getEditor(false); if (editorPart instanceof IDiagramWorkbenchPart) { diagramPart = (IDiagramWorkbenchPart) editorPart; } else if (editorPart != null) { diagramPart = (IDiagramWorkbenchPart) editorPart.getAdapter(IDiagramWorkbenchPart.class); } return diagramPart; }
Source:
public void setClientInfo(String name, String value) throws SQLClientInfoException { if (value != null) { this.properties.setProperty(name, value); } else { this.properties.remove(name); } }

Target:
public void setClientInfo(String name, String value) throws SQLClientInfoException { if (isClosed()) { throw new SQLClientInfoException(); } if (value != null) { this.properties.setProperty(name, value); } else { this.properties.remove(name); } }
Source:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); renderer.render("smooth", isSmooth()); }

Target:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); if (!isSmooth()) renderer.render("smooth", false); }
Source:
static void loadExternalLinksIntoExtensionElements(final org.kie.workbench.common.dmn.api.definition.v1_1.DRGElement source, final org.kie.dmn.model.api.DRGElement target) { if (Objects.isNull(source.getLinksHolder()) || Objects.isNull(source.getLinksHolder().getValue())) { return; } final DocumentationLinks links = source.getLinksHolder().getValue(); final DMNElement.ExtensionElements elements = getOrCreateExtensionElements(target); elements.getExternalLinks().clear(); for (final DMNExternalLink link : links.getLinks()) { final TDMNExternalLink external = new TDMNExternalLink(); external.setLinkDescription(link.getDescription()); external.setURL(link.getUrl()); elements.getExternalLinks().add(external); } target.setExtensionElements(elements); }

Target:
static void loadExternalLinksIntoExtensionElements(final org.kie.workbench.common.dmn.api.definition.v1_1.DRGElement source, final org.kie.dmn.model.api.DRGElement target) { if (Objects.isNull(source.getLinksHolder()) || Objects.isNull(source.getLinksHolder().getValue())) { return; } final DocumentationLinks links = source.getLinksHolder().getValue(); final DMNElement.ExtensionElements elements = getOrCreateExtensionElements(target); removeAllExistingLinks(elements); for (final DMNExternalLink link : links.getLinks()) { final ExternalLink external = new ExternalLink(); external.setName(link.getDescription()); external.setUrl(link.getUrl()); elements.getAny().add(external); } target.setExtensionElements(elements); }
Source:
public void testReplaceValueEqualStoreEntryCacheWriterException() throws Exception { final FakeStore realStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(realStore); final FakeCacheWriter realCache = new FakeCacheWriter(Collections.singletonMap("key", "oldValue")); this.cacheWriter = spy(realCache); doThrow(new Exception()).when(this.cacheWriter).write("key", "newValue"); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); try { ehcache.replace("key", "oldValue", "newValue"); fail(); } catch (CacheWriterException e) { } verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.ReplaceOutcome.class)); }

Target:
public void testReplaceValueEqualStoreEntryCacheWriterException() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(fakeStore); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "oldValue")); this.cacheWriter = spy(fakeWriter); doThrow(new Exception()).when(this.cacheWriter).write("key", "newValue"); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); try { ehcache.replace("key", "oldValue", "newValue"); fail(); } catch (CacheWriterException e) { } verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.ReplaceOutcome.class)); }
Source:
public Object read(JsonReader in) throws IOException { JsonToken token = in.peek(); if (token.equals(JsonToken.NUMBER)) { String str = in.nextString(); try { return Integer.parseInt(str); } catch (NumberFormatException e) { try { return Long.parseLong(str); } catch (NumberFormatException e1) { try { return Double.parseDouble(str); } catch (NumberFormatException e3) { throw e3; } } } } return objectAdapter.read(in); }

Target:
public Object read(JsonReader in) throws IOException { JsonToken token = in.peek(); if (token.equals(JsonToken.NUMBER)) { try { return in.nextLong(); } catch (NumberFormatException e) { return in.nextDouble(); } } return objectAdapter.read(in); }