auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Query restrict(Class<?> firstType, Class<?>... additionalTypes) { Assert.notNull(firstType, "firstType must not be null!"); Assert.notNull(additionalTypes, "additionalTypes must not be null"); if (restrictedTypes == null) { restrictedTypes = new HashSet<Class<?>>(); } restrictedTypes.add(firstType); for (Class<?> additionalType : additionalTypes) { restrictedTypes.add(additionalType); } if (!restrictedTypes.isEmpty()) { List<String> restrictedMappedTypes = new ArrayList<String>(); for (Class<?> restrictedType : restrictedTypes) { restrictedMappedTypes.add(SimpleTypeInformationMapper.INSTANCE.createAliasFor(ClassTypeInformation .from(restrictedType))); } addCriteria(Criteria.where(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY).in(restrictedMappedTypes)); } return this; }

Target:
public Query restrict(Class<?> firstType, Class<?>... additionalTypes) { Assert.notNull(firstType, "firstType must not be null!"); Assert.notNull(additionalTypes, "additionalTypes must not be null"); restrictedTypes.add(firstType); for (Class<?> additionalType : additionalTypes) { restrictedTypes.add(additionalType); } return this; }
Source:
private IndexProvider put( Descriptor providerDescriptor, IndexProvider provider ) { IndexProvider existing = indexProviders.putIfAbsent( providerDescriptor, provider ); indexProvidersByName.put( providerDescriptor.name(), provider ); return existing; }

Target:
private IndexProvider put( Descriptor providerDescriptor, IndexProvider provider ) { IndexProvider existing = indexProvidersByDescriptor.putIfAbsent( providerDescriptor, provider ); indexProvidersByName.putIfAbsent( providerDescriptor.name(), provider ); return existing; }
Source:
public TrackerClient getTrackerClient(Request request, RequestContext requestContext, Ring<URI> ring, Map<URI, TrackerClient> trackerClients) { TrackerClient trackerClient; URI targetHostUri = KeyMapper.TargetHostHints.getRequestContextTargetHost(requestContext); if (targetHostUri != null) { trackerClient = trackerClients.get(targetHostUri); } else { trackerClient = getTrackerClientFromRing(request, requestContext, ring, trackerClients); } if (trackerClient == null) { trackerClient = trackerClients.values().stream().findAny().orElse(null); warn(LOG, "Did not find a valid client from the ring, picked instead", trackerClient.getUri()); } addToExcludedHosts(trackerClient, requestContext); return trackerClient; }

Target:
public TrackerClient getTrackerClient(Request request, RequestContext requestContext, Ring<URI> ring, Map<URI, TrackerClient> trackerClients) { TrackerClient trackerClient; URI targetHostUri = KeyMapper.TargetHostHints.getRequestContextTargetHost(requestContext); if (targetHostUri != null) { trackerClient = getTrackerClientFromTarget(targetHostUri, requestContext, trackerClients); } else { trackerClient = getTrackerClientFromRing(request, requestContext, ring, trackerClients); } return trackerClient; }
Source:
public List<PartitionOffset> indicateOffsetChange(Topic topic, String subscription, String brokersClusterName, long timestamp, boolean dryRun) { List<PartitionOffset> partitionOffsetList = new ArrayList<>(); kafkaNamesMapper.toKafkaTopics(topic).forEach(k -> { List<Integer> partitionsIds = brokerStorage.readPartitionsIds(k.name().asString()); for (Integer partitionId : partitionsIds) { KafkaConsumer<byte[], byte[]> consumer = createKafkaConsumer(k, partitionId); long offset = findClosestOffsetJustBeforeTimestamp(consumer, k, partitionId, timestamp); PartitionOffset partitionOffset = new PartitionOffset(k.name(), offset, partitionId); partitionOffsetList.add(partitionOffset); if (!dryRun) { multiDcExecutor.execute(new SetSubscriptionOffsetRepositoryCommand(topic.getName(), subscription, brokersClusterName, partitionOffset)); } } }); return partitionOffsetList; }

Target:
public List<PartitionOffset> indicateOffsetChange(Topic topic, String subscription, String brokersClusterName, long timestamp, boolean dryRun) { List<PartitionOffset> partitionOffsetList = new ArrayList<>(); kafkaNamesMapper.toKafkaTopics(topic).forEach(k -> { List<Integer> partitionsIds = brokerStorage.readPartitionsIds(k.name().asString()); for (Integer partitionId : partitionsIds) { KafkaConsumer<byte[], byte[]> consumer = createKafkaConsumer(k, partitionId); long offset = findClosestOffsetJustBeforeTimestamp(consumer, k, partitionId, timestamp); PartitionOffset partitionOffset = new PartitionOffset(k.name(), offset, partitionId); partitionOffsetList.add(partitionOffset); if (!dryRun) { subscriptionOffsetChange.setSubscriptionOffset(topic.getName(), subscription, brokersClusterName, partitionOffset); } } }); return partitionOffsetList; }
Source:
protected Object getFeatureValue(String newText) { if (newText == null || StringUtil.isEmpty(newText)) { return "0"; } else { return newText; } }

Target:
protected Object getFeatureValue(String newText) { if (StringUtil.isEmpty(newText)) { return getDefaultFeatureAsText(); } else { return newText; } }
Source:
public void canRemoveFile() throws Exception { final Repo repo = MkContentsTest.repo(); final String path = "removeme.txt"; this.createFile(repo, path); final JsonObject json = MkContentsTest .content(path, "theDeleteMessage") .add("committer", MkContentsTest.committer()) .build(); final RepoCommit commit = repo.contents().remove(json); MatcherAssert.assertThat(commit, Matchers.notNullValue()); }

Target:
public void canRemoveFile() throws Exception { final Repo repo = MkContentsTest.repo(); final String path = "removeme.txt"; this.createFile(repo, path); final JsonObject json = MkContentsTest .content(path, "theDeleteMessage") .add("committer", MkContentsTest.committer()) .build(); final RepoCommit commit = repo.contents().remove(json); MatcherAssert.assertThat(commit, Matchers.notNullValue()); MatcherAssert.assertThat( commit.json().getString("message"), Matchers.equalTo("theDeleteMessage") ); }
Source:
public void testServiceProviderProvidesService() throws Exception { try (Builder b = new Builder();) { b.addClasspath(IO.getFile("bin_test")); b.setPrivatePackage("test.annotationheaders.spi.provider"); b.build(); b.getJar() .getManifest() .write(System.out); assertTrue(b.check()); Attributes mainAttributes = b.getJar() .getManifest() .getMainAttributes(); Header req = Header.parseHeader(mainAttributes.getValue(Constants.REQUIRE_CAPABILITY)); assertEquals(2, req.size()); assertExtender(req, "osgi.serviceloader.registrar"); assertEE(req); Header cap = Header.parseHeader(mainAttributes.getValue(Constants.PROVIDE_CAPABILITY)); assertEquals(3, cap.size()); Props p = cap.get("osgi.service"); assertNotNull(p); assertNotNull(p.get("objectClass:List<String>")); assertEquals("test.annotationheaders.spi.SPIService", p.get("objectClass:List<String>")); assertEquals("active", p.get("effective:")); } }

