auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recent_notifications); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation)); setSupportActionBar(toolbar); setupActionBar(); Fragment fragment = new RecentNotificationsFragmentV2(); getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in_support, R.anim.fade_out_support).replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recent_notifications); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation)); setSupportActionBar(toolbar); setupActionBar(); Fragment fragment = new RecentNotificationsFragment(); getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in_support, R.anim.fade_out_support).replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit(); }
Source:
public boolean isInstalled() { try { Project project = getFaceted(); project.getFacet(MavenFacet.class); return getRootTemplateDirectory().exists(); } catch (FacetNotFoundException e) { return false; } }

Target:
public boolean isInstalled() { Project project = getFaceted(); return project.hasFacet(MavenFacet.class) && getRootTemplateDirectory().exists(); }
Source:
public static String getClientIp(final String ip, final String xff) { if (xff == null || xff.isEmpty() || xff.equals("-")) { return ip; } else { String[] proxiedIps = xff.split(","); try { for (String proxiedIp : proxiedIps) { int ipVersion = getIpVersion(proxiedIp); if ((!( proxiedIp.startsWith("127.0") || proxiedIp.startsWith("192.168") || proxiedIp.startsWith("10.") || proxiedIp.startsWith("169.254") )) && ( ipVersion == 4 || ipVersion == 6 ) ) { return proxiedIp; } } return ip; } catch (ArrayIndexOutOfBoundsException e) { return ip; } } }

Target:
public static String getClientIp(final String ip, final String xff) { if (xff == null || xff.isEmpty() || xff.equals("-")) { return ip; } else { String[] proxiedIps = xff.split(","); try { for (String proxiedIp : proxiedIps) { proxiedIp = proxiedIp.trim(); int ipVersion = getIpVersion(proxiedIp); if ((!( proxiedIp.startsWith("127.0") || proxiedIp.startsWith("192.168") || proxiedIp.startsWith("10.") || proxiedIp.startsWith("169.254") )) && ( ipVersion == 4 || ipVersion == 6 ) ) { return proxiedIp; } } return ip; } catch (ArrayIndexOutOfBoundsException e) { return ip; } } }
Source:
protected <T> T get(Class<T> clazz, String path, String ...params) { path = getPath(path, params); try { HttpGet get = new HttpGet(); setupCommonHeaders(get); get.setURI(uri.resolve(path)); String json = getJSON(get); return gson.fromJson(json, clazz); } catch (IOException e) { throw new HttpClientException(e); } }

Target:
protected <T> T get(Class<T> clazz, String path, String ...params) { path = getPath(path, params); try { HttpGet get = new HttpGet(); setupCommonHeaders(get); get.setURI(uri.resolve(path)); String json = getJSON(get); return mapper.readValue(json, clazz); } catch (IOException e) { throw new HttpClientException(e); } }
Source:
public void testGetErrors() { HttpCodesUtil.HttpCode code200 = new HttpCodesUtil.HttpCode(200, "Ok"); HttpCodesUtil.HttpCode code302 = new HttpCodesUtil.HttpCode(302, "Found"); HttpCodesUtil.HttpCode code400 = new HttpCodesUtil.HttpCode(400, "Bad Request"); HttpCodesUtil.HttpCode code501 = new HttpCodesUtil.HttpCode(501, "Not Implemented"); List<HttpCodesUtil.HttpCode> codeList = Arrays.asList(code200, code400, code400, code302, code501); List<HttpCodesUtil.HttpCode> clientOrServerErrors = HttpCodesUtil.getClientOrServerErrors(codeList); Assert.assertEquals(3, clientOrServerErrors.size()); Assert.assertEquals(Arrays.asList(code400, code400, code501), clientOrServerErrors); }

Target:
public void testGetErrors() { HttpCodesUtil.HttpCode code200 = new HttpCodesUtil.HttpCode(200, "Ok"); HttpCodesUtil.HttpCode code302 = new HttpCodesUtil.HttpCode(302, "Found"); HttpCodesUtil.HttpCode code400 = new HttpCodesUtil.HttpCode(400, "Bad Request"); HttpCodesUtil.HttpCode code501 = new HttpCodesUtil.HttpCode(501, "Not Implemented"); List<HttpCodesUtil.HttpCode> codeList = Arrays.asList(code200, code400, code400, code302, code501); List<HttpCodesUtil.HttpCode> clientOrServerErrors = HttpCodesUtil.getClientOrServerErrors(codeList); Assert.assertEquals( Arrays.asList(new HttpCodesUtil.HttpCode(400, "400"), new HttpCodesUtil.HttpCode(400, "400"), new HttpCodesUtil.HttpCode(501, "501")), clientOrServerErrors); Assert.assertEquals(Arrays.asList(code400, code400, code501), clientOrServerErrors); }
Source:
public static Path getJavaExecutablePath() { String javaHome = System.getenv(JAVA_HOME); if (javaHome == null) { throw new NullPointerException(String.format("'%s' is not set", JAVA_HOME)); } return Paths.get(javaHome).resolve("bin/java"); }

Target:
public static Path getJavaExecutablePath() { Path javaHome = PROPERTIES.getJavaHome(); if (javaHome == null) { throw new NullPointerException("'java.home' is not set"); } return PROPERTIES.getJavaHome().resolve("bin/java"); }
Source:
public static void addBundleToMap(Bundle bundle, List<String> keys, Map<String, String> map) { if (bundle == null || keys == null || bundle.isEmpty() || keys.isEmpty()) { return; } if (map == null) { map = new HashMap<>(); } for (final String key : keys) { if (!TextUtils.isEmpty(key)) { map.put(key, bundle.getString(key)); } } }

