auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static byte[] toByteArray(final HttpEntity entity) throws IOException { Args.notNull(entity, "Entity"); try (final InputStream inStream = entity.getContent()) { if (inStream == null) { return null; } final ByteArrayBuffer buffer = new ByteArrayBuffer(getCheckedContentLength(entity)); final byte[] tmp = new byte[DEFAULT_BYTE_BUFFER_SIZE]; int l; while ((l = inStream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toByteArray(); } }

Target:
public static byte[] toByteArray(final HttpEntity entity) throws IOException { Args.notNull(entity, "Entity"); final int contentLength = toContentLength((int) Args.checkContentLength(entity)); try (final InputStream inStream = entity.getContent()) { if (inStream == null) { return null; } final ByteArrayBuffer buffer = new ByteArrayBuffer(contentLength); final byte[] tmp = new byte[DEFAULT_BYTE_BUFFER_SIZE]; int l; while ((l = inStream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toByteArray(); } }
Source:
public boolean supports(String databaseType) { return databaseType.equals(PostgreSQLContainer.NAME) || databaseType.equals(PostgisContainer.NAME); }

Target:
public boolean supports(String databaseType) { return databaseType.equals(PostgreSQLContainer.NAME); }
Source:
private void sendChannelReadOnlyEvent() { Request request = new Request(); request.setEvent(true); request.setData(Request.READONLY_EVENT); request.setTwoWay(false); request.setVersion(Version.getProtocolVersion()); Collection<Channel> channels = getChannels(); for (Channel channel : channels) { try { if (channel.isConnected()) { channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { logger.warn("send cannot write message error.", e); } } }

Target:
private void sendChannelReadOnlyEvent() { Request request = new Request(); request.setEvent(Request.READONLY_EVENT); request.setTwoWay(false); request.setVersion(Version.getProtocolVersion()); Collection<Channel> channels = getChannels(); for (Channel channel : channels) { try { if (channel.isConnected()) { channel.send(request, getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { logger.warn("send cannot write message error.", e); } } }
Source:
public T[] postMatch(Class declaring, AccessibleObject target) { if(cachedPostMatch == null || declaring != null || target != null) { List<Match> matches = new ArrayList<Match>(); for (InterceptorFactory factory : interceptors) { Match match = factory.postMatch(declaring, target); if (match != null) { matches.add(match); } } cachedPostMatch = createArray(matches); } return cachedPostMatch; }

Target:
public T[] postMatch(Class declaring, AccessibleObject target) { if(cachedPostMatch != null && declaring == null && target == null) { return cachedPostMatch; } List<Match> matches = new ArrayList<Match>(); for (InterceptorFactory factory : interceptors) { Match match = factory.postMatch(declaring, target); if (match != null) { matches.add(match); } } final T[] array = createArray(matches); if(declaring == null && target == null) { cachedPostMatch = array; } return array; }
Source:
public DashboardResource parse(ProjectResource parent, String id) throws ResourceNotFoundException, IOException, ConfigInvalidException { ProjectControl myCtl = parent.getControl(); if ("default".equals(id)) { return DashboardResource.projectDefault(myCtl); } List<String> parts = Lists.newArrayList( Splitter.on(':').limit(2).split(id)); if (parts.size() != 2) { throw new ResourceNotFoundException(id); } String ref = URLDecoder.decode(parts.get(0), "UTF-8"); String path = URLDecoder.decode(parts.get(1), "UTF-8"); Set<Project.NameKey> seen = Sets.newHashSet(); Project.NameKey name = myCtl.getProject().getNameKey(); ProjectControl ctl = myCtl; seen.add(name); do { try { return parse(ctl, ref, path, myCtl); } catch (Exception e) { try { ProjectState ps = ctl.getProjectState().getParentState(); if (ps == null) { break; } name = ps.getProject().getNameKey(); if (!seen.add(name)) { break; } ctl = projectFactory.controlFor(name, ctl.getCurrentUser()); } catch (NoSuchProjectException pnf) { throw new ResourceNotFoundException(id); } } } while (ctl != null); throw new ResourceNotFoundException(id); }

Target:
public DashboardResource parse(ProjectResource parent, String id) throws ResourceNotFoundException, IOException, ConfigInvalidException { ProjectControl myCtl = parent.getControl(); if ("default".equals(id)) { return DashboardResource.projectDefault(myCtl); } List<String> parts = Lists.newArrayList( Splitter.on(':').limit(2).split(id)); if (parts.size() != 2) { throw new ResourceNotFoundException(id); } String ref = URLDecoder.decode(parts.get(0), "UTF-8"); String path = URLDecoder.decode(parts.get(1), "UTF-8"); Set<Project.NameKey> seen = Sets.newHashSet(); Project.NameKey name = myCtl.getProject().getNameKey(); ProjectControl ctl = myCtl; seen.add(name); do { try { return parse(ctl, ref, path, myCtl); } catch (AmbiguousObjectException e) { throw new ResourceNotFoundException(id); } catch (IncorrectObjectTypeException e) { throw new ResourceNotFoundException(id); } catch (ResourceNotFoundException e) { try { ProjectState ps = ctl.getProjectState().getParentState(); if (ps == null) { break; } name = ps.getProject().getNameKey(); if (!seen.add(name)) { break; } ctl = projectFactory.controlFor(name, ctl.getCurrentUser()); } catch (NoSuchProjectException pnf) { throw new ResourceNotFoundException(id); } } } while (ctl != null); throw new ResourceNotFoundException(id); }
Source:
public void apply(Project project) { SarosEclipseExtension e = project.getExtensions().create(EXTENSION_NAME, SarosEclipseExtension.class); project.afterEvaluate( (p) -> { configureEclipseAfterEvaluate(p, e); }); }

Target:
public void apply(Project project) { SarosEclipseExtension e = project.getExtensions().create(EXTENSION_NAME, SarosEclipseExtension.class); project.afterEvaluate(p -> configureEclipseAfterEvaluate(p, e)); }
Source:
public void streamEventsbyName() throws IOException, InterruptedException { List<ServerSentEvent<String>> events = getServerSentEvents(ACTUATOR_STREAM_CIRCUITBREAKER_EVENTS + "/backendA"); CircuitBreakerEventsEndpointResponse circuitBreakerEventsBefore = circuitBreakerEvents(ACTUATOR_CIRCUITBREAKEREVENTS + "/backendA"); dummyService.doSomething(false); Thread.sleep(1000); try { dummyService.doSomething(true); } catch (IOException ex) { } CircuitBreakerEventsEndpointResponse circuitBreakerEventsAfter = circuitBreakerEvents(ACTUATOR_CIRCUITBREAKEREVENTS + "/backendA"); Thread.sleep(1000); assert (circuitBreakerEventsBefore.getCircuitBreakerEvents().size() < circuitBreakerEventsAfter.getCircuitBreakerEvents().size()); assert (events.size() == 2); }

Target:
public void streamEventsbyName() throws IOException, InterruptedException { List<ServerSentEvent<String>> events = getServerSentEvents(ACTUATOR_STREAM_CIRCUITBREAKER_EVENTS + "/backendB"); CircuitBreakerEventsEndpointResponse circuitBreakerEventsBefore = circuitBreakerEvents(ACTUATOR_CIRCUITBREAKEREVENTS + "/backendB"); publishEvents(); CircuitBreakerEventsEndpointResponse circuitBreakerEventsAfter = circuitBreakerEvents(ACTUATOR_CIRCUITBREAKEREVENTS + "/backendB"); Thread.sleep(1000); assertThat (circuitBreakerEventsBefore.getCircuitBreakerEvents().size()).isLessThan(circuitBreakerEventsAfter.getCircuitBreakerEvents().size()); assertThat (events.size()).isEqualTo(2); }
Source:
private AliasResolvingEquivalenceGenerator(Builder builder) { this.resolver = checkNotNull(builder.resolver); this.publishers = checkNotNull(builder.publishers); this.lookupEntryStore = checkNotNull(builder.lookupEntryStore); this.namespacesSet = checkNamespacesSet(checkNotNull(builder.namespacesSet)); this.aliasMatchingScore = checkNotNull(builder.aliasMatchingScore); this.includeUnpublishedContent = builder.includeUnpublishedContent; this.cls = checkNotNull(builder.cls); }

Target:
private AliasResolvingEquivalenceGenerator(Builder builder) { this.resolver = checkNotNull(builder.resolver); this.publishers = checkNotNull(builder.publishers); this.lookupEntryStore = checkNotNull(builder.lookupEntryStore); this.namespacesSet = checkNamespacesSet(builder.namespacesSet); this.aliasMatchingScore = checkNotNull(builder.aliasMatchingScore); this.includeUnpublishedContent = checkNotNull(builder.includeUnpublishedContent); this.cls = checkNotNull(builder.cls); }
Source:
public IgnoreConditionCreator(Class<?> aTestClass, ConditionalRun[] annotation) { this.mTestClass = aTestClass; this.conditionType = new ArrayList<>(annotation.length); for (int i = 0; i < annotation.length; i++) { this.conditionType.add(i, annotation[i].condition()); } }

Target:
public IgnoreConditionCreator(Class<?> aTestClass, ConditionalRun[] annotation) { this.mTestClass = aTestClass; this.conditionTypes = new ArrayList<>(annotation.length); for (int i = 0; i < annotation.length; i++) { this.conditionTypes.add(i, annotation[i].condition()); } }
Source:
private void updateDrawerNavigation() { if (getSupportActionBar() == null) return; final Toolbar toolbar = findViewById(R.id.toolbar); final DrawerLayout drawer = findViewById(R.id.drawer_layout); final Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_holder); if (fragment instanceof MainFragment) { getSupportActionBar().setDisplayHomeAsUpEnabled(false); if (toggle != null) { toggle.syncState(); toolbar.setNavigationOnClickListener(v -> drawer.openDrawer(GravityCompat.START)); drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNDEFINED); } return; } if (fragment instanceof SearchFragment) { getSupportActionBar().setDisplayHomeAsUpEnabled(false); if (toggle != null) { drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(v -> onHomeButtonPressed()); } return; } }

Target:
private void updateDrawerNavigation() { if (getSupportActionBar() == null) return; final Toolbar toolbar = findViewById(R.id.toolbar); final DrawerLayout drawer = findViewById(R.id.drawer_layout); final Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_holder); if (fragment instanceof SearchFragment) { if (toggle != null) { drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(v -> onHomeButtonPressed()); return; } } else { if (toggle != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(false); toggle.syncState(); toolbar.setNavigationOnClickListener(v -> drawer.openDrawer(GravityCompat.START)); drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNDEFINED); } return; } }
Source:
public void rewind() throws IOException { super.rewind(); for (int i=size-1;i>=0;i--) { File fi = getNumberedFileName(i); if (fi.exists()) { File next = getNumberedFileName(i+1); if (!next.delete()){ throw new IOException(String.format("Could not delete %s", next.getAbsolutePath())); } fi.renameTo(next); } } }

Target:
public void rewind() throws IOException { super.rewind(); for (int i=size-1;i>=0;i--) { File fi = getNumberedFileName(i); if (fi.exists()) { File next = getNumberedFileName(i+1); next.delete(); fi.renameTo(next); } } }
Source:
public void flush(int targetSubpartition) { finishBroadcastBufferBuilder(); finishSubpartitionBufferBuilder(targetSubpartition); super.flush(targetSubpartition); }

Target:
public void flush(int targetSubpartition) { flushSubpartition(targetSubpartition, true); }
Source:
public UIButtonWebBrowser setUrl(String url) { boolean trustedUrl = false; boolean trustedHostName = false; if (webBrowserConfig != null) { trustedUrl = webBrowserConfig.isUrlTrusted(url); String hostname; try { hostname = (new URL(url)).getHost(); trustedHostName = webBrowserConfig.isHostNameTrusted(hostname); } catch (MalformedURLException e) { } } if (trustedHostName || trustedUrl) { confirmed.set(true); } else { confirmed.set(false); } this.url = url; return this; }

Target:
public UIButtonWebBrowser setUrl(String url) { boolean trustedUrl = false; if (webBrowserConfig != null) { trustedUrl = webBrowserConfig.isUrlTrusted(url); } confirmed.set(trustedUrl); this.url = url; return this; }
Source:
public void testParseEncoding_Accept_Latin_One_AsISO8859_1() { Charset result = RawParseUtils.parseEncoding("encoding latin-1\n" .getBytes()); assertNotNull(result); }

Target:
public void testParseEncoding_Accept_Latin_One_AsISO8859_1() { Charset result = RawParseUtils.parseEncoding("encoding latin-1\n" .getBytes()); assertNotNull(result); assertEquals("ISO-8859-1", result.name()); }
Source:
ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(CacheMode.LOCAL); configurationBuilder.indexing().index(Index.ALL) .addProperty("default.directory_provider", "ram"); return configurationBuilder; }

Target:
ConfigurationBuilder getConfigBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(CacheMode.LOCAL); configurationBuilder.indexing().index(Index.ALL) .addProperty("default.directory_provider", "local-heap"); return configurationBuilder; }
Source:
private static String getPatchedPathWithCurrentJavaBinLocation() { String currentJavaHome = System.getProperty("java.home"); String originPathVariable = System.getenv("PATH"); return File.pathSeparator + currentJavaHome + File.separator + "bin" + File.separator + File.pathSeparator + originPathVariable; }

Target:
private static String getPatchedPathWithCurrentJavaBinLocation() { String currentJavaHome = System.getProperty("java.home"); String originPathVariable = System.getenv("PATH"); return currentJavaHome + File.separator + "bin" + File.separator + File.pathSeparator + originPathVariable; }
Source:
private Map<String, Object> populateAttributes(final Map<String, Object> rowAttributes, final List<String> names) { final Map<String, Object> newAttributes = new HashMap<>(); for (final Map.Entry<String, Object> entry : rowAttributes.entrySet()) { final String name = entry.getKey(); if (names == null || names.contains(name)) { newAttributes.put(name, entry.getValue()); } } return newAttributes; }

Target:
private Map<String, Object> populateAttributes(final Map<String, Object> rowAttributes, final List<String> names) { return rowAttributes.entrySet().stream() .filter(p -> names == null || names.contains(p.getKey())) .collect(HashMap::new, (m,v)->m.put(v.getKey(), v.getValue()), HashMap::putAll); }
Source:
public void testTotalCountValue() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(0, callback); for (CheckpointFailureReason reason : CheckpointFailureReason.values()) { failureManager.handleJobLevelCheckpointException(new CheckpointException(reason), -1); } assertEquals(1, callback.getInvokeCounter()); }

Target:
public void testTotalCountValue() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(0, callback); for (CheckpointFailureReason reason : CheckpointFailureReason.values()) { failureManager.handleJobLevelCheckpointException(new CheckpointException(reason), -1); } assertEquals(2, callback.getInvokeCounter()); }
Source:
public void testClientProxySettings() throws URISyntaxException, IOException { conf.setCurlLogging(true); final Map<String, String> headers = new HashMap<String, String>(); headers.put("key1", "value1"); headers.put("key2", "value2"); final HashSet<String> expectedCurlHeaders = new HashSet<String>(); for (final Map.Entry<String, String> entry : headers.entrySet()) { expectedCurlHeaders.add("\"" + entry.getKey() + ":" + entry.getValue() + "\""); } final HttpRequest request = new HttpRequest("POST", new URI("<LINK_0>"), headers, null ); conf.setProtocol(Protocol.HTTP); conf.setProxyHost(server.getListenAddress().getHostName()); conf.setProxyPort(server.getListenAddress().getPort()); try { client.execute(request); } catch (final UnknownHostException exception) { return; } assertNotNull(client.proxy); assertEquals(client.proxy.address(), server.getListenAddress()); assertTrue("Expected UnknownHostException. UnknownHostException not thrown while executing the request.", true); }

Target:
public void testClientProxySettings() throws URISyntaxException, IOException { HttpProxyServer server = DefaultHttpProxyServer.bootstrap() .withPort(8080) .start(); conf.setCurlLogging(true); final Map<String, String> headers = new HashMap<String, String>(); headers.put("key1", "value1"); headers.put("key2", "value2"); final HashSet<String> expectedCurlHeaders = new HashSet<String>(); for (final Map.Entry<String, String> entry : headers.entrySet()) { expectedCurlHeaders.add("\"" + entry.getKey() + ":" + entry.getValue() + "\""); } final HttpRequest request = new HttpRequest("POST", new URI("<LINK_0>"), headers, null ); conf.setProtocol(Protocol.HTTP); conf.setProxyHost(server.getListenAddress().getHostName()); conf.setProxyPort(server.getListenAddress().getPort()); client = new MockUrlHttpClient(conf); try { client.execute(request); } catch (final UnknownHostException exception) { throw exception; } assertNotNull(client.proxy); assertEquals(client.proxy.address(), server.getListenAddress()); assertTrue("Expected UnknownHostException. UnknownHostException not thrown while executing the request.", true); server.stop(); }
Source:
private void clickPopup(final int buttonNo) { final AbstractScene scene = ShaftEscape.getScene(); if (scene.getPopup() != null) { ObservableList<Node> buttons; sleep(1); buttons = ((VBox) scene.getPopup().getContent().get(1)) .getChildren(); buttons = ((HBox) buttons.get(buttons.size() - 1)).getChildren(); try { clickOn(buttons.get(buttonNo), MouseButton.PRIMARY); } catch (ArrayIndexOutOfBoundsException e) { fail("ButtonNo " + buttonNo + " does not exist"); } sleep(SHORT); } }

Target:
private void clickPopup(final int buttonNo) { if (AbstractScene.getPopup() != null) { ObservableList<Node> buttons; sleep(1); buttons = ((VBox) AbstractScene.getPopup().getContent().get(1)) .getChildren(); buttons = ((HBox) buttons.get(buttons.size() - 1)).getChildren(); try { clickOn(buttons.get(buttonNo), MouseButton.PRIMARY); } catch (ArrayIndexOutOfBoundsException e) { fail("ButtonNo " + buttonNo + " does not exist"); } sleep(SHORT); } }
Source:
protected void recoverFromException(final String curQueue, final Exception ex) { final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue); switch (recoveryStrategy) { case RECONNECT: if (ex instanceof JedisNoScriptException) { LOG.info("got JedisNoScriptException while reconnecting, reloading redis scripts"); loadRedisScripts(); } else { LOG.info("waiting for pool to reconnect to redis", ex); try { Thread.sleep(RECONNECT_SLEEP_TIME); } catch (InterruptedException e) { } } break; case TERMINATE: LOG.warn("Terminating in response to exception", ex); end(false); break; case PROCEED: this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex); break; default: LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy + " while attempting to recover from the following exception; worker proceeding...", ex); break; } }