Target:
public void testServiceProviderProvidesService() throws Exception { try (Builder b = new Builder();) { b.addClasspath(IO.getFile("bin_test")); b.setPrivatePackage("test.annotationheaders.spi.provider"); b.build(); b.getJar() .getManifest() .write(System.out); assertTrue(b.check()); Attributes mainAttributes = b.getJar() .getManifest() .getMainAttributes(); Header req = Header.parseHeader(mainAttributes.getValue(Constants.REQUIRE_CAPABILITY)); assertEquals(2, req.size()); assertExtender(req, "osgi.serviceloader.registrar"); assertEE(req); Parameters cap = OSGiHeader.parseHeader(mainAttributes.getValue(Constants.PROVIDE_CAPABILITY)); assertEquals(3, cap.size()); Attrs p = cap.get("osgi.service"); assertNotNull(p); assertNotNull(p.getTyped("objectClass")); assertThat(p.getTyped(Attrs.LIST_STRING, "objectClass")).contains("test.annotationheaders.spi.SPIService"); assertEquals("active", p.get("effective:")); } }
Source:
public final SPromise toNearRefWithResultPromise(final Object[] args) { Actor current = EventualMessage.getActorCurrentMessageIsExecutionOn(); SPromise result = SPromise.createPromise(current, promiseResolutionBreakpoint.executeCheckIsSetAndEnabled(), false, false); SResolver resolver = SPromise.createResolver(result); SteppingType step = getStepping(); DirectMessage msg = new DirectMessage(EventualMessage.getCurrentExecutingMessage(), EventualMessage.getCurrentExecutingMessageId(), current, selector, args, current, resolver, onReceive, messageReceiverBreakpoint.executeCheckIsSetAndEnabled(), promiseResolverBreakpoint.executeCheckIsSetAndEnabled()); msg.setTriggerStepping(step); current.send(msg); return result; }

Target:
public final SPromise toNearRefWithResultPromise(final Object[] args) { Actor current = EventualMessage.getActorCurrentMessageIsExecutionOn(); SPromise result = SPromise.createPromise(current, promiseResolutionBreakpoint.executeCheckIsSetAndEnabled(), false, false); SResolver resolver = SPromise.createResolver(result); DirectMessage msg = new DirectMessage(EventualMessage.getCurrentExecutingMessageId(), current, selector, args, current, resolver, onReceive, hasMessageReceiverBreakpoint(resolver), promiseResolverBreakpoint.executeCheckIsSetAndEnabled()); current.send(msg, actorPool); return result; }
Source:
private Map<String, String> getClusterSidePropertiesMap(Configuration flinkConfig) { final Map<String, String> propertiesMap = flinkConfig.toMap(); propertiesMap.remove(KubernetesConfigOptions.KUBE_CONFIG_FILE.key()); propertiesMap.remove(DeploymentOptionsInternal.CONF_DIR.key()); return propertiesMap; }

Target:
private Map<String, String> getClusterSidePropertiesMap(Configuration flinkConfig) { final Configuration clusterSideConfig = flinkConfig.clone(); clusterSideConfig.removeConfig(KubernetesConfigOptions.KUBE_CONFIG_FILE); clusterSideConfig.removeConfig(DeploymentOptionsInternal.CONF_DIR); return clusterSideConfig.toMap(); }
Source:
public WatermarkOutputMultiplexer(WatermarkOutput underlyingOutput) { this.underlyingOutput = underlyingOutput; this.watermarkPerOutputId = new HashMap<>(); this.watermarkOutputs = new ArrayList(); }

Target:
public WatermarkOutputMultiplexer(WatermarkOutput underlyingOutput) { this.underlyingOutput = underlyingOutput; this.watermarkPerOutputId = new HashMap<>(); this.watermarkOutputs = new ArrayList<>(); }
Source:
public String getDescription() { return "Moves event parameters from eventparms column to table"; }

Target:
public String getDescription() { return "Moves event parameters from the 'eventparms' column to the 'event_parameters' table."; }
Source:
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); if (certs == null || certs.length == 0) { throw new ServletException( "Couldn't get the attribute javax.servlet.request.X509Certificate from the request"); } String name = certs[0].getSubjectDN().getName(); Matcher m = REGEX_USERID.matcher(name); String userName; if (m.matches()) { userName = m.group(1); } else { throw new ServletException("Couldn't extract username from your certificate"); } final AuthRequest areq = AuthRequest.forUser(userName); final AuthResult arsp; try { arsp = accountManager.authenticate(areq); } catch (AccountException e) { String err = "Unable to authenticate user \"" + userName + "\""; log.error(err, e); throw new ServletException(err, e); } webSession.get().login(arsp, true); chain.doFilter(req, rsp); }

Target:
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); if (certs == null || certs.length == 0) { throw new ServletException( "Couldn't get the attribute javax.servlet.request.X509Certificate from the request"); } String name = certs[0].getSubjectDN().getName(); Matcher m = REGEX_USERID.matcher(name); String userName; if (m.find()) { userName = m.group(1); } else { throw new ServletException("Couldn't extract username from your certificate"); } final AuthRequest areq = AuthRequest.forUser(userName); final AuthResult arsp; try { arsp = accountManager.authenticate(areq); } catch (AccountException e) { String err = "Unable to authenticate user \"" + userName + "\""; log.error(err, e); throw new ServletException(err, e); } webSession.get().login(arsp, true); chain.doFilter(req, rsp); }
Source:
public void scenesGenerated(char[] scenesGenerated) { if (String.valueOf(scenesGenerated).equals("1111")) { this.scenesGenerated = true; stateChanged(ManagerStates.RUNNING); } if (String.valueOf(scenesGenerated).contains("2")) { String type = "nan"; switch (String.valueOf(scenesGenerated).indexOf("2")) { case 0: type = "namedScens"; break; case 1: type = "appScenes"; break; case 2: type = "zoneScenes"; break; case 3: type = "reachableScenes"; break; } logger.warn("Not all scenes are generated, try it again. Scene type is not generated.", type); stateChanged(ManagerStates.RUNNING); } }

