auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void start(boolean logProcessOutput) throws IOException, InterruptedException { List<String> startCommand = new ArrayList<>(); startCommand.add(getJavaExecutable().getPath()); startCommand.addAll(getJavaOptsProperty(Function.identity())); startCommand.add("-cp"); startCommand.add(getClassPath()); startCommand.addAll(getNuxeoProperties()); startCommand.addAll(getServerProperties()); if (strict) { startCommand.add("-Dnuxeo.start.strict"); } setServerStartCommand(startCommand); startCommand.addAll(Arrays.asList(params)); ProcessBuilder pb = new ProcessBuilder(getOSCommand(startCommand)); pb.directory(configurationGenerator.getNuxeoHome()); log.debug("Server command: " + pb.command()); nuxeoProcess = pb.start(); Thread.sleep(1000); boolean processExited = false; if (nuxeoProcess == null) { log.error(String.format("Server start failed with command: %s", pb.command())); if (SystemUtils.IS_OS_WINDOWS && configurationGenerator.getNuxeoHome().getPath().contains(" ")) { log.error("The server path must not contain spaces under Windows."); } return; } try { int exitValue = nuxeoProcess.exitValue(); if (exitValue != 0) { log.error(String.format("Server start failed (%d).", exitValue)); } processExited = true; } catch (IllegalThreadStateException e) { } logProcessStreams(nuxeoProcess, processExited || logProcessOutput); if (!processExited) { if (getPid() != null) { log.warn("Server started with process ID " + pid + "."); } else { log.warn("Sent server start command but could not get process ID."); } } }

Target:
protected void start(boolean logProcessOutput) throws IOException, InterruptedException { List<String> startCommand = new ArrayList<>(); startCommand.add(getJavaExecutable().getPath()); startCommand.addAll(getJavaOptsProperty(Function.identity())); startCommand.add("-cp"); startCommand.add(getClassPath()); startCommand.addAll(getNuxeoProperties()); startCommand.addAll(getServerProperties()); if (strict) { startCommand.add("-Dnuxeo.start.strict=true"); } setServerStartCommand(startCommand); startCommand.addAll(Arrays.asList(params)); ProcessBuilder pb = new ProcessBuilder(getOSCommand(startCommand)); pb.directory(configurationGenerator.getNuxeoHome()); log.debug("Server command: " + pb.command()); nuxeoProcess = pb.start(); Thread.sleep(1000); boolean processExited = false; if (nuxeoProcess == null) { log.error(String.format("Server start failed with command: %s", pb.command())); if (SystemUtils.IS_OS_WINDOWS && configurationGenerator.getNuxeoHome().getPath().contains(" ")) { log.error("The server path must not contain spaces under Windows."); } return; } try { int exitValue = nuxeoProcess.exitValue(); if (exitValue != 0) { log.error(String.format("Server start failed (%d).", exitValue)); } processExited = true; } catch (IllegalThreadStateException e) { } logProcessStreams(nuxeoProcess, processExited || logProcessOutput); if (!processExited) { if (getPid() != null) { log.warn("Server started with process ID " + pid + "."); } else { log.warn("Sent server start command but could not get process ID."); } } }
Source:
protected CheckoutCommand checkoutPaths() throws IOException, RefNotFoundException { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.lockDirCache(); try { TreeWalk treeWalk = new TreeWalk(revWalk.getObjectReader()); treeWalk.addTree(new DirCacheIterator(dc)); treeWalk.setFilter(PathFilterGroup.createFromStrings(paths)); List<String> files = new LinkedList<String>(); while (treeWalk.next()) if (treeWalk.isSubtree()) treeWalk.enterSubtree(); else files.add(treeWalk.getPathString()); if (startCommit != null || startPoint != null) { DirCacheEditor editor = dc.editor(); TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader()); startWalk.setFilter(treeWalk.getFilter()); startWalk.addTree(revWalk.parseCommit(getStartPoint()) .getTree()); while (startWalk.next()) if (startWalk.isSubtree()) startWalk.enterSubtree(); else { final ObjectId blobId = startWalk.getObjectId(0); editor.add(new PathEdit(startWalk.getPathString()) { public void apply(DirCacheEntry ent) { ent.setObjectId(blobId); } }); } editor.commit(); } File workTree = repo.getWorkTree(); for (String file : files) DirCacheCheckout.checkoutEntry(repo, new File(workTree, file), dc.getEntry(file)); } finally { dc.unlock(); revWalk.release(); } return this; }

Target:
protected CheckoutCommand checkoutPaths() throws IOException, RefNotFoundException { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.lockDirCache(); try { TreeWalk treeWalk = new TreeWalk(revWalk.getObjectReader()); treeWalk.setRecursive(true); treeWalk.addTree(new DirCacheIterator(dc)); treeWalk.setFilter(PathFilterGroup.createFromStrings(paths)); List<String> files = new LinkedList<String>(); while (treeWalk.next()) files.add(treeWalk.getPathString()); if (startCommit != null || startPoint != null) { DirCacheEditor editor = dc.editor(); TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader()); startWalk.setRecursive(true); startWalk.setFilter(treeWalk.getFilter()); startWalk.addTree(revWalk.parseCommit(getStartPoint()) .getTree()); while (startWalk.next()) { final ObjectId blobId = startWalk.getObjectId(0); editor.add(new PathEdit(startWalk.getPathString()) { public void apply(DirCacheEntry ent) { ent.setObjectId(blobId); } }); } editor.commit(); } File workTree = repo.getWorkTree(); for (String file : files) DirCacheCheckout.checkoutEntry(repo, new File(workTree, file), dc.getEntry(file)); } finally { dc.unlock(); revWalk.release(); } return this; }
Source:
private ProjectReadAccess getReadAccessFromForm( final MultipartForm form ) { final ProjectReadAccess.Builder readAccess = ProjectReadAccess.create(); return Optional.ofNullable( form.getAsString( PROJECT_READ_ACCESS_JSON_PROPERTY_NAME ) ). map( readAccessAsString -> { try { return new ObjectMapper(). readValue( readAccessAsString, ProjectReadAccessJson.class ); } catch ( IOException e ) { LOG.error( "Cannot parse project read access.", e ); return null; } } ). map( ProjectReadAccessJson::getProjectReadAccess ). orElseGet( readAccess::build ); }

