auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.i("onCreate"); setContentView(R.layout.activity_arrow); if (!mPreferences.getBoolean(Const.SETTINGS_SIGNED_IN, false)) finish(); arrowPreferences = getSharedPreferences("arrow", MODE_PRIVATE); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { showNoNfc(); mArrowHandler = new BaseArrowHandler(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mArrowHandler = new NfcArrowHandler(); } else { mArrowHandler = new BaseArrowHandler(); } } scanImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(ArrowActivity.this); integrator.initiateScan(); } }); switchToReceive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewFlipper.setDisplayedChild(0); } }); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_arrow); if (!mPreferences.getBoolean(Const.SETTINGS_SIGNED_IN, false)) finish(); arrowPreferences = getSharedPreferences("arrow", MODE_PRIVATE); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { showNoNfc(); mArrowHandler = new BaseArrowHandler(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mArrowHandler = new NfcArrowHandler(); } else { mArrowHandler = new BaseArrowHandler(); } } scanImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(ArrowActivity.this); integrator.initiateScan(); } }); switchToReceive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewFlipper.setDisplayedChild(0); } }); }
Source:
public Credential validate(final Credential credential, final RequestData data) throws WSSecurityException { if (credential == null || credential.getSamlAssertion() == null) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noCredential"); } final SamlAssertionWrapper assertion = credential.getSamlAssertion(); String confirmMethod = null; final List<String> methods = assertion.getConfirmationMethods(); if (!methods.isEmpty()) { confirmMethod = methods.get(0); } checkAssertion(assertion, confirmMethod); checkConditions(assertion); validateAssertion(assertion); checkSignedAssertion(assertion, data); return credential; }

Target:
public Credential validate(final Credential credential, final RequestData data) throws WSSecurityException { if (credential == null || credential.getSamlAssertion() == null) { throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noCredential"); } final SamlAssertionWrapper assertion = credential.getSamlAssertion(); String confirmMethod = null; final List<String> methods = assertion.getConfirmationMethods(); if (CollectionUtils.isNotEmpty(methods)) { confirmMethod = methods.get(0); } checkAssertion(assertion, confirmMethod); checkConditions(assertion); validateAssertion(assertion); checkSignedAssertion(assertion, data); return credential; }
Source:
@Test public void pressKeyCodeTest() throws Exception { final AndroidDriver driver = getAndroidDriver(".fingerprint.FingerprintSettings"); TimeUnit.SECONDS.sleep(2); driver.findElement(By.id("com.android.settings:id/password_entry")).sendKeys("1234\n"); TimeUnit.SECONDS.sleep(2); driver.findElement(By.xpath(" .click(); TimeUnit.SECONDS.sleep(2); driver.fingerPrint(2); driver.findElement(By.id("com.android.settings:id/next_button")).click(); TimeUnit.SECONDS.sleep(2); driver.quit(); }

Target:
@Test public void pressKeyCodeTest() throws InterruptedException { final AndroidDriver driver = getAndroidDriver(".fingerprint.FingerprintSettings"); TimeUnit.SECONDS.sleep(2); enterPasswordAndContinue(driver); driver.findElementByXPath(FIRST_IN_LIST_XPATH).click(); TimeUnit.SECONDS.sleep(2); driver.fingerPrint(2); TimeUnit.SECONDS.sleep(2); try { clickNext(driver); } catch (Exception e) { Assert.fail("fingerprint command fail to execute"); } finally { driver.quit(); } }
Source:
DelegatingTimeoutSaslServer(final SaslServer delegate, final ScheduledExecutorService scheduledExecutorService, final long timeout) { super(delegate); timeoutTask = scheduledExecutorService.schedule(() -> { if (! (isComplete() && complete.compareAndSet(false, true))) { dispose(); } return null; }, timeout, TimeUnit.SECONDS); }

Target:
DelegatingTimeoutSaslServer(final SaslServer delegate, final ScheduledExecutorService scheduledExecutorService, final long timeout) { super(delegate); timeoutTask = scheduledExecutorService.schedule(() -> { synchronized (this) { if (! (isComplete() && ! complete)) { dispose(); terminated = true; } else { complete = true; } return null; } }, timeout, TimeUnit.SECONDS); }
Source:
public void testRequestSuccessForImage() throws Throwable { enqueueFromFile("gallery_item_image.json"); Callback cb = mock(Callback.class); Call<MwQueryResponse> call = request(cb, false); server().takeRequest(); ArgumentCaptor<HashMap> captor = ArgumentCaptor.forClass(HashMap.class); verify(cb).success(eq(call), captor.capture()); Map<PageTitle, GalleryItem> result = captor.getValue(); Assert.assertTrue(result.size() > 0); GalleryItem galleryItem = (GalleryItem) result.values().toArray()[0]; Assert.assertTrue(galleryItem != null); Assert.assertThat(String.valueOf(galleryItem.getHeight()), is("1489")); Assert.assertThat(String.valueOf(galleryItem.getWidth()), is("2125")); Assert.assertThat(galleryItem.getThumbUrl(), is("<LINK_0>")); Assert.assertThat(galleryItem.getMimeType(), is("image/jpeg")); Assert.assertThat(galleryItem.getUrl(), is("<LINK_1>")); }

Target:
public void testRequestSuccessForImage() throws Throwable { enqueueFromFile("gallery_item_image.json"); Callback cb = mock(Callback.class); Call<MwQueryResponse> call = request(cb, false); server().takeRequest(); ArgumentCaptor<GalleryItem> captor = ArgumentCaptor.forClass(GalleryItem.class); verify(cb).success(eq(call), captor.capture()); GalleryItem galleryItem = captor.getValue(); Assert.assertTrue(galleryItem != null); Assert.assertThat(String.valueOf(galleryItem.getHeight()), is("1489")); Assert.assertThat(String.valueOf(galleryItem.getWidth()), is("2125")); Assert.assertThat(galleryItem.getThumbUrl(), is("<LINK_0>")); Assert.assertThat(galleryItem.getMimeType(), is("image/jpeg")); Assert.assertThat(galleryItem.getUrl(), is("<LINK_1>")); }
Source:
protected abstract <K> Object handleWriteManyCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<K> keys, boolean forwarded) throws Throwable; protected final Throwable cleanLocksAndRethrow(InvocationContext ctx, Throwable te) { lockManager.unlockAll(ctx); return te; }

Target:
protected abstract <K> Object handleWriteManyCommand(InvocationContext ctx, FlagAffectedCommand command, Collection<K> keys, boolean forwarded) throws Throwable; protected final long getLockTimeoutMillis(FlagAffectedCommand command) { return command.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT) ? 0 : cacheConfiguration.locking().lockAcquisitionTimeout(); }
Source:
public void read(Row row, int ordinal) throws StandardException { if (row.isNullAt(ordinal)) setToNull(); else { isNull = false; byte[] bytes = (byte[]) row.get(ordinal); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = null; try { in = new ObjectInputStream(bis); value = in.readObject(); } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } } } }

Target:
public void read(Row row, int ordinal) throws StandardException { if (row.isNullAt(ordinal)) setToNull(); else { isNull = false; Object object = row.get(ordinal); if (object instanceof byte[]) { value = SerializationUtils.deserialize((byte[]) object); } else { value = object; } } }
Source:
protected void verifyResults(Map <String,Integer> result, Map <String,Integer> verifyAgainst) { assert result.size() > 0 : "Results should have at least 1 answer"; for (Entry<String, Integer> e : result.entrySet()) { String key = e.getKey(); Integer count = verifyAgainst.get(key); assert count.equals(e.getValue()): "key " + e.getKey() + " does not have count " + count + " but " + e.getValue(); } }

Target:
protected void verifyResults(Map <String,Integer> result, Map <String,Integer> verifyAgainst) { assertTrue("Results should have at least 1 answer", result.size() > 0); for (Entry<String, Integer> e : result.entrySet()) { String key = e.getKey(); Integer count = verifyAgainst.get(key); assertTrue("key " + e.getKey() + " does not have count " + count + " but " + e.getValue(), count.equals(e.getValue())); } }
Source:
private static void validateStreamModifierClauses(String statement, Map<String, String> expectedGroupValues) { Matcher matcher = SQLParser.matchAnyCreateStreamStatementClause(statement); Set<String> matched = new HashSet<>(); int start = 0; while (matcher.find(start)) { start = matcher.end(); for (Map.Entry<String, String> e : expectedGroupValues.entrySet()) { String key = e.getKey(); String parsedValue = matcher.group(key); if (parsedValue == null) { continue; } assertFalse(matched.contains(key)); matched.add(key); assertEquals(expectedGroupValues.get(key), parsedValue); } } assertEquals(matched.size(), expectedGroupValues.keySet().size()); }

Target:
private static void validateStreamModifierClauses(String statement, Map<String, String> expectedGroupValues) { Matcher matcher = SQLParser.matchAnyCreateStreamStatementClause(statement); Set<String> matched = new HashSet<>(); int start = 0; while (matcher.find(start)) { start = matcher.end(); for (String group : s_allStreamModifierGroups) { String parsedValue = matcher.group(group); if (parsedValue == null) { continue; } assertTrue(expectedGroupValues.keySet().contains(group)); assertFalse(matched.contains(group)); matched.add(group); assertEquals(expectedGroupValues.get(group), parsedValue); } } assertEquals(matched.size(), expectedGroupValues.keySet().size()); }
Source:
public Optional<AccessToken> authenticate(String submittedToken) throws AuthenticationException { Optional<AccessToken> token; try { token = tokenStore.getAccessTokenByToken(submittedToken, DateTime.now()); if(!token.isPresent()) { LOGGER.warn("warning=token_not_present token={}", submittedToken); } return token; } catch (MissingRequiredScopeException e) { throw new MissingRequiredScopeAuthenticationException(e); } }

Target:
public Optional<AccessToken> authenticate(String submittedToken) throws AuthenticationException { try { final Optional<AccessToken> token = tokenStore.getAccessTokenByToken(submittedToken, DateTime.now()); if(!token.isPresent()) { LOGGER.warn("warning=token_not_present token={}", submittedToken); } return token; } catch (MissingRequiredScopeException e) { throw new MissingRequiredScopeAuthenticationException(e); } }
Source:
public void safeRun() { while (true) { Versioned<LedgerMetadata> currentMetadata = getVersionedLedgerMetadata(); Version.Occurred occurred = currentMetadata.getVersion().compare(newMetadata.getVersion()); if (Version.Occurred.BEFORE == occurred) { LOG.info("Updated ledger metadata for ledger to {}.", ledgerId, newMetadata.getValue().toSafeString()); synchronized (ReadOnlyLedgerHandle.this) { if (setLedgerMetadata(currentMetadata, newMetadata)) { break; } } } else { break; } } }

Target:
public void safeRun() { while (true) { Versioned<LedgerMetadata> currentMetadata = getVersionedLedgerMetadata(); Version.Occurred occurred = currentMetadata.getVersion().compare(newMetadata.getVersion()); if (Version.Occurred.BEFORE == occurred) { synchronized (ReadOnlyLedgerHandle.this) { if (setLedgerMetadata(currentMetadata, newMetadata)) { LOG.info("Updated ledger metadata for ledger to {}, version {}.", ledgerId, newMetadata.getValue().toSafeString(), newMetadata.getVersion()); break; } } } else { break; } } }
Source:
public DateTime increment(DateTime time) { return new DateTime(Long.MAX_VALUE / 2); }

Target:
public DateTime increment(DateTime time) { return maxDateTime; }
Source:
protected void setup(Binder binder) { httpServerBinder(binder).bindResource("/ui", "router_ui").withWelcomeFile("index.html"); configBinder(binder).bindConfig(RouterConfig.class); binder.bind(ClusterManager.class).in(Scopes.SINGLETON); binder.bind(RemoteInfoFactory.class).in(Scopes.SINGLETON); httpClientBinder(binder).bindHttpClient("query-tracker", ForQueryInfoTracker.class) .withConfigDefaults(config -> { config.setIdleTimeout(new Duration(30, SECONDS)); config.setRequestTimeout(new Duration(10, SECONDS)); }); httpClientBinder(binder).bindHttpClient("query-tracker", ForClusterInfoTracker.class) .withConfigDefaults(config -> { config.setIdleTimeout(new Duration(30, SECONDS)); config.setRequestTimeout(new Duration(10, SECONDS)); }); binder.bind(ClusterStatusTracker.class).in(Scopes.SINGLETON); jaxrsBinder(binder).bind(RouterResource.class); jaxrsBinder(binder).bind(ClusterStatusResource.class); }

Target:
protected void setup(Binder binder) { httpServerBinder(binder).bindResource("/ui", "router_ui").withWelcomeFile("index.html"); configBinder(binder).bindConfig(RouterConfig.class); binder.bind(ClusterManager.class).in(Scopes.SINGLETON); binder.bind(RemoteInfoFactory.class).in(Scopes.SINGLETON); bindHttpClient(binder, QUERY_TRACKER, ForQueryInfoTracker.class); bindHttpClient(binder, QUERY_TRACKER, ForClusterInfoTracker.class); binder.bind(ClusterStatusTracker.class).in(Scopes.SINGLETON); jaxrsBinder(binder).bind(RouterResource.class); jaxrsBinder(binder).bind(ClusterStatusResource.class); }
Source:
private CassandraNodeInfo buildInfo(JmxConnect jmx) throws UnknownHostException { Nodetool nodetool = new Nodetool(jmx); String endpoint = nodetool.getEndpoint(); return CassandraNodeInfo.newBuilder() .setOperationMode(nodetool.getOperationMode()) .setJoined(nodetool.isJoined()) .setGoosipInitialized(nodetool.isGossipInitialized()) .setGossipRunning(nodetool.isGossipRunning()) .setNativeTransportRunning(nodetool.isNativeTransportRunning()) .setRpcServerRunning(nodetool.isRPCServerRunning()) .setUptimeSeconds(nodetool.getUptimeInMillis() / 1000L) .setVersion(nodetool.getVersion()) .setHostId(nodetool.getHostID()) .setEndpoint(endpoint) .setTokenCount(nodetool.getTokenCount()) .setDataCenter(nodetool.getDataCenter(endpoint)) .setRack(nodetool.getRack(endpoint)) .setClusterName(nodetool.getClusterName()) .build(); }

Target:
private CassandraNodeInfo buildInfo(JmxConnect jmx) throws UnknownHostException { Nodetool nodetool = new Nodetool(jmx); String endpoint = nodetool.getEndpoint(); return CassandraNodeInfo.newBuilder() .setOperationMode(nodetool.getOperationMode()) .setJoined(nodetool.isJoined()) .setGossipInitialized(nodetool.isGossipInitialized()) .setGossipRunning(nodetool.isGossipRunning()) .setNativeTransportRunning(nodetool.isNativeTransportRunning()) .setRpcServerRunning(nodetool.isRPCServerRunning()) .setUptimeMillis(nodetool.getUptimeInMillis()) .setVersion(nodetool.getVersion()) .setHostId(nodetool.getHostID()) .setEndpoint(endpoint) .setTokenCount(nodetool.getTokenCount()) .setDataCenter(nodetool.getDataCenter(endpoint)) .setRack(nodetool.getRack(endpoint)) .setClusterName(nodetool.getClusterName()) .build(); }
Source:
public boolean removeAll(Collection<?> c) { try { boolean removed = false; for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null) { fireOnChangeListeners(); } } }

Target:
public boolean removeAll(Collection<?> c) { boolean removed = false; try { for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null && removed) { fireOnChangeListeners(); } } }
Source:
public CorfuServerNode(@Nonnull ServerContext serverContext, @Nonnull ImmutableMap<Class, AbstractServer> serverMap) { this.serverContext = serverContext; this.serverMap = serverMap; router = new NettyServerRouter(serverMap, serverContext.getServerEpoch()); this.serverContext.setServerRouter(router); this.close = new AtomicBoolean(false); }