Target:
public void scenesGenerated(char[] scenesGenerated) { if (String.valueOf(scenesGenerated).equals("1111")) { this.scenesGenerated = true; stateChanged(ManagerStates.RUNNING); } if (String.valueOf(scenesGenerated).contains("2")) { String type = "nan"; switch (String.valueOf(scenesGenerated).indexOf("2")) { case 0: type = "namedScens"; break; case 1: type = "appScenes"; break; case 2: type = "zoneScenes"; break; case 3: type = "reachableScenes"; break; } logger.debug("Not all scenes are generated, try it again. Scene type is not generated.", type); stateChanged(ManagerStates.RUNNING); } }
Source:
public void commit() { if (connection == null) { throw new IllegalStateException(); } try { connection.commit(); } finally { connection.close(); } }

Target:
public void commit() { endTransaction(true); }
Source:
public List<V> getAll(K name) { checkNotNull(name, "name"); int h = hashingStrategy.hashCode(name); int i = index(h); HeaderEntry<K, V> e = entries[i]; if (e == null) { return Collections.emptyList(); } LinkedList<V> values = new LinkedList<V>(); while (e != null) { if (e.hash == h && hashingStrategy.equals(name, e.key)) { values.addFirst(e.getValue()); } e = e.next; } return values; }

Target:
public List<V> getAll(K name) { requireNonNull(name, "name"); int h = hashingStrategy.hashCode(name); int i = index(h); HeaderEntry<K, V> e = entries[i]; if (e == null) { return Collections.emptyList(); } LinkedList<V> values = new LinkedList<>(); do { if (e.hash == h && hashingStrategy.equals(name, e.key)) { values.addFirst(e.getValue()); } e = e.next; } while (e != null); return values; }
Source:
public static synchronized void init(Context context) { if (context == null) { throw new IllegalArgumentException("Non-null context required."); } RealmCore.loadLibrary(context); BaseRealm.applicationContext = context; defaultConfiguration = new RealmConfiguration.Builder().build(); if (!realmInitialized) { RealmLog.add(BuildConfig.DEBUG ? new AndroidLogger(Log.DEBUG) : new AndroidLogger(Log.WARN)); } realmInitialized = true; }

Target:
public static synchronized void init(Context context) { if (BaseRealm.applicationContext == null) { if (context == null) { throw new IllegalArgumentException("Non-null context required."); } RealmCore.loadLibrary(context); RealmLog.add(BuildConfig.DEBUG ? new AndroidLogger(Log.DEBUG) : new AndroidLogger(Log.WARN)); defaultConfiguration = new RealmConfiguration.Builder(context).build(); BaseRealm.applicationContext = context.getApplicationContext(); } }
Source:
public void testNamespaceExists() throws Exception { try { client.createNamespace(creds, namespaceName); } catch (NamespaceExistsException ex) try { client.renameNamespace(creds, namespaceName, namespaceName); } catch (NamespaceExistsException ex) }

Target:
public void testNamespaceExists() throws Exception { client.createNamespace(creds, "foobar"); try { client.createNamespace(creds, namespaceName); fail("exception not thrown"); } catch (NamespaceExistsException ex) try { client.renameNamespace(creds, "foobar", namespaceName); fail("exception not thrown"); } catch (NamespaceExistsException ex) }
Source:
public void eventsShouldBeReturned(final Map<String, String> settings) throws Throwable { final FindEventsAsyncRequest asyncRequest = FindEventsRequestFactory.fromScenarioContext(); final FindEventsResponse response = this.responseClient.getResponse(asyncRequest); assertNotNull("FindEventsRequestResponse should not be null", response); assertNotNull("Expected events", response.getEvents()); assertEquals("Number of events should match", Integer.parseInt(settings.get(EXPECTED_NUMBER_OF_EVENTS)), response.getEvents().size()); for (final Event event : response.getEvents()) { Event eventMatch = null; for (final EventType item : this.getAllowedEventTypes()) { if (item.toString().equals(event.getEventType().toString())) { eventMatch = event; break; } } assertNotNull("No match found for EventType", eventMatch); } }

Target:
public void eventsShouldBeReturned(final Map<String, String> settings) throws Throwable { final FindEventsAsyncRequest findEventsAsyncRequest = FindEventsRequestFactory.fromScenarioContext(); final FindEventsResponse findEventsResponse = this.smartMeteringManagementResponseClient .getResponse(findEventsAsyncRequest); assertNotNull("FindEventsRequestResponse should not be null", findEventsResponse); assertNotNull("Expected events", findEventsResponse.getEvents()); assertEquals("Number of events should match", Integer.parseInt(settings.get(EXPECTED_NUMBER_OF_EVENTS)), findEventsResponse.getEvents().size()); for (final Event event : findEventsResponse.getEvents()) { Event eventMatch = null; for (final EventType eventType : this.getAllowedEventTypes()) { if (eventType.equals(event.getEventType())) { eventMatch = event; break; } } assertNotNull("No match found for EventType", eventMatch); } }
Source:
public void moveFile(String fileFrom, String fileTo) throws Exception { File fromLocalFile = getLocalFile(fileFrom); File toLocalFile = getLocalFile(fileTo); try { if (fromLocalFile.isDirectory()) { FileUtils.moveDirectory(fromLocalFile, toLocalFile); } else { FileUtils.moveFile(fromLocalFile, toLocalFile); } } catch (Exception e) { throw new Exception("Move failed: " + fileFrom + " --&gt; " + fileTo, e); } }

Target:
public void moveFile(String fileFrom, String fileTo) throws Exception { File fromLocalFile = getLocalFile(fileFrom); File toLocalFile = getLocalFile(fileTo); try { if (fromLocalFile.isDirectory()) { FileUtils.moveDirectory(fromLocalFile, toLocalFile); } else { FileUtils.moveFile(fromLocalFile, toLocalFile); } } catch (Exception e) { throw new Exception("Move failed: " + fileFrom + " --> " + fileTo, e); } }
Source:
private Info dockerInfo() { try { return this.dockerClient.info(); } catch (DockerException | InterruptedException e) { throw new AssertionError(e); } }

