auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { HttpRequest request = (HttpRequest) msg; JsonArray result = Json.createReader(new StringReader(request.getContent().toString(StandardCharsets.UTF_8))) .readArray(); List<Position> positions = new LinkedList<>(); Log.debug(String.format("messages received msgs_count=%d", result.size())); for (int i = 0; i < result.size(); i++) { JsonObject message = result.getJsonObject(i); String ident = message.getString("ident"); if (ident == null) { continue; } DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ident); if (deviceSession == null) { continue; } Position position = new Position(); position.setDeviceId(deviceSession.getDeviceId()); decodePosition(message, position); positions.add(position); } sendResponse(channel, HttpResponseStatus.OK); return positions; }

Target:
protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { HttpRequest request = (HttpRequest) msg; JsonArray result = Json.createReader(new StringReader(request.getContent().toString(StandardCharsets.UTF_8))) .readArray(); List<Position> positions = new LinkedList<>(); for (int i = 0; i < result.size(); i++) { JsonObject message = result.getJsonObject(i); JsonString ident = message.getJsonString("ident"); if (ident == null) { continue; } DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ident.getString()); if (deviceSession == null) { continue; } Position position = new Position(); position.setDeviceId(deviceSession.getDeviceId()); decodePosition(message, position); positions.add(position); } sendResponse(channel, HttpResponseStatus.OK); return positions; }
Source:
public void onAdapterItemSelected(int position) { if (mIsSelectOneItem) { Intent intent = new Intent(); int localId = mGridAdapter.getLocalMediaIdAtPosition(position); ArrayList<Long> remoteMediaIds = new ArrayList<>(); remoteMediaIds.add(mMediaStore.getMediaWithLocalId(localId).getMediaId()); intent.putExtra(RESULT_IDS, ListUtils.toLongArray(remoteMediaIds)); setResult(RESULT_OK, intent); finish(); } }

Target:
public void onAdapterItemSelected(int position) { if (mIsSelectOneItem) { Intent intent = new Intent(); int localId = mGridAdapter.getLocalMediaIdAtPosition(position); ArrayList<Long> remoteMediaIds = new ArrayList<>(); MediaModel media = mMediaStore.getMediaWithLocalId(localId); if (media != null) { remoteMediaIds.add(media.getMediaId()); intent.putExtra(RESULT_IDS, ListUtils.toLongArray(remoteMediaIds)); setResult(RESULT_OK, intent); finish(); } } }
Source:
public void testLockHeldByThread() throws Exception { lockManager.lock("k", "aThread", 0, TimeUnit.MILLISECONDS).lock(); try { lockManager.lock("k", new DldGlobalTransaction(), 1000, TimeUnit.MILLISECONDS).lock(); fail("TimeoutException expected!"); } catch (TimeoutException e) { } AssertJUnit.assertTrue(lockManager.getOverlapWithNotDeadlockAwareLockOwners() > 0); }

Target:
public void testLockHeldByThread() throws Exception { lockManager.lock("k", "aThread", 0, TimeUnit.MILLISECONDS).lock(); try { LockPromise promise = lockManager.lock("k", new DldGlobalTransaction(), 1000, TimeUnit.MILLISECONDS); lockManager.run(); promise.lock(); fail("TimeoutException expected!"); } catch (TimeoutException e) { } AssertJUnit.assertEquals(1, lockManager.getOverlapWithNotDeadlockAwareLockOwners()); }
Source:
private <E extends Entity> void updatePropertyData( Map<Long,Map<String,Object>> state, WritableFulltext index ) throws IOException { for ( Map.Entry<Long,Map<String,Object>> stateEntry : state.entrySet() ) { Set<String> indexedProperties = index.properties(); if ( !Collections.disjoint( indexedProperties, stateEntry.getValue().keySet() ) ) { long entityId = stateEntry.getKey(); Map<String,Object> allProperties = stateEntry.getValue().entrySet().stream().filter( entry -> indexedProperties.contains( entry.getKey() ) ).collect( Collectors.toMap( entry -> entry.getKey(), entry -> entry.getValue() ) ); if ( !allProperties.isEmpty() ) { Document document = LuceneFulltextDocumentStructure.documentRepresentingProperties( entityId, allProperties ); index.getIndexWriter().updateDocument( LuceneFulltextDocumentStructure.newTermForChangeOrRemove( entityId ), document ); } } } }

Target:
private <E extends Entity> void updatePropertyData( Map<Long,Map<String,Object>> state, WritableFulltext index ) throws IOException { for ( Map.Entry<Long,Map<String,Object>> stateEntry : state.entrySet() ) { Set<String> indexedProperties = index.properties(); if ( !Collections.disjoint( indexedProperties, stateEntry.getValue().keySet() ) ) { long entityId = stateEntry.getKey(); Map<String,Object> allProperties = stateEntry.getValue().entrySet().stream().filter( entry -> indexedProperties.contains( entry.getKey() ) ).collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue ) ); if ( !allProperties.isEmpty() ) { Document document = LuceneFulltextDocumentStructure.documentRepresentingProperties( entityId, allProperties ); index.getIndexWriter().updateDocument( LuceneFulltextDocumentStructure.newTermForChangeOrRemove( entityId ), document ); } } } }
Source:
public static String nameForItemType(Context context, ITEM_TYPE itemType) { String name = ""; switch (itemType) { case POST: name = context.getString(R.string.menu_item_type_post); break; case PAGE: name = context.getString(R.string.menu_item_type_page); break; case CATEGORY: name = context.getString(R.string.menu_item_type_category); break; case TAG: name = context.getString(R.string.menu_item_type_tag); break; case LINK: name = context.getString(R.string.menu_item_type_link); break; case JETPACK_TESTIMONIAL: name = context.getString(R.string.menu_item_type_testimonial); break; case JETPACK_PORTFOLIO: name = context.getString(R.string.menu_item_type_portfolio); break; case JETPACK_COMIC: name = context.getString(R.string.menu_item_type_comic); break; case NULL: name = ""; break; case CUSTOM: name = ""; break; } return name; }