Target:
public static Map<String, String> addBundleToMap(Bundle bundle, List<String> keys, Map<String, String> map) { if (bundle == null || keys == null || bundle.isEmpty() || keys.isEmpty()) { return map; } if (map == null) { map = new HashMap<>(); } for (final String key : keys) { if (!TextUtils.isEmpty(key)) { map.put(key, bundle.getString(key)); } } return map; }
Source:
final <E extends Throwable> E expectError(Class<E> clazz, final long totalTimeoutMillis, long pollTimeoutMillis, String errorMsg) throws Exception { long totalTimeoutRemainingMillis = totalTimeoutMillis; long timeStampA = System.nanoTime(); long timeStampB; for (;;) { Thread.sleep(Math.min(pollTimeoutMillis, totalTimeoutRemainingMillis)); if (env.asyncErrors.isEmpty()) { timeStampB = System.nanoTime(); totalTimeoutRemainingMillis =- timeStampB - timeStampA; timeStampA = timeStampB; if (totalTimeoutRemainingMillis <= 0) { return env.flopAndFail(String.format("%s within %d ms", errorMsg, totalTimeoutMillis)); } } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { return env.flopAndFail(String.format("%s within %d ms; Got %s but expected %s", errorMsg, totalTimeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } } } }

Target:
final <E extends Throwable> E expectError(Class<E> clazz, final long totalTimeoutMillis, long pollTimeoutMillis, String errorMsg) throws Exception { long totalTimeoutRemainingNs = MILLISECONDS.toNanos(totalTimeoutMillis); long timeStampANs = System.nanoTime(); long timeStampBNs; for (;;) { Thread.sleep(Math.min(pollTimeoutMillis, NANOSECONDS.toMillis(totalTimeoutRemainingNs))); if (env.asyncErrors.isEmpty()) { timeStampBNs = System.nanoTime(); totalTimeoutRemainingNs =- timeStampBNs - timeStampANs; timeStampANs = timeStampBNs; if (totalTimeoutRemainingNs <= 0) { return env.flopAndFail(String.format("%s within %d ms", errorMsg, totalTimeoutMillis)); } } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { return env.flopAndFail(String.format("%s within %d ms; Got %s but expected %s", errorMsg, totalTimeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } } } }
Source:
protected List<ByteBuffer> getValues() { maybeRefreshValues(); List<ByteBuffer> bbs; if (parameterMode == null) { assert values.isEmpty(); return Collections.emptyList(); } switch (parameterMode) { case NAMED: if (values.isEmpty()) return Collections.emptyList(); bbs = newArrayListWithCapacity(values.size()); for (Value value : values.values()) { bbs.add(value.bytes); } return bbs; case POSITIONAL: if (values.isEmpty()) return Collections.emptyList(); int last = (Integer)(values.lastEntry().getKey()); bbs = newArrayListWithCapacity(last + 1); for (int i = 0; i <= last; i++) { Value value = values.get(i); bbs.add(value == null ? BoundStatement.UNSET : value.bytes); } return bbs; default: throw new AssertionError("Unsupported parameter mode " + parameterMode); } }

Target:
protected List<ByteBuffer> getValues() { maybeRefreshValues(); List<ByteBuffer> bbs; if (parameterMode == null) { assert values.isEmpty(); return Collections.emptyList(); } switch (parameterMode) { case NAMED: if (values.isEmpty()) return Collections.emptyList(); bbs = newArrayListWithCapacity(values.size()); for (Value value : values.values()) { bbs.add(value.bytes); } return bbs; case POSITIONAL: if (values.isEmpty()) return Collections.emptyList(); int last = (Integer)(values.lastEntry().getKey()); bbs = newArrayListWithCapacity(last + 1); for (int i = 0; i <= last; i++) { Value value = values.get(i); bbs.add(value == null ? CBUtil.UNSET_VALUE : value.bytes); } return bbs; default: throw new AssertionError("Unsupported parameter mode " + parameterMode); } }
Source:
private <T> List<T> getEntities(WebTarget target, Class<T> clazz) { List<T> entities = new ArrayList<T>(); Response responseObject = target.request(MediaType.APPLICATION_JSON_TYPE).get(); try { String response = responseObject.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode() | responseCode == CatalogResponse.ResponseMessage.EXCEPTION.getCode()) { throw new RuntimeException("Error occurred :"+ getResponseMessage(response)); } ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); Iterator<JsonNode> it = node.get("entities").elements(); while (it.hasNext()) { entities.add(mapper.treeToValue(it.next(), clazz)); } } catch (Exception ex) { throw new RuntimeException(ex); } return entities; }

Target:
private <T> List<T> getEntities(WebTarget target, Class<T> clazz) { List<T> entities = new ArrayList<T>(); Response responseObject = target.request(MediaType.APPLICATION_JSON_TYPE).get(); try { String response = responseObject.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode != CatalogResponse.ResponseMessage.SUCCESS.getCode()) { throw new RuntimeException("Error occurred :"+ getResponseMessage(response)); } ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); Iterator<JsonNode> it = node.get("entities").elements(); while (it.hasNext()) { entities.add(mapper.treeToValue(it.next(), clazz)); } } catch (IOException ex) { throw new RuntimeException(ex); } return entities; }
Source:
public void process(byte[] data, int off, int len, byte[] iv) { F8Context f8ctx = new F8Context(); f8ctx.ivAccent = new byte[BLKLEN]; cipher.init(true, new KeyParameter(maskedKey)); cipher.processBlock(iv, 0, f8ctx.ivAccent, 0); cipher.init(true, new KeyParameter(encKey)); f8ctx.J = 0; f8ctx.S = new byte[BLKLEN]; Arrays.fill(f8ctx.S, (byte) 0); int inLen = len; while (inLen >= BLKLEN) { processBlock(f8ctx, data, off, data, off, BLKLEN); inLen -= BLKLEN; off += BLKLEN; } if (inLen > 0) { processBlock(f8ctx, data, off, data, off, inLen); } }