Target:
private Info dockerInfo() { try { return this.dockerClient.info(); } catch (DockerException | InterruptedException e) { throw Throwables.propagate(e); } }
Source:
private void reloadPluginWithSlug(@NonNull String slug) { int index = mItems.indexOfPluginWithSlug(slug); if (index != -1) { notifyItemChanged(index); } }

Target:
void reloadPluginWithSlug(@NonNull String slug) { int index = mItems.indexOfPluginWithSlug(slug); if (index != -1) { notifyItemChanged(index); } }
Source:
void sendRejectedNotification(Application application, ApplicationComment comment) { Map<String, Object> model = new HashMap<>(); model.put(APPLICATION, application); model.put(VACATION_TYPE, getTranslation(application.getVacationType().getCategory().getMessageKey())); model.put(DAY_LENGTH, getTranslation(application.getDayLength().name())); model.put(COMMENT, comment); final Mail mailToApplicant = Mail.builder() .withRecipient(application.getPerson()) .withSubject("subject.application.rejected") .withTemplate("rejected", model) .build(); mailService.send(mailToApplicant); final List<Person> relevantRecipientsToInform = applicationRecipientService.getRecipientsForAllowAndRemind(application); final Mail mailToRelevantRecipients = Mail.builder() .withRecipient(relevantRecipientsToInform) .withSubject("subject.application.rejected_information") .withTemplate("rejected_information", model) .build(); mailService.send(mailToRelevantRecipients); }

Target:
void sendRejectedNotification(Application application, ApplicationComment comment) { Map<String, Object> model = new HashMap<>(); model.put(APPLICATION, application); model.put(VACATION_TYPE, getTranslation(application.getVacationType().getCategory().getMessageKey())); model.put(DAY_LENGTH, getTranslation(application.getDayLength().name())); model.put(COMMENT, comment); final Mail mailToApplicant = Mail.builder() .withRecipient(application.getPerson()) .withSubject("subject.application.rejected") .withTemplate("rejected", model) .build(); mailService.send(mailToApplicant); final List<Person> relevantRecipientsToInform = applicationRecipientService.getRecipientsOfInterest(application); final Mail mailToRelevantRecipients = Mail.builder() .withRecipient(relevantRecipientsToInform) .withSubject("subject.application.rejected_information") .withTemplate("rejected_information", model) .build(); mailService.send(mailToRelevantRecipients); }
Source:
public void execute() throws OseeCoreException { Conditions.checkNotNull(comment, "comment"); if (objects.isEmpty() && deleteObjects.isEmpty()) { throw new OseeArgumentException("objects/deleteObjects cannot be empty"); } for (Object obj : new CopyOnWriteArrayList<Object>(objects)) { if (obj instanceof IAtsWorkItem) { IAtsWorkItem workItem = (IAtsWorkItem) obj; IAtsStateManager stateMgr = getStateMgr(workItem); if (stateMgr.isDirty()) { AtsCore.getStateFactory().writeToStore(workItem, this); } if (workItem.getLog().isDirty()) { AtsCore.getLogFactory().writeToStore(workItem, AtsCore.getAttrResolver(), this); } } } for (Object obj : deleteObjects) { if (obj instanceof IAtsWorkItem) { ArtifactReadable artifact = AtsServerImpl.get().getArtifact((IAtsWorkItem) obj); getTxFactory().deleteArtifact(artifact); } else { throw new OseeArgumentException("ATsChangeSet: Unhandled deleteObject type: " + obj); } } transaction.commit(); for (IExecuteListener listener : listeners) { listener.changesStored(this); } }

Target:
public void execute() throws OseeCoreException { Conditions.checkNotNull(comment, "comment"); if (objects.isEmpty() && deleteObjects.isEmpty()) { throw new OseeArgumentException("objects/deleteObjects cannot be empty"); } for (Object obj : new CopyOnWriteArrayList<Object>(objects)) { if (obj instanceof IAtsWorkItem) { IAtsWorkItem workItem = (IAtsWorkItem) obj; IAtsStateManager stateMgr = getStateMgr(workItem); if (stateMgr.isDirty()) { AtsCore.getStateFactory().writeToStore(workItem, this); } if (workItem.getLog().isDirty()) { AtsCore.getLogFactory().writeToStore(workItem, AtsCore.getAttrResolver(), this); } } } for (Object obj : deleteObjects) { if (obj instanceof IAtsWorkItem) { ArtifactReadable artifact = AtsServerImpl.get().getArtifact((IAtsWorkItem) obj); getTxFactory().deleteArtifact(artifact); } else { throw new OseeArgumentException("AtsChangeSet: Unhandled deleteObject type: " + obj); } } transaction.commit(); for (IExecuteListener listener : listeners) { listener.changesStored(this); } }
Source:
protected Set<ConstraintCheckError> doCheck(Element element, AnnotationMirror annotation) { String value = (String) annotationApiHelper.getAnnotationValue( annotation, "value" ).getValue(); if ( !BIG_DECIMAL_PATTERN.matcher( value ).matches() ) { return CollectionHelper.asSet( new ConstraintCheckError( element, annotation, "INVALID_DECIMAL_MIN_MAX_ANNOTATION_PARAMETERS" ) ); } return Collections.emptySet(); }

Target:
protected Set<ConstraintCheckError> doCheck(Element element, AnnotationMirror annotation) { String value = (String) annotationApiHelper.getAnnotationValue( annotation, "value" ).getValue(); try { new BigDecimal( value ); return Collections.emptySet(); } catch (NumberFormatException nfe) { return CollectionHelper.asSet( new ConstraintCheckError( element, annotation, "INVALID_DECIMAL_MIN_MAX_ANNOTATION_PARAMETERS" ) ); } }
Source:
private List<String> arrayToList(String[] array) { List<String> List = new ArrayList<String>(); for (int i = 0; i < array.length; i++) { List.add(array[i]); } return List; }

Target:
private List<String> arrayToList(String[] array) { return Arrays.asList(array); }
Source:
public void shouldReturnEc2Location() { Supplier<Optional<HostLocation>> hostLocationSupplier = new HostLocationSupplier(ec2SnitchSupplier, ec2LocationSupplier, Optional.empty()); assertThat(hostLocationSupplier.get()) .hasValue(ec2LocationSupplier.get().get()); }