Target:
public CorfuServerNode(@Nonnull ServerContext serverContext, @Nonnull ImmutableMap<Class, AbstractServer> serverMap) { this.serverContext = serverContext; this.serverMap = serverMap; router = new NettyServerRouter(serverMap.values().asList(), serverContext); this.serverContext.setServerRouter(router); if(serverContext.isSingleNodeSetup() && serverContext.getCurrentLayout() != null){ serverContext.setServerEpoch(serverContext.getCurrentLayout().getEpoch(), router); } this.close = new AtomicBoolean(false); }
Source:
private void processTimeoutForCallRedirection(String serviceType) { mHandler.postDelayed(new Runnable("CRP.pTFC", mTelecomLock) { @Override public void loggedRun() { boolean isCurrentRedirectionPending = serviceType == SERVICE_TYPE_CARRIER ? mIsUserDefinedRedirectionPending : mIsCarrierRedirectionPending; if (isCurrentRedirectionPending) { Log.i(CallRedirectionProcessor.this, serviceType + "call redirection has timed out."); Log.addEvent(mCall, serviceType.equals(SERVICE_TYPE_USER_DEFINED) ? LogUtils.Events.REDIRECTION_TIMED_OUT_USER : LogUtils.Events.REDIRECTION_TIMED_OUT_CARRIER); onCallRedirectionComplete(mCall); } } }.prepare(), mTimeoutsAdapter.getCallRedirectionTimeoutMillis( mContext.getContentResolver(), serviceType)); }