Target:
public void process(byte[] data, int off, int len, byte[] iv) { if (iv.length != BLKLEN) throw new IllegalArgumentException("iv.length != BLKLEN"); if (off < 0) throw new IllegalArgumentException("off < 0"); if (len < 0) throw new IllegalArgumentException("len < 0"); if (off + len > data.length) throw new IllegalArgumentException("off + len > data.length"); F8Context f8ctx = new F8Context(); f8ctx.ivAccent = new byte[BLKLEN]; cipher.init(true, new KeyParameter(maskedKey)); cipher.processBlock(iv, 0, f8ctx.ivAccent, 0); cipher.init(true, new KeyParameter(encKey)); f8ctx.J = 0; f8ctx.S = new byte[BLKLEN]; Arrays.fill(f8ctx.S, (byte) 0); int inLen = len; while (inLen >= BLKLEN) { processBlock(f8ctx, data, off, BLKLEN); inLen -= BLKLEN; off += BLKLEN; } if (inLen > 0) { processBlock(f8ctx, data, off, inLen); } }
Source:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { Player p = (Player) sender; if (cooldown.contains(p)) { p.sendMessage(ChatColor.RED + "You must wait 10 minutes to make another advertisement."); return true; } if (args.length < 1) { return false; } String message = StringUtils.join(args, " ", 0, args.length); Bukkit.broadcastMessage(ChatColor.GREEN + "[Advertisement] " + ChatColor.GOLD + sender.getName() + ChatColor.GREEN + "] " + ChatColor.DARK_GREEN + message); cooldown.add(p); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { p.sendMessage(ChatColor.GRAY + "You may now make another advertisement."); cooldown.remove(p); } }, 600L * 20L); }

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (cooldown.contains(playerSender)) { msg("You must wait 10 minutes to make another advertisement."); return true; } if (args.length == 0) { return false; } String message = StringUtils.join(args, " ", 0, args.length); Bukkit.broadcastMessage(ChatColor.GREEN + "[Advertisement] " + ChatColor.GOLD + sender.getName() + ChatColor.GREEN + "> " + ChatColor.DARK_GREEN + message); cooldown.add(playerSender); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { msg("You may now make another advertisement."); cooldown.remove(playerSender); } }, 600L * 20L); }
Source:
public static ImageFileType map(org.ovirt.engine.core.common.businessentities.storage.ImageFileType imageFileType, ImageFileType template) { switch (imageFileType) { case Unknown: return ImageFileType.UNKNOWN; case ISO: return ImageFileType.ISO; case Floppy: return ImageFileType.FLOPPY; case Disk: return ImageFileType.DISK; case All: return ImageFileType.ALL; default: return null; } }

Target:
public static ImageFileType map(org.ovirt.engine.core.common.businessentities.storage.ImageFileType imageFileType, ImageFileType template) { switch (imageFileType) { case ISO: return ImageFileType.ISO; case Floppy: return ImageFileType.FLOPPY; case Disk: return ImageFileType.DISK; case All: return ImageFileType.ALL; default: return ImageFileType.UNKNOWN; } }
Source:
public void afterPropertiesSet() throws Exception { ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException { try { Input input = AnnotationUtils.findAnnotation(method, Input.class); if (input != null) { String name = BindingBeanDefinitionRegistryUtils.getChannelName(input, method); MessageChannel sharedChannel = locateSharedChannel(name); if (sharedChannel == null) { inputHolders.put(name, new ChannelHolder( channelFactory.createBindableChannel(name, (Class<? extends MessageChannel>)method.getReturnType()), true)); } else { configureSharedMessageChannel(name, (Class<? extends MessageChannel>) method.getReturnType(), sharedChannel); } } } catch (Exception e) { throw new RuntimeException(e); } } }); ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException { try { Output output = AnnotationUtils.findAnnotation(method, Output.class); if (output != null) { String name = BindingBeanDefinitionRegistryUtils.getChannelName(output, method); MessageChannel sharedChannel = locateSharedChannel(name); if (sharedChannel == null) { outputHolders.put(name, new ChannelHolder( channelFactory.createBindableChannel(name, (Class<? extends MessageChannel>) method.getReturnType()), true)); } else { configureSharedMessageChannel(name, (Class<? extends MessageChannel>)method.getReturnType(), sharedChannel); } } } catch (Exception e) { throw new RuntimeException(e); } } }); }

Target:
public void afterPropertiesSet() throws Exception { ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException { Input input = AnnotationUtils.findAnnotation(method, Input.class); if (input != null) { String name = BindingBeanDefinitionRegistryUtils.getChannelName(input, method); Class<? extends MessageChannel> channelType = (Class<? extends MessageChannel>) method.getReturnType(); MessageChannel sharedChannel = locateSharedChannel(name); if (sharedChannel == null) { inputHolders.put(name, new ChannelHolder(createBindableChannel(name, channelType), true)); } else { if (!channelType.isAssignableFrom(sharedChannel.getClass())) { bridgeSharedChannel(channelType, sharedChannel); } } } } }); ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException { Output output = AnnotationUtils.findAnnotation(method, Output.class); if (output != null) { String name = BindingBeanDefinitionRegistryUtils.getChannelName(output, method); Class<? extends MessageChannel> channelType = (Class<? extends MessageChannel>) method.getReturnType(); MessageChannel sharedChannel = locateSharedChannel(name); if (sharedChannel == null) { outputHolders.put(name, new ChannelHolder(createBindableChannel(name, channelType), true)); } else { if (!channelType.isAssignableFrom(sharedChannel.getClass())) { bridgeSharedChannel(channelType, sharedChannel); } } } } }); }
Source:
public BroadcastStrategy(int maxTasks) { if(maxTasks < 1) { throw new DatastreamRuntimeException("Invalid maxTasks parameter: " + maxTasks); } _maxTasks = maxTasks; }

Target:
public BroadcastStrategy(int maxTasks) { _maxTasks = maxTasks < 1 ? Integer.MAX_VALUE : maxTasks; }
Source:
private void refresh(SessionInfo sessionInfo) { Date now = new Date(); Date softLimit = (Date) sessionInfo.contentOfSession.get(SOFT_LIMIT_PARAMETER_NAME); if (softLimit == null) { softLimit = now; } int softLimitValue = Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval); if (softLimitValue > 0) { sessionInfo.contentOfSession.put(SOFT_LIMIT_PARAMETER_NAME, DateUtils.addMinutes(now, softLimitValue)); } }