Target:
private ProjectReadAccess getReadAccessFromForm( final MultipartForm form ) { final ProjectReadAccess.Builder readAccess = ProjectReadAccess.create(); return Optional.ofNullable( form.getAsString( PROJECT_READ_ACCESS_JSON_PROPERTY_NAME ) ). map( readAccessAsString -> { try { return new ObjectMapper(). readValue( readAccessAsString, ProjectReadAccessJson.class ); } catch ( IOException e ) { throw new UncheckedIOException( e ); } } ). map( ProjectReadAccessJson::getProjectReadAccess ). orElseGet( readAccess::build ); }
Source:
public <T> T convert(Object source, Class<T> target) throws Exception { int arrLength = Array.getLength(source); Class<?> elementType = target.getComponentType(); Object result = Array.newInstance(elementType, arrLength); for (int count = 0; count < arrLength; count++) { Array.set(result, count, Converters.convert(Array.get(source, count), elementType)); } return (T) result; }

Target:
public <T> T convert(Object source, Class<T> target) throws Exception { int arrLength = Array.getLength(source); Class<?> elementType = target.getComponentType(); Object result = Array.newInstance(elementType, arrLength); for (int count = 0; count < arrLength; count++) { Object sourceElement = Array.get(source, count); Object converted = Converters.convert(sourceElement, elementType); if (sourceElement != null && converted == null) { return null; } Array.set(result, count, converted); } return (T) result; }
Source:
public Response add(User entity) throws SQLException { if (!Context.getPermissionsManager().isAdmin(getUserId())) { Context.getPermissionsManager().checkRegistration(getUserId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), new User(), entity); Config config = Context.getConfig(); int deviceLimit = config.getInteger("default.deviceLimit"); int expirationDuration = config.getInteger("default.expirationDuration"); if (deviceLimit > 0) { entity.setDeviceLimit(deviceLimit); } if (expirationDuration > 0) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, expirationDuration); Date expirationTime = cal.getTime(); entity.setExpirationTime(expirationTime); } } Context.getPermissionsManager().addUser(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }

Target:
public Response add(User entity) throws SQLException { if (!Context.getPermissionsManager().isAdmin(getUserId())) { Context.getPermissionsManager().checkRegistration(getUserId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), new User(), entity); entity.setDeviceLimit(Context.getConfig().getInteger("users.defaultDeviceLimit")); int expirationDays = Context.getConfig().getInteger("users.defaultExpirationDays"); if (expirationDays > 0) { entity.setExpirationTime( new Date(System.currentTimeMillis() + (long) expirationDays * 24 * 3600 * 1000)); } } Context.getPermissionsManager().addUser(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); }
Source:
static String[] getFileExtensions(String fileName) { List<String> extensions = new ArrayList<String>(); while (fileName.length() > 0) { extensions.add(fileName); if (fileName.indexOf('.') == -1) { break; } fileName = fileName.substring(fileName.indexOf('.') + 1, fileName.length()); } Collections.reverse(extensions); return extensions.toArray(new String[extensions.size()]); }