Target:
protected void recoverFromException(final String curQueue, final Exception ex) { final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue); switch (recoveryStrategy) { case RECONNECT: if (ex instanceof JedisNoScriptException) { LOG.info("Got JedisNoScriptException while reconnecting, reloading Redis scripts"); loadRedisScripts(); } else { LOG.info("Waiting " + RECONNECT_SLEEP_TIME + "ms for pool to reconnect to redis", ex); try { Thread.sleep(RECONNECT_SLEEP_TIME); } catch (InterruptedException e) { } } break; case TERMINATE: LOG.warn("Terminating in response to exception", ex); end(false); break; case PROCEED: this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex); break; default: LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy + " while attempting to recover from the following exception; worker proceeding...", ex); break; } }
Source:
private PullRequest getPullRequest(String payload, GitHub gh) throws IOException { return gh.parseEventPayload(new StringReader(payload), PullRequest.class); }

Target:
private PullRequest getPullRequest(String payload, GitHub gh) throws IOException { @SuppressWarnings("UnnecessaryLocalVariable") PullRequest pr = gh.parseEventPayload(new StringReader(payload), PullRequest.class); return pr; }
Source:
private MergingReport mergeManifests( File mainManifestFile, List<File> libraryManifestFiles, BuckEventAndroidLogger logger) { try { MergingReport mergingReport = ManifestMerger2 .newMerger(mainManifestFile, logger, ManifestMerger2.MergeType.APPLICATION) .withFeatures( ManifestMerger2.Invoker.Feature.NO_PLACEHOLDER_REPLACEMENT, ManifestMerger2.Invoker.Feature.REMOVE_TOOLS_DECLARATIONS, ManifestMerger2.Invoker.Feature.SKIP_BLAME) .addLibraryManifests(Iterables.toArray(libraryManifestFiles, File.class)) .merge(); if (mergingReport.getResult().isError()) { mergingReport.log(logger); throw new HumanReadableException("Error generating manifest file"); } return mergingReport; } catch (ManifestMerger2.MergeFailureException e) { throw new HumanReadableException(e, "Error generating manifest file"); } }