Target:
private void refresh(SessionInfo sessionInfo) { Date now = new Date(); int softLimitValue = Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval); if (softLimitValue > 0) { sessionInfo.contentOfSession.put(SOFT_LIMIT_PARAMETER_NAME, DateUtils.addMinutes(now, softLimitValue)); } }
Source:
public void refresh() { if (Widgets.isAccessible(idValue)) { String legacyPcrId = (new AtsAttributeResolverServiceImpl()).getSoleAttributeValue(workItem, AtsAttributeTypes.LegacyPcrId, ""); idValue.setText(workItem.getAtsId() + " | " + legacyPcrId); if (workItem.isTeamWorkflow()) { teamWfIdValue.setText(((TeamWorkFlowArtifact) workItem).getTeamName()); } else if ((workItem.isTask() || workItem.isReview()) && workItem.getParentTeamWorkflow() != null) { IAtsTeamWorkflow parentTeamWorkflow = workItem.getParentTeamWorkflow(); parentIdValue.setText(AtsClientService.get().getWorkItemService().getCombinedPcrId(parentTeamWorkflow)); } IAtsAction action = workItem.getParentAction(); if (action != null) { actionIdValue.setText(action.getAtsId()); } } }

Target:
public void refresh() { if (Widgets.isAccessible(idValue)) { String legacyPcrId = (AtsClientService.get()).getAttributeResolver().getSoleAttributeValueAsString(workItem, AtsAttributeTypes.LegacyPcrId, ""); if (Strings.isValid(legacyPcrId)) { legacyPcrId = " | " + legacyPcrId; } else { legacyPcrId = ""; } idValue.setText(workItem.getAtsId() + legacyPcrId); if (workItem.isTeamWorkflow()) { teamWfIdValue.setText(((TeamWorkFlowArtifact) workItem).getTeamName()); } else if ((workItem.isTask() || workItem.isReview()) && workItem.getParentTeamWorkflow() != null) { IAtsTeamWorkflow parentTeamWorkflow = workItem.getParentTeamWorkflow(); parentIdValue.setText(AtsClientService.get().getWorkItemService().getCombinedPcrId(parentTeamWorkflow)); } IAtsAction action = workItem.getParentAction(); if (action != null) { actionIdValue.setText(action.getAtsId()); } } }
Source:
public void batchComplete() { this.requiredBytes = 0; this.sequence = 0; this.batch = new Batch(); }

Target:
private void batchComplete() { requiredBytes = 0; sequence = 0; batch = new Batch(); }
Source:
public static Value floor( AnyValue in ) { if ( in == NO_VALUE ) { return NO_VALUE; } else if ( in instanceof NumberValue ) { return doubleValue( Math.floor( ((NumberValue) in).doubleValue() ) ); } else { throw new CypherTypeException( "ceil requires numbers", null ); } }

Target:
public static Value floor( AnyValue in ) { if ( in == NO_VALUE ) { return NO_VALUE; } else if ( in instanceof NumberValue ) { return doubleValue( Math.floor( ((NumberValue) in).doubleValue() ) ); } else { throw needsNumbers( "floor()" ); } }
Source:
public void setFocus() { if (fSourceViewer != null && fSourceViewer.getTextWidget() != null && !fSourceViewer.getTextWidget().isDisposed()) { fSourceViewer.getTextWidget().setFocus(); } }