Target:
private void processTimeoutForCallRedirection(String serviceType) { mHandler.postDelayed(new Runnable("CRP.pTFC", mTelecomLock) { @Override public void loggedRun() { boolean isCurrentRedirectionPending = serviceType.equals(SERVICE_TYPE_USER_DEFINED) ? mIsUserDefinedRedirectionPending : mIsCarrierRedirectionPending; if (isCurrentRedirectionPending) { Log.i(CallRedirectionProcessor.this, serviceType + "call redirection has timed out."); Log.addEvent(mCall, serviceType.equals(SERVICE_TYPE_USER_DEFINED) ? LogUtils.Events.REDIRECTION_TIMED_OUT_USER : LogUtils.Events.REDIRECTION_TIMED_OUT_CARRIER); onCallRedirectionComplete(mCall); } } }.prepare(), mTimeoutsAdapter.getCallRedirectionTimeoutMillis( mContext.getContentResolver(), serviceType)); }
Source:
private Map<String,Map<String,MccMncRecord>> initOperatorMap(AssetManager assetManager) { Map<String,Map<String, MccMncRecord>> map = new HashMap<>(); String json = null; try { final InputStream stream = assetManager.open("mcc-mnc-dict.json"); MainActivity.info("operator stream: " + stream); int size = stream.available(); byte[] buffer = new byte[size]; stream.read(buffer); stream.close(); ObjectMapper mapper = new ObjectMapper(); json = new String(buffer, "UTF-8"); MainActivity.info("operator load complete."); JSONObject jObject = new JSONObject(json); Iterator<String> mccKeys = jObject.keys(); while( mccKeys.hasNext() ){ String key = (String)mccKeys.next(); JSONObject country = jObject.getJSONObject(key); Map<String, MccMncRecord> mccMap = null; if (map.containsKey(key)) { mccMap = map.get(key); } else { mccMap = new HashMap<>(); map.put(key, mccMap); } Iterator<String> mncKeys = country.keys(); while( mncKeys.hasNext() ) { String mncKey = (String)mncKeys.next(); MccMncRecord record = mapper.readValue(country.getJSONObject(mncKey).toString(), MccMncRecord.class); mccMap.put(mncKey, record); } } } catch (final IOException ex) { MainActivity.error("exception loading cell operators: " + ex, ex); } catch (final JSONException ex) { MainActivity.error("exception parsing cell operators: " + ex, ex); } return map; }

