auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AssertionType getAssertion(Object obj) { try { if (obj != null) { if (obj instanceof AssertionType) { return (AssertionType) obj; } else { return getAssertionType(obj.getClass().getDeclaredMethods(), obj); } } } catch (IllegalAccessException | InvocationTargetException ex) { LOG.info("Unable to extract AssertionType from Object", ex); } return null; }

Target:
public AssertionType getAssertion(Object obj) { try { if (obj != null) { if (obj instanceof AssertionType) { return (AssertionType) obj; } else { return getAssertionType(obj.getClass().getDeclaredMethods(), obj); } } } catch (IllegalAccessException | InvocationTargetException ex) { LOG.error("Unable to extract AssertionType from Object: {}", ex.getLocalizedMessage(), ex); } return null; }
Source:
public void testSourceFileIsSourceFile() { assertTrue(policy.isStudentSourceFile(Paths.get("src/hello.rs"))); }

Target:
public void testSourceFileIsSourceFile() { assertTrue(policy.isStudentSourceFile(Paths.get("src", "hello.rs"))); }
Source:
public void cleanUp() throws Exception { super.cleanup(); }

Target:
public void cleanUp() throws Exception { super.cleanup(); serverConfigurationManager.restoreToLastConfiguration(); }
Source:
void onPlayPause() { if(controller == null) { return; } controller.init(); controller.playPause(); }

Target:
void onPlayPause() { if (controller == null) { return; } controller.playPause(); }
Source:
public static boolean delete(File file) { Assert.notNull(file, "File to delete must not be null."); return delete(file, false); }

Target:
public static boolean delete(File file) throws IOException { Assert.notNull(file, "File to delete must not be null."); return delete(file, false); }
Source:
public void setDiskState(HardwareState state, boolean allowChangesThroughClusterMap) { this.allowChangesThroughClustermap = allowChangesThroughClusterMap; this.state = state; }

Target:
public synchronized void setDiskState(HardwareState state, boolean allowChangesThroughClusterMap) { this.allowChangesThroughClustermap = allowChangesThroughClusterMap; this.state = state; }
Source:
private void validateCertificateChain(Certificate[] certs) throws KeyStoreException, CertificateExpiredException, CertificateNotYetValidException { if(certs == null) { throw new KeyStoreException("Empty chain"); } int len = certs.length; Date nextMonth = new Date(); nextMonth.setMonth((nextMonth.getMonth()%12) + 1); for (int i = 0; i < len; i++) { if(certs[i].getType().equals("X.509")) { X509Certificate xCert = (X509Certificate)certs[i]; boolean valid = false; try { xCert.checkValidity(); valid = true; xCert.checkValidity(nextMonth); } catch (CertificateExpiredException e) { if(!valid) { throw new CertificateExpiredException("The folowing certificate has expired\n" + xCert); } logger.warn("The following certificate will expire soon\n" + xCert); } catch (CertificateNotYetValidException e) { throw new CertificateNotYetValidException( "The following certificate is not yet valid\n" + xCert); } } } }

Target:
private void validateCertificateChain(Certificate[] certs) throws KeyStoreException, CertificateExpiredException, CertificateNotYetValidException { if(certs == null) { throw new KeyStoreException("Empty chain"); } int len = certs.length; Date nextMonth = new Date(); nextMonth.setMonth((nextMonth.getMonth()%12) + 1); for (int i = 0; i < len; i++) { if(certs[i].getType().equals("X.509")) { X509Certificate xCert = (X509Certificate)certs[i]; xCert.checkValidity(); try { xCert.checkValidity(nextMonth); } catch (CertificateExpiredException e) { logger.warn("The following certificate will expire soon " + xCert); } } } }
Source:
public void gc() { if (garbageSendingDeque.size() == SENDING_QUEUE_CAPACITY) { log.info("Drains sending queue"); sendGarbage(); } if (garbageSendingDeque.size() == SENDING_QUEUE_CAPACITY) { log.info("Stop drains receiving queue because sending queue is full"); return; } Map<Long, SMRGarbageEntry> addressToGarbage = new HashMap<>(); int drainCount = 0; SMRGarbageEntry garbageEntry; while ((garbageEntry = garbageReceivingQueue.poll()) != null && drainCount < BATCH_SIZE) { long globalAddress = garbageEntry.getGlobalAddress(); if (!addressToGarbage.containsKey(globalAddress)) { addressToGarbage.put(globalAddress, garbageEntry); } else { addressToGarbage.get(globalAddress).merge(garbageEntry); } ++drainCount; } if (drainCount == 0) { log.trace("Garbage Informer has nothing to send"); } GarbageBatch garbageBatch = new GarbageBatch(addressToGarbage.values(), lastMarkers, rt); lastMarkers.clear(); garbageSendingDeque.offer(garbageBatch); sendGarbage(); }

Target:
public synchronized void gc() { if (garbageSendingDeque.size() >= SENDING_QUEUE_CAPACITY) { log.debug("GarbageInformer: Drains sending queue"); sendGarbage(); } if (garbageSendingDeque.size() >= SENDING_QUEUE_CAPACITY) { log.debug("GarbageInformer: Stop drains receiving queue because sending queue is full"); return; } Map<UUID, Long> lastMarkers = new HashMap<>(); Map<Long, SMRGarbageEntry> addressToGarbage = new HashMap<>(); List<SMRGarbageEntry> garbageEntries = new ArrayList<>(); garbageReceivingQueue.drainTo(garbageEntries, BATCH_SIZE); if (garbageEntries.isEmpty()) { log.trace("Garbage Informer has nothing to send"); return; } for (SMRGarbageEntry garbageEntry : garbageEntries) { long globalAddress = garbageEntry.getGlobalAddress(); if (!addressToGarbage.containsKey(globalAddress)) { addressToGarbage.put(globalAddress, garbageEntry); } else { addressToGarbage.get(globalAddress).merge(garbageEntry); } } GarbageBatch garbageBatch = new GarbageBatch(addressToGarbage.values(), lastMarkers); garbageSendingDeque.offer(garbageBatch); sendGarbage(); }
Source:
private boolean isChildObjectRemoved(Set<Object> children, Set<Object> childrenFromTreeContextEntry, int notificationType) { return !children.containsAll(childrenFromTreeContextEntry) && (Notification.REMOVE == notificationType || Notification.REMOVE_MANY == notificationType); }