Target:
public void setFocus() { StyledText widget = fSourceViewer.getTextWidget(); if (fSourceViewer != null && widget != null && !widget.isDisposed()) { widget.setFocus(); } }
Source:
protected Response internalIssueRequest(Request request) throws IOException, ServiceException { final URL finalURL = request.getFinalURL(); boolean success = false; try { final HTTPResponse httpResponse; if (request.requiresPost()) { final String postContentType = request.getPostContentType(); ByteArrayOutputStream out = new ByteArrayOutputStream(); request.performPostOutput(out); byte[] byteArray = out.toByteArray(); LOGGER.fine(new String(byteArray)); InputStream in = new ByteArrayInputStream(byteArray); try { httpResponse = httpClient.post(finalURL, in, postContentType); } finally { in.close(); } } else { httpResponse = httpClient.get(finalURL); } final Response response = request.createResponse(httpResponse); success = true; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Executed request to URL: " + finalURL.toExternalForm()); } return response; } finally { if (!success) { LOGGER.log(Level.SEVERE, "Failed to execute request " + finalURL); } } }

Target:
protected Response internalIssueRequest(Request request) throws IOException, ServiceException { final URL finalURL = request.getFinalURL(); LOGGER.fine("FinalURL:" + finalURL); boolean success = false; try { final HTTPResponse httpResponse; if (request.requiresPost()) { final String postContentType = request.getPostContentType(); ByteArrayOutputStream out = new ByteArrayOutputStream(); request.performPostOutput(out); InputStream in; if (LOGGER.isLoggable(Level.FINE)) { byte[] byteArray = out.toByteArray(); LOGGER.fine(new String(byteArray)); in = new ByteArrayInputStream(byteArray); } else { in = new ByteArrayInputStream(out.toByteArray()); } try { httpResponse = httpClient.post(finalURL, in, postContentType); } finally { in.close(); } } else { httpResponse = httpClient.get(finalURL); } final Response response = request.createResponse(httpResponse); success = true; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Executed request to URL: " + finalURL.toExternalForm()); } return response; } finally { if (!success) { LOGGER.log(Level.SEVERE, "Failed to execute request " + finalURL); } } }
Source:
protected void subscribe(String eventKey) { CommandEntity commandEntity = buildCommandEntity(getCommandId(), true); commandEntity.setWaitingForEVent(true); CommandCoordinatorUtil.subscribe(eventKey, commandEntity); }

Target:
protected void subscribe(String eventKey) { CommandEntity commandEntity = buildCommandEntity(getCommandId(), true); commandEntity.setWaitingForEvent(true); CommandCoordinatorUtil.subscribe(eventKey, commandEntity); }
Source:
public LoginData(JsonNode root) throws IOException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> treeData = mapper.readValue(root, Map.class); Object data = treeData.get("SecurityToken"); if(data == null) throw new IOException("Could not find SecurityToken in JSON data"); securityToken = data.toString(); logger.debug("myq securityToken: {}", securityToken); }

Target:
public LoginData(JsonNode root) throws IOException, InvalidDataException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> treeData = mapper.readValue(root, Map.class); Object data = treeData.get("SecurityToken"); if (data == null) throw new InvalidDataException( "Could not find SecurityToken in JSON data"); securityToken = data.toString(); logger.debug("myq securityToken: {}", securityToken); }
Source:
public void copyDetailsFromOtherCuObjectCodeActivationGlobal(CuObjectCodeActivationGlobal oldGlobal) { for (CuObjectCodeGlobalDetail oldDetail : oldGlobal.getObjectCodeGlobalDetails()) { CuObjectCodeGlobalDetail newDetail = (CuObjectCodeGlobalDetail) ObjectUtils.deepCopy(oldDetail); newDetail.setObjectId(null); newDetail.setDocumentNumber(getDocumentNumber()); newDetail.setVersionNumber(new Long(0)); getObjectCodeGlobalDetails().add(newDetail); } }

Target:
public void copyDetailsFromOtherCuObjectCodeActivationGlobal(CuObjectCodeActivationGlobal oldGlobal) { for (CuObjectCodeGlobalDetail oldDetail : oldGlobal.getObjectCodeGlobalDetails()) { CuObjectCodeGlobalDetail newDetail = (CuObjectCodeGlobalDetail) ObjectUtils.deepCopy(oldDetail); newDetail.setObjectId(null); newDetail.setDocumentNumber(getDocumentNumber()); newDetail.setVersionNumber(new Long(1)); getObjectCodeGlobalDetails().add(newDetail); } }
Source:
public void testWithTableLevelUCFNoConnLevelUCF() throws Exception { long tableUpdateCacheFrequency = 1000; long connUpdateCacheFrequency = -1; String fullTableName = DEFAULT_SCHEMA_NAME + QueryConstants.NAME_SEPARATOR + generateUniqueName(); int numSelectExecutions = 2; int numExpectedGetTableCalls = 1; setUpTableAndConnections(fullTableName, tableUpdateCacheFrequency, connUpdateCacheFrequency); verifyExpectedGetTableCalls(fullTableName, numSelectExecutions, numExpectedGetTableCalls); Thread.sleep(tableUpdateCacheFrequency); verifyExpectedGetTableCalls(fullTableName, numSelectExecutions, numExpectedGetTableCalls); }

Target:
public void testWithTableLevelUCFNoConnLevelUCF() throws Exception { final long tableUpdateCacheFrequency = 1000; String fullTableName = DEFAULT_SCHEMA_NAME + QueryConstants.NAME_SEPARATOR + generateUniqueName(); int numExecutions = 2; int numExpectedGetTableCalls = 1; setUpTableAndConnections(fullTableName, String.valueOf(tableUpdateCacheFrequency), null); verifyExpectedGetTableCalls(fullTableName, numExecutions, numExpectedGetTableCalls); Thread.sleep(tableUpdateCacheFrequency); verifyExpectedGetTableCalls(fullTableName, numExecutions, numExpectedGetTableCalls); }
Source:
void addMemoryAreaMetrics(List<MetricFamilySamples> sampleFamilies) { MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage(); GaugeMetricFamily used = new GaugeMetricFamily( "jvm_memory_bytes_used", "Used bytes of a given JVM memory area.", Collections.singletonList("area")); used.addMetric(Collections.singletonList("heap"), heapUsage.getUsed()); used.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getUsed()); sampleFamilies.add(used); GaugeMetricFamily committed = new GaugeMetricFamily( "jvm_memory_bytes_committed", "Committed (bytes) of a given JVM memory area.", Collections.singletonList("area")); committed.addMetric(Collections.singletonList("heap"), heapUsage.getCommitted()); committed.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getCommitted()); sampleFamilies.add(committed); GaugeMetricFamily max = new GaugeMetricFamily( "jvm_memory_bytes_max", "Max (bytes) of a given JVM memory area.", Collections.singletonList("area")); max.addMetric(Collections.singletonList("heap"), heapUsage.getMax()); max.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getMax()); sampleFamilies.add(max); GaugeMetricFamily init = new GaugeMetricFamily( "jvm_memory_bytes_init", "Init bytes of a given JVM memory area.", Collections.singletonList("area")); init.addMetric(Collections.singletonList("heap"), heapUsage.getInit()); init.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getInit()); sampleFamilies.add(init); }

Target:
void addMemoryAreaMetrics(List<MetricFamilySamples> sampleFamilies) { MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage(); GaugeMetricFamily used = new GaugeMetricFamily( "jvm_memory_bytes_used", "Used bytes of a given JVM memory area.", Collections.singletonList("area")); used.addMetric(Collections.singletonList("heap"), heapUsage.getUsed()); used.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getUsed()); sampleFamilies.add(used); GaugeMetricFamily committed = new GaugeMetricFamily( "jvm_memory_bytes_committed", "Committed (bytes) of a given JVM memory area.", Collections.singletonList("area")); committed.addMetric(Collections.singletonList("heap"), heapUsage.getCommitted()); committed.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getCommitted()); sampleFamilies.add(committed); GaugeMetricFamily max = new GaugeMetricFamily( "jvm_memory_bytes_max", "Max (bytes) of a given JVM memory area.", Collections.singletonList("area")); max.addMetric(Collections.singletonList("heap"), heapUsage.getMax()); max.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getMax()); sampleFamilies.add(max); GaugeMetricFamily init = new GaugeMetricFamily( "jvm_memory_bytes_init", "Initial bytes of a given JVM memory area.", Collections.singletonList("area")); init.addMetric(Collections.singletonList("heap"), heapUsage.getInit()); init.addMetric(Collections.singletonList("nonheap"), nonHeapUsage.getInit()); sampleFamilies.add(init); }
Source:
public SecurityGroupTool(JcloudsLocation location, SecurityGroupDefinition sgDef) { this.location = location; this.sgDef = sgDef; }