Target:
private MergingReport mergeManifests( File mainManifestFile, List<File> libraryManifestFiles, BuckEventAndroidLogger logger) { try { MergingReport mergingReport = ManifestMerger2 .newMerger(mainManifestFile, logger, ManifestMerger2.MergeType.APPLICATION) .withFeatures( ManifestMerger2.Invoker.Feature.NO_PLACEHOLDER_REPLACEMENT, ManifestMerger2.Invoker.Feature.REMOVE_TOOLS_DECLARATIONS, ManifestMerger2.Invoker.Feature.SKIP_BLAME) .addLibraryManifests(Iterables.toArray(libraryManifestFiles, File.class)) .merge(); if (mergingReport.getResult().isError()) { for (MergingReport.Record record : mergingReport.getLoggingRecords()) { logger.error(null, record.toString()); } throw new HumanReadableException("Error generating manifest file"); } return mergingReport; } catch (ManifestMerger2.MergeFailureException e) { throw new HumanReadableException(e, "Error generating manifest file"); } }
Source:
public static boolean atHashCheckRequired(List<String> responseTypes) { Set<String> types = Sets.newHashSet(); responseTypes.forEach((s) -> { if (s != null && !s.isEmpty()) { types.addAll(Lists.newArrayList(s.split(" "))); } }); if (types.contains("token") && types.contains("id_token")) return true; return false; }