Target:
private Map<String,Map<String,MccMncRecord>> initOperatorMap(AssetManager assetManager) { Map<String,Map<String, MccMncRecord>> map = new HashMap<>(); String json = null; try { final InputStream stream = assetManager.open("mcc-mnc-dict.json"); MainActivity.info("operator stream: " + stream); BufferedInputStream bis = new BufferedInputStream(stream); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while(result != -1) { buf.write((byte) result); result = bis.read(); } json = buf.toString("UTF-8"); if (null != bis) { bis.close(); } if (null != buf) { buf.close(); } if (null != stream) { stream.close(); } ObjectMapper mapper = new ObjectMapper(); MainActivity.info("operator load complete."); JSONObject jObject = new JSONObject(json); Iterator<String> mccKeys = jObject.keys(); while( mccKeys.hasNext() ){ String key = (String)mccKeys.next(); JSONObject country = jObject.getJSONObject(key); Map<String, MccMncRecord> mccMap = map.get(key); if (null == mccMap) { mccMap = new HashMap<>(); map.put(key, mccMap); } Iterator<String> mncKeys = country.keys(); while( mncKeys.hasNext() ) { String mncKey = (String)mncKeys.next(); MccMncRecord record = mapper.readValue(country.getJSONObject(mncKey).toString(), MccMncRecord.class); mccMap.put(mncKey, record); } } } catch (final IOException ex) { MainActivity.error("exception loading cell operators: " + ex, ex); } catch (final JSONException ex) { MainActivity.error("exception parsing cell operators: " + ex, ex); } return map; }
Source:
void uriTagValueIsRootWhenBestMatchingPatternIsEmpty() { this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, ""); this.response.setStatus(301); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("ROOT"); }

Target:
void uriTagValueIsRootWhenBestMatchingPatternIsEmpty() { this.request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, ""); this.response.setStatus(301); Tag tag = WebMvcTags.uri(this.request, this.response); assertThat(tag.getValue()).isEqualTo("root"); }
Source:
public Iterator<T> iterator() { Preconditions.checkNotNull(delimeter); Preconditions.checkNotNull(path); Preconditions.checkNotNull(objectCreator); return new Iterator<T>() { private Scanner scanner; { init(); } private void init() { try { scanner = new Scanner(new File(path)).useDelimiter(delimeter); } catch (FileNotFoundException e) { throw Throwables.propagate(e); } } @Override public boolean hasNext() { return scanner.hasNextLine(); } @Override public T next() { return objectCreator.createObject(new String []{ scanner.next() }); } @Override public void remove() { throw new UnsupportedOperationException("Read only iterator!"); } }; }

Target:
public Iterator<T> iterator() { Preconditions.checkNotNull(delimeter); Preconditions.checkNotNull(path); Preconditions.checkNotNull(objectCreator); return new AbstractIterator<T>() { private Scanner scanner; { init(); } private void init() { try { scanner = new Scanner(new File(path)).useDelimiter(delimeter); } catch (FileNotFoundException e) { throw Throwables.propagate(e); } } @Override protected T computeNext() { try { return objectCreator.createObject(scanner.next()); } catch (NoSuchElementException e) { return endOfData(); } } }; }
Source:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSceneView = findViewById(R.id.sceneView); ArcGISScene scene = new ArcGISScene(Basemap.createImagery()); mSceneView.setScene(scene); Camera camera = new Camera(32.7321157, -117.150072, 452.282774, 25.481533, 78.0945859, 0.0); mSceneView.setViewpointCamera(camera); Surface surface = new Surface(); surface.getElevationSources().add(new ArcGISTiledElevationSource(getString(R.string.elevation_source_url))); scene.setBaseSurface(surface); mPointCloudLayer = new PointCloudLayer( getExternalFilesDir(null) + getString(R.string.scene_layer_package_location)); mPointCloudLayer.addDoneLoadingListener(() -> { if (mPointCloudLayer.getLoadStatus() == LoadStatus.LOADED) { mSceneView.getScene().getOperationalLayers().add(mPointCloudLayer); } else { String error = "Point cloud layer failed to load: " + mPointCloudLayer.getLoadError().getMessage(); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); Log.e(TAG, error); } }); mPointCloudLayer.loadAsync(); }