Target:
public SecurityGroupTool(JcloudsLocation location, SecurityGroupDefinition sgDef) { this.location = Preconditions.checkNotNull(location); this.sgDef = Preconditions.checkNotNull(sgDef); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LiteralParseNode other = (LiteralParseNode) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LiteralParseNode other = (LiteralParseNode) obj; return type.isComparableTo(other.type) && type.compareTo(value, other.value, other.type) == 0; }
Source:
private boolean waitForScanState(ScanStates state) { try { while (!getScanState().equals(state)) { scanState.wait(); } return true; } catch (InterruptedException e) { tsLogger.logger.warn("problem waiting for scanLock whilst in state " + state.name(), e); return false; } }

Target:
private boolean waitForScanState(ScanStates state) { try { do { scanState.wait(); } while (!getScanState().equals(state)); return true; } catch (InterruptedException e) { tsLogger.logger.warn("problem waiting for scanLock whilst in state " + state.name(), e); return false; } }
Source:
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) { if (closeConnectionReason.isIntended) return; if (!connection.getPeersNodeAddressOptional().isPresent()) return; NodeAddress peersNodeAddress = connection.getPeersNodeAddressOptional().get(); ArrayList<Map.Entry<ByteArray, ProtectedStorageEntry>> toBackDate = map.entrySet().stream() .filter(entry -> entry.getValue().getProtectedStoragePayload() instanceof ExpirablePayload) .filter(entry -> entry.getValue().getProtectedStoragePayload() instanceof RequiresOwnerIsOnlinePayload) .filter(entry -> ((RequiresOwnerIsOnlinePayload) entry.getValue().getProtectedStoragePayload()).getOwnerNodeAddress().equals(peersNodeAddress)) .collect(Collectors.toCollection(ArrayList::new)); toBackDate.forEach(mapEntry -> { log.debug("We remove the data as the data owner got disconnected with " + "closeConnectionReason=" + closeConnectionReason); mapEntry.getValue().backDate(); }); ArrayList<Map.Entry<ByteArray, ProtectedStorageEntry>> toRemoveList = toBackDate.stream().filter(mapEntry -> mapEntry.getValue().isExpired(this.clock)) .collect(Collectors.toCollection(ArrayList::new)); toRemoveList.forEach(toRemoveItem -> { log.debug("We found an expired data entry. We remove the protectedData:\n\t" + Utilities.toTruncatedString(toRemoveItem.getValue())); }); removeFromMapAndDataStore(toRemoveList); if (sequenceNumberMap.size() > this.maxSequenceNumberMapSizeBeforePurge) sequenceNumberMap.setMap(getPurgedSequenceNumberMap(sequenceNumberMap.getMap())); }

Target:
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) { if (closeConnectionReason.isIntended) return; if (!connection.getPeersNodeAddressOptional().isPresent()) return; NodeAddress peersNodeAddress = connection.getPeersNodeAddressOptional().get(); map.values().stream() .filter(protectedStorageEntry -> protectedStorageEntry.getProtectedStoragePayload() instanceof RequiresOwnerIsOnlinePayload) .filter(protectedStorageEntry -> ((RequiresOwnerIsOnlinePayload) protectedStorageEntry.getProtectedStoragePayload()).getOwnerNodeAddress().equals(peersNodeAddress)) .forEach(protectedStorageEntry -> { log.debug("Backdating due to closeConnectionReason={}", protectedStorageEntry, closeConnectionReason); protectedStorageEntry.backDate(); }); }
Source:
public URI getServiceContainerGroup() { if (serviceGroupId == null) { return null; } return absoluteUri(SERVICE_CONTAINER_GROUPS, serviceGroupId); }

Target:
public URI getServiceContainerGroup() { return absoluteUri(SERVICE_CONTAINER_GROUPS, serviceGroupId); }
Source:
private void doTestAddAsync(AsyncTaskStatusEnum asyncStatus, CreationStatus creationStatus) throws Exception { setUriInfo(setUpBasicUriExpectations()); setUriInfo(setUpBasicUriExpectations()); setUpGetPayloadExpectations(1, 0); setUpGetBallooningExpectations(1, 0); setUpGetCertuficateExpectations(1, 0); setUpEntityQueryExpectations(VdcQueryType.GetVdsGroupByVdsGroupId, GetVdsGroupByVdsGroupIdParameters.class, new String[] { "VdsGroupId" }, new Object[] { GUIDS[1] }, getVdsGroupEntity()); setUpEntityQueryExpectations(VdcQueryType.GetVmTemplate, GetVmTemplateParameters.class, new String[] { "Id" }, new Object[] { GUIDS[0] }, getTemplateEntity(0)); setUpCreationExpectations(VdcActionType.AddVmFromScratch, AddVmFromScratchParameters.class, new String[] { "StorageDomainId"}, new Object[] { Guid.Empty}, true, true, GUIDS[0], asList(GUIDS[1]), asList(new AsyncTaskStatus(asyncStatus)), VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class, new String[] { "Id" }, new Object[] { GUIDS[0] }, getEntity(0)); VM model = getModel(0); model.setCluster(new Cluster()); model.getCluster().setId(GUIDS[1].toString()); model.setTemplate(new Template()); model.getTemplate().setId(DEFAULT_TEMPLATE_ID); Response response = collection.add(model); assertEquals(202, response.getStatus()); assertTrue(response.getEntity() instanceof VM); verifyModel((VM)response.getEntity(), 0); VM created = (VM)response.getEntity(); assertNotNull(created.getCreationStatus()); assertEquals(creationStatus.value(), created.getCreationStatus().getState()); }