Target:
public static boolean atHashCheckRequired(List<String> responseTypes) { return responseTypes.stream().anyMatch(s -> ResponseType.fromString(s, " ").contains(ResponseType.TOKEN)); }
Source:
public String readMonitoring() throws InterruptedException { String result = null; int retry = 0; do { try { result = receiveMonitorOPEN(monitorSk); } catch (IOException e) { try { MyHomeSocketFactory.disconnect(monitorSk); } catch (IOException e1) { } retry++; Thread.sleep(1000); System.err.println("Monitor connection problem retry temptative: " + retry); try { startMonitoring(); } catch (IOException e1) { } continue; } } while (result == null); return result; }

Target:
public String readMonitoring() throws InterruptedException { String result = null; int retry = 0; do { try { result = receiveMonitorOPEN(monitorSk); } catch (IOException e) { try { MyHomeSocketFactory.disconnect(monitorSk); } catch (IOException e1) { } retry++; Thread.sleep(1000); logger.warn("Monitor connection problem. Attempting retry {}.", retry); try { startMonitoring(); } catch (IOException e1) { } } } while (result == null); return result; }
Source:
protected ExceptionHolder findZuulException(Throwable throwable) { if (throwable.getCause() instanceof ZuulRuntimeException) { Throwable cause = throwable.getCause().getCause().getCause(); if (cause instanceof ClientException && cause.getCause() != null && cause.getCause().getCause() instanceof SocketTimeoutException) { ZuulException zuulException = new ZuulException("", 504, ZuulException.class.getName() + ": Hystrix Readed time out"); return new ZuulExceptionHolder(zuulException); } return new ZuulExceptionHolder((ZuulException) throwable.getCause().getCause()); } if (throwable.getCause() instanceof ZuulException) { return new ZuulExceptionHolder((ZuulException) throwable.getCause()); } if (throwable instanceof ZuulException) { return new ZuulExceptionHolder((ZuulException) throwable); } return new DefaultExceptionHolder(throwable); }

