auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Unit<Length> lookup( final String name ) { if (!name.equals(name.toLowerCase())) { return lookup(name.toLowerCase()); } Unit<Length> unit = lookup( SI.class, name); if (unit != null) { return unit; } unit = lookup( NonSI.class, name); if (unit != null) { return unit; } if (name.endsWith("s")) { return lookup(name.substring( 0, name.length() - 1)); } if (name.toLowerCase().startsWith( "kilo") && (name.length() > 4)) { Unit<Length> u = lookup(name.substring(4)); if (u != null) { return u.multiply(1000); } } if (name.equalsIgnoreCase("feet")) { return USCustomary.FOOT; } if (name.equalsIgnoreCase("meter")) { return SI.METRE; } if (name.equalsIgnoreCase("unity")) { return (Unit) AbstractUnit.ONE; } return null; }

Target:
public static Unit<Length> lookup( final String name ) { String lowerCaseName = name.toLowerCase(); Unit<Length> unit = lookup( SI.class, lowerCaseName); if (unit != null) { return unit; } unit = lookup( NonSI.class, lowerCaseName); if (unit != null) { return unit; } if (lowerCaseName.endsWith("s")) { return lookup(lowerCaseName.substring( 0, lowerCaseName.length() - 1)); } if (lowerCaseName.startsWith("kilo") && (lowerCaseName.length() > 4)) { Unit<Length> u = lookup(lowerCaseName.substring(4)); if (u != null) { return u.multiply(1000); } } if (lowerCaseName.equals("feet")) { return USCustomary.FOOT; } if (lowerCaseName.equals("meter")) { return SI.METRE; } if (lowerCaseName.equals("unity")) { return (Unit) AbstractUnit.ONE; } return null; }
Source:
protected void triggerShutdown() { latch.countDown(); super.triggerShutdown(); }

Target:
protected void triggerShutdown() { latch.countDown(); }
Source:
public static void viewBlogPlans(Context context, int blogLocalTableId) { Intent intent = new Intent(context, PlansActivity.class); intent.putExtra(PlansActivity.ARG_LOCAL_TABLE_BLOG_ID, blogLocalTableId); slideInFromRight(context, intent); AnalyticsUtils.trackWithCurrentBlogDetails(AnalyticsTracker.Stat.OPENED_PLANS); }

Target:
public static void viewBlogPlans(Context context, int blogLocalTableId) { Intent intent = new Intent(context, PlansActivity.class); intent.putExtra(PlansActivity.ARG_LOCAL_TABLE_BLOG_ID, blogLocalTableId); slideInFromRight(context, intent); AnalyticsUtils.trackWithBlogDetails(AnalyticsTracker.Stat.OPENED_PLANS, WordPress.getBlog(blogLocalTableId)); }
Source:
public static Long toTimeMicros(String seconds, String microseconds) { return NumberUtils.parseNumber(seconds, Long.class) * 1000 * 1000L + NumberUtils.parseNumber(microseconds, Long.class); }

Target:
public static Long toTimeMicros(String seconds, String microseconds) { return TimeUnit.SECONDS.toMicros(NumberUtils.parseNumber(seconds, Long.class)) + NumberUtils.parseNumber(microseconds, Long.class); }
Source:
public UserAgentInterceptor(String userAgent) { this.userAgent = userAgent; }

Target:
private UserAgentInterceptor(String userAgent) { checkArgument(VALID_USER_AGENT.matcher(userAgent).matches(), "User Agent must match pattern '%s': %s", VALID_USER_AGENT, userAgent); this.userAgent = userAgent; }
Source:
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { progress.begin("Loading SKOS code list", ProgressIndicator.UNKNOWN); try { URI loc = getSource().getLocation(); InputStream in = getSource().getInput(); codelist = new SkosCodeList(in, loc); progress.setCurrentTask("Code list loaded."); } catch (Exception ex) { throw new RuntimeException(ex); } reporter.setSuccess(true); return reporter; }

Target:
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { progress.begin("Loading SKOS code list", ProgressIndicator.UNKNOWN); try { URI loc = getSource().getLocation(); InputStream in = getSource().getInput(); codelist = new SkosCodeList(in, loc); progress.setCurrentTask("Code list loaded."); reporter.setSuccess(true); } catch (Exception ex) { reporter.error(new IOMessageImpl("Error in loading skos code list", ex)); reporter.setSuccess(false); } return reporter; }
Source:
public void testServerShouldTerminateConnectionIdleForTooLong() throws InterruptedException { int inactivityTime = 3; int concurrentConnections = 10; final Random random = new Random(); final CountDownLatch latch = new CountDownLatch(concurrentConnections); final Server server = new Server(host, randomPort, inactivityTime); final AtomicBoolean otherCause = new AtomicBoolean(false); server.setMessageListener(new MessageListener() { public void onNewConnection(ChannelHandlerContext ctx) { if (random.nextInt(10) < 1) { throw new RuntimeException("Dummy"); } } @Override public void onConnectionClose(ChannelHandlerContext ctx) { latch.countDown(); } @Override public void onNewMessage(ChannelHandlerContext ctx, Message message) { if (random.nextInt(10) < 1) { throw new RuntimeException("Dummy"); } } @Override public void onException(ChannelHandlerContext ctx, Throwable cause) { if (!"Dummy".equals(cause.getMessage())) { otherCause.set(true); } } }); Runnable serverTask = new Runnable() { @Override public void run() { try { server.listen(); } catch (InterruptedException e) { } } }; Thread thread = new Thread(serverTask); thread.start(); sleep(1000); try { Long started = System.currentTimeMillis() / 1000L; for (int i = 0; i < concurrentConnections; i++) { connectClient(); } latch.await(10, TimeUnit.SECONDS); Long ended = System.currentTimeMillis() / 1000L; double diff = ended - started; assertThat(diff, is(closeTo(inactivityTime, 0.1))); assertThat(otherCause.get(), is(false)); } finally { server.stop(); } }