Target:
static List<String> getFileExtensions(String fileName) { List<String> extensions = new ArrayList<String>(); while (fileName.length() > 0) { extensions.add(fileName); if (fileName.indexOf('.') == -1) { break; } fileName = fileName.substring(fileName.indexOf('.') + 1, fileName.length()); } Collections.reverse(extensions); return extensions; }
Source:
public void setup() { databaseHelper.addObject("" + "person: Jaap Veldhuis\n" + "nic-hdl: JAAP-TEST\n" + "source: TEST"); databaseHelper.addObject("" + "mntner: TEST-MNT\n" + "descr: Test Maintainer\n" + "admin-c: JAAP-TEST\n" + "auth: SSO person@net.net\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); databaseHelper.addObject("" + "mntner: XS4ALL-MNT\n" + "descr: XS4ALL Maintainer\n" + "admin-c: JAAP-TEST\n" + "auth: SSO person@net.net\n" + "auth: MD5-PW $1$Y8rG1Ste$QzFB.VSD5mDy7nlb/BJix/ #XS4ALL-MNT\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); databaseHelper.updateObject("" + "person: Jaap Veldhuis\n" + "e-mail: jaapx@ripe.net\n" + "address: Hoofdstraat 1\n" + "phone: +31 6 12345678\n" + "nic-hdl: JAAP-TEST\n" + "mnt-by: TEST-MNT\n" + "mnt-by: XS4ALL-MNT\n" + "source: TEST" ); }

Target:
public void setup() { databaseHelper.addObject("" + "person: Jaap Knasterhuis\n" + "nic-hdl: JAAP-TEST\n" + "source: TEST"); databaseHelper.addObject("" + "mntner: TEST-MNT\n" + "descr: Test Maintainer\n" + "admin-c: JAAP-TEST\n" + "auth: SSO person@net.net\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); databaseHelper.addObject("" + "mntner: TEST2-MNT\n" + "descr: XS4ALL Maintainer\n" + "admin-c: JAAP-TEST\n" + "auth: SSO person@net.net\n" + "auth: MD5-PW $1$Y8rG1Ste$QzFB.VSD5mDy7nlb/BJix/ #TEST2-MNT\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); databaseHelper.updateObject("" + "person: Jaap Veldhuis\n" + "e-mail: jaapx@ripe.net\n" + "address: Hoofdstraat 1\n" + "phone: +31 6 12345678\n" + "nic-hdl: JAAP-TEST\n" + "mnt-by: TEST-MNT\n" + "mnt-by: TEST2-MNT\n" + "source: TEST" ); }
Source:
public static Map<String, String> getProjectSettings(IJavaProject javaProject) { Map<String, String> options= new HashMap<>(javaProject.getOptions(true)); ProfileVersioner versioner= new ProfileVersioner(); int profileVersion= new ProjectScope(javaProject.getProject()) .getNode(JavaUI.ID_PLUGIN) .getInt(FORMATTER_SETTINGS_VERSION, versioner.getCurrentVersion()); if (profileVersion == versioner.getCurrentVersion()) return options; CustomProfile profile= new CustomProfile(null, options, profileVersion, null); versioner.update(profile); return profile.getSettings(); }

Target:
public static Map<String, String> getProjectSettings(IJavaProject javaProject) { Map<String, String> options= new HashMap<>(javaProject.getOptions(true)); ProfileVersioner versioner= new ProfileVersioner(); IEclipsePreferences prefs= new ProjectScope(javaProject.getProject()).getNode(JavaUI.ID_PLUGIN); if (prefs == null) return options; int profileVersion= prefs.getInt(FORMATTER_SETTINGS_VERSION, versioner.getCurrentVersion()); if (profileVersion == versioner.getCurrentVersion()) return options; CustomProfile profile= new CustomProfile(null, options, profileVersion, null); versioner.update(profile); return profile.getSettings(); }
Source:
public void ThrottleOnOverTestWithQuota() throws Exception { ApiRateLimitChecker.setEntropy(entropy); ApiRateLimitChecker.setExpirationWaitMillis(1); ApiRateLimitChecker.setNotificationWaitMillis(1); List<JsonRateLimit> scenarios = new ArrayList<>(); int limit = 5000; scenarios.add(new JsonRateLimit(limit, limit, soon)); setupStubs(scenarios); for (int i = 0; i < 100; i++) { apiRateLimitCheckerThrottleOnOver.checkApiRateLimit(listener, github); } assertEquals(0, handler.getView().stream().map(LogRecord::getMessage).filter(m -> m.contains("Sleeping")).count()); }

Target:
public void ThrottleOnOverTestWithQuota() throws Exception { List<RateLimit> scenarios = new ArrayList<>(); int limit = 5000; scenarios.add(new RateLimit(limit, limit, soon)); setupStubs(scenarios); for (int i = 0; i < 100; i++) { ApiRateLimitChecker.ThrottleOnOver.checkApiRateLimit(listener, github); } assertEquals(0, countOfOutputLinesContaining("Sleeping")); }
Source:
public List<String> handlePlayerNameTabComplete(CommonSender sender, String[] args) { ArrayList<String> mostLike = new ArrayList<>(); if(args.length == 1) { if (isValidNameDelimiter(args[0])) { String[] names = splitNameDelimiter(args[0]); String lookup = names[names.length - 1]; if (plugin.getConfig().isOfflineAutoComplete()) { for (CharSequence charSequence : plugin.getPlayerStorage().getAutoCompleteTree().getKeysStartingWith(lookup)) { mostLike.add(args[0] + charSequence.toString().substring(lookup.length())); } } } else if (plugin.getConfig().isOfflineAutoComplete()) { for (CharSequence charSequence : plugin.getPlayerStorage().getAutoCompleteTree().getKeysStartingWith(args[0])) { mostLike.add(charSequence.toString()); } } else { CommonPlayer senderPlayer = sender instanceof CommonPlayer ? (CommonPlayer) sender : null; String lower = args[0].toLowerCase(); for (CommonPlayer player : plugin.getServer().getOnlinePlayers()) { if ((senderPlayer == null || senderPlayer.canSee(player)) && player.getName().toLowerCase().startsWith(lower)) { mostLike.add(player.getName()); } } } } if(args.length == 2) { String lookup = args[1]; if(lookup.startsWith("#")) { return plugin.getReasonsConfig().getReasons().keySet().stream().map(k -> "#" + k) .filter(k -> k.startsWith(lookup)).collect(Collectors.toList()); } } if (mostLike.size() > 100) return mostLike.subList(0, 99); return mostLike; }

Target:
public List<String> handlePlayerNameTabComplete(CommonSender sender, String[] args) { ArrayList<String> mostLike = new ArrayList<>(); if(args.length == 1) { if (isValidNameDelimiter(args[0])) { String[] names = splitNameDelimiter(args[0]); String lookup = names[names.length - 1]; if (plugin.getConfig().isOfflineAutoComplete()) { for (CharSequence charSequence : plugin.getPlayerStorage().getAutoCompleteTree().getKeysStartingWith(lookup)) { mostLike.add(args[0] + charSequence.toString().substring(lookup.length())); } } } else if (plugin.getConfig().isOfflineAutoComplete()) { for (CharSequence charSequence : plugin.getPlayerStorage().getAutoCompleteTree().getKeysStartingWith(args[0])) { mostLike.add(charSequence.toString()); } } else { CommonPlayer senderPlayer = sender instanceof CommonPlayer ? (CommonPlayer) sender : null; String lower = args[0].toLowerCase(); for (CommonPlayer player : plugin.getServer().getOnlinePlayers()) { if ((senderPlayer == null || senderPlayer.canSee(player)) && player.getName().toLowerCase().startsWith(lower)) { mostLike.add(player.getName()); } } } } if(args.length > 1) { String lookup = args[1]; if(lookup.startsWith("#")) { return plugin.getReasonsConfig().getReasons().keySet().stream().map(k -> "#" + k) .filter(k -> k.startsWith(lookup)).collect(Collectors.toList()); } } if (mostLike.size() > 100) return mostLike.subList(0, 99); return mostLike; }
Source:
public void update() { System.out.println("update :" + this.getClass().getSimpleName()); }

Target:
public void update() { LOGGER.info("update AI component"); }
Source:
public void shouldHaveTheSessionTimeout() throws Exception { final Cluster cluster = TestClientFactory.open(); final Client client = cluster.connect(name.getMethodName()); final ResultSet results1 = client.submit("x = [1,2,3,4,5,6,7,8,9]"); final AtomicInteger counter = new AtomicInteger(0); results1.stream().map(i -> i.get(Integer.class) * 2).forEach(i -> assertEquals(counter.incrementAndGet() * 2, Integer.parseInt(i.toString()))); final ResultSet results2 = client.submit("x[0]+1"); assertEquals(2, results2.all().get().get(0).getInt()); Thread.sleep(3500); try { client.submit("x[1]+2").all().get(); fail("Session should be dead"); } catch (Exception ex) { final Throwable cause = ex.getCause(); assertThat(cause, instanceOf(ResponseException.class)); assertEquals(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION, ((ResponseException) cause).getResponseStatusCode()); assertEquals(2, client.submit("1+1").all().join().get(0).getInt()); } finally { cluster.close(); } this.stopServer(); assertEquals(2, recordingAppender.getMessages().stream() .filter(msg -> msg.contains("Session shouldHaveTheSessionTimeout closed")).count()); }

Target:
public void shouldHaveTheSessionTimeout() throws Exception { final Cluster cluster = TestClientFactory.open(); final Client client = cluster.connect(name.getMethodName()); final ResultSet results1 = client.submit("x = [1,2,3,4,5,6,7,8,9]"); final AtomicInteger counter = new AtomicInteger(0); results1.stream().map(i -> i.get(Integer.class) * 2).forEach(i -> assertEquals(counter.incrementAndGet() * 2, Integer.parseInt(i.toString()))); final ResultSet results2 = client.submit("x[0]+1"); assertEquals(2, results2.all().get().get(0).getInt()); Thread.sleep(3500); try { client.submit("x[1]+2").all().get(); fail("Session should be dead"); } catch (Exception ex) { final Throwable cause = ex.getCause(); assertThat(cause, instanceOf(ResponseException.class)); assertEquals(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION, ((ResponseException) cause).getResponseStatusCode()); assertEquals(2, client.submit("1+1").all().join().get(0).getInt()); } finally { cluster.close(); } assertEquals(2, recordingAppender.getMessages().stream() .filter(msg -> msg.contains("Session shouldHaveTheSessionTimeout closed")).count()); }
Source:
public void start() { startMetrics(); systemAdmins.start(); zkUtils.validateZkVersion(); leaderElector.tryBecomeLeader(); zkUtils.subscribeToJobModelVersionChange(new ZkJobModelVersionChangeHandler(zkUtils)); }

Target:
public void start() { ZkKeyBuilder keyBuilder = zkUtils.getKeyBuilder(); zkUtils.validateZkVersion(); zkUtils.validatePaths(new String[]{keyBuilder.getProcessorsPath(), keyBuilder.getJobModelVersionPath(), keyBuilder .getJobModelPathPrefix()}); startMetrics(); systemAdmins.start(); leaderElector.tryBecomeLeader(); zkUtils.subscribeToJobModelVersionChange(new ZkJobModelVersionChangeHandler(zkUtils)); }
Source:
public BlobClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); URL url; try { url = new URL(endpoint); this.endpoint = new URL(url.getProtocol() + "://" + url.getAuthority()); String path = url.getPath(); if (path != null && !path.isEmpty() && !path.equals("/")) { path = path.replaceAll("^/", "").replaceAll("/$", ""); String[] segments = path.split("/", 2); if (segments.length != 2) { throw new IllegalArgumentException("Endpoint should contain 0 or at least 2 path segments"); } else { this.containerName = segments[0]; this.blobName = segments[1]; } } } catch (MalformedURLException ex) { throw new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."); } SASTokenCredential credential = SASTokenCredential.fromQuery(url.getQuery()); if (credential != null) { this.sasTokenCredential = credential; } return this; }

Target:
public BlobClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); URL url; try { url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + "://" + parts.host(); if (parts.containerName() != null) { this.containerName = parts.containerName(); } if (parts.blobName() != null) { this.blobName = parts.blobName(); } if (parts.snapshot() != null) { this.snapshot = parts.snapshot(); } } catch (MalformedURLException | UnknownHostException ex) { throw new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."); } SASTokenCredential credential = SASTokenCredential.fromQuery(url.getQuery()); if (credential != null) { this.credential(credential); } return this; }
Source:
public void setDateCreated(Date dateCreated) { if(dateCreated == null) { this.dateCreated = null; return; } this.dateCreated = (Date) dateCreated.clone(); }

Target:
public void setDateCreated(Date dateCreated) { if(dateCreated == null) { this.dateCreated = null; return; } this.dateCreated = new Date(dateCreated.getTime()); }
Source:
public void testOptionWithinObjectIfMissing_shouldBeNone() throws SQLException { final SomethingWithOption result = dbRule.getSharedHandle() .registerRowMapper(ConstructorMapper.factory(SomethingWithOption.class)) .createQuery("select id, name from something where id = 2") .mapTo(SomethingWithOption.class) .findOnly(); assertThat(result.getName()).isInstanceOf(Option.class); assertThat(result.getName().getOrNull()).isNull(); }

Target:
public void testOptionWithinObjectIfMissing_shouldBeNone() throws SQLException { final SomethingWithOption result = dbRule.getSharedHandle() .registerRowMapper(ConstructorMapper.factory(SomethingWithOption.class)) .createQuery("select id, name from something where id = 2") .mapTo(SomethingWithOption.class) .findOnly(); assertThat(result.getName()).isInstanceOf(Option.class); assertThat(result).isEqualTo(new SomethingWithOption(2, Option.none())); }
Source:
protected void setResult(T... newUserSelection) { if (newUserSelection == null) { result = Collections.emptyList(); } else { result = Arrays.asList(newUserSelection); } }

Target:
protected void setResult(T... newUserSelection) { if (newUserSelection == null) { result = null; } else { result = Arrays.asList(newUserSelection); } }
Source:
public static Optional<RuntimeException> fromMultipleRuntimeExceptions(List<RuntimeException> exceptions) { switch (exceptions.size()) { case 0: return Optional.empty(); case 1: return Optional.of(exceptions.get(0)); default: CacheConfigurationException exception = log.multipleConfigurationValidationErrors(); exceptions.forEach(e -> exception.addSuppressed(e)); return Optional.of(exception); } }

Target:
public static Optional<RuntimeException> fromMultipleRuntimeExceptions(List<RuntimeException> exceptions) { switch (exceptions.size()) { case 0: return Optional.empty(); case 1: { RuntimeException e = exceptions.get(0); return e instanceof CacheConfigurationException ? Optional.of(e) : Optional.of(new CacheConfigurationException(e)); } default: { CacheConfigurationException exception = log.multipleConfigurationValidationErrors(); exceptions.forEach(e -> exception.addSuppressed(e)); return Optional.of(exception); } } }
Source:
public void sendMessagePipelining_withNegativeReply() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("421 4.7.0 Temporary system problem"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }

Target:
public void sendMessagePipelining_withNegativeReply() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("."); server.output("554 no valid recipients"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(550, e.getReplyCode()); assertEquals("remote mail to <user2@localhost> not allowed", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
Source:
public void refresh() throws IOException { if (!featureToggleService.isFeatureEnabled(FEATURE_NAME)) { return; } final long selector = System.currentTimeMillis() - DELAY_MILLIS; synchronized (this) { final Iterator<ListenerInfo> it = toAdd.iterator(); while (it.hasNext()) { final ListenerInfo first = it.next(); if (first.addedAt.getTime() >= selector) { break; } listeners.computeIfAbsent(first.connectionInfo, info -> new ArrayList<>()).add(first.callback); it.remove(); } } final Map<ConnectionInfo, ConnectionState> currentConnections = readAllConnectionStates(); final Set<ConnectionInfo> keys = new HashSet<>(listeners.keySet()); final AtomicInteger closedCount = new AtomicInteger(); for (final ConnectionInfo key : keys) { if (CLOSED_STATES.contains(currentConnections.getOrDefault(key, ConnectionState.TCP_CLOSE))) { LOG.info("Notifying about connection close via crutch: " + key); listeners.remove(key).forEach(callable -> { if (callable.getAsBoolean()) { closedCount.incrementAndGet(); } }); } } if (closedCount.get() > 0) { meterClosed.mark(closedCount.get()); } }

Target:
public void refresh() throws IOException { if (!featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.CONNECTION_CLOSE_CRUTCH)) { return; } synchronized (toAdd) { toAdd.forEach((conn, toAddListeners) -> { listeners.computeIfAbsent(conn, c -> new ArrayList<>()).addAll(toAddListeners); }); toAdd.clear(); } final Map<ConnectionInfo, ConnectionState> currentConnections = readAllConnectionStates(); final long closedCount = new HashSet<>(listeners.keySet()).stream() .filter(key -> CLOSED_STATES.contains(currentConnections.getOrDefault(key, ConnectionState.TCP_CLOSE))) .mapToLong(key -> { LOG.info("Notifying about connection close via crutch: " + key); return listeners.remove(key).stream().filter(BooleanSupplier::getAsBoolean).count(); }).sum(); if (closedCount > 0) { meterClosed.mark(closedCount); } }
Source:
public Observable<File> save() { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { File folder = app.getExternalFilesDir(null); if (folder == null) { subscriber.onError(new IOException("External storage is not mounted.")); return; } String fileName = LOG_FILE_FORMAT.format(new Date()); File output = new File(folder, fileName); BufferedSink sink = null; try { sink = Okio.buffer(Okio.sink(output)); List<Entry> entries = bufferedLogs(); for (Entry entry : entries) { sink.writeUtf8(entry.prettyPrint()).writeByte('\n'); } } catch (IOException e) { subscriber.onError(e); } finally { if (sink != null) { try { sink.close(); } catch (IOException e) { subscriber.onError(e); } } } subscriber.onNext(output); subscriber.onCompleted(); } }); }

Target:
public Observable<File> save() { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { File folder = app.getExternalFilesDir(null); if (folder == null) { subscriber.onError(new IOException("External storage is not mounted.")); return; } String fileName = LOG_FILE_FORMAT.get().format(new Date()); File output = new File(folder, fileName); BufferedSink sink = null; try { sink = Okio.buffer(Okio.sink(output)); List<Entry> entries = bufferedLogs(); for (Entry entry : entries) { sink.writeUtf8(entry.prettyPrint()).writeByte('\n'); } subscriber.onNext(output); subscriber.onCompleted(); } catch (IOException e) { subscriber.onError(e); } finally { if (sink != null) { try { sink.close(); } catch (IOException e) { subscriber.onError(e); } } } } }); }
Source:
public void loginHintWithExistingUser() { getCleanup(bc.consumerRealmName()).addCleanup( new UserCreator( adminClient.realm(bc.consumerRealmName()), UserBuilder.create() .username(bc.getUserLogin()) .password(bc.getUserPassword()) .email(bc.getUserEmail()) .enabled(true) .build() ) ); driver.navigate().to(getAccountUrl(bc.consumerRealmName())); waitForPageToLoad(); driver.navigate().to(driver.getCurrentUrl() + "&login_hint=" + USER_EMAIL + "&kc_idp_hint=" + IDP_OIDC_ALIAS); waitForPageToLoad(); loginPage.login(bc.getUserPassword()); updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); idpConfirmLinkPage.assertCurrent(); idpConfirmLinkPage.clickLinkAccount(); loginPage.login(bc.getUserPassword()); accountPage.isCurrent(); }