Target:
public static String nameForItemType(Context context, ITEM_TYPE itemType) { String name = ""; switch (itemType) { case POST: name = context.getString(R.string.menu_item_type_post); break; case PAGE: name = context.getString(R.string.menu_item_type_page); break; case CATEGORY: name = context.getString(R.string.menu_item_type_category); break; case TAG: name = context.getString(R.string.menu_item_type_tag); break; case LINK: name = context.getString(R.string.menu_item_type_link); break; case JETPACK_TESTIMONIAL: name = context.getString(R.string.menu_item_type_testimonial); break; case JETPACK_PORTFOLIO: name = context.getString(R.string.menu_item_type_portfolio); break; case JETPACK_COMIC: name = context.getString(R.string.menu_item_type_comic); break; default: break; } return name; }
Source:
private static void setErrorResponse(HttpMessage msg, String responseStatus, Exception cause, String errorType) throws HttpMalformedHeaderException { StringBuilder strBuilder = new StringBuilder(); if (cause instanceof SSLException) { strBuilder.append("An exception occurred while attempting to connect to: "); strBuilder.append(msg.getRequestHeader().getURI().toString()).append('\n'); strBuilder.append("The exception was: " + cause.getMessage()); strBuilder.append('\n').append('\n'); strBuilder.append(Constant.messages.getString("network.sslconnector.handshake.error.help", Constant.messages.getString("network.sslconnector.handshake.error.help.url"))); LOGGER.warn(strBuilder.toString()); if (LOGGER.isDebugEnabled()) { LOGGER.debug(cause, cause); strBuilder.append("\n\nStack Trace:\n"); for (String stackTraceFrame : ExceptionUtils.getRootCauseStackTrace(cause)) { strBuilder.append(stackTraceFrame).append('\n'); } } } else { strBuilder.append(errorType) .append(" [") .append(cause.getClass().getName()) .append("]: ") .append(cause.getLocalizedMessage()) .append("\n\nStack Trace:\n"); for (String stackTraceFrame : ExceptionUtils.getRootCauseStackTrace(cause)) { strBuilder.append(stackTraceFrame).append('\n'); } } setErrorResponse(msg, responseStatus, strBuilder.toString()); }

Target:
private static void setErrorResponse(HttpMessage msg, String responseStatus, Exception cause, String errorType) throws HttpMalformedHeaderException { StringBuilder strBuilder = new StringBuilder(); if (cause instanceof SSLException) { strBuilder.append(Constant.messages.getString("network.ssl.error.connect")); strBuilder.append(msg.getRequestHeader().getURI().toString()).append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.exception")).append(cause.getMessage()) .append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.exception.rootcause")) .append(ExceptionUtils.getRootCauseMessage(cause)).append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.help", Constant.messages.getString("network.ssl.error.help.url"))); log.warn(strBuilder.toString()); if (log.isDebugEnabled()) { log.debug(cause, cause); strBuilder.append("\n\nStack Trace:\n"); for (String stackTraceFrame : ExceptionUtils.getRootCauseStackTrace(cause)) { strBuilder.append(stackTraceFrame).append('\n'); } } } else { strBuilder.append(errorType) .append(" [") .append(cause.getClass().getName()) .append("]: ") .append(cause.getLocalizedMessage()) .append("\n\nStack Trace:\n"); for (String stackTraceFrame : ExceptionUtils.getRootCauseStackTrace(cause)) { strBuilder.append(stackTraceFrame).append('\n'); } } setErrorResponse(msg, responseStatus, strBuilder.toString()); }
Source:
public void setDiskSpaceThreshold(float diskSpaceThreshold, float diskUsageWarnThreshold) { validateThreshold(diskSpaceThreshold, diskUsageWarnThreshold); this.diskUsageThreshold = diskSpaceThreshold; this.diskUsageWarnThreshold = diskUsageWarnThreshold; }

Target:
void setDiskSpaceThreshold(float diskSpaceThreshold, float diskUsageWarnThreshold) { validateThreshold(diskSpaceThreshold, diskUsageWarnThreshold); this.diskUsageThreshold = diskSpaceThreshold; this.diskUsageWarnThreshold = diskUsageWarnThreshold; }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveAuthServlet"); try { String redirectUrl; if (StringUtils.isEmpty(SSOUtils.getSsoSession(request).getClientId())) { redirectUrl = ssoContext.getEngineUrl(); } else { Credentials userCredentials = getUserCredentials(request); try { if (SSOUtils.isUserAuthenticated(request)) { log.debug("User is authenticated redirecting to {}", SSOConstants.INTERACTIVE_REDIRECT_TO_MODULE_URI); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_REDIRECT_TO_MODULE_URI; } else { redirectUrl = authenticateUser(request, response, userCredentials); } } catch (AuthenticationException ex) { if (userCredentials != null) { String profile = userCredentials.getProfile() == null ? "N/A" : userCredentials.getProfile(); log.error("Cannot authenticate user '{}@{}': {}", userCredentials.getUsername(), profile, ex.getMessage()); log.debug("Cannot authenticate user", ex); SSOUtils.getSsoSession(request).setLoginMessage(ex.getMessage()); } log.debug("Redirecting to LoginPage"); SSOUtils.getSsoSession(request).setReauthenticate(false); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_LOGIN_FORM_URI; } } if (redirectUrl != null) { response.sendRedirect(redirectUrl); } } catch (Exception ex) { SSOUtils.redirectToErrorPage(request, response, ex); } }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveAuthServlet"); try { String redirectUrl; if (StringUtils.isEmpty(SSOUtils.getSsoSession(request).getClientId())) { redirectUrl = ssoContext.getEngineUrl(); } else { Credentials userCredentials = getUserCredentials(request); try { if (SSOUtils.isUserAuthenticated(request)) { log.debug("User is authenticated redirecting to {}", SSOConstants.INTERACTIVE_REDIRECT_TO_MODULE_URI); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_REDIRECT_TO_MODULE_URI; } else { redirectUrl = authenticateUser(request, response, userCredentials); } } catch (AuthenticationException ex) { if (userCredentials != null) { String profile = userCredentials.getProfile() == null ? "N/A" : userCredentials.getProfile(); log.error("Cannot authenticate user '{}@{}': {}", userCredentials.getUsername(), profile, ex.getMessage()); log.debug("Exception", ex); SSOUtils.getSsoSession(request).setLoginMessage(ex.getMessage()); } log.debug("Redirecting to LoginPage"); SSOUtils.getSsoSession(request).setReauthenticate(false); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_LOGIN_FORM_URI; } } if (redirectUrl != null) { response.sendRedirect(redirectUrl); } } catch (Exception ex) { SSOUtils.redirectToErrorPage(request, response, ex); } }
Source:
public Object createNew(Object arg) { try { return createNew0(arg); } catch (Exception e) { throw rethrow(e); } }