Target:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSceneView = findViewById(R.id.sceneView); ArcGISScene scene = new ArcGISScene(Basemap.createImagery()); mSceneView.setScene(scene); Camera camera = new Camera(32.7321157, -117.150072, 452.282774, 25.481533, 78.0945859, 0.0); mSceneView.setViewpointCamera(camera); Surface surface = new Surface(); surface.getElevationSources().add(new ArcGISTiledElevationSource(getString(R.string.elevation_source_url))); scene.setBaseSurface(surface); PointCloudLayer pointCloudLayer = new PointCloudLayer( getExternalFilesDir(null) + getString(R.string.scene_layer_package_location)); mSceneView.getScene().getOperationalLayers().add(pointCloudLayer); pointCloudLayer.addDoneLoadingListener(() -> { if (pointCloudLayer.getLoadStatus() != LoadStatus.LOADED) { String error = "Point cloud layer failed to load: " + pointCloudLayer.getLoadError().getMessage(); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); Log.e(TAG, error); } }); }
Source:
private List<String> getSecuritygroup(final String parameters) { if (parameters == null) { return null; } List<String> securityGroups = new ArrayList<>(); try { securityGroups = JsonPath.read(parameters, "$.Test.instancesSet.items[*].networkInterfaceSet.items[*].groupSet.items[*].groupId"); } catch( PathNotFoundException e) { LOG.error("could not fetch security groups from event"); } return securityGroups; }

Target:
private List<String> getSecuritygroup(final String parameters) { if (parameters == null) { return null; } List<String> securityGroups = new ArrayList<>(); try { securityGroups = JsonPath.read(parameters, "$.instancesSet.items[*].networkInterfaceSet.items[*].groupSet.items[*].groupId"); } catch( PathNotFoundException e) { LOG.error("could not fetch security groups from event"); } return securityGroups; }
Source:
public EmptyContainerDecoder(ObjectMapper mapper, Decoder delegate) { this.delegate = delegate; this.blankInstanceCache = Caffeine.newBuilder() .maximumSize(10_000) .expireAfterAccess(10, TimeUnit.MINUTES) .build(new BlankInstanceLoader(mapper)); }

Target:
public EmptyContainerDecoder(ObjectMapper mapper, Decoder delegate) { this.delegate = delegate; this.blankInstanceCache = Caffeine.newBuilder() .maximumSize(1000) .expireAfterAccess(10, TimeUnit.MINUTES) .build(new BlankInstanceLoader(mapper)); }
Source:
public void testReadTableBeforeCreationCompleted() { assertThatNoTableIsCreated(); SchemaTableName tableName = new SchemaTableName("default", "temp_table"); ConnectorOutputTableHandle table = metadata.beginCreateTable( SESSION, new ConnectorTableMetadata(tableName, ImmutableList.of(), ImmutableMap.of()), Optional.empty()); List<SchemaTableName> tableNames = metadata.listTables(SESSION, null); assertTrue(tableNames.size() == 1, "Expected exactly one table."); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, tableName); List<ConnectorTableLayoutResult> tableLayouts = metadata.getTableLayouts(SESSION, tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertTrue(tableLayouts.size() == 1, "Expected exactly one layout."); ConnectorTableLayout tableLayout = tableLayouts.get(0).getTableLayout(); ConnectorTableLayoutHandle tableLayoutHandle = tableLayout.getHandle(); assertTrue(tableLayoutHandle instanceof MemoryTableLayoutHandle); assertTrue(((MemoryTableLayoutHandle) tableLayoutHandle).getHosts().isEmpty(), "Hosts should be empty"); metadata.finishCreateTable(SESSION, table, ImmutableList.of()); }

Target:
public void testReadTableBeforeCreationCompleted() { assertNoTables(); SchemaTableName tableName = new SchemaTableName("default", "temp_table"); ConnectorOutputTableHandle table = metadata.beginCreateTable( SESSION, new ConnectorTableMetadata(tableName, ImmutableList.of(), ImmutableMap.of()), Optional.empty()); List<SchemaTableName> tableNames = metadata.listTables(SESSION, null); assertTrue(tableNames.size() == 1, "Expected exactly one table"); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, tableName); List<ConnectorTableLayoutResult> tableLayouts = metadata.getTableLayouts(SESSION, tableHandle, Constraint.alwaysTrue(), Optional.empty()); assertTrue(tableLayouts.size() == 1, "Expected exactly one layout."); ConnectorTableLayout tableLayout = tableLayouts.get(0).getTableLayout(); ConnectorTableLayoutHandle tableLayoutHandle = tableLayout.getHandle(); assertTrue(tableLayoutHandle instanceof MemoryTableLayoutHandle); assertTrue(((MemoryTableLayoutHandle) tableLayoutHandle).getDataFragments().isEmpty(), "Data fragments should be empty"); metadata.finishCreateTable(SESSION, table, ImmutableList.of()); }
Source:
public void handleEvent(Event event) { ReplicationAction action = ReplicationAction.fromEvent(event); String[] paths = action.getPaths(); Set<String> tobeFlushedDomains = getListOfDomains(paths, action); for(String key : tobeFlushedDomains){ flushSiteMapXml(action); } }

Target:
public void handleEvent(Event event) { if(isMaster){ ReplicationAction action = ReplicationAction.fromEvent(event); ValueMap jobProperties = getJobProperties(action); Job siteMapGenerationJob = jobManager.addJob(TOPIC, null, jobProperties); log.debug("event offloaded to the sitemap flush job"+siteMapGenerationJob.getId()); } }
Source:
private void saveDownloadedFile() { OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId()); long syncDate = System.currentTimeMillis(); file.setLastSyncDateForProperties(syncDate); file.setLastSyncDateForData(syncDate); file.setNeedsUpdateThumbnail(true); file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp()); file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp()); file.setEtag(mCurrentDownload.getEtag()); file.setMimetype(mCurrentDownload.getMimeType()); file.setStoragePath(mCurrentDownload.getSavePath()); file.setFileLength((new File(mCurrentDownload.getSavePath()).length())); file.setRemoteId(mCurrentDownload.getFile().getRemoteId()); mStorageManager.saveFile(file); FileDataStorageManager.triggerMediaScan(file.getStoragePath()); mStorageManager.saveConflict(file, null); }