Target:
private void doTestAddAsync(AsyncTaskStatusEnum asyncStatus, CreationStatus creationStatus) throws Exception { setUriInfo(setUpBasicUriExpectations()); setUpGetPayloadExpectations(1, 0); setUpGetBallooningExpectations(1, 0); setUpGetCertuficateExpectations(1, 0); setUpEntityQueryExpectations(VdcQueryType.GetVdsGroupByVdsGroupId, GetVdsGroupByVdsGroupIdParameters.class, new String[] { "VdsGroupId" }, new Object[] { GUIDS[1] }, getVdsGroupEntity()); setUpEntityQueryExpectations(VdcQueryType.GetVmTemplate, GetVmTemplateParameters.class, new String[] { "Id" }, new Object[] { GUIDS[0] }, getTemplateEntity(0)); setUpCreationExpectations(VdcActionType.AddVmFromScratch, AddVmFromScratchParameters.class, new String[] { "StorageDomainId"}, new Object[] { Guid.Empty}, true, true, GUIDS[0], asList(GUIDS[1]), asList(new AsyncTaskStatus(asyncStatus)), VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class, new String[] { "Id" }, new Object[] { GUIDS[0] }, getEntity(0)); VM model = getModel(0); model.setCluster(new Cluster()); model.getCluster().setId(GUIDS[1].toString()); model.setTemplate(new Template()); model.getTemplate().setId(DEFAULT_TEMPLATE_ID); Response response = collection.add(model); assertEquals(202, response.getStatus()); assertTrue(response.getEntity() instanceof VM); verifyModel((VM)response.getEntity(), 0); VM created = (VM)response.getEntity(); assertNotNull(created.getCreationStatus()); assertEquals(creationStatus.value(), created.getCreationStatus().getState()); }
Source:
public void testReplicaCleanup() throws Exception { ZKWatcher zkw = TEST_UTIL.getZooKeeperWatcher(); List<String> metaReplicaZnodes = zkw.getMetaReplicaNodes(); assertEquals(metaReplicaZnodes.size(), 3); final HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster(); master.stop("Restarting"); TEST_UTIL.waitFor(30000, () -> master.isStopped()); TEST_UTIL.getMiniHBaseCluster().getConfiguration().setInt(HConstants.META_REPLICAS_NUM, 1); JVMClusterUtil.MasterThread newMasterThread = TEST_UTIL.getMiniHBaseCluster().startMaster(); final HMaster newMaster = newMasterThread.getMaster(); TEST_UTIL.waitFor(30000, () -> newMaster.getMasterQuotaManager() != null); zkw = TEST_UTIL.getZooKeeperWatcher(); metaReplicaZnodes = zkw.getMetaReplicaNodes(); assertEquals(metaReplicaZnodes.size(), 1); }

Target:
public void testReplicaCleanup() throws Exception { ZKWatcher zkw = TEST_UTIL.getZooKeeperWatcher(); List<String> metaReplicaZnodes = zkw.getMetaReplicaNodes(); assertEquals(3, metaReplicaZnodes.size()); final HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster(); master.stop("Restarting"); TEST_UTIL.waitFor(30000, () -> master.isStopped()); TEST_UTIL.getMiniHBaseCluster().getConfiguration().setInt(HConstants.META_REPLICAS_NUM, 1); JVMClusterUtil.MasterThread newMasterThread = TEST_UTIL.getMiniHBaseCluster().startMaster(); final HMaster newMaster = newMasterThread.getMaster(); TEST_UTIL.waitFor(30000, () -> newMaster.getMasterQuotaManager() != null); zkw = TEST_UTIL.getZooKeeperWatcher(); metaReplicaZnodes = zkw.getMetaReplicaNodes(); assertEquals(1, metaReplicaZnodes.size()); }
Source:
public GameUserDetails(GameUserBean gameUserBean, int detailsRequesterId) { this.id = gameUserBean.getGameUserId(); this.user = new UserDetails(gameUserBean.getUser()); this.colorId = gameUserBean.getColorId(); this.ready = gameUserBean.isReady(); this.moveOrder = gameUserBean.getMoveOrder(); this.achievements = new AchievementsDetails(gameUserBean.getAchievements()); if (user.getId() == detailsRequesterId) { this.availableActions = GSON.fromJson(gameUserBean.getAvailableActions(), AllAvailableActionsDetails.class); this.resources = new ResourcesDetails(gameUserBean.getResources()); this.developmentCards = new DevelopmentCardsDetails(gameUserBean.getDevelopmentCards()); } }

Target:
public GameUserDetails(GameUserBean gameUserBean, int detailsRequesterId) { this.id = gameUserBean.getGameUserId(); this.user = new UserDetails(gameUserBean.getUser()); this.colorId = gameUserBean.getColorId(); this.ready = gameUserBean.isReady(); this.moveOrder = gameUserBean.getMoveOrder(); this.achievements = new AchievementsDetails(gameUserBean.getAchievements()); if (user.getId() == detailsRequesterId) { this.availableActions = GSON.fromJson(gameUserBean.getAvailableActions(), AvailableActionsDetails.class); this.resources = new ResourcesDetails(gameUserBean.getResources()); this.developmentCards = new DevelopmentCardsDetails(gameUserBean.getDevelopmentCards()); } }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (item.getClass() == SwitchItem.class) { return; } else if (item.getClass() == ContactItem.class) { return; } else if (item.getClass() == NumberItem.class) { return; } else { logger.debug( "Item '{}' is of type '{}'. Please make sure that transformation is " + "inplace to convert to polled data to a format understood " + "by the item. Furthermore, make sure that commands are converted to " + "DecimalType or any command accepted by Switch, Contact or Number items.", item.getName(), item.getClass().getSimpleName()); } }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (item.getClass() == SwitchItem.class) { return; } else if (item.getClass() == ContactItem.class) { return; } else if (item.getClass() == NumberItem.class) { return; } else { logger.debug( "Item '{}' is of type '{}'. Please make sure that transformation is " + "in place to convert the polled data to a format understood " + "by the item. Furthermore, make sure that commands are converted to " + "DecimalType or any command accepted by Switch, Contact or Number items.", item.getName(), item.getClass().getSimpleName()); } }
Source:
public void refreshStereotypeCommentStructure() { if (comment != null) { removeUnappliedStereotypes(comment); } if (stereoList.size() != 0) { comment = createCommentNode(); for (Stereotype stereotype : stereoList) { refreshStereotypeCompartmentStructure(stereotype); refreshStereotypeBraceStructure(stereotype); } } }