Target:
public Object createNew(Object arg) { try { return createNew0(arg); } catch (Exception e) { throw new GuardianException(transferThrowable(e)); } }
Source:
public UserProfile() { this.userPortalVmLoginAutomatically = true; this.sshPublicKey = ""; }

Target:
public UserProfile() { userPortalVmLoginAutomatically = true; sshPublicKey = ""; }
Source:
private void initDottedLineSourceAndLayer(@NonNull Style loadedMapStyle) { loadedMapStyle.addSource(new GeoJsonSource(SOURCE_ID)); loadedMapStyle.addLayerBelow( new LineLayer( "DIRECTIONS_LAYER_ID", SOURCE_ID).withProperties( lineWidth(4.5f), lineColor(Color.BLACK), lineTranslate(new Float[] {0f, 4f}), lineDasharray(new Float[] {1.2f, 1.2f}) ), "road-label-small"); }

Target:
private void initDottedLineSourceAndLayer(@NonNull Style loadedMapStyle) { loadedMapStyle.addSource(new GeoJsonSource(SOURCE_ID)); loadedMapStyle.addLayerBelow( new LineLayer( DIRECTIONS_LAYER_ID, SOURCE_ID).withProperties( lineWidth(4.5f), lineColor(Color.BLACK), lineTranslate(new Float[] {0f, 4f}), lineDasharray(new Float[] {1.2f, 1.2f}) ), LAYER_BELOW_ID); }
Source:
public void saveObservation(Observation observation, long encounterID) { createObservableIO(() -> { observation.setEncounterID(encounterID); new ObservationTable().insert(observation); return null; }); }

Target:
public Observable<Long> saveObservation(Observation observation, long encounterID) { return createObservableIO(() -> { observation.setEncounterID(encounterID); return new ObservationTable().insert(observation); }); }
Source:
public int getCurrentPage() { StaplerRequest req = Stapler.getCurrentRequest(); if(req == null) return 1; int page = req.getParameter("page") == null ? 1 : Integer.parseInt(req.getParameter("page").toString()); page = Math.max(page, 1); int component = req.getParameter("component") == null ? 1 : Integer.parseInt(req.getParameter("component").toString()); if(component != componentNumber) { page = 1; } return page; }

Target:
public int getCurrentPage() { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { return 1; } int page = req.getParameter("page") == null ? 1 : Integer.parseInt(req.getParameter("page").toString()); page = Math.max(page, 1); int component = req.getParameter("component") == null ? 1 : Integer.parseInt(req.getParameter("component").toString()); if (component != componentNumber) { page = 1; } return page; }
Source:
public void testTheNormalStuff() { assertThat( OrderMapper.INSTANCE.mapNormal( null ) ).isNull(); assertThat( OrderMapper.INSTANCE.mapNormal( "SPECIAL" ) ).isEqualTo( OrderType.EXTRA ); assertThat( OrderMapper.INSTANCE.mapNormal( "DEFAULT" ) ).isEqualTo( OrderType.STANDARD ); assertThat( OrderMapper.INSTANCE.mapNormal( "RETAIL" ) ).isEqualTo( OrderType.RETAIL ); assertThat( OrderMapper.INSTANCE.mapNormal( "B2B" ) ).isEqualTo( OrderType.B2B ); assertThat( OrderMapper.INSTANCE.mapNormal( "RETAIL" ) ).isEqualTo( OrderType.RETAIL ); assertThat( OrderMapper.INSTANCE.mapNormal( "STANDARD" ) ).isEqualTo( OrderType.STANDARD ); assertThat( OrderMapper.INSTANCE.mapNormal( "NORMAL" ) ).isEqualTo( OrderType.NORMAL ); }

Target:
public void testTheNormalStuff() { assertThat( OrderMapper.INSTANCE.mapNormal( null ) ).isNull(); assertThat( OrderMapper.INSTANCE.mapNormal( "SPECIAL" ) ).isEqualTo( OrderType.EXTRA ); assertThat( OrderMapper.INSTANCE.mapNormal( "DEFAULT" ) ).isEqualTo( OrderType.STANDARD ); assertThat( OrderMapper.INSTANCE.mapNormal( "RETAIL" ) ).isEqualTo( OrderType.RETAIL ); assertThat( OrderMapper.INSTANCE.mapNormal( "B2B" ) ).isEqualTo( OrderType.B2B ); assertThat( OrderMapper.INSTANCE.mapNormal( "STANDARD" ) ).isEqualTo( OrderType.STANDARD ); assertThat( OrderMapper.INSTANCE.mapNormal( "NORMAL" ) ).isEqualTo( OrderType.NORMAL ); assertThat( OrderMapper.INSTANCE.mapNormal( "blah" ) ).isEqualTo( OrderType.RETAIL ); }
Source:
public void setError(@NonNull Throwable e) { errorTextView.setText(ThrowableUtil.getErrorString(getContext(), e)); messageTextView.setText(ThrowableUtil.getErrorDetailString(getContext(), e)); }