Target:
private void saveDownloadedFile() { OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId()); long syncDate = System.currentTimeMillis(); file.setLastSyncDateForProperties(syncDate); file.setLastSyncDateForData(syncDate); file.setNeedsUpdateThumbnail(true); file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp()); file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp()); file.setEtag(mCurrentDownload.getEtag()); file.setMimetype(mCurrentDownload.getMimeType()); file.setStoragePath(mCurrentDownload.getSavePath()); file.setFileLength((new File(mCurrentDownload.getSavePath()).length())); file.setRemoteId(mCurrentDownload.getFile().getRemoteId()); mStorageManager.saveFile(file); mStorageManager.triggerMediaScan(file.getStoragePath()); mStorageManager.saveConflict(file, null); }
Source:
public GuiTab addTo(Class<? extends GuiContainer> parentContainer) { if (parentContainer == GuiContainerCreative.class) { throw new IllegalArgumentException("Cannot add tabs to creative inventory. Use CreativeTabs instead"); } else if (parentContainer == InventoryEffectRenderer.class) { throw new IllegalArgumentException(name + " tab has a parent that is ambiguous with the creative inventory. cannot proceed with registry."); } this.parentContainer = parentContainer; tabRegistry.put(parentContainer, this); return this; }

Target:
public GuiTab addTo(Class<? extends GuiContainer> parentContainer) { if (parentContainer == GuiContainerCreative.class) { throw new IllegalArgumentException("Cannot add tabs to creative inventory. Use CreativeTabs instead"); } else if (parentContainer.isAssignableFrom(InventoryEffectRenderer.class)) { throw new IllegalArgumentException(name + " tab has a parent that is ambiguous with the creative inventory. cannot proceed with registry."); } this.parentContainer = parentContainer; tabRegistry.put(parentContainer, this); return this; }
Source:
public String evaluate(Run<?, ?> run, FilePath workspace, TaskListener listener, String macroName) { AbstractTestResultAction<?> testResult = run.getAction(AbstractTestResultAction.class); SummarizedTestResult result = prepareSummarizedTestResult(testResult); switch (outputFormat) { case "yaml": try { return result.toYamlString(); } catch (Exception e) { } return "Bad format"; default: return result.toString(); } }

Target:
public String evaluate(Run<?, ?> run, FilePath workspace, TaskListener listener, String macroName) throws MacroEvaluationException { AbstractTestResultAction<?> testResult = run.getAction(AbstractTestResultAction.class); SummarizedTestResult result = prepareSummarizedTestResult(testResult); switch (outputFormat) { case "yaml": try { return result.toYamlString(); } catch (JsonProcessingException e) { throw new MacroEvaluationException("Unable to serialize to yaml", MACRO_NAME, e.getCause()); } catch (Exception e) { throw e; } default: return result.toString(); } }
Source:
public void failedWithBearerTokenFromConfiguration() throws Exception { SaslClient saslClient = createSaslClientFromConfiguration(URI.create("protocol://test3.org")); assertNotNull("OAuth2SaslClient is null", saslClient); SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER) .setServerName("resourceserver.comn") .setProtocol("imap") .addRealm("oauth-realm", createSecurityRealmMock()) .setDefaultRealmName("oauth-realm") .build(); byte[] message = AbstractSaslParticipant.NO_BYTES; message = saslClient.evaluateChallenge(message); try { message = saslServer.evaluateResponse(message); } catch (SaslException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); IllegalArgumentException cause = (IllegalArgumentException) e.getCause(); assertTrue(cause.getMessage().contains("ELY01114")); } }

Target:
public void failedWithBearerTokenFromConfiguration() throws Exception { SaslClient saslClient = createSaslClientFromConfiguration(URI.create("protocol://test3.org")); assertNotNull("OAuth2SaslClient is null", saslClient); SaslServer saslServer = new SaslServerBuilder(OAuth2SaslServerFactory.class, SaslMechanismInformation.Names.OAUTHBEARER) .setServerName("resourceserver.comn") .setProtocol("imap") .addRealm("oauth-realm", createSecurityRealmMock()) .setDefaultRealmName("oauth-realm") .build(); byte[] message = AbstractSaslParticipant.NO_BYTES; message = saslClient.evaluateChallenge(message); message = saslServer.evaluateResponse(message); assertFalse(saslServer.isComplete()); assertEquals("{\"status\":\"invalid_token\"}", ByteIterator.ofBytes(message).base64Decode().asUtf8String().drainToString()); }
Source:
public IdentityProvider buildAndCreate(Client client) { IdentityProvider createdIdp = client.createIdentityProvider(client.instantiate(IdentityProvider.class) .setType(IdentityProvider.TypeEnum.FACEBOOK) .setName(name) .setProtocol(client.instantiate(Protocol.class) .setType(Protocol.TypeEnum.OAUTH2) .setScopes(scopes) .setCredentials(client.instantiate(IdentityProviderCredentials.class) .setClient(client.instantiate(IdentityProviderCredentialsClient.class) .setClientId(clientId) .setClientSecret(clientSecret)))) .setPolicy(client.instantiate(IdentityProviderPolicy.class) .setProvisioning(client.instantiate(Provisioning.class) .setAction(Provisioning.ActionEnum.AUTO) .setProfileMaster(isProfileMaster) .setGroups(client.instantiate(ProvisioningGroups.class) .setAction(ProvisioningGroups.ActionEnum.NONE)) .setConditions(client.instantiate(ProvisioningConditions.class) .setDeprovisioned(client.instantiate(ProvisioningDeprovisionedCondition.class) .setAction(ProvisioningDeprovisionedCondition.ActionEnum.NONE)) .setSuspended(client.instantiate(ProvisioningSuspendedCondition.class) .setAction(ProvisioningSuspendedCondition.ActionEnum.NONE)))) .setAccountLink(client.instantiate(PolicyAccountLink.class) .setFilter(null) .setAction(PolicyAccountLink.ActionEnum.AUTO)) .setSubject(client.instantiate(PolicySubject.class) .setUserNameTemplate(client.instantiate(PolicyUserNameTemplate.class) .setTemplate(userNameTemplate)) .setMatchType(policySubjectMatchType)) .setMaxClockSkew(maxClockSkew))); return createdIdp; }