Target:
private boolean isChildObjectRemoved(Set<Object> children, Set<Object> childrenFromTreeContextEntry, int notificationType) { return (Notification.REMOVE == notificationType || Notification.REMOVE_MANY == notificationType) && !children.containsAll(childrenFromTreeContextEntry); }
Source:
private void validateParameter(String name, String value) { Class<? extends IParameterValidator> validators[] = wrappedParameter.validateWith(); if (validators != null && validators.length>0) { for(final Class<? extends IParameterValidator> validator: validators) { validateParameter(this, validator, name, value); } } }

Target:
private void validateParameter(String name, String value) { final Class<? extends IParameterValidator> validators[] = wrappedParameter.validateWith(); if (validators != null && validators.length > 0) { for(final Class<? extends IParameterValidator> validator: validators) { validateParameter(this, validator, name, value); } } }
Source:
static long Proc (long handle, long user_data) { long webView = handle; if (OS.G_TYPE_CHECK_INSTANCE_TYPE (handle, WebKitGTK.webkit_download_get_type ())) { webView = WebKitGTK.webkit_download_get_web_view(handle); } Browser browser = FindBrowser (webView); if (browser == null) return 0; WebKit webkit = (WebKit)browser.webBrowser; return webkit.webViewProc (handle, user_data); }

Target:
static long Proc (long handle, long user_data) { long webView = handle; if (WEBKIT2 && OS.G_TYPE_CHECK_INSTANCE_TYPE (handle, WebKitGTK.webkit_download_get_type ())) { webView = WebKitGTK.webkit_download_get_web_view(handle); } Browser browser = FindBrowser (webView); if (browser == null) return 0; WebKit webkit = (WebKit)browser.webBrowser; return webkit.webViewProc (handle, user_data); }
Source:
public String whichCommand(String command, IProject project) throws IOException { if (project != null) { String[] envp = updateEnvironment(null, project); try { IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project); URI whichUri = URI.create(WHICH_CMD); IPath whichPath = new Path(proxy.toPath(whichUri)); IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project); Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor()); if (pProxy != null){ BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream())); String errorLine; if((errorLine = error.readLine()) != null){ throw new IOException(errorLine); } error.close(); String readLine = reader.readLine(); ArrayList<String> lines = new ArrayList<String>(); while (readLine != null) { lines.add(readLine); readLine = reader.readLine(); } reader.close(); if (project.getLocationURI() != null && !lines.isEmpty()) { if(project.getLocationURI().toString().startsWith("rse:") && lines.size() > 1) { command = lines.get(lines.size()-2); } else { command = lines.get(0); } } else { command = lines.get(0); } } } catch (CoreException e) { } } return command; }