Target:
public void setError(@NonNull Throwable e) { ThrowableUtil.AppError error = ThrowableUtil.getAppError(getContext(), e); errorTextView.setText(error.getError()); messageTextView.setText(error.getDetail()); }
Source:
public void testAuthenticationSupport() { try ( CassandraContainer cassandraContainer = new CassandraContainer<>() .withAuthentication() .withConfigurationOverride("cassandra-authentication-test-configuration") ) { cassandraContainer.start(); ResultSet resultSet = performQuery(cassandraContainer.getCluster(), "SELECT release_version FROM system.local"); assertTrue("Query was not applied", resultSet.wasApplied()); } }

Target:
public void testAuthenticationSupport() { try ( CassandraContainer cassandraContainer = new CassandraContainer<>() .withConfigurationOverride("cassandra-authentication-test-configuration") ) { cassandraContainer.start(); ResultSet resultSet = performQuery(cassandraContainer.getCluster(), "SELECT release_version FROM system.local"); assertTrue("Query was not applied", resultSet.wasApplied()); } }
Source:
public void onMinecartPass(EntityMinecart cart) { if (powered && cart.canBeRidden() && cart.riddenByEntity != null) { double x = getPos().getX(); double z = getPos().getZ(); double offset = 1.5; IBlockState state = getWorld().getBlockState(getPos()); EnumRailDirection dir = state.getValue(((BlockRailBase) state.getBlock()).getShapeProperty()); if (dir == EnumRailDirection.NORTH_SOUTH) if (mirrored) x += offset; else x -= offset; else if (mirrored) z += offset; else z -= offset; CartUtils.dismount(cart, x + 0.5, getPos().getY() + 1, z + 0.5); cart.getEntityData().setInteger("MountPrevention", TIME_TILL_NEXT_MOUNT); } }

Target:
public void onMinecartPass(EntityMinecart cart) { if (powered && cart.canBeRidden() && cart.riddenByEntity != null) { double x = getPos().getX(); double z = getPos().getZ(); double offset = 1.5; IBlockState state = getWorld().getBlockState(getPos()); EnumRailDirection dir = TrackTools.getTrackDirectionRaw(state); if (dir == EnumRailDirection.NORTH_SOUTH) if (mirrored) x += offset; else x -= offset; else if (mirrored) z += offset; else z -= offset; CartUtils.dismount(cart, x + 0.5, getPos().getY() + 1, z + 0.5); cart.getEntityData().setInteger("MountPrevention", TIME_TILL_NEXT_MOUNT); } }
Source:
private void checkIfPageIsSaved() { if (getTitle() != null) { getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, savedPageCheckCallbacks); } }

Target:
private void checkIfPageIsSaved() { if (getActivity() != null && getTitle() != null) { getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, savedPageCheckCallbacks); } }
Source:
private boolean checkAndEstablishConnectionWithNewAM() { boolean response = false; int attempt = 1; while (attempt <= RETRY_COUNT) { String newCoordinatorUrl = SERDE.fromBytes(coordinatorStreamStore.get(CoordinationConstants.YARN_COORDINATOR_URL)); try { if (coordinatorUrl.equals(newCoordinatorUrl)) { LOG.info("Attempt to discover new AM. Sleep for {}ms before next attempt.", attempt, sleepDurationForReconnectWithAM); Thread.sleep(sleepDurationForReconnectWithAM); } else { LOG.info("Found new AM: {}. Establishing heartbeat with the new AM.", newCoordinatorUrl); coordinatorUrl = newCoordinatorUrl; containerHeartbeatClient = getContainerHeartbeatClient(); response = containerHeartbeatClient.requestHeartbeat().isAlive(); LOG.info("Received heartbeat response: from new AM: {}", response, this.coordinatorUrl); break; } } catch (InterruptedException e) { LOG.warn("Interrupted during sleep."); Thread.currentThread().interrupt(); } attempt++; } return response; }

Target:
private boolean checkAndEstablishConnectionWithNewAM() { boolean response = false; int attempt = 1; while (attempt <= retryCount) { String newCoordinatorUrl = SERDE.fromBytes(coordinatorStreamStore.get(CoordinationConstants.YARN_COORDINATOR_URL)); try { if (coordinatorUrl.equals(newCoordinatorUrl)) { LOG.info("Attempt to discover new AM. Sleep for {}ms before next attempt.", attempt, sleepDurationForReconnectWithAM); Thread.sleep(sleepDurationForReconnectWithAM); } else { LOG.info("Found new AM: {}. Establishing heartbeat with the new AM.", newCoordinatorUrl); coordinatorUrl = newCoordinatorUrl; containerHeartbeatClient = createContainerHeartbeatClient(coordinatorUrl, containerExecutionId); response = containerHeartbeatClient.requestHeartbeat().isAlive(); LOG.info("Received heartbeat response: from new AM: {}", response, this.coordinatorUrl); break; } } catch (InterruptedException e) { LOG.warn("Interrupted during sleep."); Thread.currentThread().interrupt(); } attempt++; } return response; }
Source:
protected boolean compareAndSetGlobalState(final int expVal, final int newVal, final Thread newThread, final boolean bargingProhibited) { try { return CU.outTx( retryTopologySafe(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try (IgniteInternalTx tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) { GridCacheLockState val = lockView.get(key); if (val == null) if (reCreate) { val = new GridCacheLockState(0, ctx.nodeId(), 0, failoverSafe, fair); lockView.put(key, val); } else throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name); final long newThreadID = newThread.getId(); LinkedList<UUID> nodes = val.getNodes(); if (!(bargingProhibited && hasPredecessor(nodes))) { if (val.get() == expVal || ctx.discovery().node(val.getId()) == null) { val.set(newVal); val.setId(thisNode); val.setThreadId(newThreadID); val.setSignals(null); if (val.isFair() && (nodes.isEmpty() || !bargingProhibited)) nodes.addFirst(thisNode); val.setNodes(nodes); val.setChanged(true); lockView.put(key, val); tx.commit(); return true; } } return false; } catch (Exception e) { if (interruptAll) { log.info("Node is stopped (or lock is broken in non-failover safe mode)," + " aborting transaction."); return true; } else { if (Thread.currentThread().isInterrupted()) { log.info("Thread is interrupted while attempting to acquire lock."); sync.release(0); return false; } U.error(log, "Failed to compare and set: " + this, e); } throw e; } } }), ctx ); } catch (IgniteCheckedException e) { throw U.convertException(e); } }