Target:
public void loginHintWithExistingUser() { try (Creator<UserResource> c = Creator.create(adminClient.realm(bc.consumerRealmName()), UserBuilder.create() .username(bc.getUserLogin()) .password(bc.getUserPassword()) .email(bc.getUserEmail()) .enabled(true) .build() )) { driver.navigate().to(getAccountUrl(bc.consumerRealmName())); waitForPageToLoad(); driver.navigate().to(driver.getCurrentUrl() + "&login_hint=" + USER_EMAIL + "&kc_idp_hint=" + IDP_OIDC_ALIAS); waitForPageToLoad(); loginPage.login(bc.getUserPassword()); updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); idpConfirmLinkPage.assertCurrent(); idpConfirmLinkPage.clickLinkAccount(); loginPage.login(bc.getUserPassword()); accountPage.isCurrent(); } }
Source:
public byte[] decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> client.decrypt(algorithm, cipherText, null, null, null, context)).block(); }

Target:
public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(algorithm, cipherText, null, null, null, Context.NONE); }
Source:
private static NetworkFilter fetchVnicProfileNetworkFilter(VmNic vmNic) { VnicProfile vnicProfile = DbFacade.getInstance().getVnicProfileDao().get(vmNic.getVnicProfileId()); final Guid networkFilterId = vnicProfile.getNetworkFilterId(); return DbFacade.getInstance().getNetworkFilterDao().getNetworkFilterById(networkFilterId); }