Target:
public String whichCommand(String command, IProject project) throws IOException { if (project != null) { String[] envp = updateEnvironment(null, project); try { IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project); URI whichUri = URI.create(WHICH_CMD); IPath whichPath = new Path(proxy.toPath(whichUri)); IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project); Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor()); if (pProxy != null){ BufferedReader error = new BufferedReader(new InputStreamReader(pProxy.getErrorStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(pProxy.getInputStream())); String errorLine; if((errorLine = error.readLine()) != null){ throw new IOException(errorLine); } error.close(); String readLine = reader.readLine(); ArrayList<String> lines = new ArrayList<String>(); while (readLine != null) { lines.add(readLine); readLine = reader.readLine(); } reader.close(); if (!lines.isEmpty()) { if (project.getLocationURI() != null) { if (project.getLocationURI().toString().startsWith("rse:")) { if (lines.size() > 1) { command = lines.get(lines.size() - 2); } } else { command = lines.get(0); } } else { command = lines.get(0); } } } } catch (CoreException e) { } } return command; }
Source:
public List<String> resolveArtifacts(List<Dependency> dependencies) throws MojoExecutionException { List<String> files = new ArrayList<String>(); if (dependencies == null || dependencies.isEmpty()) { return files; } MavenSession session = legacySupport.getSession(); MavenProject project = session.getCurrentProject(); for (Dependency dependency : dependencies) { Artifact artifact = repositorySystem.createDependencyArtifact(dependency); ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setResolveRoot(true).setResolveTransitively(false); request.setLocalRepository(session.getLocalRepository()); request.setRemoteRepositories(project.getRemoteArtifactRepositories()); request.setOffline(session.isOffline()); request.setForceUpdate(session.getRequest().isUpdateSnapshots()); ArtifactResolutionResult result = repositorySystem.resolve(request); try { resolutionErrorHandler.throwErrors(request, result); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Failed to resolve doclet artifact " + dependency.getManagementKey(), e); } files.add(artifact.getFile().getAbsolutePath()); } return files; }

Target:
public List<String> resolveArtifacts(List<Dependency> dependencies) throws MojoExecutionException { List<String> files = new ArrayList<String>(); if (dependencies == null || dependencies.isEmpty()) { return files; } MavenSession session = legacySupport.getSession(); MavenProject project = session.getCurrentProject(); for (Dependency dependency : dependencies) { Artifact artifact = repositorySystem.createDependencyArtifact(dependency); ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setResolveRoot(true).setResolveTransitively(false); request.setLocalRepository(session.getLocalRepository()); request.setRemoteRepositories(project.getPluginArtifactRepositories()); request.setOffline(session.isOffline()); request.setForceUpdate(session.getRequest().isUpdateSnapshots()); ArtifactResolutionResult result = repositorySystem.resolve(request); try { resolutionErrorHandler.throwErrors(request, result); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Failed to resolve doclet artifact " + dependency.getManagementKey(), e); } files.add(artifact.getFile().getAbsolutePath()); } return files; }
Source:
public CookieFilter(String username, String password){ Map<String,String> cookieRequestMap = new HashMap<String, String>(); cookieRequestMap.put("name",username); cookieRequestMap.put("password",password); JSONHelper helper = new JSONHelper(); cookieRequestBody = helper.toJson(cookieRequestMap); }

Target:
public CookieFilter(String username, String password){ this.sessionRequestBody = String.format("name=%s&password=%s",username,password); this.username = username; }
Source:
public void putOutOfRotation() { logger.warn("Putting host out of rotation"); outOfRotation.set(true); for (ServiceRegistry serviceRegistry : serviceRegistries) { serviceRegistry.unregister(); } }

Target:
public void putOutOfRotation() { logger.warn("Putting host out of rotation"); outOfRotation.set(true); for (ServiceRegistry serviceRegistry : serviceRegistries) { logger.info("Unregistering ServiceRegistry {}", serviceRegistry); try { serviceRegistry.unregister(); } catch (RuntimeException e) { logger.warn("Failed to unregister ServiceRegistry {}. Exception: {}", serviceRegistry, e); } } }
Source:
public List<Map<String, Object>> getRefundsByChargeId(long chargeId) { List<Map<String, Object>> ret = jdbi.withHandle(h -> h.createQuery("SELECT external_id, reference, amount, status, created_date, charge_id, refunded_by " + "FROM refunds r " + "WHERE charge_id = :charge_id") .bind("charge_id", chargeId) .list()); return ret; }

Target:
public List<Map<String, Object>> getRefundsByChargeId(long chargeId) { List<Map<String, Object>> ret = jdbi.withHandle(h -> h.createQuery("SELECT external_id, reference, amount, status, created_date, charge_id, user_external_id " + "FROM refunds r " + "WHERE charge_id = :charge_id") .bind("charge_id", chargeId) .list()); return ret; }
Source:
public String getRestURI(String baseServiceURI) { StringBuilder requestURI = new StringBuilder(); requestURI.append(baseServiceURI); if (StringUtils.isNotBlank(this.getEntityName())) { appendToURI(requestURI, this.getEntityName()); } if (StringUtils.isNotBlank(this.getEntityVersion())) { appendToURI(requestURI, this.schema +"="+ this.getEntityVersion()); } return requestURI.toString(); }

Target:
public String getRestURI(String baseServiceURI) { StringBuilder requestURI = new StringBuilder(); requestURI.append(baseServiceURI); if (StringUtils.isNotBlank(this.getEntityName())) { appendToURI(requestURI, this.getEntityName()); } if (StringUtils.isNotBlank(this.getEntityVersion())) { appendToURI(requestURI, "schema="+ this.getEntityVersion()); } return requestURI.toString(); }
Source:
protected void doInvokeListener(ChannelAwareMessageListener listener, Channel channel, Object data) { Message message = null; RabbitResourceHolder resourceHolder = null; Channel channelToUse = channel; boolean boundHere = false; try { if (!isExposeListenerChannel()) { resourceHolder = getTransactionalResourceHolder(); channelToUse = resourceHolder.getChannel(); if (isChannelLocallyTransacted() && !TransactionSynchronizationManager.isActualTransactionActive()) { resourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder); boundHere = true; } } else { if (isChannelLocallyTransacted()) { RabbitResourceHolder localResourceHolder = new RabbitResourceHolder(channelToUse, false); localResourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), localResourceHolder); boundHere = true; } } try { if (data instanceof List) { ((ChannelAwareBatchMessagelistener) listener).onMessageBatch((List<Message>) data, channelToUse); } else { message = (Message) data; listener.onMessage(message, channelToUse); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } } finally { cleanUpAfterInvoke(resourceHolder, channelToUse, boundHere); } }

Target:
protected void doInvokeListener(ChannelAwareMessageListener listener, Channel channel, Object data) { Message message = null; RabbitResourceHolder resourceHolder = null; Channel channelToUse = channel; boolean boundHere = false; try { if (!isExposeListenerChannel()) { resourceHolder = getTransactionalResourceHolder(); channelToUse = resourceHolder.getChannel(); if (isChannelLocallyTransacted() && !TransactionSynchronizationManager.isActualTransactionActive()) { resourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), resourceHolder); boundHere = true; } } else { if (isChannelLocallyTransacted()) { RabbitResourceHolder localResourceHolder = new RabbitResourceHolder(channelToUse, false); localResourceHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(this.getConnectionFactory(), localResourceHolder); boundHere = true; } } try { if (data instanceof List) { listener.onMessageBatch((List<Message>) data, channelToUse); } else { message = (Message) data; listener.onMessage(message, channelToUse); } } catch (Exception e) { throw wrapToListenerExecutionFailedExceptionIfNeeded(e, message); } } finally { cleanUpAfterInvoke(resourceHolder, channelToUse, boundHere); } }
Source:
public Person getTech() { if (null != engineer) { return engineer; } return tech; }

Target:
public @Nullable Person getTech() { return (getEngineer() != null) ? getEngineer() : tech; }
Source:
protected Void doInBackground(Object... voids) { AdvertisingIdClient.Info adInfo = null; try { adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); } catch (IOException e) { } catch (GooglePlayServicesNotAvailableException e) { } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); } if (adInfo != null) { id = adInfo.getId(); Log.d(TAG, "Advertising ID: " + id); SeptaServiceFactory.getNotificationsService().setDeviceId(context, id); } return null; }

Target:
protected Void doInBackground(Object... voids) { AdvertisingIdClient.Info adInfo; try { adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); id = adInfo.getId(); Log.d(TAG, "Advertising ID: " + id); SeptaServiceFactory.getNotificationsService().setDeviceId(context, id); } catch (IOException e) { CrashlyticsManager.logException(TAG, e); } catch (GooglePlayServicesNotAvailableException e) { CrashlyticsManager.logException(TAG, e); } catch (GooglePlayServicesRepairableException e) { CrashlyticsManager.logException(TAG, e); CrashlyticsManager.log(Log.ERROR, TAG, e.getMessage()); } catch (Exception e) { CrashlyticsManager.logException(TAG, e); CrashlyticsManager.log(Log.ERROR, TAG, e.getMessage()); } return null; }
Source:
public void testTextBuildWhenCalendarServiceNotAvailable() { String content = builder.buildContentString(notIcs); System.out.println(content); assertTrue(content.matches(serviceNotAvailablePattern)); assertTrue(content.matches(withoutDefaultUrlPattern)); }