Target:
protected boolean compareAndSetGlobalState(final int expVal, final int newVal, final Thread newThread, final boolean bargingProhibited) { try { return CU.outTx( retryTopologySafe(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try (IgniteInternalTx tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) { GridCacheLockState val = getCacheLockState(); if (val == null) throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name); final long newThreadID = newThread.getId(); LinkedList<UUID> nodes = val.getNodes(); if (!(bargingProhibited && hasPredecessor(nodes))) { if (val.get() == expVal || ctx.discovery().node(val.getId()) == null) { val.set(newVal); val.setId(thisNode); val.setThreadId(newThreadID); val.setSignals(null); if (val.isFair() && (nodes.isEmpty() || !bargingProhibited)) nodes.addFirst(thisNode); val.setNodes(nodes); val.setChanged(true); lockView.put(key, val); tx.commit(); return true; } } return false; } catch (Exception e) { if (interruptAll) { log.info("Node is stopped (or lock is broken in non-failover safe mode)," + " aborting transaction."); return true; } else { if (Thread.currentThread().isInterrupted()) { log.info("Thread is interrupted while attempting to acquire lock."); sync.release(0); return false; } U.error(log, "Failed to compare and set: " + this, e); } throw e; } } }), ctx ); } catch (IgniteCheckedException e) { throw U.convertException(e); } }
Source:
ChainedDownsamplingIterator(final Iterator<SAMRecord> iterator, final double proportion, final int seed) { super(new ConstantMemoryDownsamplingIterator(iterator, Math.min(1, proportion + 0.01), seed), proportion, seed); final long discarded = ((ConstantMemoryDownsamplingIterator) getUnderlyingIterator()).getDiscardedCount(); for (long i=0; i<discarded; ++i) recordDiscardedRecord(null); }

Target:
ChainedDownsamplingIterator(final Iterator<SAMRecord> iterator, final double proportion, final int seed) { super(new ConstantMemoryDownsamplingIterator(iterator, adjustProportion(proportion), seed), proportion, seed); final long discarded = ((ConstantMemoryDownsamplingIterator) getUnderlyingIterator()).getDiscardedCount(); recordDiscardRecords(discarded); }
Source:
public void shouldAddPermissionForUsersWhenUsingChainExtension() throws OperationException { List<String> users = Arrays.asList("jchastain", "rdeniro", "dwashington"); users.forEach(user -> when(userManager.getUserModel(user)).thenReturn(new SimpleDocumentModel(user))); DocumentModel doc = session.getDocument(new PathRef("/src")); OperationContext ctx = new OperationContext(session); ctx.setInput(doc); Object object = automationService.run(ctx, "testAddPermissionToUsers"); assertThat(object, instanceOf(DocumentModel.class)); DocumentModel documentModel = (DocumentModel) object; ACL acl = documentModel.getACP().getACL("local"); assertNotNull("Local ACL cannot be null !", acl); assertThat("ACEs size must be the same then users size !", acl.getACEs(), arrayWithSize(users.size())); Map<String, ACE> mapAceByUser = Arrays.stream(acl.getACEs()) .collect(Collectors.toMap(ACE::getUsername, ace -> ace)); for (String user : users) { ACE ace = mapAceByUser.get(user); assertNotNull(String.format("User of %s must have a defined ACE", user), ace); assertThat(String.format("User of %s must have a Read permission on document %s", user, documentModel), SecurityConstants.READ, equalTo(ace.getPermission())); } }

Target:
public void shouldAddPermissionForUsersWhenUsingChainExtension() throws OperationException { List<String> users = Arrays.asList("jchastain", "rdeniro", "dwashington"); users.forEach(user -> when(userManager.getUserModel(user)).thenReturn(new SimpleDocumentModel(user))); DocumentModel doc = session.getDocument(new PathRef("/src")); OperationContext ctx = new OperationContext(session); ctx.setInput(doc); DocumentModel documentModel = (DocumentModel) automationService.run(ctx, "testAddPermissionToUsers"); ACP acp = documentModel.getACP(); assertNotNull(acp); ACL acl = acp.getACL("local"); assertNotNull(acl); Map<String, Object> params = Collections.singletonMap("permission", SecurityConstants.READ); Assert.assertTrue(acl.getACEs().length >= 3); for (String user : users) { assertExpectedPermissions(acl, params, user); } }
Source:
public static MBExpression create(JSONArray json) { String name; if (json.get(0) instanceof String) { name = (String) json.get(0); if (colors.contains(name)) { return new MBColor(json); } else if (decisions.contains(name)) { return new MBDecision(json); } else if (featureData.contains(name)) { return new MBFeatureData(json); } else if (heatMap.contains(name)) { return new MBHeatmap(json); } else if (lookUp.contains(name)) { return new MBLookup(json); } else if (math.contains(name)) { return new MBMath(json); } else if (ramps.contains(name)) { return new MBRampsScalesCurves(json); } else if (string.contains(name)) { return new MBString(json); } else if (types.contains(name)) { return new MBTypes(json); } else if (variableBindings.contains(name)) { return new MBVariableBinding(json); } else if (zoom.contains(name)) { return new MBZoom(json); } else { throw new MBFormatException("Expression \"" + name + "\" not supported."); } } throw new MBFormatException("Requires a string name of the expression at position 0"); }