Target:
protected ExceptionHolder findZuulException(Throwable throwable) { if (throwable.getCause() instanceof ZuulRuntimeException) { Throwable cause = null; if (throwable.getCause().getCause() != null) { cause = throwable.getCause().getCause().getCause(); } if (cause instanceof ClientException && cause.getCause() != null && cause.getCause().getCause() instanceof SocketTimeoutException) { ZuulException zuulException = new ZuulException("", 504, ZuulException.class.getName() + ": Hystrix Readed time out"); return new ZuulExceptionHolder(zuulException); } return new ZuulExceptionHolder((ZuulException) throwable.getCause().getCause()); } if (throwable.getCause() instanceof ZuulException) { return new ZuulExceptionHolder((ZuulException) throwable.getCause()); } if (throwable instanceof ZuulException) { return new ZuulExceptionHolder((ZuulException) throwable); } return new DefaultExceptionHolder(throwable); }
Source:
public FormValidation doCheckHookUrl(@QueryParameter String value) { try { HttpURLConnection con = (HttpURLConnection) new URL(value).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty(GitHubWebHook.URL_VALIDATION_HEADER, "true"); con.connect(); if (con.getResponseCode()!=200) { return FormValidation.error("Got "+con.getResponseCode()+" from "+value); } String v = con.getHeaderField(GitHubWebHook.X_INSTANCE_IDENTITY); if (v == null) { return FormValidation.warning("It doesn't look like " + value + " is talking to any Jenkins. Are you running your own app?"); } RSAPublicKey key = identity.getPublic(); String expected = new String(Base64.encodeBase64(key.getEncoded()), "UTF-8" ); if (!expected.equals(v)) { return FormValidation.error(value+" is connecting to different Jenkins instances"); } return FormValidation.ok(); } catch (UnsupportedEncodingException ex) { return FormValidation.error("Unsupported exception "+ex.getLocalizedMessage()); } catch (IOException e) { return FormValidation.error(e,"Failed to test a connection to "+value); } }

Target:
public FormValidation doCheckHookUrl(@QueryParameter String value) { try { HttpURLConnection con = (HttpURLConnection) new URL(value).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty(GitHubWebHook.URL_VALIDATION_HEADER, "true"); con.connect(); if (con.getResponseCode()!=200) { return FormValidation.error("Got "+con.getResponseCode()+" from "+value); } String v = con.getHeaderField(GitHubWebHook.X_INSTANCE_IDENTITY); if (v == null) { return FormValidation.warning("It doesn't look like " + value + " is talking to any Jenkins. Are you running your own app?"); } RSAPublicKey key = identity.getPublic(); String expected = new String(Base64.encodeBase64(key.getEncoded()), "UTF-8" ); if (!expected.equals(v)) { return FormValidation.error(value+" is connecting to different Jenkins instances"); } return FormValidation.ok(); } catch (UnsupportedEncodingException ex) { return FormValidation.error("Unsupported exception {0}", ex.getLocalizedMessage()); } catch (IOException e) { return FormValidation.error(e,"Failed to test a connection to "+value); } }
Source:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (!nextRequestHandler.needsCoordinator()) { time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.lookupCoordinator(nextRequestHandler); transactionManager.retry(nextRequestHandler); }

Target:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.retry(nextRequestHandler); }
Source:
public void saveLibraryDilutions(final Collection<LibraryDilution> libraryDilutions) throws IOException { log.info("Migrating library dilutions..."); for (LibraryDilution ldi : libraryDilutions) { log.debug("Saving library dilution " + ldi.getName()); if (replaceChangeLogs) { if (ldi.getCreationDate() == null || ldi.getLastModified() == null) { throw new IOException("Cannot save dilution due to missing timestamps"); } } else { ldi.setCreationDate(timeStamp); ldi.setLastModified(timeStamp); } if (ldi.getLibrary().getId() == AbstractDilution.UNSAVED_ID && ldi.getLibrary().getLibraryAdditionalInfo() != null && ldi.getLibrary().getLibraryAdditionalInfo().getPreMigrationId() != null) { ldi.setLibrary(serviceManager.getLibraryDao().getByPreMigrationId(ldi.getLibrary().getLibraryAdditionalInfo().getPreMigrationId())); if (ldi.getLibrary() == null) { throw new IOException("No Library found with pre-migration ID " + ldi.getLibrary().getLibraryAdditionalInfo().getPreMigrationId()); } } ldi.setId(serviceManager.getDilutionDao().save(ldi)); log.debug("Saved library dilution " + ldi.getName()); } log.info(libraryDilutions.size() + " library dilutions migrated."); }

Target:
public void saveLibraryDilutions(final Collection<LibraryDilution> libraryDilutions) throws IOException { log.info("Migrating library dilutions..."); for (LibraryDilution ldi : libraryDilutions) { String friendlyName = " of " + ldi.getLibrary().getAlias(); if (ldi.getPreMigrationId() != null) { friendlyName += " with pre-migration id " + ldi.getPreMigrationId(); } log.debug("Saving library dilution " + friendlyName); if (replaceChangeLogs) { if (ldi.getCreationDate() == null || ldi.getLastModified() == null) { throw new IOException("Cannot save dilution due to missing timestamps"); } } else { ldi.setCreationDate(timeStamp); ldi.setLastModified(timeStamp); } if (ldi.getLibrary().getId() == AbstractDilution.UNSAVED_ID && ldi.getLibrary().getLibraryAdditionalInfo() != null && ldi.getLibrary().getLibraryAdditionalInfo().getPreMigrationId() != null) { ldi.setLibrary(serviceManager.getLibraryDao().getByPreMigrationId(ldi.getLibrary().getLibraryAdditionalInfo().getPreMigrationId())); if (ldi.getLibrary() == null) { throw new IOException("No Library found with pre-migration ID " + ldi.getLibrary().getLibraryAdditionalInfo().getPreMigrationId()); } } ldi.setId(serviceManager.getDilutionDao().save(ldi)); log.debug("Saved library dilution " + friendlyName); } log.info(libraryDilutions.size() + " library dilutions migrated."); }
Source:
protected void processFiltered(File file, List<String> lines) throws CheckstyleException { String filePath; String folderPath; try { filePath = file.getCanonicalPath(); folderPath = file.getParentFile().getCanonicalPath(); } catch (IOException ex) { filePath = file.getAbsolutePath(); folderPath = file.getParentFile().getAbsolutePath(); } if (ignoreFileExtensions) { final int extension = filePath.lastIndexOf('.'); final int separator = filePath.lastIndexOf(File.separatorChar); if (extension > separator) { filePath = filePath.substring(0, extension); } } if (isMatchFolder(folderPath) && isMatchFile(filePath)) { if (match) { log(0, MSG_MATCH, filePath); } else { log(0, MSG_MISMATCH, filePath); } } }