Target:
public void testTextBuildWhenCalendarServiceNotAvailable() { String content = builder.buildContentString(notIcs); assertTrue(content.matches(serviceNotAvailablePattern)); assertTrue(content.matches(withoutDefaultUrlPattern)); }
Source:
public void clear() { Arrays.fill(keys, null); count = 0; }

Target:
public void clear() { Arrays.fill(keys, null); Arrays.fill(values, null); count = 0; }
Source:
public Date getEndDate() { return endDate; }

Target:
public Date getEndDate() { return endDate == null ? null : new Date(endDate.getTime()); }
Source:
public Query createQuery() { final SearchFactoryImplementor searchFactory = queryContext.getFactory(); final DocumentBuilderIndexedEntity<?> documentBuilder = Helper.getDocumentBuilder( queryContext ); if ( fieldsContext.size() == 0 ) { Integer docId = getLuceneDocumentIdFromEntityId( documentBuilder ); IndexReader indexReader = null; try { indexReader = searchFactory.getIndexReaderAccessor().open( queryContext.getEntityType() ); String[] fieldNames = getAllCompatibleFieldNames( documentBuilder ); return new MoreLikeThisBuilder( documentBuilder, searchFactory ) .fieldNames( fieldNames ) .indexReader( indexReader ) .documentNumber( docId ) .createQuery(); } finally { if ( indexReader != null ) { searchFactory.getIndexReaderAccessor().close( indexReader ); } } } return null; }

Target:
public Query createQuery() { Query query; final SearchFactoryImplementor searchFactory = queryContext.getFactory(); final DocumentBuilderIndexedEntity<?> documentBuilder = Helper.getDocumentBuilder( queryContext ); IndexReader indexReader = searchFactory.getIndexReaderAccessor().open( queryContext.getEntityType() ); try { String[] fieldNames = getAllCompatibleFieldNames( documentBuilder ); if ( fieldsContext.size() == 0 ) { fieldsContext.addAll( fieldNames ); } query = new MoreLikeThisBuilder( documentBuilder, searchFactory ) .compatibleFieldNames( fieldNames ) .fieldsContext( fieldsContext ) .queryContext( queryContext ) .indexReader( indexReader ) .inputType( inputType ) .input( input ) .otherMoreLikeThisContext( moreLikeThisContext ) .createQuery(); } finally { searchFactory.getIndexReaderAccessor().close( indexReader ); } return queryCustomizer.setWrappedQuery( query ).createQuery(); }
Source:
public void userCannotSignUpWithExistingUsernameDesktop() { RegisterPage form = performUnsuccessfulSignUpOnDesktopAs(createUserWithExistingUsername()); assertEquals(form.getError(), USERNAME_TAKEN_MSG); }

Target:
public void userCannotSignUpWithExistingUsernameDesktop() { RegisterPage form = performSignUpExpectingFailureOnDesktopAs(createUserWithExistingUsername()); assertEquals(form.getError(), USERNAME_TAKEN_MSG); }
Source:
public static BlockChangeFlag fromNativeInt(int flag) { for (SpongeBlockChangeFlag spongeBlockChangeFlag : getInstance().getValues()) { if (spongeBlockChangeFlag.getRawFlag() == flag) { return spongeBlockChangeFlag; } } return BlockChangeFlags.ALL; }

Target:
public static SpongeBlockChangeFlag fromNativeInt(int flag) { final SpongeBlockChangeFlag spongeBlockChangeFlag = getInstance().maskedFlags.get(flag); if (spongeBlockChangeFlag != null) { return spongeBlockChangeFlag; } return (SpongeBlockChangeFlag) BlockChangeFlags.ALL; }
Source:
private SecureStore getSecureStore(String className, Injector injector) { try { @SuppressWarnings("unchecked") Class<? extends SecureStore> clazz = (Class<? extends SecureStore>) Class.forName(className); return injector.getInstance(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException( String.format("Cannot load SecureStore implementation: %s"), e); } }

Target:
private SecureStore getSecureStore(String className, Injector injector) { try { @SuppressWarnings("unchecked") Class<? extends SecureStore> clazz = (Class<? extends SecureStore>) Class.forName(className); return injector.getInstance(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException( String.format("Cannot load SecureStore implementation: %s", className), e); } }
Source:
protected String getMessage(final String key) { String msg = messageProperties.getProperty(key); if (msg == null && key.contains(".")) { String newKey = key; while (msg == null && newKey.contains(".")) { newKey = newKey.substring(0, newKey.lastIndexOf(".")); msg = messageProperties.getProperty(newKey); } } return msg; }

Target:
protected String getMessage(final String key) { return messageProperties.getProperty(key); }
Source:
static OperationDefinition getOperationDefinition() { return new SimpleOperationDefinitionBuilder(OPERATION_NAME, HostResolver.getResolver("host.server")) .setReplyType(ModelType.STRING) .setRuntimeOnly() .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) .build(); }

Target:
static OperationDefinition getOperationDefinition() { return new SimpleOperationDefinitionBuilder(OPERATION_NAME, HostResolver.getResolver("host.server")) .setRuntimeOnly() .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) .build(); }
Source:
public void addDpdkPort(String bridgeName, String port, String vlan, DpdkHelper.VHostUserMode vHostUserMode, String dpdkOvsPath) { String type = vHostUserMode == DpdkHelper.VHostUserMode.SERVER ? dpdkPortVhostUserType : dpdkPortVhostUserClientType; StringBuilder stringBuilder = new StringBuilder(); if (Integer.parseInt(vlan) > 0 && Integer.parseInt(vlan) < 4095) { stringBuilder.append(String.format("ovs-vsctl add-port %s %s " + "vlan_mode=access tag=%s " + "-- set Interface %s type=%s", bridgeName, port, vlan, port, type)); } else { stringBuilder.append(String.format("ovs-vsctl add-port %s %s " + "-- set Interface %s type=%s", bridgeName, port, port, type)); } if (vHostUserMode == DpdkHelper.VHostUserMode.CLIENT) { stringBuilder.append(String.format(" options:vhost-server-path=%s/%s", dpdkOvsPath, port)); } String cmd = stringBuilder.toString(); s_logger.debug("DPDK property enabled, executing: " + cmd); Script.runSimpleBashScript(cmd); }