Target:
public void shouldReturnEc2Location() { Supplier<Optional<HostLocation>> hostLocationSupplier = new HostLocationSupplier(ec2SnitchSupplier, ec2LocationSupplier, Optional.empty()); assertThat(hostLocationSupplier.get()).isEqualTo(ec2LocationSupplier.get()); }
Source:
private boolean checkDrProducer() { long bytesPend = 0, segsPend = 0; try { StatsSource ss = getStatsSource(StatsSelector.DRPRODUCERPARTITION); if (ss != null) { int ix_totalBytes = getIndex(ss, DRProducerStatsBase.Columns.TOTAL_BYTES); int ix_lastQueued = getIndex(ss, DRProducerStatsBase.Columns.LAST_QUEUED_DRID); int ix_lastAcked = getIndex(ss, DRProducerStatsBase.Columns.LAST_ACK_DRID); for (Object[] row : ss.getStatsRows(false, System.currentTimeMillis())) { long totalBytes = asLong(row[ix_totalBytes]); long lastQueuedDrId = asLong(row[ix_lastQueued]); long lastAckedDrId = asLong(row[ix_lastAcked]); bytesPend += totalBytes; if (lastQueuedDrId > lastAckedDrId) { segsPend += lastQueuedDrId - lastAckedDrId; } } } } catch (Exception ex) { warn("checkDrProducer", ex); } drprod_bytesPend = bytesPend; drprod_segsPend = segsPend; return isActive("DR producer: outstanding segments %d, bytes %d", segsPend, bytesPend); }

Target:
private boolean checkDrProducer() { long bytesPend = 0, rowsPend = 0; try { StatsSource ss = getStatsSource(StatsSelector.DRPRODUCERPARTITION); if (ss != null) { int ixTotalBytes = getIndex(ss, DRProducerStatsBase.Columns.TOTAL_BYTES); int ixLastQueued = getIndex(ss, DRProducerStatsBase.Columns.LAST_QUEUED_DRID); int ixLastAcked = getIndex(ss, DRProducerStatsBase.Columns.LAST_ACK_DRID); for (Object[] row : ss.getStatsRows(false, System.currentTimeMillis())) { long totalBytes = asLong(row[ixTotalBytes]); long lastQueuedDrId = asLong(row[ixLastQueued]); long lastAckedDrId = asLong(row[ixLastAcked]); bytesPend += totalBytes; if (lastQueuedDrId > lastAckedDrId) { rowsPend += lastQueuedDrId - lastAckedDrId; } } } } catch (Exception ex) { warn("checkDrProducer", ex); } drprodBytesPend = bytesPend; drprodRowsPend = rowsPend; return isActive("DR producer: outstanding rows %d, bytes %d", rowsPend, bytesPend); }
Source:
public boolean isCidrFormatValid(String cidr) { return (cidr != null && cidr.matches(ValidationUtils.CIDR_FORMAT_PATTERN)); }

Target:
public boolean isCidrFormatValid(String cidr) { return cidr != null && cidr.matches(ValidationUtils.CIDR_FORMAT_PATTERN); }
Source:
private Long handleOffsets(String number) throws NumberFormatException, IllegalArgumentException{ long now = System.currentTimeMillis(); if (number.startsWith("+")) { String offset = number.substring(1); Duration duration = new Duration(offset); return now + duration.getValue(); } else if (number.startsWith("-")) { String offset = number.substring(1); Duration duration = new Duration(offset); return now - duration.getValue(); } else { return Long.parseLong(number); } }