Target:
public void testServerShouldTerminateConnectionIdleForTooLong() throws InterruptedException { int inactivityTime = 3; int concurrentConnections = 10; final Random random = new Random(); final CountDownLatch latch = new CountDownLatch(concurrentConnections); final AtomicBoolean exceptionClose = new AtomicBoolean(false); final Server server = new Server(host, randomPort, inactivityTime); server.setMessageListener(new MessageListener() { @Override public void onNewConnection(ChannelHandlerContext ctx) { } @Override public void onConnectionClose(ChannelHandlerContext ctx) { latch.countDown(); } @Override public void onNewMessage(ChannelHandlerContext ctx, Message message) { } @Override public void onException(ChannelHandlerContext ctx, Throwable cause) { exceptionClose.set(true); } }); Runnable serverTask = new Runnable() { @Override public void run() { try { server.listen(); } catch (InterruptedException e) { } } }; Thread thread = new Thread(serverTask); thread.start(); sleep(1000); try { Long started = System.currentTimeMillis() / 1000L; for (int i = 0; i < concurrentConnections; i++) { connectClient(); } assertThat(latch.await(10, TimeUnit.SECONDS), is(true)); Long ended = System.currentTimeMillis() / 1000L; double diff = ended - started; assertThat(diff, is(closeTo(inactivityTime, 0.1))); assertThat(exceptionClose.get(), is(false)); } finally { server.stop(); } }
Source:
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { if (keyPropertiesPerBean.containsKey(mbeanName)) { return keyPropertiesPerBean.get(mbeanName); } LinkedHashMap<String, String> keyProperties = new LinkedHashMap<String, String>(); String properties = mbeanName.getKeyPropertyListString(); Matcher match = PROPERTY_PATTERN.matcher(properties); while (match.lookingAt()) { keyProperties.put(match.group(1), match.group(2)); properties = properties.substring(match.end()); if (properties.startsWith(",")) { properties = properties.substring(1); } match.reset(properties); } keyPropertiesPerBean.put(mbeanName, keyProperties); return keyProperties; }

Target:
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName); if (keyProperties == null) { keyProperties = new LinkedHashMap<String, String>(); String properties = mbeanName.getKeyPropertyListString(); Matcher match = PROPERTY_PATTERN.matcher(properties); while (match.lookingAt()) { keyProperties.put(match.group(1), match.group(2)); properties = properties.substring(match.end()); if (properties.startsWith(",")) { properties = properties.substring(1); } match.reset(properties); } keyPropertiesPerBean.put(mbeanName, keyProperties); } return keyProperties; }
Source:
private EventExecutorGroup createEventExecutorGroup(int size, long keepAliveSecs) { if (size <= 0) { return ImmediateEventExecutor.INSTANCE; } ThreadFactory threadFactory = new ThreadFactory() { private final ThreadGroup threadGroup = new ThreadGroup(serviceName + "-executor-thread"); private final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(threadGroup, r, String.format("%s-executor-%d", serviceName, count.getAndIncrement())); t.setDaemon(true); return t; } }; Executor executor = new ThreadPoolExecutor(0, size, keepAliveSecs, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); return new MultithreadEventExecutorGroup(size, executor, DEFAULT_MAX_PENDING_EXECUTOR_TASKS, rejectedExecutionHandler) { @Override protected EventExecutor newChild(Executor executor, Object... args) throws Exception { return new DefaultEventExecutor(this, executor, (Integer) args[0], (RejectedExecutionHandler) args[1]); } }; }

Target:
private EventExecutorGroup createEventExecutorGroup(int size, long keepAliveSecs) { if (size <= 0) { return null; } ThreadFactory threadFactory = new ThreadFactory() { private final ThreadGroup threadGroup = new ThreadGroup(serviceName + "-executor-thread"); private final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(threadGroup, r, String.format("%s-executor-%d", serviceName, count.getAndIncrement())); t.setDaemon(true); return t; } }; Executor executor = new ThreadPoolExecutor(0, size, keepAliveSecs, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); return new MultithreadEventExecutorGroup(size, executor, DEFAULT_MAX_PENDING_EXECUTOR_TASKS, rejectedExecutionHandler) { @Override protected EventExecutor newChild(Executor executor, Object... args) throws Exception { return new DefaultEventExecutor(this, executor, (Integer) args[0], (RejectedExecutionHandler) args[1]); } }; }
Source:
public static Path getApexDFSRootDir(FileSystem fs, Configuration conf) { boolean useImpersonated = conf.getBoolean(StramUserLogin.DT_APP_PATH_IMPERSONATED, false); String userShortName = null; if (useImpersonated) { try { userShortName = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException ex) { LOG.warn("Error getting current/login user name in getApexDFSRootDir", ex); } } if (!useImpersonated || userShortName == null) { return getDTDFSRootDir(fs, conf); } return evalDFSRootDir(fs, conf, APEX_APP_DFS_ROOT_DIR, userShortName, true, false); }