Target:
public static MBExpression create(JSONArray json) { String name; if (json.get(0) instanceof String) { name = (String) json.get(0); if (colors.contains(name)) { return new MBColor(json); } else if (decisions.contains(name)) { return new MBDecision(json); } else if (featureData.contains(name)) { return new MBFeatureData(json); } else if (heatMap.contains(name)) { return new MBHeatmap(json); } else if (lookUp.contains(name)) { return new MBLookup(json); } else if (math.contains(name)) { return new MBMath(json); } else if (ramps.contains(name)) { return new MBRampsScalesCurves(json); } else if (string.contains(name)) { return new MBString(json); } else if (types.contains(name)) { return new MBTypes(json); } else if (variableBindings.contains(name)) { return new MBVariableBinding(json); } else if (zoom.contains(name)) { return new MBZoom(json); } else { throw new MBFormatException( "Data expression \"" + name + "\" invalid. It may be misspelled or not supported by this implementation:" + json); } } throw new MBFormatException("Requires a string name of the data expression at position 0"); }
Source:
static void quoteListenerAndHostAttributeKeys(Node objLit, AbstractCompiler compiler) { Preconditions.checkState(objLit.isObjectLit()); boolean changeMade = false; for (Node keyNode : objLit.children()) { if (keyNode.isComputedProp()) { continue; } if (!keyNode.getString().equals("listeners") && !keyNode.getString().equals("hostAttributes")) { continue; } for (Node keyToQuote : keyNode.getFirstChild().children()) { keyToQuote.setQuotedString(); changeMade = true; } } if (changeMade) { compiler.reportCodeChange(); } }

Target:
static void quoteListenerAndHostAttributeKeys(Node objLit, AbstractCompiler compiler) { Preconditions.checkState(objLit.isObjectLit()); for (Node keyNode : objLit.children()) { if (keyNode.isComputedProp()) { continue; } if (!keyNode.getString().equals("listeners") && !keyNode.getString().equals("hostAttributes")) { continue; } for (Node keyToQuote : keyNode.getFirstChild().children()) { keyToQuote.setQuotedString(); compiler.reportCodeChange(); } } }
Source:
public void unsetModelRepository(ModelRepository modelRepo) { modelRepo.removeModelRepositoryChangeListener(this); this.modelRepo = null; }