Target:
protected void processFiltered(File file, List<String> lines) throws CheckstyleException { final String fileName = getFileName(file); final String folderPath = getFolderPath(file); if (isMatchFolder(folderPath) && isMatchFile(fileName)) { log(); } }
Source:
private CommonAggregateStats getPlaceholderCommonAggregateStats(Object component) { CommonAggregateStats commonStats = new CommonAggregateStats(); Map<String, Object> jsonMap = StormCommon.componentConf(component); int numTasks = (int) (long) jsonMap.getOrDefault(Config.TOPOLOGY_TASKS, 0); commonStats.set_num_executors(numTasks); commonStats.set_num_tasks(numTasks); commonStats.set_emitted(0); commonStats.set_transferred(0); commonStats.set_acked(0); return commonStats; }

Target:
private CommonAggregateStats getPlaceholderCommonAggregateStats(Object component) { CommonAggregateStats commonStats = new CommonAggregateStats(); int numExecutors = 0; try { numExecutors = StormCommon.numStartExecutors(component); } catch (InvalidTopologyException e) { } Map<String, Object> jsonMap = StormCommon.componentConf(component); int numTasks = ObjectReader.getInt(jsonMap.getOrDefault(Config.TOPOLOGY_TASKS, numExecutors)); commonStats.set_num_executors(numExecutors); commonStats.set_num_tasks(numTasks); commonStats.set_emitted(0); commonStats.set_transferred(0); commonStats.set_acked(0); return commonStats; }
Source:
public VolatilitySurface getVolSurface(final DoubleMatrix1D modelParameters) { final Function1D<double[], Double> func = new BasisFunctionAggregation<>(_bSplines, modelParameters.getData()); final Function2D<Double, Double> func2D = new Function2D<Double, Double>() { @Override public Double evaluate(final Double t, final Double k) { return func.evaluate(new double[] {t, k }); } }; final FunctionalDoublesSurface surface = new FunctionalDoublesSurface(func2D); return new VolatilitySurface(surface); }

Target:
public VolatilitySurface getVolSurface(final DoubleMatrix1D modelParameters) { ArgumentChecker.notNull(modelParameters, "modelParameters"); final Function1D<double[], Double> func = new BasisFunctionAggregation<>(_bSplines, modelParameters.getData()); final Function2D<Double, Double> func2D = new Function2D<Double, Double>() { @Override public Double evaluate(final Double t, final Double k) { return func.evaluate(new double[] {t, k }); } }; final FunctionalDoublesSurface surface = new FunctionalDoublesSurface(func2D); return new VolatilitySurface(surface); }
Source:
public int copyTo(final Map<String,?> props, InputStream src, long filesize, final String destination) { final long finalFilesize; final InputStream finalSrc; if (filesize==-1) { try { File tempFile = File.createTempFile("sshcopy", "data"); tempFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tempFile); ResourceUtils.copy(src, out); out.close(); finalFilesize = tempFile.length(); finalSrc = new FileInputStream(tempFile); } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(src); } } else { finalFilesize = filesize; finalSrc = src; } return execSsh(props, new Function<SshTool,Integer>() { public Integer apply(SshTool ssh) { return ssh.createFile(props, destination, finalSrc, finalFilesize); }}); }

Target:
public int copyTo(final Map<String,?> props, InputStream src, long filesize, final String destination) { final long finalFilesize; final InputStream finalSrc; if (filesize==-1) { try { File tempFile = ResourceUtils.writeToTempFile(src, "sshcopy", "data"); finalFilesize = tempFile.length(); finalSrc = new FileInputStream(tempFile); } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(src); } } else { finalFilesize = filesize; finalSrc = src; } return execSsh(props, new Function<SshTool,Integer>() { public Integer apply(SshTool ssh) { return ssh.createFile(props, destination, finalSrc, finalFilesize); }}); }
Source:
private void checkPercentageValidity(int percentage, String message) { if (percentage < 0 || percentage > 100) { throw new IllegalArgumentException(message); } }

Target:
private static void checkPercentageValidity(int percentage, String message) { if (percentage < 0 || percentage > 100) { throw new IllegalArgumentException(message); } }
Source:
public WebSocket akkaStreamsSocket() { return WebSocket.Json.accept( request -> { Sink<JsonNode, ?> in = Sink.foreach(System.out::println); final MessageDTO messageDTO = new MessageDTO("1", "1", "Title", "Test Body"); Source<JsonNode, ?> out = Source.tick( Duration.ofSeconds(2), Duration.ofSeconds(2), MessageConverter.messageToJsonNode(messageDTO) ); return Flow.fromSinkAndSource(in, out); }); }

Target:
public WebSocket akkaStreamsSocket() { return WebSocket.Json.accept( request -> { Sink<JsonNode, ?> in = Sink.foreach(System.out::println); MessageDTO messageDTO = new MessageDTO("1", "1", "Title", "Test Body"); Source<JsonNode, ?> out = Source.tick( Duration.ofSeconds(2), Duration.ofSeconds(2), MessageConverter.messageToJsonNode(messageDTO) ); return Flow.fromSinkAndSource(in, out); }); }
Source:
public static int getIntParameter(String inParameter, int inDefault) { try { return getConfig().getInt(inParameter, inDefault); } catch (RuntimeException e) { return 0; } }