Target:
private Long handleOffsets(String number) throws NumberFormatException, IllegalArgumentException{ long now = System.currentTimeMillis(); if (number.startsWith("+")) { String offset = number.substring(1).trim(); Duration duration = new Duration(offset); return now + duration.toMillis(); } else if (number.startsWith("-")) { String offset = number.substring(1).trim(); Duration duration = new Duration(offset); return now - duration.toMillis(); } else { return Long.parseLong(number); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { CustomSiriusEditor editor = getCurrentEditor(); if (editor != null) { QuickOutlineDescriptor descriptor = VSMDefaultQuickOutlineDescriptorFactory.createDescriptor(editor); ViewpointInformationPresenter presenter = ViewpointInformationPresenterFactory.createInformationPresenter(editor.getControl(), descriptor, editor.getEditingDomain().getResourceSet() .getResources().get(0).getContents().get(0)); presenter.showInformation(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { CustomSiriusEditor editor = getCurrentEditor(); if (editor != null) { Object root = null; try { root = editor.getEditingDomain().getResourceSet().getResources().get(0).getContents().get(0); } catch (NullPointerException npe) { } if (root != null) { SiriusInformationPresenter presenter = SiriusInformationPresenterFactory.createInformationPresenter(editor.getControl(), createDescriptor(editor), root); presenter.showInformation(); } } return null; }
Source:
IJavaCompletionProposal[] getSuggestions(Set<String> pkgs, IInvocationContext context) { List<RepositoryPlugin> ps = listRepositories(); final BndBuildPathHandler handler = getBuildPathHandler(context); SetMultimap<String, String> bundles = MultimapBuilder.treeKeys() .treeSetValues() .build(); String wsName = null; for (String pkg : pkgs) { for (RepositoryPlugin p : ps) { Set<Capability> caps = null; if (p instanceof Repository) { caps = searchRepository((Repository) p, pkg); } else if (p instanceof WorkspaceRepository) { try { caps = searchRepository(getWorkspaceRepo(), pkg); wsName = p.getName(); } catch (Exception e) { logger.logError("Error trying to fetch the repository for the current workspace", e); } } if (caps == null) { continue; } for (Capability cap : caps) { final String bsn = capabilityToBSN(cap); try { if (!handler.containsBundle(bsn)) { bundles.put(bsn, p.getName()); } } catch (Exception e) { e.printStackTrace(); } } } } if (bundles.isEmpty()) { return null; } IJavaCompletionProposal[] retval = new IJavaCompletionProposal[bundles.keySet() .size()]; int i = 0; for (Map.Entry<String, Collection<String>> bundle : bundles.asMap() .entrySet()) { final int relevance = bundle.getValue() .contains(wsName) ? ADD_BUNDLE_WORKSPACE : ADD_BUNDLE; retval[i++] = new AddBundleCompletionProposal(bundle.getKey(), relevance, context); } return retval; }

Target:
IJavaCompletionProposal[] getSuggestions(Set<String> pkgs, IInvocationContext context) throws CoreException { List<RepositoryPlugin> ps = listRepositories(); final BndBuildPathHandler handler = getBuildPathHandler(context); MultiMap<String, String> bundles = new MultiMap<>(); String wsName = null; boolean loggedWorkspaceError = false; for (String pkg : pkgs) { for (RepositoryPlugin p : ps) { Collection<Capability> caps = null; if (p instanceof Repository) { caps = searchRepository((Repository) p, pkg); } else if (p instanceof WorkspaceRepository) { try { caps = searchRepository(getWorkspaceRepo(), pkg); wsName = p.getName(); } catch (Exception e) { if (!loggedWorkspaceError) { logger.logError("Error trying to fetch the repository for the current workspace", e); loggedWorkspaceError = true; } } } if (caps == null) { continue; } for (Capability cap : caps) { final String bsn = capabilityToBSN(cap); if (bsn != null && !handler.containsBundle(bsn)) { bundles.add(bsn, p.getName()); } } } } if (bundles.isEmpty()) { return null; } IJavaCompletionProposal[] retval = new IJavaCompletionProposal[bundles.size()]; int i = 0; for (Map.Entry<String, List<String>> bundle : bundles.entrySet()) { final int relevance = bundle.getValue() .contains(wsName) ? ADD_BUNDLE_WORKSPACE : ADD_BUNDLE; retval[i++] = new AddBundleCompletionProposal(bundle.getKey(), bundle.getValue(), relevance, context); } return retval; }
Source:
private void assertVcAreEqual(final VariantContext actual, final VariantContext expected) { if (expected == null) { Assert.assertNull(actual); return; } Assert.assertNotNull(actual); Assert.assertEquals(actual.getContig(), expected.getContig()); Assert.assertEquals(actual.getStart(), expected.getStart()); Assert.assertEquals(actual.getEnd(), expected.getEnd()); expected.getAlleles().sort(new AlleleComparator()); actual.getAlleles().sort(new AlleleComparator()); Assert.assertEquals(expected.getAlleles(), actual.getAlleles()); assertGenotypeContextsAreEquals(actual.getGenotypes(), expected.getGenotypes()); }

Target:
private void assertVcAreEqual(final VariantContext actual, final VariantContext expected) { if (expected == null) { Assert.assertNull(actual); return; } Assert.assertNotNull(actual, "null status"); Assert.assertEquals(actual.getContig(), expected.getContig(),"Different contigs: "); Assert.assertEquals(actual.getStart(), expected.getStart(), "Different starts: "); Assert.assertEquals(actual.getEnd(), expected.getEnd(), "Different ends: "); Assert.assertTrue(actual.hasSameAllelesAs(expected), "Alleles differ between " + actual + " and " + expected + ": "); assertGenotypeContextsAreEquals(actual.getGenotypes(), expected.getGenotypes()); }
Source:
Byte[] toBytes(Integer v) { Byte[] barr = ArrayUtils.toObject(ByteBuffer.allocate(9).putLong(1, v).array()); barr[0] = 0x19; return barr; }

Target:
Byte[] toBytes(Integer v) { Byte[] barr = ArrayUtils.toObject(ByteBuffer.allocate(9).putLong(1, v).array()); barr[0] = ValueTag.XS_INTEGER_TAG; return barr; }
Source:
public static RoomValidationHelper createInstance(){ Injector injector = Guice.createInjector(new RoomRuntimeModule()); return new RoomValidationHelper(injector.getInstance(RoomParser.class)); }

Target:
public static RoomValidationHelper createInstance(){ Injector injector = new org.eclipse.etrice.core.RoomStandaloneSetup().createInjector(); return new RoomValidationHelper(injector.getInstance(RoomParser.class)); }
Source:
private SCM findSCM(CruiseConfig modifiedConfig) { SCMs scms = modifiedConfig.getSCMs(); SCM existingSCM = scms.find(globalScmConfig.getSCMId()); if (existingSCM == null) { result.notFound(LocalizedMessage.string("SCM_MATERIAL_NOT_FOUND"), HealthStateType.notFound()); throw new NullPointerException(String.format("The pluggable scm material with id '%s' is not found.", globalScmConfig.getSCMId())); } else { return existingSCM; } }

Target:
private SCM findSCM(CruiseConfig modifiedConfig) { SCMs scms = modifiedConfig.getSCMs(); SCM existingSCM = scms.find(globalScmConfig.getSCMId()); if (existingSCM == null) { result.notFound(LocalizedMessage.string("RESOURCE_NOT_FOUND"), HealthStateType.notFound()); throw new NullPointerException(String.format("The pluggable scm material with id '%s' is not found.", globalScmConfig.getSCMId())); } else { return existingSCM; } }
Source:
public boolean shouldBroadcastPublicIpv4Addr() { return configInstance.getBooleanProperty(namespace + ADVERTISE_PUBLIC_IPV4_ADDR, super.shouldBroadcastPublicIpv4Addr()).get(); }

Target:
public boolean shouldBroadcastPublicIpv4Addr() { return configInstance.getBooleanProperty(namespace + BROADCAST_PUBLIC_IPV4_ADDR_KEY, super.shouldBroadcastPublicIpv4Addr()).get(); }
Source:
public static APIQuerySubmissionResult submitQuery() throws IOException, InjectionException, URISyntaxException { final SourceConfiguration localTextSocketSource1Conf = new TextSocketSourceConfigurationBuilderImpl() .set(TextSocketSourceParameters.SOCKET_HOST_ADDRESS, source1Host) .set(TextSocketSourceParameters.SOCKET_HOST_PORT, source1Port) .build(); final SourceConfiguration localTextSocketSource2Conf = new TextSocketSourceConfigurationBuilderImpl() .set(TextSocketSourceParameters.SOCKET_HOST_ADDRESS, source2Host) .set(TextSocketSourceParameters.SOCKET_HOST_PORT, source2Port) .build(); final SinkConfiguration localTextSocketSinkConf = new TextSocketSinkConfigurationBuilderImpl() .set(TextSocketSinkParameters.SOCKET_HOST_ADDRESS, SINK_HOST) .set(TextSocketSinkParameters.SOCKET_HOST_PORT, SINK_PORT) .build(); final MISTBiFunction<Integer, Integer, Integer> reduceFunction = (v1, v2) -> { return v1 + v2; }; final ContinuousStream sourceStream1 = new TextSocketSourceStream<>(localTextSocketSource1Conf) .map(s -> new Tuple2(s, 1)); final ContinuousStream sourceStream2 = new TextSocketSourceStream<>(localTextSocketSource2Conf) .map(s -> new Tuple2(s, 1)); final Sink sink = sourceStream1 .union(sourceStream2) .reduceByKey(0, String.class, reduceFunction) .textSocketOutput(localTextSocketSinkConf); final MISTQuery query = sink.getQuery(); final MISTExecutionEnvironment executionEnvironment = new MISTExecutionEnvironmentImpl(driverHost, driverPort); return executionEnvironment.submit(query); }

Target:
public static APIQuerySubmissionResult submitQuery() throws IOException, InjectionException, URISyntaxException, StreamTypeMismatchException { final SourceConfiguration localTextSocketSource1Conf = new TextSocketSourceConfigurationBuilderImpl() .set(TextSocketSourceParameters.SOCKET_HOST_ADDRESS, source1Host) .set(TextSocketSourceParameters.SOCKET_HOST_PORT, source1Port) .build(); final SourceConfiguration localTextSocketSource2Conf = new TextSocketSourceConfigurationBuilderImpl() .set(TextSocketSourceParameters.SOCKET_HOST_ADDRESS, source2Host) .set(TextSocketSourceParameters.SOCKET_HOST_PORT, source2Port) .build(); final SinkConfiguration localTextSocketSinkConf = new TextSocketSinkConfigurationBuilderImpl() .set(TextSocketSinkParameters.SOCKET_HOST_ADDRESS, SINK_HOST) .set(TextSocketSinkParameters.SOCKET_HOST_PORT, SINK_PORT) .build(); final MISTBiFunction<Integer, Integer, Integer> reduceFunction = (v1, v2) -> { return v1 + v2; }; final ContinuousStream sourceStream1 = new TextSocketSourceStream<>(localTextSocketSource1Conf) .map(s -> new Tuple2(s, 1)); final ContinuousStream sourceStream2 = new TextSocketSourceStream<>(localTextSocketSource2Conf) .map(s -> new Tuple2(s, 1)); final Sink sink = sourceStream1 .union(sourceStream2) .reduceByKey(0, String.class, reduceFunction) .textSocketOutput(localTextSocketSinkConf); final MISTQuery query = sink.getQuery(); final MISTExecutionEnvironment executionEnvironment = new MISTExecutionEnvironmentImpl(driverHost, driverPort); return executionEnvironment.submit(query); }
Source:
private void drawText(Canvas canvas, PointF pos) { if (mText != null && mText != "") { Iterator<Paint> iter = mTextStyle.iterator(); while (iter.hasNext()) { Paint p = iter.next(); p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); } } }

Target:
private void drawText(Canvas canvas, PointF pos) { if (mText != null && mText != "") { for (Paint p : mTextStyle) { p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); } } }
Source:
public void should_pass_if_actual_contains_given_values_exactly_with_null_elements() { iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Luke", "Yoda", "Leia")); actual.add(null); iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Luke", "Yoda", "Leia", null)); }

Target:
public void should_pass_if_actual_contains_given_values_exactly_with_null_elements() { iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Leia", "Yoda", "Luke")); actual.add(null); iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Leia", null, "Yoda", "Luke")); }
Source:
protected String getRepositoryAlias(String url) { String alias = url; alias = alias.substring(alias.lastIndexOf("/") + 1); final int lastDotIndex = alias.lastIndexOf('.'); if (lastDotIndex > 0) { alias = alias.substring(0, lastDotIndex); } return alias; }