Target:
public void refreshStereotypeCommentStructure() { if (comment != null) { removeUnappliedStereotypes(comment); } if (!stereotypeList.isEmpty()) { comment = createCommentNode(); for (Stereotype stereotype : stereotypeList) { refreshStereotypeCompartmentStructure(stereotype); refreshStereotypeBraceStructure(stereotype); } } }
Source:
Bundle findHighestAntVersion(ExportedPackage[] packages) { Bundle bundle = null; HashSet<Bundle> bundles = new HashSet<>(); for (ExportedPackage package1 : packages) { bundle = package1.getExportingBundle(); if (bundle == null) { continue; } if ("org.apache.ant".equals(bundle.getSymbolicName())) { bundles.add(bundle); } } Bundle highest = null; Bundle temp = null; for (Iterator<Bundle> iter = bundles.iterator(); iter.hasNext();) { temp = iter.next(); if (highest == null) { highest = temp; } else { if (highest.getVersion().compareTo(temp.getVersion()) < 0) { highest = temp; } } } return highest; }

Target:
Bundle findHighestAntVersion(ExportedPackage[] packages) { Bundle bundle = null; HashSet<Bundle> bundles = new HashSet<>(); for (ExportedPackage pckg : packages) { bundle = pckg.getExportingBundle(); if (bundle == null) { continue; } if ("org.apache.ant".equals(bundle.getSymbolicName())) { bundles.add(bundle); } } Bundle highest = null; Bundle temp = null; for (Iterator<Bundle> iter = bundles.iterator(); iter.hasNext();) { temp = iter.next(); if (highest == null) { highest = temp; } else { if (highest.getVersion().compareTo(temp.getVersion()) < 0) { highest = temp; } } } return highest; }
Source:
public void setDescent (int descent) { checkLayout(); if (descent < -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if (this.descent == descent) return; freeRuns(); this.descent = descent; }

Target:
public void setDescent (int descent) { checkLayout(); if (descent < -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); descent = DPIUtil.autoScaleUp(descent); if (this.descentInPixels == descent) return; freeRuns(); this.descentInPixels = descent; }
Source:
public void testFavorLocalCacheUseLocalRTSucceeds() throws PackageManager.NameNotFoundException, OperationCanceledException, IOException, AuthenticatorException, InterruptedException, NoSuchAlgorithmException { final Calendar expiredTime = new GregorianCalendar(); expiredTime.add(Calendar.MINUTE, -MINUS_MINUITE); final ITokenCacheStore cacheStore = getTokenCache(expiredTime.getTime(), false, false); final AccountManager mockedAccountManager = getMockedAccountManager(); mockAccountManagerGetAccountBehavior(mockedAccountManager); mockGetAuthTokenCall(mockedAccountManager, true); final FileMockContext mockContext = createMockContext(); mockContext.setMockedAccountManager(mockedAccountManager); prepareSuccessHttpUrlConnection(); prepareAuthForBrokerCall(); final AuthenticationContext authContext = new AuthenticationContext(mockContext, VALID_AUTHORITY, false, cacheStore); final TestAuthCallback callback = new TestAuthCallback(); authContext.acquireTokenSilentAsync("resource", "clientid", TEST_USERID, callback); final CountDownLatch signal = new CountDownLatch(1); signal.await(ACTIVITY_TIME_OUT, TimeUnit.MILLISECONDS); verify(mockedAccountManager, times(0)).getAuthToken(Mockito.any(Account.class), Matchers.anyString(), Matchers.any(Bundle.class), Matchers.eq(false), (AccountManagerCallback<Bundle>) Matchers.eq(null), Matchers.any(Handler.class)); assertNull(callback.getCallbackException()); assertNotNull(callback.getCallbackResult()); assertTrue(callback.getCallbackResult().getAccessToken().equals("I am a new access token")); assertTrue(cacheStore.getAll().hasNext()); cacheStore.removeAll(); }

Target:
public void testFavorLocalCacheUseLocalRTSucceeds() throws PackageManager.NameNotFoundException, OperationCanceledException, IOException, AuthenticatorException, InterruptedException { final ITokenCacheStore cacheStore = getTokenCache(getExpireDate(-MINUS_MINUITE), false, false, null); final AccountManager mockedAccountManager = getMockedAccountManager(); mockAccountManagerGetAccountBehavior(mockedAccountManager); mockGetAuthTokenCall(mockedAccountManager, true); final FileMockContext mockContext = createMockContext(); mockContext.setMockedAccountManager(mockedAccountManager); prepareSuccessHttpUrlConnection(); prepareAuthForBrokerCall(); final AuthenticationContext authContext = new AuthenticationContext(mockContext, VALID_AUTHORITY, false, cacheStore); final TestAuthCallback callback = new TestAuthCallback(); authContext.acquireTokenSilentAsync("resource", "clientid", TEST_USERID, callback); final CountDownLatch signal = new CountDownLatch(1); signal.await(ACTIVITY_TIME_OUT, TimeUnit.MILLISECONDS); verify(mockedAccountManager, times(0)).getAuthToken(Mockito.any(Account.class), Matchers.anyString(), Matchers.any(Bundle.class), Matchers.eq(false), (AccountManagerCallback<Bundle>) Matchers.eq(null), Matchers.any(Handler.class)); assertNull(callback.getCallbackException()); assertNotNull(callback.getCallbackResult()); assertTrue(callback.getCallbackResult().getAccessToken().equals("I am a new access token")); assertTrue(cacheStore.getAll().hasNext()); cacheStore.removeAll(); }
Source:
public Descriptor getDefaultYamlMergeStrategy() { Jenkins jenkins = Jenkins.getInstanceOrNull(); if (jenkins == null) { return null; } return jenkins.getDescriptor(YamlMergeStrategy.defaultStrategy().getClass()); }

Target:
public YamlMergeStrategy getDefaultYamlMergeStrategy() { return YamlMergeStrategy.defaultStrategy(); }