Target:
private static NetworkFilter fetchVnicProfileNetworkFilter(VmNic vmNic) { if (vmNic.getVnicProfileId() != null) { VnicProfile vnicProfile = DbFacade.getInstance().getVnicProfileDao().get(vmNic.getVnicProfileId()); if (vnicProfile != null) { final Guid networkFilterId = vnicProfile.getNetworkFilterId(); return networkFilterId == null ? null : DbFacade.getInstance().getNetworkFilterDao().getNetworkFilterById(networkFilterId); } } return null; }
Source:
public Map<String, GuestId> getGuestIdMap(Iterable<String> guestIds, Owner owner) { if (guestIds == null || owner == null) { return Collections.<String, GuestId>emptyMap(); } String hql = "SELECT gid FROM GuestId gid " + "WHERE gid.consumer.owner = :owner AND gid.guestIdLower IN (:guest_ids)" + "ORDER BY gid.updated DESC"; TypedQuery<GuestId> query = this.getEntityManager().createQuery(hql, GuestId.class); Map<String, GuestId> output = new HashMap<String, GuestId>(); for (List<String> block : this.partition(guestIds)) { List<String> sanitized = new ArrayList<String>(block); for (String guestId : block) { if (guestId != null && !guestId.isEmpty() && !output.containsKey(guestId)) { sanitized.add(guestId.toLowerCase()); output.put(guestId, null); } } List<GuestId> guests = query .setParameter("owner", owner) .setParameter("guest_ids", sanitized) .getResultList(); if (guests != null) { for (GuestId fetched : guests) { GuestId existing = output.get(fetched.getGuestId()); if (existing == null || this.safeDateAfter(fetched.getUpdated(), existing.getUpdated())) { output.put(fetched.getGuestId(), fetched); } } } } return output; }