Target:
public void addDpdkPort(String bridgeName, String port, String vlan, DpdkHelper.VHostUserMode vHostUserMode, String dpdkOvsPath) { String type = vHostUserMode == DpdkHelper.VHostUserMode.SERVER ? dpdkPortVhostUserType : dpdkPortVhostUserClientType; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(String.format("ovs-vsctl add-port %s %s ", bridgeName, port)); if (Integer.parseInt(vlan) > 0 && Integer.parseInt(vlan) < 4095) { stringBuilder.append(String.format("vlan_mode=access tag=%s ", vlan)); } stringBuilder.append(String.format("-- set Interface %s type=%s", port, type)); if (vHostUserMode == DpdkHelper.VHostUserMode.CLIENT) { stringBuilder.append(String.format(" options:vhost-server-path=%s/%s", dpdkOvsPath, port)); } String cmd = stringBuilder.toString(); s_logger.debug("DPDK property enabled, executing: " + cmd); Script.runSimpleBashScript(cmd); }
Source:
public Matrix muli(final Matrix matrix) { if (matrix.isDense()) { throw new UnsupportedOperationException(); } else { ((NumericOps) breezeMatrix).$colon$times$eq(((CSCMatrix) matrix).breezeMatrix, MatrixOps.EMULI_SS); return this; } }

Target:
public Matrix muli(final Matrix matrix) { if (matrix.isDense()) { ((NumericOps) breezeMatrix).$colon$times$eq(((DenseMatrix) matrix).getBreezeMatrix(), MatrixOps.EMULI_MM); } else { ((NumericOps) breezeMatrix).$colon$times$eq(((CSCMatrix) matrix).breezeMatrix, MatrixOps.EMULI_SS); } return this; }
Source:
public void testBasicLogFormatting() { BasicLogger logger = new BasicLogger(); Database.log.setCustom(logger); Log.d(LogDomain.DATABASE, "TEST DEBUG"); assertEquals("TEST DEBUG", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG", new Exception("whoops")); assertEquals("TEST DEBUG (java.lang.Exception: whoops)", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %s %d %f", "arg", 1, 3.0F); assertEquals("TEST DEBUG arg 1 3.000000", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %s %d %f", new Exception("whoops"), "arg", 1, 3.0F); assertEquals("TEST DEBUG arg 1 3.000000 (java.lang.Exception: whoops)", logger.getMessage()); }

Target:
public void testBasicLogFormatting() { BasicLogger logger = new BasicLogger(); Database.log.setCustom(logger); Log.d(LogDomain.DATABASE, "TEST DEBUG"); assertEquals("TEST DEBUG", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG", new Exception("whoops")); assertEquals("TEST DEBUG (java.lang.Exception: whoops)", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %2$s %1$d %3$.2f", 1, "arg", 3.0F); assertEquals("TEST DEBUG arg 1 3.00", logger.getMessage()); Log.d(LogDomain.DATABASE, "TEST DEBUG %2$s %1$d %3$.2f", new Exception("whoops"), 1, "arg", 3.0F); assertEquals("TEST DEBUG arg 1 3.00 (java.lang.Exception: whoops)", logger.getMessage()); }
Source:
public void testQueueUpdatedUponDownloadComplete() throws Exception { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); { List<FeedItem> queue = writeTestQueue("a"); FeedItem item = DBReader.getFeedItem(queue.get(0).getId()); FeedMedia media = new FeedMedia(item, "<LINK_1>", 12345, "audio/mp3"); item.setMedia(media); DBWriter.setFeedMedia(media).get(); DBWriter.setFeedItem(item).get(); } PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); final FeedItem testItem = pstm.getQueue().get(0); assertThat("The item is not yet downloaded", testItem.getMedia().isDownloaded(), is(false)); { FeedItem item = DBReader.getFeedItem(testItem.getId()); item.getMedia().setDownloaded(true); item.getMedia().setFile_url("file://123"); item.setAutoDownload(false); DBWriter.setFeedMedia(item.getMedia()).get(); DBWriter.setFeedItem(item).get(); } Thread.sleep(10); final FeedItem itemUpdated = pstm.getQueue().get(0); assertThat("The queue in PlaybackService has been updated item after download is completed", itemUpdated.getMedia().isDownloaded(), is(true)); pstm.shutdown(); }

Target:
public void testQueueUpdatedUponDownloadComplete() throws Exception { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); { List<FeedItem> queue = writeTestQueue("a"); FeedItem item = DBReader.getFeedItem(queue.get(0).getId()); FeedMedia media = new FeedMedia(item, "<LINK_0>", 12345, "audio/mp3"); item.setMedia(media); DBWriter.setFeedMedia(media).get(); DBWriter.setFeedItem(item).get(); } PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); final FeedItem testItem = pstm.getQueue().get(0); assertFalse("The item should not yet be downloaded", testItem.getMedia().isDownloaded()); withFeedItemEventListener( feedItemEventListener -> { FeedItem item = DBReader.getFeedItem(testItem.getId()); item.getMedia().setDownloaded(true); item.getMedia().setFile_url("file://123"); item.setAutoDownload(false); DBWriter.setFeedMedia(item.getMedia()).get(); DBWriter.setFeedItem(item).get(); Awaitility.await() .atMost(1000, TimeUnit.MILLISECONDS) .until(() -> feedItemEventListener.getEvents().size() > 0); final FeedItem itemUpdated = pstm.getQueue().get(0); assertTrue("media.isDownloaded() should be true - The queue in PlaybackService should be updated after download is completed", itemUpdated.getMedia().isDownloaded()); }); pstm.shutdown(); }
Source:
public RichText build() { return new RichText(Common.nonNullOrEmpty(mText), mElements); }