Target:
public static int getIntParameter(String inParameter, int inDefault) { try { return getConfig().getInt(inParameter, inDefault); } catch (ConversionException e) { return inDefault; } }
Source:
public List<Environment.Variable> environment() { List<Environment.Variable> env = new ArrayList<>(asList( Environment.Variable.newBuilder() .setName("CRATE_HEAP_SIZE") .setValue(String.format("%sm", configuration.resHeap.longValue())) .build() )); return env; }

Target:
public List<Environment.Variable> environment() { List<Environment.Variable> env = asList( Environment.Variable.newBuilder() .setName("CRATE_HEAP_SIZE") .setValue(String.format("%sm", configuration.resHeap.longValue())) .build() ); return env; }
Source:
public void onEventMainThread(DiscussionThreadFollowedEvent event) { for (int i = 0; i < discussionPostsAdapter.getCount(); ++i) { if (discussionPostsAdapter.getItem(i).getIdentifier().equalsIgnoreCase(event.getDiscussionThread().getIdentifier())) { discussionPostsAdapter.replace(event.getDiscussionThread(), i); break; } } }

Target:
public void onEventMainThread(DiscussionThreadFollowedEvent event) { for (int i = 0; i < discussionPostsAdapter.getCount(); ++i) { if (discussionPostsAdapter.getItem(i).hasSameId(event.getDiscussionThread())) { discussionPostsAdapter.replace(event.getDiscussionThread(), i); break; } } }
Source:
public void updated(Map<String, Object> properties) { cancelPollTask(); this.options = new WatchdogServiceOptions(properties); if (this.options.isEnabled()) { this.rebootCauseWriter = new RebootCauseFileWriter(this.options.getRebootCauseFilePath()); try (PrintWriter wdWriter = new PrintWriter(WD_FILE);) { wdWriter.write(this.options.getWatchdogDevice()); } catch (IOException e) { logger.error("Unable to write watchdog config file", e); } this.pollTask = this.pollExecutor.scheduleAtFixedRate(() -> { Thread.currentThread().setName("WatchdogServiceImpl"); checkCriticalComponents(); }, 0, this.options.getPingInterval(), TimeUnit.MILLISECONDS); } else { disableWatchdog(); } }

Target:
public void updated(Map<String, Object> properties) { cancelPollTask(); this.options = new WatchdogServiceOptions(properties); if (this.options.isEnabled()) { this.rebootCauseWriter = new RebootCauseFileWriter(this.options.getRebootCauseFilePath()); try (PrintWriter wdWriter = new PrintWriter(this.options.getWatchdogEnabledTemporaryFilePath())) { wdWriter.write(this.options.getWatchdogDevice()); } catch (IOException e) { logger.error("Unable to write watchdog enabled temporary file", e); } this.pollTask = this.pollExecutor.scheduleAtFixedRate(() -> { Thread.currentThread().setName("WatchdogServiceImpl"); checkCriticalComponents(); }, 0, this.options.getPingInterval(), TimeUnit.MILLISECONDS); } else { disableWatchdog(); } }
Source:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); trace(this, "Starting XWalk webview..."); this.simprints = new SimprintsSupport(this); this.photoGrabber = new PhotoGrabber(this); this.mrdt = new MrdtSupport(this); try { this.smsSender = new SmsSender(this); } catch (Exception ex) { error(ex, "Failed to create SmsSender."); } this.settings = SettingsStore.in(this); this.appUrl = settings.getAppUrl(); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); if (settings.allowsConfiguration() && appUrl.contains("app.medicmobile.org")) { View webviewContainer = findViewById(R.id.lytWebView); webviewContainer.setPadding(10, 10, 10, 10); webviewContainer.setBackgroundColor(R.drawable.warning_background); } container = (XWalkView) findViewById(R.id.wbvMain); configureUseragent(); enableLocationUpdates(); setUpUiClient(container); enableRemoteChromeDebugging(); enableJavascript(container); enableStorage(container); enableUrlHandlers(container); browseToRoot(); if (settings.allowsConfiguration()) { toast(redactUrl(appUrl)); } sharedPreferences = getSharedPreferences(MY_LAST_ACTIVITY, 0); String recentNavigation = sharedPreferences.getString(MY_LAST_ACTIVITY, ""); if (!(recentNavigation != null && recentNavigation.isEmpty())) { container.loadUrl(recentNavigation); Log.d("Gopinath", sharedPreferences.getString(MY_LAST_ACTIVITY, "")); } }

Target:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); trace(this, "Starting XWalk webview..."); this.simprints = new SimprintsSupport(this); this.photoGrabber = new PhotoGrabber(this); this.mrdt = new MrdtSupport(this); try { this.smsSender = new SmsSender(this); } catch(Exception ex) { error(ex, "Failed to create SmsSender."); } this.settings = SettingsStore.in(this); this.appUrl = settings.getAppUrl(); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); if(settings.allowsConfiguration() && appUrl.contains("app.medicmobile.org")) { View webviewContainer = findViewById(R.id.lytWebView); webviewContainer.setPadding(10, 10, 10, 10); webviewContainer.setBackgroundColor(R.drawable.warning_background); } container = (XWalkView) findViewById(R.id.wbvMain); configureUseragent(); enableLocationUpdates(); setUpUiClient(container); enableRemoteChromeDebugging(); enableJavascript(container); enableStorage(container); enableUrlHandlers(container); browseToRoot(); if(settings.allowsConfiguration()) { toast(redactUrl(appUrl)); } sharedPreferences = getSharedPreferences(MY_LAST_ACTIVITY, 0); String recentNavigation = sharedPreferences.getString(MY_LAST_ACTIVITY, ""); if (!(recentNavigation != null && recentNavigation.isEmpty())) { container.loadUrl(recentNavigation); } }
Source:
public ResponseEntity<Problem> conflict(final ConflictException ex, final NativeWebRequest request) { LOG.error(ex.getMessage(), ex); return Responses.create(Response.Status.CONFLICT, ex.getMessage(), request); }