Target:
public void unsetModelRepository(ModelRepository modelRepo) { this.modelRepo = null; }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveChangePasswdServlet"); Credentials userCredentials = null; String redirectUrl; try { log.debug("User is not authenticated extracting credentials from request."); userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Unable to extract user credentials from request"); } if (!userCredentials.getNewCredentials().equals(userCredentials.getConfirmedNewCredentials())) { throw new AuthenticationException("The passwords don't match."); } redirectUrl = changeUserPasswd(request, userCredentials); } catch (AuthenticationException ex) { String msg = String.format("Change Password for user '%s' failed : %s", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.error(msg); log.debug("Exception", ex); SSOUtils.getSsoSession(request).setChangePasswdMessage(msg); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_CHANGE_PASSWD_FORM_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveChangePasswdServlet"); Credentials userCredentials = null; String redirectUrl; try { log.debug("User is not authenticated extracting credentials from request."); userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Unable to extract user credentials from request"); } if (!userCredentials.getNewCredentials().equals(userCredentials.getConfirmedNewCredentials())) { throw new AuthenticationException("The passwords don't match."); } redirectUrl = changeUserPasswd(request, userCredentials); } catch (Exception ex) { String msg = String.format("Change Password for user '%s' failed : %s", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.error(msg); log.debug("Exception", ex); SSOUtils.getSsoSession(request).setChangePasswdMessage(msg); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_CHANGE_PASSWD_FORM_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }
Source:
public Member getMemberByUserExtSources(PerunSession sess, Vo vo, List<UserExtSource> ueas) throws InternalErrorException, MemberNotExistsException { if (ueas == null) { throw new InternalErrorException("Given userExtSources are null."); } if (ueas.isEmpty()) { throw new InternalErrorException("Given userExtSources are empty."); } Set<Member> foundMembers = new HashSet<>(); for (UserExtSource ues: ueas) { try { foundMembers.add(getMembersManagerImpl().getMemberByUserExtSource(sess, vo, ues)); } catch (MemberNotExistsException e) { throw new MemberNotExistsException("Member with userExtSources " + ueas + " doesn't exists."); } } if (foundMembers.size() > 1) { throw new InternalErrorException("Given userExtSources do not belong to the same member."); } else { return (Member)foundMembers.toArray()[0]; } }

Target:
public Member getMemberByUserExtSources(PerunSession sess, Vo vo, List<UserExtSource> ueas) throws InternalErrorException, MemberNotExistsException { if (ueas == null) { throw new InternalErrorException("Given userExtSources are null."); } if (ueas.isEmpty()) { throw new InternalErrorException("Given userExtSources are empty."); } Set<Member> foundMembers = new HashSet<>(); for (UserExtSource ues: ueas) { try { foundMembers.add(getMembersManagerImpl().getMemberByUserExtSource(sess, vo, ues)); } catch (MemberNotExistsException e) { } } if (foundMembers.isEmpty()) { throw new MemberNotExistsException("Member with userExtSources " + ueas + " doesn't exists."); } if (foundMembers.size() > 1) { throw new InternalErrorException("Given userExtSources do not belong to the same member."); } else { return (Member)foundMembers.toArray()[0]; } }
Source:
public ErrorObjects build() { if (errors.isEmpty()) { throw new IllegalArgumentException("at least one error object"); } return container; }

Target:
public ErrorObjects build() { if (errors.isEmpty()) { throw new IllegalArgumentException("At least one error is required"); } validateCurrentError(); return new ErrorObjects(errors); }
Source:
public CompletableFuture<Void> putAllAsync(List<Entry<K, V>> records) { writeMetrics.numPutAlls.inc(); long startNs = System.nanoTime(); Preconditions.checkNotNull(rwTable, "Cannot write to a read-only table: " + rdTable); return rwTable.putAllAsync(records).handleAsync((result, e) -> { if (e != null) { throw new SamzaException("Failed to put records " + records, e); } else if (!isWriteAround) { Set<K> allKeys = new HashSet<>(); List<K> delKeys = new ArrayList<>(); List<Entry<K, V>> putRecords = new ArrayList<>(); records.forEach(r -> { allKeys.add(r.getKey()); if (r.getValue() != null) { putRecords.add(r); } else { delKeys.add(r.getKey()); } }); cache.deleteAll(delKeys); cache.putAll(putRecords); } writeMetrics.putAllNs.update(System.nanoTime() - startNs); return result; }); }

Target:
public CompletableFuture<Void> putAllAsync(List<Entry<K, V>> records) { writeMetrics.numPutAlls.inc(); long startNs = System.nanoTime(); Preconditions.checkNotNull(rwTable, "Cannot write to a read-only table: " + rdTable); return rwTable.putAllAsync(records).handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to put records " + records, e); } else if (!isWriteAround) { cache.putAll(records); } writeMetrics.putAllNs.update(System.nanoTime() - startNs); return result; }); }
Source:
private static void setCompressionProperties(Configuration config, HiveCompressionCodec compression) { boolean compressed = compression != HiveCompressionCodec.NONE; config.setBoolean(COMPRESSRESULT.varname, compressed); config.setBoolean("mapred.output.compress", compressed); config.setBoolean(FileOutputFormat.COMPRESS, compressed); config.set(HIVE_ORC_DEFAULT_COMPRESS.varname, compression.getOrcCompressionKind().name()); config.set(HIVE_ORC_COMPRESSION.varname, compression.getOrcCompressionKind().name()); config.set(OrcFile.OrcTableProperties.COMPRESSION.getPropName(), compression.getOrcCompressionKind().name()); if (compression.getCodec().isPresent()) { config.set("mapred.output.compression.codec", compression.getCodec().get().getName()); config.set(FileOutputFormat.COMPRESS_CODEC, compression.getCodec().get().getName()); } else { config.unset("mapred.output.compression.codec"); config.unset(FileOutputFormat.COMPRESS_CODEC); } compression.getParquetCompressionCodec().ifPresent(parquetCompressionCodec -> config.set(ParquetOutputFormat.COMPRESSION, parquetCompressionCodec.name())); config.set(FileOutputFormat.COMPRESS_TYPE, BLOCK.toString()); }

Target:
private static void setCompressionProperties(Configuration config, HiveCompressionCodec compression) { boolean compressed = compression != HiveCompressionCodec.NONE; config.setBoolean(COMPRESSRESULT.varname, compressed); config.setBoolean("mapred.output.compress", compressed); config.setBoolean(FileOutputFormat.COMPRESS, compressed); config.set(HIVE_ORC_DEFAULT_COMPRESS.varname, compression.getOrcCompressionKind().name()); config.set(HIVE_ORC_COMPRESSION.varname, compression.getOrcCompressionKind().name()); config.set(OrcFile.OrcTableProperties.COMPRESSION.getPropName(), compression.getOrcCompressionKind().name()); if (compression.getCodec().isPresent()) { config.set("mapred.output.compression.codec", compression.getCodec().get().getName()); config.set(FileOutputFormat.COMPRESS_CODEC, compression.getCodec().get().getName()); } else { config.unset("mapred.output.compression.codec"); config.unset(FileOutputFormat.COMPRESS_CODEC); } compression.getParquetCompressionCodec().ifPresent(codec -> config.set(ParquetOutputFormat.COMPRESSION, codec.name())); config.set(FileOutputFormat.COMPRESS_TYPE, BLOCK.toString()); }
Source:
public void onPause() { super.onPause(); if (getAllowStartStopFromHeadsetKey()) { unregisterHeadsetListener(); } unRegisterStartStopListener(); }

Target:
public void onPause() { super.onPause(); }
Source:
public SAMRecordIterator assertSorted(final SortOrder sortOrder) { throw new RuntimeException("assertSorted is not implemented."); }

Target:
public SAMRecordIterator assertSorted(final SortOrder sortOrder) { throw new UnsupportedOperationException("assertSorted is not implemented."); }
Source:
private PlaybackController setupPlaybackController() { return new PlaybackController(getActivity(), true) { @Override public ImageButton getPlayButton() { return butPlay; } @Override public boolean loadMediaInfo() { ExternalPlayerFragment fragment = ExternalPlayerFragment.this; if (fragment != null) { return fragment.loadMediaInfo(); } else { return false; } } }; }

Target:
private PlaybackController setupPlaybackController() { return new PlaybackController(getActivity(), true) { @Override public void onPositionObserverUpdate() { ExternalPlayerFragment.this.onPositionObserverUpdate(); } @Override public ImageButton getPlayButton() { return butPlay; } @Override public boolean loadMediaInfo() { ExternalPlayerFragment fragment = ExternalPlayerFragment.this; if (fragment != null) { return fragment.loadMediaInfo(); } else { return false; } } @Override public void onShutdownNotification() { playbackDone(); } @Override public void onPlaybackEnd() { playbackDone(); } }; }
Source:
public String getProvider() { return provider != null ? provider : ""; }

Target:
public String getProvider() { return provider; }
Source:
public void run() { UIOutputCallbackControllerServiceImpl uiOutputCallbackControllerServiceImpl = UIEventAdaptorServiceInternalValueHolder.getUIOutputCallbackRegisterServiceImpl(); CopyOnWriteArrayList<Session> sessions = uiOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId); if (sessions != null) { for (Session session : sessions) { synchronized (session) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "Cannot send to endpoint", e, log, tenantId); } } } } else if(!isLoggedDroppedMessage) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "No clients registered", log, tenantId); isLoggedDroppedMessage = true; } }