Target:
public Map<String, GuestId> getGuestIdMap(Iterable<String> guestIds, Owner owner) { if (guestIds == null || owner == null) { return Collections.<String, GuestId>emptyMap(); } String hql = "SELECT gid FROM GuestId gid " + "WHERE gid.consumer.owner = :owner AND gid.guestIdLower IN (:guest_ids)" + "ORDER BY gid.updated DESC"; TypedQuery<GuestId> query = this.getEntityManager().createQuery(hql, GuestId.class); Map<String, GuestId> output = new HashMap<String, GuestId>(); for (List<String> block : this.partition(guestIds)) { List<String> sanitized = new ArrayList<String>(block.size()); for (String guestId : block) { if (guestId != null && !guestId.isEmpty() && !output.containsKey(guestId)) { sanitized.add(guestId.toLowerCase()); output.put(guestId, null); } } List<GuestId> guests = query .setParameter("owner", owner) .setParameter("guest_ids", sanitized) .getResultList(); if (guests != null) { for (GuestId fetched : guests) { GuestId existing = output.get(fetched.getGuestId()); if (existing == null || this.safeDateAfter(fetched.getUpdated(), existing.getUpdated())) { output.put(fetched.getGuestId(), fetched); } } } } return output; }
Source:
public void accept(final Socket socket) throws IOException { socket.setSoTimeout(BkBasic.TIMEOUT); final InputStream input = socket.getInputStream(); try { while (true) { final Request request = new RqLive(input); this.print( BkBasic.addSocketHeaders( request, socket ), new BufferedOutputStream(socket.getOutputStream()) ); if (input.available() <= 0) { break; } } } catch (final SocketTimeoutException exc) { } finally { input.close(); } }