Target:
public RichText build() { return new RichText(Preconditions.checkNotNull(mText), mElements); }
Source:
public String format(String input) { List<String> sentences = StringUtil.getStringAsSentences(input); StringBuilder result = new StringBuilder(); for (String sentence : sentences) { Title title = new Title(new LowerCaseFormatter().format(sentence)); title.getWords().stream().findFirst().ifPresent(Word::toUpperFirst); result.append(title.toString() + " "); } result.deleteCharAt(result.length() - 1); return result.toString(); }

Target:
public String format(String input) { return StringUtil.getStringAsSentences(input) .stream() .map(new LowerCaseFormatter()::format) .map(Title::new) .map(title -> { title.getFirstWord().ifPresent(Word::toUpperFirst); return title; }) .map(Object::toString) .collect(Collectors.joining(" ")); }
Source:
protected void editCell(GridWidget gridWidget) { super.editCell(gridWidget); final GridData model = gridWidget.getModel(); if (model.getSelectedHeaderCells().size() > 0) { final GridData.SelectedCell selectedCell = model.getSelectedHeaderCells().get(0); final BaseGridRendererHelper rendererHelper = gridWidget.getRendererHelper(); final int uiHeaderRowIndex = selectedCell.getRowIndex(); final int uiColumnIndex = findUiColumnIndex(model.getColumns(), selectedCell.getColumnIndex()); final GridColumn<?> column = model.getColumns().get(uiColumnIndex); final double columnXCoordinate = rendererHelper.getColumnOffset(column) + column.getWidth() / 2; final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(columnXCoordinate); if (column instanceof ScenarioGridColumn) { if (!isEditableHeader(column, uiHeaderRowIndex)) { return; } final GridBodyCellEditContext cellEditContext = makeRenderContext(gridWidget, rendererHelper.getRenderingInformation(), ci, null, uiHeaderRowIndex); final double yCoordinate = uiHeaderRowIndex * rendererHelper.getRenderingInformation().getHeaderRowHeight() + 1; final ScenarioHeaderMetaData metaData = ScenarioSimulationGridHeaderUtilities.getColumnScenarioHeaderMetaData(gridWidget, column, yCoordinate); if (metaData != null) { metaData.edit(cellEditContext); } } } }

Target:
protected void editCell(GridWidget gridWidget) { super.editCell(gridWidget); final GridData model = gridWidget.getModel(); if (model.getSelectedHeaderCells().size() > 0) { final GridData.SelectedCell selectedCell = model.getSelectedHeaderCells().get(0); final BaseGridRendererHelper rendererHelper = gridWidget.getRendererHelper(); final int uiHeaderRowIndex = selectedCell.getRowIndex(); final int uiColumnIndex = findUiColumnIndex(model.getColumns(), selectedCell.getColumnIndex()); final GridColumn<?> column = model.getColumns().get(uiColumnIndex); final double columnXCoordinate = rendererHelper.getColumnOffset(column) + column.getWidth() / 2; final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(columnXCoordinate); if (column instanceof ScenarioGridColumn) { if (!isEditableHeader(column, uiHeaderRowIndex)) { return; } final GridBodyCellEditContext cellEditContext = makeRenderContext(gridWidget, rendererHelper.getRenderingInformation(), ci, null, uiHeaderRowIndex); final ScenarioHeaderMetaData metaData = ScenarioSimulationGridHeaderUtilities.getColumnScenarioHeaderMetaData((ScenarioGridColumn) column, uiHeaderRowIndex); if (metaData != null) { metaData.edit(cellEditContext); } } } }
Source:
public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPartSite site = getSite(); if (site != null) { IWorkbenchPage page = site.getPage(); if (fPartListener != null) { page.removePartListener(fPartListener); } if (fPartListener2 != null) { page.removePartListener(fPartListener2); } } }

Target:
public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPage page = getSite().getPage(); if (fPartListener != null) { page.removePartListener(fPartListener); } if (fPartListener2 != null) { page.removePartListener(fPartListener2); } }
Source:
public void setResponse(int status, InputStream entity, MultiValueMap<String, String> headers) throws IOException { RequestContext context = RequestContext.getCurrentContext(); RequestContext.getCurrentContext().setResponseStatusCode(status); if (entity != null) { RequestContext.getCurrentContext().setResponseDataStream(entity); } boolean isOriginResponseGzipped = false; if (headers.containsKey(CONTENT_ENCODING) || headers.containsKey(CONTENT_ENCODING_LOWER)) { Collection<String> collection = null; if (headers.containsKey(CONTENT_ENCODING)) { collection = headers.get(CONTENT_ENCODING); } else { collection = headers.get(CONTENT_ENCODING_LOWER); } for (String header : collection) { if (HTTPRequestUtils.getInstance().isGzipped(header)) { isOriginResponseGzipped = true; break; } } } context.setResponseGZipped(isOriginResponseGzipped); for (Entry<String, List<String>> header : headers.entrySet()) { RequestContext ctx = RequestContext.getCurrentContext(); String name = header.getKey(); for (String value : header.getValue()) { ctx.addOriginResponseHeader(name, value); if (name.equalsIgnoreCase("content-length")) { ctx.setOriginContentLength(value); } if (isIncludedHeader(name)) { ctx.addZuulResponseHeader(name, value); } } } }