Target:
public static Path getApexDFSRootDir(FileSystem fs, Configuration conf) { boolean useImpersonated = conf.getBoolean(StramUserLogin.DT_APP_PATH_IMPERSONATED, false); String userShortName = null; if (useImpersonated) { try { userShortName = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException ex) { LOG.warn("Error getting current/login user name", ex); } } if (!useImpersonated || userShortName == null) { return getDTDFSRootDir(fs, conf); } return evalDFSRootDir(fs, conf, APEX_APP_DFS_ROOT_DIR, userShortName, true, false); }
Source:
public ConfigBuilder writeTo(View<?> view) { if (view instanceof Dataset && view instanceof FileSystemDataset) { FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return writeTo(view.getUri()); }

Target:
public ConfigBuilder writeTo(View<?> view) { if (view instanceof FileSystemDataset) { FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return writeTo(view.getUri()); }
Source:
abstract JsonParser createParser(Object obj) throws IOException; private boolean findAttribute(JsonParser parser, String path) throws IOException { JsonToken token = parser.getCurrentToken(); if (token != JsonToken.START_OBJECT) { return false; } parser.getCurrentToken(); while (true) { token = parser.nextToken(); if (token == JsonToken.END_OBJECT) { return false; } if (path.equals(parser.getCurrentName())) { parser.nextToken(); return true; } else { parser.nextToken(); parser.skipChildren(); } } }

Target:
abstract JsonParser createParser(Object obj) throws IOException; private boolean findAttribute(JsonParser parser, String path) throws IOException { JsonToken token = parser.getCurrentToken(); if (token != JsonToken.START_OBJECT) { return false; } while (true) { token = parser.nextToken(); if (token == JsonToken.END_OBJECT) { return false; } if (path.equals(parser.getCurrentName())) { parser.nextToken(); return true; } else { parser.nextToken(); parser.skipChildren(); } } }
Source:
public static org.ovirt.engine.core.common.job.Job map(Job job, org.ovirt.engine.core.common.job.Job entity) { org.ovirt.engine.core.common.job.Job target = entity != null ? entity : new org.ovirt.engine.core.common.job.Job(); target.setId(new Guid(job.getId())); if (job.isSetDescription()) { target.setDescription(job.getDescription()); } if (job.isSetStatus()) { target.setStatus(map(job.getStatus(), null)); } if (job.isSetOwner()) { target.setOwnerId(new Guid(job.getOwner().getId())); } target.setStartTime(job.isSetStartTime() ? job.getStartTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setEndTime(job.isSetEndTime() ? job.getEndTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setLastUpdateTime(job.isSetLastUpdated() ? job.getLastUpdated().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setExternal(job.isSetExternal() ? job.isExternal() : true); target.setAutoCleared(job.isSetAutoCleared() ? job.isAutoCleared() : true); return target; }

Target:
public static org.ovirt.engine.core.common.job.Job map(Job job, org.ovirt.engine.core.common.job.Job entity) { org.ovirt.engine.core.common.job.Job target = entity != null ? entity : new org.ovirt.engine.core.common.job.Job(); target.setId(GuidUtils.asGuid(job.getId())); if (job.isSetDescription()) { target.setDescription(job.getDescription()); } if (job.isSetStatus()) { target.setStatus(map(job.getStatus(), null)); } if (job.isSetOwner()) { target.setOwnerId(GuidUtils.asGuid(job.getOwner().getId())); } target.setStartTime(job.isSetStartTime() ? job.getStartTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setEndTime(job.isSetEndTime() ? job.getEndTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setLastUpdateTime(job.isSetLastUpdated() ? job.getLastUpdated().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setExternal(job.isSetExternal() ? job.isExternal() : true); target.setAutoCleared(job.isSetAutoCleared() ? job.isAutoCleared() : true); return target; }
Source:
public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Builder spanBuilder = getSpanBuilder(spanName, context); Span span = spanBuilder.startSpan(); if (span.isRecording()) { span.setAttribute(AZ_NAMESPACE_KEY, AttributeValue.stringAttributeValue(HttpTraceUtil.parseNamespaceProvider(spanName))); } return context.addData(PARENT_SPAN_KEY, span); }

Target:
public Context start(String spanName, Context context) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Builder spanBuilder = getSpanBuilder(spanName, context); Span span = spanBuilder.startSpan(); if (span.isRecording()) { String tracingNamespace = getOrDefault(context, AZ_TRACING_NAMESPACE_KEY, null, String.class); if (tracingNamespace != null) { span.setAttribute(AZ_NAMESPACE_KEY, AttributeValue.stringAttributeValue(tracingNamespace)); } } return context.addData(PARENT_SPAN_KEY, span); }
Source:
public void onCompletion(GetBlobResult result, Exception exception) { try { restResponseChannel.setHeader(RestUtils.Headers.DATE, new GregorianCalendar().getTime()); if (exception == null && result != null) { setResponseHeaders(result.getBlobInfo()); mockBlobStorageService.handleResponse(restRequest, restResponseChannel, result.getBlobDataChannel(), null); } else { if (exception != null && exception instanceof RouterException) { exception = new RestServiceException(exception, RestServiceErrorCode.getRestServiceErrorCode(((RouterException) exception).getErrorCode())); } mockBlobStorageService.handleResponse(restRequest, restResponseChannel, null, exception); } } catch (Exception e) { exception = exception == null ? e : exception; if (result != null && result.getBlobDataChannel() != null) { try { result.getBlobDataChannel().close(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } mockBlobStorageService.handleResponse(restRequest, restResponseChannel, null, exception); } }

Target:
public void onCompletion(GetBlobResult result, Exception exception) { try { restResponseChannel.setHeader(RestUtils.Headers.DATE, new GregorianCalendar().getTime()); if (exception == null && result != null) { setResponseHeaders(result.getBlobInfo()); } else if (exception != null && exception instanceof RouterException) { exception = new RestServiceException(exception, RestServiceErrorCode.getRestServiceErrorCode(((RouterException) exception).getErrorCode())); } } catch (Exception e) { exception = exception == null ? e : exception; } finally { ReadableStreamChannel channel = result != null ? result.getBlobDataChannel() : null; mockBlobStorageService.handleResponse(restRequest, restResponseChannel, channel, exception); } }
Source:
public static byte[] parseHexBytes(Map<String, ?> map, String key) { Object v = map.get(key); if (v == null) { return null; } String s = (String)v; try { int length = s.length(); byte[] data = new byte[length / 2]; for(int i = 0; i < length; i += 2) { data[i / 2] = (byte)((hexValueOf(s.charAt(i)) << 4) | hexValueOf(s.charAt(i + 1))); } return data; } catch (NumberFormatException e) { throw newIllegalStateException(ERROR_FILE_CORRUPT, "Error parsing the value {0}", v, e); } }

Target:
public static byte[] parseHexBytes(Map<String, ?> map, String key) { Object v = map.get(key); if (v == null) { return null; } return StringUtils.convertHexToBytes((String)v); }
Source:
private Integer eightBitUnsignedAtOffset(byte[] c, int offset) { Integer lowerByte = c[offset] & 0xFF; return lowerByte; }

Target:
private Integer eightBitUnsignedAtOffset(byte[] c, int offset) { return c[offset] & 0xFF; }
Source:
public void should_fail_if_neither_name_nor_version_is_changed() throws Exception { final MustUpdateValidator mustUpdateValidator = new MustUpdateValidator(aPool().withName("Pool").withVersion("1.0").build(), new WritableValue("Pool", String.class), new WritableValue("1.0", String.class)); final IStatus status = mustUpdateValidator.validate(); StatusAssert.assertThat(status).isNotOK(); }

Target:
public void should_fail_if_neither_name_nor_version_is_changed() throws Exception { final MustUpdateValidator mustUpdateValidator = new MustUpdateValidator(aPool().withName("Pool").withVersion("1.0").build(), new WritableValue("Pool", String.class), new WritableValue("1.0", String.class)); final IStatus status = mustUpdateValidator.validate(); assertThat(status).isNotOK(); }
Source:
private URI getSolrUri(List<NameValuePair> params) { URI uri; try { uri = new URL(runtimeConfiguration.getSolrServer(), "?" + URLEncodedUtils.format(params, "UTF-8")).toURI(); } catch (IllegalStateException | MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException("Solr server URI is null or malformed", e); } return uri; }

Target:
private URI getSolrUri(List<NameValuePair> params) throws SolrUndefinedException { try { URL solrServer = runtimeConfiguration.getSolrServer() .orElseThrow(() -> new SolrUndefinedException("Solr server URI must be defined " + "in wombat.yaml in order to use solr features such as search, RSS, or " + "listing recent articles on the homepage.")); return new URL(solrServer, "?" + URLEncodedUtils.format(params, "UTF-8")).toURI(); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
void scan(String prefix) { if (ALL.equals(prefix)) { scanOne(HEAD); scanOne(Constants.FETCH_HEAD); scanOne(Constants.MERGE_HEAD); scanTree(R_REFS, refsDir); if (newLoose == null && curIdx < curLoose.size()) newLoose = curLoose.copy(curIdx); } else if (prefix.startsWith(R_REFS) && prefix.endsWith("/")) { curIdx = -(curLoose.find(prefix) + 1); File dir = new File(refsDir, prefix.substring(R_REFS.length())); scanTree(prefix, dir); while (curIdx < curLoose.size()) { if (!curLoose.get(curIdx).getName().startsWith(prefix)) break; if (newLoose == null) newLoose = curLoose.copy(curIdx); curIdx++; } if (newLoose != null) { while (curIdx < curLoose.size()) newLoose.add(curLoose.get(curIdx++)); } } }

Target:
void scan(String prefix) { if (ALL.equals(prefix)) { scanOne(HEAD); scanTree(R_REFS, refsDir); if (newLoose == null && curIdx < curLoose.size()) newLoose = curLoose.copy(curIdx); } else if (prefix.startsWith(R_REFS) && prefix.endsWith("/")) { curIdx = -(curLoose.find(prefix) + 1); File dir = new File(refsDir, prefix.substring(R_REFS.length())); scanTree(prefix, dir); while (curIdx < curLoose.size()) { if (!curLoose.get(curIdx).getName().startsWith(prefix)) break; if (newLoose == null) newLoose = curLoose.copy(curIdx); curIdx++; } if (newLoose != null) { while (curIdx < curLoose.size()) newLoose.add(curLoose.get(curIdx++)); } } }
Source:
public List<VmCheckpoint> getAllForVm(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vm_id", id); List<VmCheckpoint> checkpoints = getCallsHandler().executeReadList("GetVmCheckpointsByVmId", vmCheckpointRowMapper, parameterSource); checkpoints.stream().sorted((o1, o2) -> { if (o1.getId() == o2.getId()) { return 0; } return o2.getParentId().equals(o1.getId()) ? -1 : 1; }); return checkpoints; }

Target:
public List<VmCheckpoint> getAllForVm(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vm_id", id); return getCallsHandler().executeReadList("GetVmCheckpointsByVmId", vmCheckpointRowMapper, parameterSource); }
Source:
public StreamClient getStreamClient() { String host = getRequiredProperty(this.key + "host"); int port = Integer.parseInt(getRequiredProperty(this.key + "port")); Boolean ssl = Boolean.valueOf(getProperty(this.key + "ssl", DEFAULT_SSL)); RestStreamClient.Builder builder = RestStreamClient.builder(host, port).ssl(ssl); String authClientClassPath = getProperty(this.key + "auth_client", DEFAULT_AUTH_CLIENT); String authClientPropertiesPath = getProperty(this.key + "auth_client_properties", DEFAULT_AUTH_CLIENT_PROPERTIES); try { AuthenticationClient authClient = (AuthenticationClient) Class.forName(authClientClassPath).getConstructor().newInstance(); authClient.setConnectionInfo(host, port, ssl); authClient.configure(new ConfigurationLoaderImpl().load(new File(authClientPropertiesPath)).getProperties()); builder.authClient(authClient); } catch (ReflectiveOperationException e) { LOG.error("Can not resolve class {}: {}", authClientClassPath, e.getMessage()); } catch (ConfigurationLoadingException e) { LOG.error("Can not load Authentication Client properties file {}: {}", authClientPropertiesPath, e.getMessage()); } String apiKey = getProperty(this.key + "apiKey"); if (apiKey != null && !apiKey.equals("")) { builder.apiKey(apiKey); } builder.writerPoolSize(Integer.parseInt(getProperty(this.key + "writerPoolSize", DEFAULT_WRITER_POOL_SIZE))); builder.version(getProperty(this.key + "version", DEFAULT_VERSION)); return builder.build(); }

Target:
public StreamClient getStreamClient() { String host = getRequiredProperty(this.key + "host"); int port = Integer.parseInt(getRequiredProperty(this.key + "port")); boolean ssl = Boolean.valueOf(getProperty(this.key + "ssl", DEFAULT_SSL)); RestStreamClient.Builder builder = RestStreamClient.builder(host, port).ssl(ssl); String authClientClassPath = getProperty(this.key + "auth_client", DEFAULT_AUTH_CLIENT); String authClientPropertiesPath = getProperty(this.key + "auth_client_properties", DEFAULT_AUTH_CLIENT_PROPERTIES); try { AuthenticationClient authClient = (AuthenticationClient) Class.forName(authClientClassPath).getConstructor().newInstance(); authClient.setConnectionInfo(host, port, ssl); authClient.configure(new ConfigurationLoaderImpl().load(new File(authClientPropertiesPath)).getProperties()); builder.authClient(authClient); } catch (ReflectiveOperationException e) { LOG.error("Can not resolve class {}: {}", authClientClassPath, e.getMessage(), e); } catch (ConfigurationLoadingException e) { LOG.error("Can not load Authentication Client properties file {}: {}", authClientPropertiesPath, e.getMessage(), e); } String apiKey = getProperty(this.key + "apiKey"); if (apiKey != null && !apiKey.equals("")) { builder.apiKey(apiKey); } builder.writerPoolSize(Integer.parseInt(getProperty(this.key + "writerPoolSize", DEFAULT_WRITER_POOL_SIZE))); builder.version(getProperty(this.key + "version", DEFAULT_VERSION)); return builder.build(); }
Source:
private CompletionStage<RestResponse> removeCache(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder().status(NO_CONTENT); String cacheName = request.variables().get("cacheName"); RestCacheManager<Object> restCacheManager = invocationHelper.getRestCacheManager(); Cache<?, ?> cache = restCacheManager.getCache(cacheName, request); if (cache == null) { responseBuilder.status(HttpResponseStatus.NOT_FOUND); return CompletableFuture.completedFuture(responseBuilder.build()); } return CompletableFuture.supplyAsync(() -> { Subject.doAs(request.getSubject(), (PrivilegedAction<Void>) () -> { restCacheManager.getCacheManagerAdmin(request).removeCache(cacheName); return null; }); responseBuilder.status(OK); return responseBuilder.build(); }, invocationHelper.getExecutor()); }

Target:
private CompletionStage<RestResponse> removeCache(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder().status(NO_CONTENT); String cacheName = request.variables().get("cacheName"); RestCacheManager<Object> restCacheManager = invocationHelper.getRestCacheManager(); Cache<?, ?> cache = restCacheManager.getCache(cacheName, request); if (cache == null) { responseBuilder.status(HttpResponseStatus.NOT_FOUND); return CompletableFuture.completedFuture(responseBuilder.build()); } return CompletableFuture.supplyAsync(() -> { restCacheManager.getCacheManagerAdmin(request).removeCache(cacheName); responseBuilder.status(OK); return responseBuilder.build(); }, invocationHelper.getExecutor()); }
Source:
protected Server createServer(String serverName) { List<Hdd.CreateHdd> hdds = new ArrayList<Hdd.CreateHdd>(); Hdd.CreateHdd hdd = Hdd.CreateHdd.create(30, Boolean.TRUE); hdds.add(hdd); Hardware.CreateHardware hardware = Hardware.CreateHardware.create(4.0, 1.0, 2.0, hdds); return api.serverApi().create(Server.CreateServer.create(serverName, "testing with jclouds", hardware, "81504C620D98BCEBAA5202D145203B4B", "908DC2072407C94C8054610AD5A53B8C", "Test123!", null, Boolean.TRUE, null, null, null, null) ); }

Target:
protected Server createServer(String serverName) { List<Hdd.CreateHdd> hdds = new ArrayList<Hdd.CreateHdd>(); Hdd.CreateHdd hdd = Hdd.CreateHdd.create(30, Boolean.TRUE); hdds.add(hdd); Hardware.CreateHardware hardware = Hardware.CreateHardware.create(4.0, 1.0, 2.0, hdds); return api.serverApi().create(Server.CreateServer.builder() .name(serverName) .description("testing with jclouds") .hardware(hardware) .applianceId("81504C620D98BCEBAA5202D145203B4B") .dataCenterId("908DC2072407C94C8054610AD5A53B8C") .password("Test123!") .powerOn(Boolean.TRUE).build()); }
Source:
public void testRunStarted(Description description){ Log.i("run started", description.getDisplayName()); }

Target:
public void testRunStarted(Description description){ Log.i("Run started", description.getDisplayName()); }
Source:
public static void setSelector(Service target, String key, String value) { ServiceSpec spec = target.getSpec(); if (spec == null) { target.setSpec(spec = new ServiceSpec()); } HashMap<String, String> selector = new HashMap<>(); selector.put(key, value); spec.setSelector(selector); }

Target:
public static void setSelector(Service target, String key, String value) { ServiceSpec spec = target.getSpec(); if (spec == null) { spec = new ServiceSpec(); target.setSpec(spec); } HashMap<String, String> selector = new HashMap<>(); selector.put(key, value); spec.setSelector(selector); }
Source:
public TokenStream testBadSetup() throws IOException { Tokenizer tok = new StandardTokenizer(); TokenStream ts = new StopFilter(tok, FrenchAnalyzer.getDefaultStopSet()); ts = new ASCIIFoldingFilter(ts, false); ts = new PreserveOriginalFilter(ts); return ts; }

Target:
public void testBadSetup() throws IOException { try (Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tok = new StandardTokenizer(); TokenStream ts = new StopFilter(tok, FrenchAnalyzer.getDefaultStopSet()); ts = new ASCIIFoldingFilter(ts, false); ts = new PreserveOriginalFilter(ts); return new TokenStreamComponents(tok, ts); } }) { a.tokenStream("", ""); } }
Source:
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { if (ex instanceof IllegalArgumentException) { return handleIllegalArgument((IllegalArgumentException) ex, request, response, handler); } else if (ex instanceof ValidationException) { return handleValidation((ValidationException) ex, request, response, handler); } else if (ex instanceof NotFoundException) { return handleNotFound((NotFoundException) ex, request, response, handler); } else if (ex instanceof NotImplementedException) { return handleNotImplemented((NotImplementedException) ex, request, response, handler); } } catch (Exception handlerException) { logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException); } return null; }

Target:
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { if (ex instanceof IllegalArgumentException) { return handleIllegalArgument((IllegalArgumentException) ex, request, response, handler); } else if (ex instanceof ValidationException) { return handleValidation((ValidationException) ex, request, response, handler); } else if (ex instanceof NotFoundException) { return handleNotFound((NotFoundException) ex, request, response, handler); } else if (ex instanceof NotImplementedException) { return handleNotImplemented((NotImplementedException) ex, request, response, handler); } } catch (Exception handlerException) { logger.error("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException); } return null; }
Source:
public void transform(StructuredRecord input, Emitter<KeyValue<NullWritable, OrcStruct>> emitter) throws Exception { StringBuilder builder = new StringBuilder(); HiveSchemaConverter.appendType(builder, input.getSchema()); TypeDescription schema = TypeDescription.fromString(builder.toString()); OrcStruct pair = (OrcStruct) OrcStruct.createValue(schema); List<Schema.Field> fields = input.getSchema().getFields(); for (int i = 0; i < fields.size(); i++) { String fieldval = input.get(fields.get(i).getName()); pair.setFieldValue(fields.get(i).getName(), new Text(fieldval)); } emitter.emit(new KeyValue<NullWritable, OrcStruct>(NullWritable.get(), pair)); }

Target:
public void transform(StructuredRecord input, Emitter<KeyValue<NullWritable, OrcStruct>> emitter) throws Exception { emitter.emit(new KeyValue<>(NullWritable.get(), recordTransformer.transform(input, input.getSchema()))); }
Source:
public String extractContentAsDocument(String version, String destination, String soapAction, String soapMessage) throws SOAPException, TransformerException, ParserConfigurationException, FileNotFoundException, UnsupportedEncodingException { MessageFactory messageFactory = null; if (version.equals(SOAP12)) { messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); } else { messageFactory = MessageFactory.newInstance(); } SOAPMessage message = messageFactory.createMessage(); MimeHeaders mimeHeaders = message.getMimeHeaders(); if (SOAP12.equals(version)) { mimeHeaders.addHeader("Content-Type", "application/soap+_xml; charset=utf-8; action=\"" + soapAction+"\""); } else { mimeHeaders.setHeader("SOAPAction", soapAction); } SOAPPart soapPart = message.getSOAPPart(); String encoding = getEncoding(soapMessage); ByteArrayInputStream stream = new ByteArrayInputStream(soapMessage.getBytes(encoding)); StreamSource preppedMsgSrc = new StreamSource(stream); soapPart.setContent(preppedMsgSrc); message.saveChanges(); SOAPMessage reply = connection.call(message, destination); SOAPPart reSoapPart = reply.getSOAPPart(); if (reSoapPart != null && reSoapPart instanceof SOAPPartImpl) { ((SOAPPartImpl) reSoapPart).setSourceCharsetEncoding(encoding); } try { TransformerFactory tf = TransformerFactory.newInstance(); tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); Transformer t = tf.newTransformer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform(reSoapPart.getContent(), new StreamResult(bos)); return bos.toString(encoding); } catch (Exception e) { e.printStackTrace(); return null; } }

Target:
public String extractContentAsDocument(String version, String destination, String soapAction, String soapMessage) throws SOAPException, TransformerException, ParserConfigurationException, FileNotFoundException, UnsupportedEncodingException { MessageFactory messageFactory = null; if (version.equals(SOAP12)) { messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); } else { messageFactory = MessageFactory.newInstance(); } SOAPMessage message = messageFactory.createMessage(); MimeHeaders mimeHeaders = message.getMimeHeaders(); setSoapAction(version, soapAction, mimeHeaders); SOAPPart soapPart = message.getSOAPPart(); String encoding = getEncoding(soapMessage); ByteArrayInputStream stream = new ByteArrayInputStream(soapMessage.getBytes(encoding)); StreamSource preppedMsgSrc = new StreamSource(stream); soapPart.setContent(preppedMsgSrc); message.saveChanges(); SOAPMessage reply = connection.call(message, destination); SOAPPart reSoapPart = reply.getSOAPPart(); if (reSoapPart != null && reSoapPart instanceof SOAPPartImpl) { ((SOAPPartImpl) reSoapPart).setSourceCharsetEncoding(encoding); } try { TransformerFactory tf = TransformerFactory.newInstance(); tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); Transformer t = tf.newTransformer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform(reSoapPart.getContent(), new StreamResult(bos)); return bos.toString(encoding); } catch (Exception e) { e.printStackTrace(); return null; } }
Source:
public void tearDown() { if (artifact != null) { artifact.purgeFromBranch(); } }

Target:
public void tearDown() { if (artifact != null) { artifact.delete(); } }
Source:
private void loadChecksAndTestEntries(final List<StudyEntryDto> studyEntryDtoList, final List<StudyEntryDto> checkList, final List<StudyEntryDto> testEntryList) { studyEntryDtoList.sort(Comparator.comparing(StudyEntryDto::getEntryNumber)); for (final StudyEntryDto studyEntryDto : studyEntryDtoList) { final Optional<String> entryType = studyEntryDto.getStudyEntryPropertyValue(TermId.ENTRY_TYPE.getId()); if (entryType.isPresent()) { if (SystemDefinedEntryType.TEST_ENTRY.getEntryTypeCategoricalId() == Integer.valueOf(entryType.get())) { testEntryList.add(studyEntryDto); } else { checkList.add(studyEntryDto); } } } }

Target:
void loadChecksAndTestEntries(final List<StudyEntryDto> studyEntryDtoList, final List<StudyEntryDto> checkList, final List<StudyEntryDto> testEntryList) { studyEntryDtoList.sort(Comparator.comparing(StudyEntryDto::getEntryNumber)); for (final StudyEntryDto studyEntryDto : studyEntryDtoList) { final Optional<String> entryType = studyEntryDto.getStudyEntryPropertyValue(TermId.ENTRY_TYPE.getId()); if (entryType.isPresent()) { if (SystemDefinedEntryType.TEST_ENTRY.getEntryTypeCategoricalId() == Integer.valueOf(entryType.get())) { testEntryList.add(studyEntryDto); } else { checkList.add(studyEntryDto); } } } }
Source:
public static <T> RunnableFuture<T> wrap(RunnableFuture<T> rf) { final Map<WeakReference<? extends ExecutorInheritableThreadLocal<?>>, Object> mapForNewThread = ExecutorInheritableThreadLocal.getMapForNewThread(); return new ForwardingRunnableFuture<T>(rf) { @Override public void run() { ConcurrentMap<WeakReference<? extends ExecutorInheritableThreadLocal<?>>, Object> oldMap = ExecutorInheritableThreadLocal.installMapOnThread(mapForNewThread); try { super.run(); } finally { ExecutorInheritableThreadLocal.uninstallMapOnThread(oldMap); } } }; }

Target:
public static <T> RunnableFuture<T> wrap(RunnableFuture<T> rf) { Runnable wrappedRunnable = wrapRunnable(rf); return new ForwardingRunnableFuture<>(wrappedRunnable, rf); }
Source:
public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } SonarLintSubmitter submitter = SonarLintUtils.get(project, SonarLintSubmitter.class); VirtualFile selectedFile = SonarLintUtils.get(SonarLintAppUtils.class).getSelectedFile(project); if (selectedFile == null) { SonarLintUtils.get(project, SonarLintConsole.class).error("No filesPerModule for analysis"); return; } submitter.submitFiles(Collections.singleton(selectedFile), TriggerType.ACTION, executeBackground(e)); }

Target:
public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } SonarLintSubmitter submitter = SonarLintUtils.get(project, SonarLintSubmitter.class); VirtualFile selectedFile = SonarLintUtils.get(SonarLintAppUtils.class).getSelectedFile(project); if (selectedFile == null) { SonarLintUtils.get(project, SonarLintConsole.class).error("No files for analysis"); return; } submitter.submitFiles(Collections.singleton(selectedFile), TriggerType.ACTION, executeBackground(e)); }
Source:
public int compare(DSpaceObject dso1, DSpaceObject dso2) { if (dso1 == dso2){ return 0; }else if (dso1 == null){ return -1; }else if (dso2 == null){ return 1; }else { return ObjectUtils.compare(dso1.getName(),dso2.getName()); } }

Target:
public int compare(DSpaceObject dso1, DSpaceObject dso2) { if (dso1 == dso2){ return 0; }else if (dso1 == null){ return -1; }else if (dso2 == null){ return 1; }else { String name1 = StringUtils.trimToEmpty(dso1.getName()); String name2 = StringUtils.trimToEmpty(dso2.getName()); return name1.compareToIgnoreCase(name2); } }
Source:
public HTMLNode getHTMLText() { HTMLNode content = new HTMLNode("div"); content.addChild("p", l10n("text")); content.addChild("p", frefFiles); HTMLNode form = content.addChild("form", new String[] {"action", "method"}, new String[] {"/friends/", "post"}); form.addChild("input", new String[] {"type", "name", "value"}, new String[] {"hidden", "formPassword", node.clientCore.formPassword}); form.addChild("input", new String[] {"type", "name", "value"}, new String[] {"hidden", "peers-offers-files", "true"}); ConnectionsToadlet.drawPeerTrustInputForAddPeerBox(form); ConnectionsToadlet.drawPeerVisibilityInputForAddPeerBox(form); form.addChild("input", new String[] {"type", "name", "value"}, new String[] {"submit", "add", "Connect"}); return content; }

Target:
public HTMLNode getHTMLText() { HTMLNode content = new HTMLNode("div"); content.addChild("p", l10n("text")); content.addChild("p", frefFiles); HTMLNode form = content.addChild("form", new String[] {"action", "method"}, new String[] {"/friends/", "post"}); form.addChild("input", new String[] {"type", "name", "value"}, new String[] {"hidden", "formPassword", node.clientCore.formPassword}); form.addChild("input", new String[] {"type", "name", "value"}, new String[] {"hidden", "peers-offers-files", "true"}); form.addChild(new PeerTrustInputForAddPeerBoxNode("DarknetConnectionsToadlet.")); form.addChild(new PeerVisibilityInputForAddPeerBoxNode("DarknetConnectionsToadlet.")); form.addChild("input", new String[] {"type", "name", "value"}, new String[] {"submit", "add", "Connect"}); return content; }
Source:
private ArrayList<StorageType> getStorageTypesList(String storageTypesString) throws SQLException { List<String> splitTypes = split(storageTypesString); if (splitTypes == null) { return null; } ArrayList<StorageType> types = new ArrayList<>(splitTypes.size()); for (String typeStr : splitTypes) { try { types.add(StorageType.forValue(Integer.parseInt(typeStr))); } catch (NumberFormatException e) { throw new SQLException("Could not parse disk image storage domain type " + typeStr); } } return types; }

Target:
private ArrayList<StorageType> getStorageTypesList(String storageTypesString) throws SQLException { List<String> splitTypes = split(storageTypesString); if (splitTypes == null) { return null; } ArrayList<StorageType> types = new ArrayList<>(splitTypes.size()); for (String typeStr : splitTypes) { try { types.add(StorageType.forValue(Integer.parseInt(typeStr))); } catch (NumberFormatException e) { throw new SQLException("Could not parse disk image storage domain type " + typeStr, e); } } return types; }
Source:
public VoltTable[] run( String targetStream, int pkey ) { if (targetStream.equals("S_ALLOW_NULLS_REPL")) { voltQueueSQL(i_insert_select_repl); } else if (targetStream.equals("S_ALLOW_NULLS")) { voltQueueSQL(i_insert_select_part); } else { assert(false); throw new RuntimeException("Don't call this."); } return voltExecuteSQL(); }

Target:
public VoltTable[] run( String targetStream, int pkey ) { if (targetStream.equals("S_ALLOW_NULLS_REPL")) { voltQueueSQL(i_insert_select_repl); } else if (targetStream.equals("S_ALLOW_NULLS")) { voltQueueSQL(i_insert_select_part); } else { throw new RuntimeException("Don't call this."); } return voltExecuteSQL(); }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { return; } validateKeyPatternsInConfig(config); stick = setupStick(config); if (stick != null) { setupNonStickDevices(config); setProperlyConfigured(true); } else { logger.error("Plugwise needs at least one Stick in order to operate"); } }

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { return; } validateKeyPatternsInConfig(config); stick = setupStick(config); if (stick != null) { setupNonStickDevices(config); setProperlyConfigured(true); } else { logger.warn("Plugwise needs at least one Stick in order to operate"); } }
Source:
public void handleGetMbusEncryptionKeyStatusByChannelResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType resultType, final OsgpException exception, final GetMbusEncryptionKeyStatusByChannelResponseDto getMbusEncryptionKeyStatusByChannelResponseDto) { LOGGER.info("handleGetMbusEncryptionKeyStatusByChannelResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); final EncryptionKeyStatusType encryptionKeyStatusType = EncryptionKeyStatusType .valueOf(getMbusEncryptionKeyStatusByChannelResponseDto.getEncryptionKeyStatus().name()); this.webServiceResponseMessageSender.send( ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()) .withResult(resultType).withOsgpException(exception).withDataObject(encryptionKeyStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }

Target:
public void handleGetMbusEncryptionKeyStatusByChannelResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType resultType, final OsgpException exception, final GetMbusEncryptionKeyStatusByChannelResponseDto getMbusEncryptionKeyStatusByChannelResponseDto) { LOGGER.info("handleGetMbusEncryptionKeyStatusByChannelResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); final EncryptionKeyStatusType encryptionKeyStatusType = EncryptionKeyStatusType .valueOf(getMbusEncryptionKeyStatusByChannelResponseDto.getEncryptionKeyStatus().name()); ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()) .withResult(resultType).withOsgpException(exception).withDataObject(encryptionKeyStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
@Test public void logSuccessfulRequestResponseOnDebugWhenResponseBodyPresent() throws Exception { final List<String> logMessages = new ArrayList<String>(); RestAdapter.Log log = new RestAdapter.Log() { public void log(String message) { logMessages.add(message); } }; Example example = new RestAdapter.Builder() .setClient(mockClient) .setExecutors(mockRequestExecutor, mockCallbackExecutor) .setServer("<LINK_1>") .setProfiler(mockProfiler) .setLog(log) .setDebug(true) .build() .create(Example.class); when(mockClient.execute(any(Request.class))) .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("{}"))); example.something(); assertThat(logMessages.size()).isEqualTo(5); assertThat(logMessages.get(0)).isEqualTo("---> HTTP GET <LINK_0>"); assertThat(logMessages.get(1)).isEqualTo("---> END HTTP (0-byte body)"); assertThat(logMessages.get(2)).matches("<--- HTTP 200 <LINK_0> \\([0-9]+ms\\)"); assertThat(logMessages.get(3)).isEqualTo("{}"); assertThat(logMessages.get(4)).isEqualTo("<--- END HTTP (2-byte body)"); }

Target:
@Test public void logSuccessfulRequestResponseOnDebugWhenResponseBodyPresent() throws Exception { final List<String> logMessages = new ArrayList<String>(); RestAdapter.Log log = new RestAdapter.Log() { public void log(String message) { logMessages.add(message); } }; Example example = new RestAdapter.Builder() .setClient(mockClient) .setExecutors(mockRequestExecutor, mockCallbackExecutor) .setServer("<LINK_1>") .setProfiler(mockProfiler) .setLog(log) .setDebug(true) .build() .create(Example.class); when(mockClient.execute(any(Request.class))) .thenReturn(new Response(200, "OK", NO_HEADERS, new TypedString("{}"))); example.something(); assertThat(logMessages).hasSize(5); assertThat(logMessages.get(0)).isEqualTo("---> HTTP GET <LINK_0>"); assertThat(logMessages.get(1)).isEqualTo("---> END HTTP (0-byte body)"); assertThat(logMessages.get(2)).matches("<--- HTTP 200 <LINK_0> \\([0-9]+ms\\)"); assertThat(logMessages.get(3)).isEqualTo("{}"); assertThat(logMessages.get(4)).isEqualTo("<--- END HTTP (2-byte body)"); }