Target:
public void accept(final Socket socket) throws IOException { socket.setSoTimeout(Tv.THOUSAND); final InputStream input = socket.getInputStream(); final OutputStream output = socket.getOutputStream(); final BufferedOutputStream buffered = new BufferedOutputStream(output); try { while (true) { final Request request = new RqLive(input); this.print( BkBasic.addSocketHeaders( request, socket ), buffered ); if (input.available() <= 0) { break; } } } catch (final SocketTimeoutException exc) { } finally { input.close(); output.close(); } }
Source:
public void adsAdTypeAsyncSuccessWithAd() { Page page = new Page("project43", "SyntheticTests/AdType/Async/Success"); MobileAdsBaseObject ads = new MobileAdsBaseObject(driver, page.getUrl()); ads.scrollToFooter(); ads.waitForSlot(AdsContent.MOBILE_BOTTOM_LB); ads.verifyImgAdLoadedInSlot(AdsContent.MOBILE_BOTTOM_LB, DFP_IMAGE_URL); }

Target:
public void adsAdTypeAsyncSuccessWithAd() { Page page = new Page("project43", "SyntheticTests/AdType/Async/Success"); MobileAdsBaseObject ads = new MobileAdsBaseObject(driver, page.getUrl()); ads.scrollToRecirculationPrefooter(); ads.waitForSlot(AdsContent.MOBILE_BOTTOM_LB); ads.verifyImgAdLoadedInSlot(AdsContent.MOBILE_BOTTOM_LB, DFP_IMAGE_URL); }
Source:
public final ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { final AbstractChannelHandlerContext ctx; checkMultiplicity(handler); if (name == null) { name = generateName(handler); } AbstractChannelHandlerContext newCtx = newContext(name, handler); EventExecutor executor = executor(); boolean inEventLoop = executor().inEventLoop(); synchronized (handlers) { int i = findCtxIdx(context -> context.name().equals(baseName)); if (i == -1) { throw new NoSuchElementException(baseName); } if (context(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } ctx = handlers.get(i); handlers.add(i + 1, newCtx); if (!inEventLoop) { try { executor.execute(() -> addAfter0(ctx, newCtx)); return this; } catch (Throwable cause) { handlers.remove(newCtx); throw cause; } } } addAfter0(ctx, newCtx); return this; }

Target:
public final ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { final AbstractChannelHandlerContext ctx; checkMultiplicity(handler); if (name == null) { name = generateName(handler); } AbstractChannelHandlerContext newCtx = newContext(name, handler); EventExecutor executor = executor(); boolean inEventLoop = executor.inEventLoop(); synchronized (handlers) { int i = findCtxIdx(context -> context.name().equals(baseName)); if (i == -1) { throw new NoSuchElementException(baseName); } if (context(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } ctx = handlers.get(i); handlers.add(i + 1, newCtx); if (!inEventLoop) { try { executor.execute(() -> addAfter0(ctx, newCtx)); return this; } catch (Throwable cause) { handlers.remove(i + 1); throw cause; } } } addAfter0(ctx, newCtx); return this; }
Source:
public void analyze_appActivitySameAppWithinConflictIntervalButNotContinuous_activityRecordNotMergedButNoNewGoalConflictMessageCreated() { ZonedDateTime now = now(); DayActivity existingDayActivity = mockExistingActivity(gamblingGoal, now.minusMinutes(10), now.minusMinutes(5), "Lotto App"); service.analyze(userAnonId, createSingleAppActivity("Lotto App", now.minusMinutes(4), now.minusMinutes(2))); verifyNoGoalConflictMessagesCreated(); List<Activity> activities = existingDayActivity.getActivities(); assertThat(activities.size(), equalTo(2)); assertThat(activities.get(1).getApp(), equalTo(Optional.of("Lotto App"))); assertThat(activities.get(1).getDurationMinutes(), equalTo(2)); }

Target:
public void analyze_appActivitySameAppWithinConflictIntervalButNotContinuous_activityRecordNotMergedButNoNewGoalConflictMessageCreated() { ZonedDateTime now = now(); ZonedDateTime existingActivityEndTime = now.minusMinutes(5); DayActivity existingDayActivity = mockExistingActivity(gamblingGoal, now.minusMinutes(10), now.minusMinutes(5), "Lotto App"); service.analyze(userAnonId, createSingleAppActivity("Lotto App", existingActivityEndTime.plusSeconds(1), now.minusMinutes(2))); verifyNoGoalConflictMessagesCreated(); List<Activity> activities = existingDayActivity.getActivities(); assertThat(activities.size(), equalTo(2)); assertThat(activities.get(1).getApp(), equalTo(Optional.of("Lotto App"))); assertThat(activities.get(1).getDurationMinutes(), equalTo(2)); }
Source:
public boolean tryLock(int timeoutMs) { if (!isInUse.compareAndSet(false, true)) { return false; } final String path; try { path = createAndGetLockPath(); } catch (InterruptedException e) { log.log( java.util.logging.Level.WARNING, "InterruptedException while trying to get lock path " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.WARNING, "KeeperException while trying to get lock path " + absoluteLockPath, e); return false; } try { absoluteLockPath = zk.create( path.toString(), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); log.log( java.util.logging.Level.INFO, "Created lock node with path: " + absoluteLockPath); final boolean wait = true; return attemptToLock(timeoutMs, wait); } catch (InterruptedException e) { log.log( java.util.logging.Level.INFO, "InterruptedException while trying to create lock " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.INFO, "KeeperException while trying to create lock " + absoluteLockPath, e); return false; } }

Target:
public boolean tryLock(int timeoutMs) { if (!isInUse.compareAndSet(false, true)) { return false; } final String path; try { path = createAndGetLockPath(); } catch (InterruptedException e) { log.log( java.util.logging.Level.WARNING, "InterruptedException while trying to get lock path " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.WARNING, "KeeperException while trying to get lock path " + absoluteLockPath, e); return false; } try { absoluteLockPath = zk.create( path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); log.log( java.util.logging.Level.INFO, "Created lock node with path: " + absoluteLockPath); final boolean wait = true; return attemptToLock(timeoutMs, wait); } catch (InterruptedException e) { log.log( java.util.logging.Level.INFO, "InterruptedException while trying to create lock " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.INFO, "KeeperException while trying to create lock " + absoluteLockPath, e); return false; } }
Source:
public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if (wf.getName().contains(actionName)) { if (wf.getExternalStatus() != null) { return wf.getExternalStatus(); } } } return ""; }