Target:
public IdentityProvider buildAndCreate(Client client) { IdentityProvider createdIdp = client.createIdentityProvider(client.instantiate(IdentityProvider.class) .setType(IdentityProvider.TypeEnum.FACEBOOK) .setName(name) .setProtocol(client.instantiate(Protocol.class) .setType(Protocol.TypeEnum.OAUTH2) .setScopes(scopes) .setCredentials(client.instantiate(IdentityProviderCredentials.class) .setClient(client.instantiate(IdentityProviderCredentialsClient.class) .setClientId(clientId) .setClientSecret(clientSecret)))) .setPolicy(client.instantiate(IdentityProviderPolicy.class) .setProvisioning(client.instantiate(Provisioning.class) .setAction(Provisioning.ActionEnum.AUTO) .setProfileMaster(isProfileMaster) .setGroups(client.instantiate(ProvisioningGroups.class) .setAction(ProvisioningGroups.ActionEnum.NONE)) .setConditions(client.instantiate(ProvisioningConditions.class) .setDeprovisioned(client.instantiate(ProvisioningDeprovisionedCondition.class) .setAction(ProvisioningDeprovisionedCondition.ActionEnum.NONE)) .setSuspended(client.instantiate(ProvisioningSuspendedCondition.class) .setAction(ProvisioningSuspendedCondition.ActionEnum.NONE)))) .setAccountLink(client.instantiate(PolicyAccountLink.class) .setFilter(null) .setAction(PolicyAccountLink.ActionEnum.AUTO)) .setSubject(client.instantiate(PolicySubject.class) .setUserNameTemplate(client.instantiate(PolicyUserNameTemplate.class) .setTemplate(userName)) .setMatchType(matchType)) .setMaxClockSkew(maxClockSkew))); return createdIdp; }
Source:
public Map<String, ColumnMetadata> extractData(ResultSet rs) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); Map<String, ColumnMetadata> metadataMap = new LinkedHashMap<>(metadata.getColumnCount(), 1.0f); for (int col = 1; col <= metadata.getColumnCount(); col++) { String columnName = metadata.getColumnName(col); String typeName = metadata.getColumnTypeName(col); int size = metadata.getColumnDisplaySize(col); metadataMap.put(columnName, new ColumnMetadata(columnName, resolveTypeAlias(typeName), size)); } return metadataMap; }

Target:
public Map<String, ColumnMetadata> extractData(ResultSet rs) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); Map<String, ColumnMetadata> metadataMap = new LinkedHashMap<>(metadata.getColumnCount() * 2); for (int col = 1; col <= metadata.getColumnCount(); col++) { String columnName = metadata.getColumnName(col); String typeName = metadata.getColumnTypeName(col); int size = metadata.getColumnDisplaySize(col); metadataMap.put(columnName, new ColumnMetadata(columnName, resolveTypeAlias(typeName), size)); } return metadataMap; }
Source:
protected List<String> getOutputTables() throws FalconException { List<String> tables = new ArrayList<String>(); try { JSONArray outputs = message.getJSONObject(ADFJsonConstants.ADF_REQUEST_ACTIVITY) .getJSONArray(ADFJsonConstants.ADF_REQUEST_OUTPUTS); for (int i = 0; i < outputs.length(); i++) { tables.add(outputs.getJSONObject(i).getString(ADFJsonConstants.ADF_REQUEST_NAME)); } } catch (JSONException e) { throw new FalconException("Error while parsing output tables in ADF request."); } return tables; }

Target:
protected List<String> getOutputTables() throws FalconException { List<String> tables = new ArrayList<String>(); try { JSONArray outputs = message.getJSONObject(ADFJsonConstants.ADF_REQUEST_ACTIVITY) .getJSONArray(ADFJsonConstants.ADF_REQUEST_OUTPUTS); for (int i = 0; i < outputs.length(); i++) { tables.add(outputs.getJSONObject(i).getString(ADFJsonConstants.ADF_REQUEST_NAME)); } } catch (JSONException e) { throw new FalconException("Error while reading output table names in ADF request."); } return tables; }
Source:
public void removeVariable() { TestSuiteModel testSuite = new TestSuiteModel(); String variable_indentifier = "variable_indentifier"; String variable_content = "variable_content"; String variable_description = "variable_description"; testSuite.setVariable(variable_indentifier, variable_content, variable_description); assertEquals(1, testSuite.getVariables().size()); assertEquals(variable_indentifier, testSuite.getVariables().get(0).getName()); assertEquals(variable_content, testSuite.getVariables().get(0).getContent()); assertEquals(variable_description, testSuite.getVariables().get(0).getDescription()); testSuite.removeVariable(variable_indentifier); assertNull(testSuite.getVariable(variable_indentifier)); testSuite.setVariable(variable_indentifier, variable_content, variable_description); assertEquals(1, testSuite.getVariables().size()); assertEquals(variable_indentifier, testSuite.getVariables().get(0).getName()); assertEquals(variable_content, testSuite.getVariables().get(0).getContent()); assertEquals(variable_description, testSuite.getVariables().get(0).getDescription()); testSuite.removeVariable(testSuite.getVariable(variable_indentifier)); assertNull(testSuite.getVariable(variable_indentifier)); }

Target:
public void removeVariable() { TestSuiteModel testSuite = new TestSuiteModel(); for (int index = 0; index < elements; index++) { testSuite.setVariable(variableIndentifier[index], variableContent[index], variableDescription[index]); } for (int index = 0; index < elements; index++) { testSuite.removeVariable(variableIndentifier[index]); } }
Source:
public boolean isForwarded(String name) { final HaxeMacroClass forwardMeta = getMeta(FORWARD); if (forwardMeta != null) { HaxeCustomMeta customMeta = forwardMeta.getCustomMeta(); final HaxeExpressionList expressionList = customMeta.getExpressionList(); if (expressionList == null) return true; for (HaxeExpression expression : expressionList.getExpressionList()) { if (expression.getText().equals(name)) return true; } } return false; }

Target:
public boolean isForwarded(String name) { final HaxeMacroClass forwardMeta = getMeta(FORWARD); if (forwardMeta != null) { final HaxeCustomMeta customMeta = forwardMeta.getCustomMeta(); final HaxeExpressionList expressionList = customMeta.getExpressionList(); if (expressionList == null) return true; final List<HaxeExpression> list = expressionList.getExpressionList(); if (list.isEmpty()) return true; for (HaxeExpression expression : list) { if (expression.getText().equals(name)) return true; } } return false; }
Source:
private void gainLeadershipWithRetry() { if (!gainLeadershipBlocking()) { try { Thread.sleep(GAIN_LEADERSHIP_BACKOFF_MILLIS); } catch (InterruptedException e) { log.warn("gain leadership backoff interrupted"); } gainLeadershipWithRetry(); } }