Target:
public void setResponse(int status, InputStream entity, MultiValueMap<String, String> headers) throws IOException { RequestContext context = RequestContext.getCurrentContext(); RequestContext.getCurrentContext().setResponseStatusCode(status); if (entity != null) { RequestContext.getCurrentContext().setResponseDataStream(entity); } HttpHeaders httpHeaders = new HttpHeaders(); for (Entry<String, List<String>> header : headers.entrySet()) { List<String> values = header.getValue(); for (String value : values) { httpHeaders.add(header.getKey(), value); } } boolean isOriginResponseGzipped = false; if (httpHeaders.containsKey(CONTENT_ENCODING)) { List<String> collection = httpHeaders.get(CONTENT_ENCODING); for (String header : collection) { if (HTTPRequestUtils.getInstance().isGzipped(header)) { isOriginResponseGzipped = true; break; } } } context.setResponseGZipped(isOriginResponseGzipped); for (Entry<String, List<String>> header : headers.entrySet()) { RequestContext ctx = RequestContext.getCurrentContext(); String name = header.getKey(); for (String value : header.getValue()) { ctx.addOriginResponseHeader(name, value); if (name.equalsIgnoreCase(CONTENT_LENGTH)) { ctx.setOriginContentLength(value); } if (isIncludedHeader(name)) { ctx.addZuulResponseHeader(name, value); } } } }
Source:
public void adsTrackingOptOutMercury() { networkTrafficInterceptor.startIntercepting(); Boolean noKikimoraRequestFound = false; Boolean noKruxRequestFound = false; Page page = new Page(TestAdsTrackingOptOutOasis.TEST_WIKI, TestAdsTrackingOptOutOasis.TEST_PAGE); String url = TestAdsTrackingOptOutOasis.appendTrackingOptOutParameters(page.getUrl()); MobileAdsBaseObject mobileAdsBaseObject = new MobileAdsBaseObject(driver, url); try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KIKIMORA_PATTERN); } catch (TimeoutException exception) { noKikimoraRequestFound = true; } try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KRUX_PATTERN); } catch (TimeoutException exception) { noKruxRequestFound = true; } assertTrue(noKikimoraRequestFound); assertTrue(noKruxRequestFound); }

Target:
public void adsTrackingOptOutMercury() { networkTrafficInterceptor.startIntercepting(); Boolean noKikimoraRequestFound = false; Boolean noKruxRequestFound = false; Page page = new Page(TestAdsTrackingOptOutOasis.TEST_WIKI, TestAdsTrackingOptOutOasis.TEST_PAGE); String url = TestAdsTrackingOptOutOasis.appendTrackingOptOutParameters(page.getUrl()); MobileAdsBaseObject mobileAdsBaseObject = new MobileAdsBaseObject(driver, url); try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KIKIMORA_PATTERN); } catch (TimeoutException exception) { noKikimoraRequestFound = true; } try { mobileAdsBaseObject.wait.forSuccessfulResponseByUrlPattern(networkTrafficInterceptor, TestAdsTrackingOptOutOasis.KRUX_PATTERN); } catch (TimeoutException exception) { noKruxRequestFound = true; } Assertion.assertTrue( noKikimoraRequestFound, "Kikimora tracking is not disabled, request to Data Warehouse was found" ); Assertion.assertTrue( noKruxRequestFound, "Krux tracking is not disabled, request to Krux services was found" ); }
Source:
private Map<String, Map<String, String>> generatePartitionOverrideFromAllDCs() { Map<String, Map<String, String>> partitionOverrideInfos = new HashMap<>(); for (PartitionId partitionId : staticClusterMap.getAllPartitionIds(null)) { String partitionName = partitionId.toPathString(); Map<String, String> partitionProperties = new HashMap<>(); partitionProperties.put(ClusterMapUtils.PARTITION_STATE, ClusterMapUtils.READ_WRITE_STR); for (ReplicaId replicaId : partitionId.getReplicaIds()) { if (replicaId.isSealed()) { partitionProperties.put(ClusterMapUtils.PARTITION_STATE, ClusterMapUtils.READ_ONLY_STR); break; } } partitionOverrideInfos.put(partitionName, partitionProperties); } return partitionOverrideInfos; }

Target:
private Map<String, Map<String, String>> generatePartitionOverrideFromAllDCs() { Map<String, Map<String, String>> partitionOverrideInfos = new HashMap<>(); for (PartitionId partitionId : staticClusterMap.getAllPartitionIds(null)) { String partitionName = partitionId.toPathString(); Map<String, String> partitionProperties = new HashMap<>(); partitionProperties.put(ClusterMapUtils.PARTITION_STATE, partitionId.getPartitionState() == PartitionState.READ_WRITE ? ClusterMapUtils.READ_WRITE_STR : ClusterMapUtils.READ_ONLY_STR); partitionOverrideInfos.put(partitionName, partitionProperties); } return partitionOverrideInfos; }
Source:
public void refreshViewer() { Display.getDefault().asyncExec(new Runnable(){ @Override public void run() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow wbWindow = wb.getActiveWorkbenchWindow(); if (wbWindow == null) { return; } IWorkbenchPage activePage = wbWindow.getActivePage(); if (activePage == null) { return; } for (IViewReference viewReference : activePage.getViewReferences()) { IViewPart viewPart = viewReference.getView(false); if (viewPart instanceof CommonNavigator) { CommonViewer commonViewer = ((CommonNavigator) viewPart).getCommonViewer(); Object element = TmfProjectModelElement.this; if (element instanceof TmfProjectElement) { element = getResource(); } commonViewer.refresh(element); } } }}); }