Target:
public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if ((wf.getName().contains(actionName)) && (wf.getExternalStatus() != null)) { return wf.getExternalStatus(); } } return ""; }
Source:
private void addAdaptiveExercisesFromStub(Course returnedFromServer, Course courseStub) { Set<Exercise> set = new HashSet<>(returnedFromServer.getExercises()); set.addAll(courseStub.getExercises()); returnedFromServer.setExercises(new ArrayList<>(set)); }

Target:
private void addAdaptiveExercisesFromStub(Course returnedFromServer, Course courseStub) { Set<Exercise> exercises = new HashSet<>(returnedFromServer.getExercises()); exercises.addAll(courseStub.getExercises()); returnedFromServer.setExercises(new ArrayList<>(exercises)); }
Source:
public Control onMessage(byte[] data, WebSocketSession session) { try { BinaryDecoder decoder = decoders.get(session.getConnection()); if (decoder == null) { decoder = new BinaryDecoder(); decoders.put(session.getConnection(), decoder); } try { return onMessage(decoder.decode(data), session); } catch (IOException e) { log.error("Invalid message"); return Control.malformedRequest("Invalid message"); } } catch (Exception e) { log.info("onMessage(data={}, session={}", data, session); log.error("Unexpected exception: " + e.getMessage(), e); return Control.error(e.getMessage()); } }

Target:
public Control onMessage(byte[] data, WebSocketSession session) throws Exception { try { BinaryDecoder decoder = decoders.get(session.getConnection()); if (decoder == null) { decoder = new BinaryDecoder(); decoders.put(session.getConnection(), decoder); } try { return onMessage(decoder.decode(data), session); } catch (IOException e) { log.error("Invalid message"); return Control.malformedRequest("Invalid message"); } } catch (RuntimeException e) { log.info("onMessage(data={}, session={}", data, session); log.error("Unexpected exception: " + e.getMessage(), e); return Control.error(e.getMessage()); } catch (Exception e) { log.info("onMessage(data={}, session={}", data, session); log.error("Unexpected exception: " + e.getMessage(), e); throw(e); } }
Source:
public void testUpdateUserMetadataWithoutTokens() { io.dockstore.openapi.client.ApiClient adminWebClient = getOpenAPIWebClient(ADMIN_USERNAME, testingPostgres); io.dockstore.openapi.client.ApiClient userWebClient = getOpenAPIWebClient(USER_2_USERNAME, testingPostgres); io.dockstore.openapi.client.api.UsersApi adminApi = new io.dockstore.openapi.client.api.UsersApi(adminWebClient); io.dockstore.openapi.client.api.UsersApi userApi = new io.dockstore.openapi.client.api.UsersApi(userWebClient); io.dockstore.openapi.client.model.User admin = adminApi.getUser(); io.dockstore.openapi.client.model.Profile userProfile = userApi.getUser().getUserProfiles().get("github.com"); testingPostgres.runUpdateStatement("DELETE FROM token"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); userApi.updateUserMetadata(); userProfile = userApi.getUser().getUserProfiles().get("github.com"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); }

Target:
public void testUpdateUserMetadataWithoutTokens() { io.dockstore.openapi.client.ApiClient adminWebClient = getOpenAPIWebClient(ADMIN_USERNAME, testingPostgres); io.dockstore.openapi.client.ApiClient userWebClient = getOpenAPIWebClient(USER_2_USERNAME, testingPostgres); io.dockstore.openapi.client.api.UsersApi adminApi = new io.dockstore.openapi.client.api.UsersApi(adminWebClient); io.dockstore.openapi.client.api.UsersApi userApi = new io.dockstore.openapi.client.api.UsersApi(userWebClient); io.dockstore.openapi.client.model.User admin = adminApi.getUser(); io.dockstore.openapi.client.model.Profile userProfile = userApi.getUser().getUserProfiles().get("github.com"); testingPostgres.runUpdateStatement("DELETE FROM token WHERE tokensource <> 'dockstore'"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); userApi.updateUserMetadata(); userProfile = userApi.getUser().getUserProfiles().get("github.com"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); }
Source:
public void deleteLocalDocument(final String docId) throws DocumentNotFoundException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(docId), "Input document id can not be empty"); try { queue.submit(new SQLQueueCallable<Object>() { @Override public Object call(SQLDatabase db) throws Exception { String[] whereArgs = {docId}; int rowsDeleted = db.delete("localdocs", "docid=? ", whereArgs); if (rowsDeleted == 0) { throw new DocumentNotFoundException("No local document with doc id: " + docId); } return null; } }).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new DocumentNotFoundException(String.format("Did not find document with id: %s",docId),e); } }

Target:
public void deleteLocalDocument(final String docId) throws DocumentNotFoundException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(docId), "Input document id can not be empty"); try { queue.submit(new SQLQueueCallable<Object>() { @Override public Object call(SQLDatabase db) throws Exception { String[] whereArgs = {docId}; int rowsDeleted = db.delete("localdocs", "docid=? ", whereArgs); if (rowsDeleted == 0) { throw new DocumentNotFoundException(docId, (String) null); } return null; } }).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new DocumentNotFoundException(docId,null,e); } }