Target:
protected String getRepositoryAlias(String url) { String alias = url; alias = alias.substring(alias.lastIndexOf('/') + 1); final int lastDotIndex = alias.lastIndexOf('.'); if (lastDotIndex > 0) { alias = alias.substring(0, lastDotIndex); } return alias; }
Source:
protected Object convertGroup(Group group) { Object obj; try { obj = pojoClass.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new RuntimeException(ex); } for (int i = 0; i < columnFieldSetters.size(); i++) { ParquetFilePOJOReader.ActiveFieldInfo afi = columnFieldSetters.get(i); afi = columnFieldSetters.get(i); int fieldIndex = schema.getFieldIndex(afi.fieldInfo.getColumnName()); SupportType st = afi.fieldInfo.getType(); switch (st) { case BOOLEAN: Boolean booleanVal = Boolean.parseBoolean(group.getValueToString(fieldIndex, 0)); pojoSetters.get(afi.fieldInfo.getPojoFieldExpression()).set(obj, booleanVal); break; case INTEGER: Integer intVal = Integer.parseInt(group.getValueToString(fieldIndex, 0)); pojoSetters.get(afi.fieldInfo.getPojoFieldExpression()).set(obj, intVal); break; case LONG: Long longVal = Long.parseLong(group.getValueToString(fieldIndex, 0)); pojoSetters.get(afi.fieldInfo.getPojoFieldExpression()).set(obj, longVal); break; case FLOAT: Float floatVal = Float.parseFloat(group.getValueToString(fieldIndex, 0)); pojoSetters.get(afi.fieldInfo.getPojoFieldExpression()).set(obj, floatVal); break; case DOUBLE: Double doubleVal = Double.parseDouble(group.getValueToString(fieldIndex, 0)); pojoSetters.get(afi.fieldInfo.getPojoFieldExpression()).set(obj, doubleVal); break; case STRING: pojoSetters.get(afi.fieldInfo.getPojoFieldExpression()).set(obj, group.getValueToString(fieldIndex, 0)); break; default: throw new ParquetEncodingException("Unsupported column type: " + schema.getType(fieldIndex)); } } return obj; }