Target:
private void gainLeadershipWithRetry() { while (!gainLeadershipBlocking()) { try { Thread.sleep(GAIN_LEADERSHIP_BACKOFF.toMillis()); } catch (InterruptedException e) { log.warn("gain leadership backoff interrupted"); } } }
Source:
private static String getType(String metric, AggregatorFactory[] aggs, int i) { if(aggs[i].getName().equals(metric)) { return aggs[i].getTypeName(); } for(AggregatorFactory agg : aggs) { if(agg.getName().equals(metric)) { return agg.getTypeName(); } } return null; }

Target:
private static String getType(String metric, AggregatorFactory[] aggs, int i) { if (aggs[i].getName().equals(metric)) { return aggs[i].getTypeName(); } log.warn("Aggs disordered, fall backs to loop."); for (AggregatorFactory agg : aggs) { if (agg.getName().equals(metric)) { return agg.getTypeName(); } } return null; }
Source:
public void getBulkObjectWithSyncNoUpdate() throws Exception { final String bucketName = "test_get_bulk_object_with_sync_no_update"; try { Util.createBucket(client, bucketName); Util.loadBookTestData(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "get_bulk", "-b", bucketName, "-d", Util.DOWNLOAD_BASE_NAME, "--sync"}); CommandResponse response = Util.command(client, args); assertThat(response.getMessage(), is("SUCCESS: Synced all the objects from " + bucketName + " to ." + File.separator + "." + File.separator + "output")); final File destFolder = new File(Util.DOWNLOAD_BASE_NAME); DateTime now = new DateTime(); for( final File currentFile : destFolder.listFiles()) { currentFile.setLastModified(now.getMillis()); } response = Util.command(client, args); assertThat(response.getMessage(), is("SUCCESS: All files are up to date")); } finally { Util.deleteBucket(client, bucketName); Util.deleteLocalFiles(); } }

Target:
public void getBulkObjectWithSyncNoUpdate() throws Exception { final String bucketName = "test_get_bulk_object_with_sync_no_update"; try { Util.createBucket(client, bucketName); Util.loadBookTestData(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "get_bulk", "-b", bucketName, "-d", Util.DOWNLOAD_BASE_NAME, "--sync"}); CommandResponse response = Util.command(client, args); assertThat(response.getMessage(), is("SUCCESS: Synced all the objects from " + bucketName + " to ." + File.separator + "." + File.separator + "output")); final File destFolder = new File(Util.DOWNLOAD_BASE_NAME); final DateTime now = new DateTime(); for( final File currentFile : destFolder.listFiles()) { currentFile.setLastModified(now.getMillis()); } response = Util.command(client, args); assertThat(response.getMessage(), is("SUCCESS: All files are up to date")); } finally { Util.deleteBucket(client, bucketName); Util.deleteLocalFiles(); } }
Source:
public BasicBSONObject call() throws Exception { if (!entity.getAttribute(SERVICE_UP)) { LOG.debug("No serverStatus data: Service not up"); return null; } String hostname = entity.getAttribute(SoftwareProcessEntity.HOSTNAME); Integer port = entity.getAttribute(PORT); MongoClient client = null; try { client = new MongoClient(hostname, port); } catch (UnknownHostException e) { LOG.warn("No serverStatus data: " + e.getMessage()); return null; } String dbName = Iterables.getFirst(client.getDatabaseNames(), "test"); DB db = client.getDB(dbName); CommandResult statusResult = db.command("serverStatus"); client.close(); if (!statusResult.ok()) { LOG.warn("No serverStatus data: " + statusResult.getErrorMessage()); return null; } else { return statusResult; } }

Target:
public BasicBSONObject call() throws Exception { if (!entity.getAttribute(SERVICE_UP)) { LOG.debug("No serverStatus data for {}: Service not up", entity); return null; } String hostname = entity.getAttribute(SoftwareProcessEntity.HOSTNAME); Integer port = entity.getAttribute(PORT); MongoClient client = null; try { client = new MongoClient(hostname, port); } catch (UnknownHostException e) { LOG.warn("No serverStatus data for {}: {}", entity, e.getMessage()); return null; } String dbName = Iterables.getFirst(client.getDatabaseNames(), "test"); try { DB db = client.getDB(dbName); CommandResult statusResult = db.command("serverStatus"); if (!statusResult.ok()) { LOG.warn("No serverStatus data for {}: {}", entity, statusResult.getErrorMessage()); return null; } else { return statusResult; } } finally { client.close(); } }
Source:
public void whenContextExistsInExlusivePIDCreateMultipleServicesUpdateWithDuplicate() throws IOException { String configDirectory = configBaseDirectory + SEP + "multiple_service_contexts_duplicates"; String servicesDirectory = "multiple_contexts"; initialize(null); String absoluteConfigDirectory = configDirectory + SEP + servicesDirectory; ConfigDispatcher cd = new ConfigDispatcher(bundleContext, configAdmin, Paths.get(absoluteConfigDirectory)); processConfigDirectory(absoluteConfigDirectory, cd); File srcDupFile = new File(configDirectory + SEP + "duplicate" + SEP + "service-ctx1duplicate.cfg"); cd.processConfigFile(srcDupFile); verifyValueOfConfigurationPropertyWithContext("service.pid#ctx1", "property1", "valueDup"); verifyValueOfConfigurationPropertyWithContext("service.pid#ctx2", "property1", "value2"); }

Target:
public void whenContextExistsInExlusivePIDCreateMultipleServicesUpdateWithDuplicate() throws IOException { String configDirectory = configBaseDirectory + SEP + "multiple_service_contexts_duplicates"; String servicesDirectory = "multiple_contexts"; initialize(null); cd.processConfigFile(new File(getAbsoluteConfigDirectory(configDirectory, servicesDirectory))); File srcDupFile = new File(configDirectory + SEP + "duplicate" + SEP + "service-ctx1duplicate.cfg"); cd.processConfigFile(srcDupFile); verifyValueOfConfigurationPropertyWithContext("service.pid#ctx1", "property1", "valueDup"); verifyValueOfConfigurationPropertyWithContext("service.pid#ctx2", "property1", "value2"); }