Target:
public void refreshViewer() { Display.getDefault().asyncExec(() -> { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow wbWindow = wb.getActiveWorkbenchWindow(); if (wbWindow == null) { return; } IWorkbenchPage activePage = wbWindow.getActivePage(); if (activePage == null) { return; } for (IViewReference viewReference : activePage.getViewReferences()) { IViewPart viewPart = viewReference.getView(false); if (viewPart instanceof CommonNavigator) { CommonViewer commonViewer = ((CommonNavigator) viewPart).getCommonViewer(); Object element = TmfProjectModelElement.this; if (element instanceof TmfProjectElement) { element = getResource(); } commonViewer.refresh(element); } } }); }
Source:
public <V> DataSet<LocatedRow> readTextFile(SpliceOperation op, String location, String characterDelimiter, String columnDelimiter, int[] baseColumnMap, OperationContext context, Qualifier[][] qualifiers, DataValueDescriptor probeValue, ExecRow execRow) throws StandardException { assert baseColumnMap != null:"baseColumnMap Null"; try { Dataset<Row> table = null; try { table = SpliceSpark.getSession().read().csv(location); if (op == null && baseColumnMap[0] == 1) { for(int index = 0; index< baseColumnMap.length; index++) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[index].dataType()); table = table.withColumn(ft.name(), cl); } } else { for( int index = 0; index< baseColumnMap.length; index++) { if (baseColumnMap[index] != -1) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[baseColumnMap[index]].dataType()); table = table.withColumn(ft.name(), cl); } } } } catch (Exception e) { return handleExceptionInCaseOfEmptySet(e,location); } table = processExternalDataset(table,baseColumnMap,qualifiers,probeValue); return new SparkDataSet(table .rdd().toJavaRDD() .map(new RowToLocatedRowFunction(context,execRow))); } catch (Exception e) { throw StandardException.newException( SQLState.EXTERNAL_TABLES_READ_FAILURE,e.getMessage()); } }

Target:
public <V> DataSet<LocatedRow> readTextFile(SpliceOperation op, String location, String characterDelimiter, String columnDelimiter, int[] baseColumnMap, OperationContext context, Qualifier[][] qualifiers, DataValueDescriptor probeValue, ExecRow execRow) throws StandardException { assert baseColumnMap != null:"baseColumnMap Null"; try { Dataset<Row> table = null; try { table = SpliceSpark.getSession().read().csv(location); if (op == null) { for(int index = 0; index < execRow.schema().fields().length; index++) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[index].dataType()); table = table.withColumn(ft.name(), cl); } } else { for( int index = 0; index< baseColumnMap.length; index++) { if (baseColumnMap[index] != -1) { StructField ft = table.schema().fields()[index]; Column cl = new Column(ft.name()).cast(execRow.schema().fields()[baseColumnMap[index]].dataType()); table = table.withColumn(ft.name(), cl); } } } } catch (Exception e) { return handleExceptionInCaseOfEmptySet(e,location); } table = processExternalDataset(table,baseColumnMap,qualifiers,probeValue); return new SparkDataSet(table .rdd().toJavaRDD() .map(new RowToLocatedRowFunction(context,execRow))); } catch (Exception e) { throw StandardException.newException( SQLState.EXTERNAL_TABLES_READ_FAILURE,e.getMessage()); } }
Source:
public void testSetInstanceCapacityMap() { Map<String, Integer> capacityDataMap = new HashMap<>(); capacityDataMap.put("item1", 1); capacityDataMap.put("item2", 2); capacityDataMap.put("item3", 3); Map<String, String> capacityDataMapString = new HashMap<>(); capacityDataMapString.put("item1", "1"); capacityDataMapString.put("item2", "2"); capacityDataMapString.put("item3", "3"); InstanceConfig testConfig = new InstanceConfig("testConfig"); testConfig.setInstanceCapacityMap(capacityDataMap); Assert.assertEquals(testConfig.getRecord().getMapField(InstanceConfig.InstanceConfigProperty. INSTANCE_CAPACITY_MAP.name()), capacityDataMapString); }

Target:
public void testSetInstanceCapacityMap() { Map<String, Integer> capacityDataMap = ImmutableMap.of("item1", 1, "item2", 2, "item3", 3); Map<String, String> capacityDataMapString = ImmutableMap.of("item1", "1", "item2", "2", "item3", "3"); InstanceConfig testConfig = new InstanceConfig("testConfig"); testConfig.setInstanceCapacityMap(capacityDataMap); Assert.assertEquals(testConfig.getRecord().getMapField(InstanceConfig.InstanceConfigProperty. INSTANCE_CAPACITY_MAP.name()), capacityDataMapString); }
Source:
private Map<Integer, IssueMetadata> processUpdates(Map<Integer, IssueMetadata> metadata) { String currentUser = prefs.getLastLoginUsername(); for (Map.Entry<Integer, IssueMetadata> entry : metadata.entrySet()) { IssueMetadata currentMetadata = entry.getValue(); Date lastNonSelfUpdate = new Date(0); Date lastSelfUpdate = new Date(0); boolean isUpdatedByOthers = false; boolean isUpdatedBySelf = false; for (TurboIssueEvent event : currentMetadata.getEvents()) { if (isNewEventByOther(currentUser, event, lastNonSelfUpdate)) { lastNonSelfUpdate = event.getDate(); isUpdatedByOthers = true; } if (isNewEventBySelf(currentUser, event, lastSelfUpdate)){ lastSelfUpdate = event.getDate(); isUpdatedBySelf = true; } } for (Comment comment : currentMetadata.getComments()) { if (isNewCommentByOther(currentUser, comment, lastNonSelfUpdate)) { lastNonSelfUpdate = comment.getCreatedAt(); isUpdatedByOthers = true; } if (isNewCommentBySelf(currentUser, comment, lastSelfUpdate)){ lastSelfUpdate = comment.getCreatedAt(); isUpdatedBySelf = true; } } entry.setValue(new IssueMetadata(currentMetadata, LocalDateTime.ofInstant(lastNonSelfUpdate.toInstant(), ZoneId.systemDefault()), LocalDateTime.ofInstant(lastSelfUpdate.toInstant(), ZoneId.systemDefault()), calculateCommentCount(currentMetadata.getComments(), currentUser, UpdatedKind.OTHER_UPDATED), calculateCommentCount(currentMetadata.getComments(), currentUser, UpdatedKind.SELF_UPDATED), isUpdatedByOthers, isUpdatedBySelf )); } return metadata; }

Target:
private Map<Integer, IssueMetadata> processUpdates(Map<Integer, IssueMetadata> metadata) { String currentUser = prefs.getLastLoginUsername(); for (Map.Entry<Integer, IssueMetadata> entry : metadata.entrySet()) { IssueMetadata currentMetadata = entry.getValue(); entry.setValue(new IssueMetadata(currentMetadata, currentUser)); } return metadata; }