Target:
protected Object convertGroup(Group group) { Object obj; try { obj = pojoClass.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new RuntimeException(ex); } for (int i = 0; i < activeFieldInfos.size(); i++) { try { ParquetFilePOJOReader.ActiveFieldInfo afi = activeFieldInfos.get(i); switch (afi.primitiveTypeName) { case BOOLEAN: Boolean booleanVal = Boolean.parseBoolean(group.getValueToString(afi.fieldIndex, 0)); ((PojoUtils.SetterBoolean<Object>)afi.setter).set(obj, booleanVal); break; case INT32: Integer intVal = Integer.parseInt(group.getValueToString(afi.fieldIndex, 0)); ((PojoUtils.SetterInt<Object>)afi.setter).set(obj, intVal); break; case INT64: Long longVal = Long.parseLong(group.getValueToString(afi.fieldIndex, 0)); ((PojoUtils.SetterLong<Object>)afi.setter).set(obj, longVal); break; case FLOAT: Float floatVal = Float.parseFloat(group.getValueToString(afi.fieldIndex, 0)); ((PojoUtils.SetterFloat<Object>)afi.setter).set(obj, floatVal); break; case DOUBLE: Double doubleVal = Double.parseDouble(group.getValueToString(afi.fieldIndex, 0)); ((PojoUtils.SetterDouble<Object>)afi.setter).set(obj, doubleVal); break; case BINARY: ((PojoUtils.Setter<Object, String>)afi.setter).set(obj, group.getValueToString(afi.fieldIndex, 0)); break; default: throw new ParquetEncodingException("Unsupported column type: " + afi.primitiveTypeName); } } catch (InvalidRecordException e) { logger.error("Field not found in schema ", e); } } return obj; }
Source:
public void distributeEntities() { synchronized (memberChangeMutex) { Function<Entity, String> bucketFunction = getConfig(BUCKET_FUNCTION); EntitySpec<? extends BasicGroup> bucketSpec = getConfig(BUCKET_SPEC); if (bucketFunction == null || bucketSpec == null) return; Map<String, BasicGroup> buckets = getAttribute(BUCKETS); Multimap<String, Entity> entityMapping = Multimaps.index( Iterables.filter(getMembers(), Predicates.compose(Predicates.notNull(), bucketFunction)), bucketFunction); for (String name : entityMapping.keySet()) { BasicGroup bucket = buckets.get(name); if (bucket == null) { bucket = addChild(EntitySpec.create(bucketSpec).displayName(name)); Entities.manage(bucket); buckets.put(name, bucket); } bucket.setMembers(entityMapping.get(name)); } Set<String> empty = ImmutableSet.copyOf(Sets.difference(buckets.keySet(), entityMapping.keySet())); for (String name : empty) { Group removed = buckets.remove(name); removeChild(removed); Entities.unmanage(removed); } setAttribute(BUCKETS, buckets); } }

Target:
public void distributeEntities() { synchronized (memberChangeMutex) { Function<Entity, String> bucketFunction = getConfig(BUCKET_FUNCTION); EntitySpec<? extends BasicGroup> bucketSpec = getConfig(BUCKET_SPEC); if (bucketFunction == null || bucketSpec == null) return; Map<String, BasicGroup> buckets = MutableMap.copyOf(getAttribute(BUCKETS)); Multimap<String, Entity> entityMapping = Multimaps.index( Iterables.filter(getMembers(), Predicates.compose(Predicates.notNull(), bucketFunction)), bucketFunction); for (String name : entityMapping.keySet()) { BasicGroup bucket = buckets.get(name); if (bucket == null) { bucket = addChild(EntitySpec.create(bucketSpec).displayName(name)); Entities.manage(bucket); buckets.put(name, bucket); } bucket.setMembers(entityMapping.get(name)); } Set<String> empty = ImmutableSet.copyOf(Sets.difference(buckets.keySet(), entityMapping.keySet())); for (String name : empty) { Group removed = buckets.remove(name); removeChild(removed); Entities.unmanage(removed); } setAttribute(BUCKETS, ImmutableMap.copyOf(buckets)); } }
Source:
public String getMessage() { if (lightblueResponse != null) { StringBuffer sb = new StringBuffer(super.getMessage()); if (!StringUtils.isEmpty(lightblueResponse.getRequestId())) { sb.append(" RequestID:").append(lightblueResponse.getRequestId()); } sb.append(' ').append(lightblueResponse.getText()); return sb.toString(); } else { return super.getMessage(); } }

Target:
public String getMessage() { if (lightblueResponse != null) { StringBuffer sb = new StringBuffer(super.getMessage()); if (!StringUtils.isEmpty(lightblueResponse.getRequestId())) { sb.append(" RequestID=").append(lightblueResponse.getRequestId()); } sb.append(' ').append(lightblueResponse.getText()); return sb.toString(); } else { return super.getMessage(); } }
Source:
public void close() { if (_baselineCalculateExecutor != null) { _baselineCalculateExecutor.shutdown(); } if (_assignmentMetadataStore != null) { _assignmentMetadataStore.close(); } _metricCollector.unregister(); }

Target:
public void close() { if (_baselineCalculateExecutor != null) { _baselineCalculateExecutor.shutdownNow(); } if (_assignmentMetadataStore != null) { _assignmentMetadataStore.close(); } _metricCollector.unregister(); }
Source:
private void startTracing() throws Throwable { final AsyncCompletionWaitor wait = new AsyncCompletionWaitor(); fSession.getExecutor().submit(new Runnable() { @Override public void run() { fTraceService.getTraceStatus( fTraceTargetDmc, new DataRequestMonitor<ITraceStatusDMData>(fSession.getExecutor(), null) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { if (getData().isTracingSupported()) { fTraceService.startTracing( fTraceTargetDmc, new RequestMonitor(fSession.getExecutor(), null) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { wait.waitFinished(getStatus()); } }); } else { wait.waitFinished(getStatus()); } } }); } }); wait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER); assertTrue(wait.getMessage(), wait.isOK()); }

Target:
private void startTracing() throws Throwable { final AsyncCompletionWaitor wait = new AsyncCompletionWaitor(); fSession.getExecutor().submit(new Runnable() { @Override public void run() { fTraceService.getTraceStatus( fTraceTargetDmc, new DataRequestMonitor<ITraceStatusDMData>(fSession.getExecutor(), null) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { if (isSuccess() && getData().isTracingSupported()) { fTraceService.startTracing( fTraceTargetDmc, new RequestMonitor(fSession.getExecutor(), null) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { wait.waitFinished(getStatus()); } }); } else { wait.waitFinished(getStatus()); } } }); } }); wait.waitUntilDone(AsyncCompletionWaitor.WAIT_FOREVER); assertTrue(wait.getMessage(), wait.isOK()); }
Source:
public long getSwapUsed() { long swapAvailable = 0; List<String> memInfo = null; try { memInfo = FileUtil.readFile("/proc/meminfo"); } catch (IOException e) { LOG.error("Problem with /proc/meminfo: {}", e.getMessage()); } for (String checkLine : memInfo) { if (checkLine.startsWith("SwapFree:")) { String[] memorySplit = checkLine.split("\\s+"); swapAvailable = parseMeminfo(memorySplit); break; } } return swapAvailable; }

Target:
public long getSwapUsed() { long swapFree = 0; long swapTotal = 0; List<String> memInfo = null; try { memInfo = FileUtil.readFile("/proc/meminfo"); for (String checkLine : memInfo) { if (checkLine.startsWith("SwapFree:")) { String[] memorySplit = checkLine.split("\\s+"); swapFree = parseMeminfo(memorySplit); break; } } swapTotal = getSwapTotal(); } catch (IOException e) { LOG.error("Problem with /proc/meminfo: {}", e.getMessage()); } return swapTotal - swapFree; }