Target:
public ResponseEntity<Problem> conflict(final ConflictException ex, final NativeWebRequest request) { LOG.debug(ex.getMessage(), ex); return Responses.create(Response.Status.CONFLICT, ex.getMessage(), request); }
Source:
public boolean isEmbedded() { return (embeddedServer != null); }

Target:
public boolean isEmbedded() { return embeddedServer != null; }
Source:
private void initializeHandler(final Thing thing, final ThingHandler thingHandler) { logger.debug("Calling initialize handler for thing '{}' at '{}'.", thing.getUID(), thingHandler); try { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.initialize(); return null; } }); } catch (TimeoutException ex) { ThingStatusInfo statusInfo = buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); setThingStatus(thing, statusInfo); logger.warn("Initializing handler for thing '{}' takes more than {}ms.", thing.getUID(), SafeMethodCaller.DEFAULT_TIMEOUT); } catch (Exception ex) { ThingStatusInfo statusInfo = buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); setThingStatus(thing, statusInfo); logger.error("Exception occured while initializing handler of thing '" + thing.getUID() + "': " + ex.getMessage(), ex); } }

Target:
private void initializeHandler(final Thing thing, final ThingHandler thingHandler) { logger.debug("Calling initialize handler for thing '{}' at '{}'.", thing.getUID(), thingHandler); try { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.initialize(); return null; } }); } catch (TimeoutException ex) { logger.warn("Initializing handler for thing '{}' takes more than {}ms.", thing.getUID(), SafeMethodCaller.DEFAULT_TIMEOUT); } catch (Exception ex) { ThingStatusInfo statusInfo = buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); setThingStatus(thing, statusInfo); logger.error("Exception occured while initializing handler of thing '" + thing.getUID() + "': " + ex.getMessage(), ex); } }
Source:
protected void setUp() throws Exception { super.setUp(); availablePrefixes = CompoundInterpreter.INSTANCE.getAllNewEmtpyExpressions(); assertFalse("At least one interpreter should be declared", availablePrefixes.isEmpty()); DiagramDescription diagramDescription = DescriptionFactory.eINSTANCE.createDiagramDescription(); interpreterContext = SiriusInterpreterContextFactory.createInterpreterContext(diagramDescription, DescriptionPackage.Literals.DIAGRAM_DESCRIPTION__PRECONDITION_EXPRESSION); }

Target:
protected void setUp() throws Exception { super.setUp(); availableEmptyExpressions = CompoundInterpreter.INSTANCE.getAllNewEmtpyExpressions(); assertFalse("At least one interpreter should be declared", availableEmptyExpressions.isEmpty()); DiagramDescription diagramDescription = DescriptionFactory.eINSTANCE.createDiagramDescription(); interpreterContext = SiriusInterpreterContextFactory.createInterpreterContext(diagramDescription, DescriptionPackage.Literals.DIAGRAM_DESCRIPTION__PRECONDITION_EXPRESSION); }
Source:
public void setRetainUntil(DocumentRef docRef, Calendar retainUntil, String comment) throws PropertyException { Document doc = resolveReference(docRef); checkPermission(doc, READ); if (!doc.isRecord()) { throw new PropertyException("Document is not a record"); } Calendar current = doc.getRetainUntil(); if (Objects.equals(current, retainUntil)) { return; } checkPermission(doc, SET_RETENTION); Map<String, Serializable> options = new HashMap<>(); options.put(CoreEventConstants.RETAIN_UNTIL, retainUntil); boolean retainUntilIndeterminate = retainUntil == null || RETAIN_UNTIL_INDETERMINATE.compareTo(retainUntil) == 0; options.put("comment", retainUntilIndeterminate ? "" : retainUntil.toInstant().toString()); DocumentModel docModel = readModel(doc); boolean currentIndeterminate = current == null || RETAIN_UNTIL_INDETERMINATE.compareTo(current) == 0; String beforeRetentionEvent = currentIndeterminate ? DocumentEventTypes.BEFORE_SET_RETENTION : DocumentEventTypes.BEFORE_EXTEND_RETENTION; notifyEvent(beforeRetentionEvent, docModel, options, null, null, true, false); doc.setRetainUntil(retainUntil); docModel = readModel(doc); String afterRetentionEvent = currentIndeterminate ? DocumentEventTypes.AFTER_SET_RETENTION : DocumentEventTypes.AFTER_EXTEND_RETENTION; notifyEvent(afterRetentionEvent, docModel, options, null, null, true, false); }

Target:
public void setRetainUntil(DocumentRef docRef, Calendar retainUntil, String comment) throws PropertyException { Document doc = resolveReference(docRef); checkPermission(doc, READ); if (!doc.isRecord()) { throw new PropertyException("Document is not a record"); } Calendar current = doc.getRetainUntil(); if (current!=null && retainUntil!=null && current.compareTo(retainUntil) == 0) { return; } checkPermission(doc, SET_RETENTION); Map<String, Serializable> options = new HashMap<>(); options.put(CoreEventConstants.RETAIN_UNTIL, retainUntil); boolean retainUntilIndeterminate = retainUntil == null || RETAIN_UNTIL_INDETERMINATE.compareTo(retainUntil) == 0; options.put("comment", retainUntilIndeterminate ? "" : retainUntil.toInstant().toString()); DocumentModel docModel = readModel(doc); boolean currentIndeterminate = current == null || RETAIN_UNTIL_INDETERMINATE.compareTo(current) == 0; String beforeRetentionEvent = currentIndeterminate ? DocumentEventTypes.BEFORE_SET_RETENTION : DocumentEventTypes.BEFORE_EXTEND_RETENTION; notifyEvent(beforeRetentionEvent, docModel, options, null, null, true, false); doc.setRetainUntil(retainUntil); docModel = readModel(doc); String afterRetentionEvent = currentIndeterminate ? DocumentEventTypes.AFTER_SET_RETENTION : DocumentEventTypes.AFTER_EXTEND_RETENTION; notifyEvent(afterRetentionEvent, docModel, options, null, null, true, false); }