Target:
public void run() { UIOutputCallbackControllerServiceImpl uiOutputCallbackControllerServiceImpl = UIEventAdaptorServiceInternalValueHolder.getUIOutputCallbackRegisterServiceImpl(); CopyOnWriteArrayList<Session> sessions = uiOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId); if (sessions != null) { doLogDroppedMessage = true; for (Session session : sessions) { synchronized (session) { try { session.getBasicRemote().sendText(message); } catch (IOException e) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "Cannot send to endpoint", e, log, tenantId); } } } } else if(doLogDroppedMessage) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "No clients registered", log, tenantId); doLogDroppedMessage = false; } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { String url = String.format(Locale.US, "<LINK_0>", mRepoOwner, mRepoName, mRef, mPath); switch (item.getItemId()) { case R.id.browser: IntentUtils.launchBrowser(this, Uri.parse(url)); return true; case R.id.share: IntentUtils.share(this, getString(R.string.share_file_subject, FileUtils.getFileName(mPath), mRepoOwner + "/" + mRepoName), url); return true; case MENU_ITEM_HISTORY: startActivity(CommitHistoryActivity.makeIntent(this, mRepoOwner, mRepoName, mRef, mPath)); return true; case R.id.view_raw: boolean newState = !mViewRawText; item.setChecked(newState); mViewRawText = newState; onRefresh(); return true; } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(MenuItem item) { String url = String.format(Locale.US, "<LINK_0>", mRepoOwner, mRepoName, mRef, mPath); switch (item.getItemId()) { case R.id.browser: IntentUtils.launchBrowser(this, Uri.parse(url)); return true; case R.id.share: IntentUtils.share(this, getString(R.string.share_file_subject, FileUtils.getFileName(mPath), mRepoOwner + "/" + mRepoName), url); return true; case MENU_ITEM_HISTORY: startActivity(CommitHistoryActivity.makeIntent(this, mRepoOwner, mRepoName, mRef, mPath)); return true; case R.id.view_raw: mViewRawText = !mViewRawText; item.setChecked(mViewRawText); onRefresh(); return true; } return super.onOptionsItemSelected(item); }
Source:
public BigDecimal convert( final String value ) { return new BigDecimal( value ); }

Target:
public BigDecimal convert( final String value ) { try { return new BigDecimal( value ); } catch ( NumberFormatException nfe ) { return new BigDecimal( "0.0" ); } }
Source:
public String toString() { final StringBuilder sb = new StringBuilder("FilePosition{"); sb.append("line=").append(line); sb.append(", column=").append(column); sb.append('}'); return sb.toString(); }

Target:
public String toString() { return new ToStringBuilder(this) .append("line", line) .append("column", column) .toString(); }
Source:
public void onDonePressed() { if (mEmailFieldValidator.validate(mEmailEditText.getText())) { if (getFlowParams().passwordResetSettings != null) customResetPassword(); else normalResetPassword(); } }

Target:
public void onDonePressed() { if (mEmailFieldValidator.validate(mEmailEditText.getText())) { if (getFlowParams().passwordResetSettings != null) { resetPassword(mEmailEditText.getText().toString(), getFlowParams().passwordResetSettings); } else { resetPassword(mEmailEditText.getText().toString(), null); } } }
Source:
public PipelinePostProcessorHandler(List<PipelinePostProcessor> postProcessors) { this.postProcessors = postProcessors; }

Target:
public PipelinePostProcessorHandler(List<PipelinePostProcessor> postProcessors) { postProcessors.sort(Comparator.comparing(PipelinePostProcessor::priority)); this.postProcessors = postProcessors; }
Source:
private void testMSIEndpointWithSystemAssigned() { if (CoreUtils.isNullOrEmpty(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT)) && CoreUtils.isNullOrEmpty(CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET))) { throw logger.logExceptionAsError( new IllegalStateException("testMSIEndpointWithUserAssigned - MSIEndpoint and Identity Point not" + "configured in the environment. Atleast one should be configuured")); } assertConfigPresence(Configuration.PROPERTY_MSI_SECRET, "testMSIEndpointWithSystemAssigned - MSISecret not configured in the environment."); IdentityClient client = new IdentityClientBuilder().build(); AccessToken accessToken = client.authenticateToManagedIdentityEndpoint( CONFIGURATION.get(PROPERTY_IDENTITY_ENDPOINT), CONFIGURATION.get(PROPERTY_IDENTITY_HEADER), CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT), CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET), new TokenRequestContext().addScopes("<LINK_0>")) .flatMap(token -> { if (token == null || token.getToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalStateException( "Access Token not returned from System Assigned Identity"))); } else { return Mono.just(token); } }).block(); if (accessToken == null) { System.out.println("Error: Access token is null."); return; } System.out.printf("Received token with length %d and expiry at %s %n " + "testMSIEndpointWithSystemAssigned - Succeeded %n", accessToken.getToken().length(), accessToken.getExpiresAt().format(DateTimeFormatter.ISO_DATE_TIME)); }

Target:
private void testMSIEndpointWithSystemAssigned() { if (CoreUtils.isNullOrEmpty(CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT)) && CoreUtils.isNullOrEmpty(CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET))) { throw logger.logExceptionAsError( new IllegalStateException("testMSIEndpointWithUserAssigned - MSIEndpoint and Identity Point not" + "configured in the environment. At least one should be configured")); } assertConfigPresence(Configuration.PROPERTY_MSI_SECRET, "testMSIEndpointWithSystemAssigned - MSISecret not configured in the environment."); IdentityClient client = new IdentityClientBuilder().build(); AccessToken accessToken = client.authenticateToManagedIdentityEndpoint( CONFIGURATION.get(PROPERTY_IDENTITY_ENDPOINT), CONFIGURATION.get(PROPERTY_IDENTITY_HEADER), CONFIGURATION.get(Configuration.PROPERTY_MSI_ENDPOINT), CONFIGURATION.get(Configuration.PROPERTY_MSI_SECRET), new TokenRequestContext().addScopes("<LINK_0>")) .flatMap(token -> { if (token == null || token.getToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalStateException( "Access Token not returned from System Assigned Identity"))); } else { return Mono.just(token); } }).block(); if (accessToken == null) { System.out.println("Error: Access token is null."); return; } System.out.printf("Received token with length %d and expiry at %s %n " + "testMSIEndpointWithSystemAssigned - Succeeded %n", accessToken.getToken().length(), accessToken.getExpiresAt().format(DateTimeFormatter.ISO_DATE_TIME)); }