auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public final void cleanExpiredUsersSessions() { Date now = new Date(); Iterator<Entry<String, SessionInfo>> iter = sessionInfoMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, SessionInfo> entry = iter.next(); ConcurrentMap<String, Object> sessionMap = entry.getValue().contentOfSession; Date hardLimit = (Date) sessionMap.get(HARD_LIMIT_PARAMETER_NAME); Date softLimit = (Date) sessionMap.get(SOFT_LIMIT_PARAMETER_NAME); if ((hardLimit != null && hardLimit.before(now)) || (softLimit != null && softLimit.before(now))) { <START> removeSessionImpl(entry.getKey(), Acct.ReportReason.PRINCIPAL_SESSION_EXPIRED, "Session has expired"); <END> } } }</code><technical_language>add principal name message</technical_language>

Target:
public final void cleanExpiredUsersSessions() { Date now = new Date(); Iterator<Entry<String, SessionInfo>> iter = sessionInfoMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, SessionInfo> entry = iter.next(); ConcurrentMap<String, Object> sessionMap = entry.getValue().contentOfSession; Date hardLimit = (Date) sessionMap.get(HARD_LIMIT_PARAMETER_NAME); Date softLimit = (Date) sessionMap.get(SOFT_LIMIT_PARAMETER_NAME); if ((hardLimit != null && hardLimit.before(now)) || (softLimit != null && softLimit.before(now))) { removeSessionImpl(entry.getKey(), Acct.ReportReason.PRINCIPAL_SESSION_EXPIRED, "Session has expired for principal %1$s", getPrincipal(entry.getKey())); } } }
Source:
<code>DiscoveryDataPacket collectExchangeData(DiscoveryDataPacket dataPacket) { if (locNode.isDaemon()) return dataPacket; assert dataPacket != null; assert dataPacket.joiningNodeId() != null; DiscoveryDataBag dataBag = dataPacket.bagForDataCollection(); exchange.collect(dataBag); if (dataPacket.joiningNodeId().equals(locNode.id())) dataPacket.marshalJoiningNodeData( dataBag, marshaller(), <START> log, <END> allNodesSupport(IgniteFeatures.DATA_PAKET_COMPRESSION)); else dataPacket.marshalGridNodeData( dataBag, locNode.id(), marshaller(), log, allNodesSupport(IgniteFeatures.DATA_PAKET_COMPRESSION)); return dataPacket; }</code><technical_language>log argument in method</technical_language>

Target:
DiscoveryDataPacket collectExchangeData(DiscoveryDataPacket dataPacket) { if (locNode.isDaemon()) return dataPacket; assert dataPacket != null; assert dataPacket.joiningNodeId() != null; DiscoveryDataBag dataBag = dataPacket.bagForDataCollection(); exchange.collect(dataBag); if (dataPacket.joiningNodeId().equals(locNode.id())) dataPacket.marshalJoiningNodeData( dataBag, marshaller(), allNodesSupport(IgniteFeatures.DATA_PACKET_COMPRESSION), ignite.configuration().getNetworkCompressionLevel(), log); else dataPacket.marshalGridNodeData( dataBag, locNode.id(), marshaller(), allNodesSupport(IgniteFeatures.DATA_PACKET_COMPRESSION), ignite.configuration().getNetworkCompressionLevel(), log); return dataPacket; }
Source:
<code><START> private Boolean check() { <END> if (mJobId == null) { return false; } JobInfo jobInfo; try { jobInfo = mClient.getJobStatus(mJobId); } catch (IOException e) { LOG.warn("Failed to get status for job (jobId={})", mJobId, e); return false; } switch (jobInfo.getStatus()) { case CREATED: case RUNNING: return null; case CANCELED: case COMPLETED: return true; case FAILED: return false; default: throw new IllegalStateException(String.format("Unexpected Status: %s", jobInfo.getStatus())); } }</code><technical_language>Instead of returning a boolean state, simplification</technical_language>

Target:
private Status check() { if (mJobId == null) { return Status.FAILED; } JobInfo jobInfo; try { jobInfo = mClient.getJobStatus(mJobId); } catch (IOException e) { LOG.warn("Failed to get status for job (jobId={})", mJobId, e); return Status.FAILED; } return jobInfo.getStatus(); }
Source:
<code>public Long getBytes(String path) { <START> return getMemorySize(path).toBytes(); <END> }</code><technical_language>I throw IllegalArgumentException throw ConfigException.BadValue ... API break mess somebody's code. solution: a variant of ConfigMemorySize.toBytes takes origin/path information. Another option: call toBytesBigInteger do range check here</technical_language>

Target:
public Long getBytes(String path) { BigInteger bytes = getBytesBigInteger(path); ConfigValue v = find(path, ConfigValueType.STRING); return toLong(bytes, v.origin(), path); }
Source:
<code>public void getGroupMembers_shouldReturnAllGroupMembers() throws Exception { executeDataSet("ObsWithGroupMembers.xml"); <START> assertEquals(1, getResource().getByUniqueId("47f18998-96cc-11e0-8d6b-9b9415a91423").getGroupMembers().size()); <END> assertEquals(2, getResource().getByUniqueId("5117f5d4-96cc-11e0-8d6b-9b9415a91433").getGroupMembers().size()); }</code><technical_language>asserts testing related webservices.rest module, calling Obs.getGroupMembers(). resource.getGroupMembers(resource.getByUniqueId("..."))</technical_language>

Target:
public void getGroupMembers_shouldReturnAllGroupMembers() throws Exception { executeDataSet("ObsWithGroupMembers.xml"); ObsResource1_8 resource = getResource(); Set<Obs> groupMembers1 = (Set<Obs>) ObsResource1_8.getGroupMembers(resource.getByUniqueId("47f18998-96cc-11e0-8d6b-9b9415a91423")); assertEquals(1, groupMembers1.size()); Set<Obs> groupMembers2 = (Set<Obs>) ObsResource1_8.getGroupMembers(resource.getByUniqueId("5117f5d4-96cc-11e0-8d6b-9b9415a91433")); assertEquals(2, groupMembers2.size()); }
Source:
<code>public void testApplicationKeepAlive() throws Exception { MyNodeManager nm = new MyNodeManager(); try { YarnConfiguration conf = createNMConfig(); conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); conf.setLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS, 4000l); nm.init(conf); nm.start(); GenericTestUtils.waitFor(() -> nm.getServiceState() == STATE.STARTED, 20, 10000); int waitCount = 0; while (nm.getServiceState() == STATE.STARTED && heartBeatID < 12 && waitCount++ < 60000000) { Thread.sleep(100l); } Assert.assertTrue(heartBeatID >= 12); MyResourceTracker3 rt = (MyResourceTracker3) nm.getNodeStatusUpdater().getRMClient(); rt.context.getApplications().remove(rt.appId); Assert.assertEquals(1, rt.keepAliveRequests.size()); int numKeepAliveRequests = rt.keepAliveRequests.get(rt.appId).size(); LOG.info("Number of Keep Alive Requests: [" + numKeepAliveRequests + "]"); Assert.assertTrue(numKeepAliveRequests == 2 || numKeepAliveRequests == 3); waitCount = 0; <START> while (nm.getServiceState() == STATE.STARTED && heartBeatID < 20 <END> && waitCount++ < 60000000) { Thread.sleep(100l); } Assert.assertTrue(heartBeatID >= 20); int numKeepAliveRequests2 = rt.keepAliveRequests.get(rt.appId).size(); Assert.assertEquals(numKeepAliveRequests, numKeepAliveRequests2); } finally { if (nm.getServiceState() == STATE.STARTED) nm.stop(); } }</code><technical_language>waitFor()</technical_language>

Target:
public void testApplicationKeepAlive() throws Exception { MyNodeManager nm = new MyNodeManager(); try { YarnConfiguration conf = createNMConfig(); conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); conf.setLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS, 4000l); nm.init(conf); nm.start(); GenericTestUtils.waitFor(() -> nm.getServiceState() == STATE.STARTED, 20, 10000); GenericTestUtils.waitFor( () -> nm.getServiceState() != STATE.STARTED || heartBeatID.get() >= 12, 100L, 60000000); Assert.assertTrue(heartBeatID.get() >= 12); MyResourceTracker3 rt = (MyResourceTracker3) nm.getNodeStatusUpdater().getRMClient(); rt.context.getApplications().remove(rt.appId); Assert.assertEquals(1, rt.keepAliveRequests.size()); int numKeepAliveRequests = rt.keepAliveRequests.get(rt.appId).size(); LOG.info("Number of Keep Alive Requests: [" + numKeepAliveRequests + "]"); Assert.assertTrue(numKeepAliveRequests == 2 || numKeepAliveRequests == 3); GenericTestUtils.waitFor( () -> nm.getServiceState() != STATE.STARTED || heartBeatID.get() >= 20, 100L, 60000000); Assert.assertTrue(heartBeatID.get() >= 20); int numKeepAliveRequests2 = rt.keepAliveRequests.get(rt.appId).size(); Assert.assertEquals(numKeepAliveRequests, numKeepAliveRequests2); } finally { if (nm != null) { nm.stop(); nm.waitForServiceToStop(10000); } } }
Source:
<code>public MachinePublicKeyProvider( @Named("env.CHE_MACHINE_AUTH_SIGNATURE__ALGORITHM") String alg, @Named("env.CHE_MACHINE_AUTH_SIGNATURE__PUBLIC__KEY") String key) { <START> checkArgument(key != null && !key.isEmpty(), "Signature key for token validation is not found"); <END> checkArgument(alg != null && !alg.isEmpty(), "Algorithm for signature key is not defined"); this.publicKey = key; this.algorithm = alg; }</code><technical_language>AFAIK env vars injected this support set env vars. it</technical_language>

Target:
public MachinePublicKeyProvider( @Named("env.CHE_MACHINE_AUTH_SIGNATURE__ALGORITHM") String alg, @Named("env.CHE_MACHINE_AUTH_SIGNATURE__PUBLIC__KEY") String key) { this.publicKey = key; this.algorithm = alg; }
Source:
<code>public void handleCheckStateChangedEvent(Collection<ITmfTreeViewerEntry> entries) { cancelUpdate(); Iterable<TmfGenericTreeEntry> counterEntries = Iterables.filter(entries, TmfGenericTreeEntry.class); Collection<@NonNull Long> selectedIds = Lists.newArrayList(Iterables.transform(counterEntries, e -> e.getModel().getId())); <START> if (!selectedIds.equals(fSelectedIds)) { <END> clearContent(); fSelectedIds = selectedIds; } updateContent(); }</code><technical_language>point is clear entries if some removed compared previous state, selectedIds.containsAll(fSelectedIds) remove more clear cases? (replace selectedIds a hashset in case) Also, actual clearing / update org.eclipse.tracecompass.tmf.ui.viewers.xycharts.linecharts.TmfCommonXAxisChartViewer.UpdateThread.updateDisplay, this code there, avoid clear/update pattern in child classes</technical_language>

Target:
public void handleCheckStateChangedEvent(Collection<ITmfTreeViewerEntry> entries) { cancelUpdate(); Iterable<TmfGenericTreeEntry> counterEntries = Iterables.filter(entries, TmfGenericTreeEntry.class); Collection<@NonNull Long> selectedIds = Lists.newArrayList(Iterables.transform(counterEntries, e -> e.getModel().getId())); if (!selectedIds.containsAll(fSelectedIds)) { clearContent(); } fSelectedIds = selectedIds; updateContent(); }
Source:
<code>void dispatch(DebugEvent[] events) { fEvents = events; if (!fEventFilters.isEmpty()) { fMode = NOTIFY_FILTERS; for (IDebugEventFilter iDebugEventFilter : fEventFilters) { fFilter = iDebugEventFilter; SafeRunner.run(this); if (fEvents == null || fEvents.length == 0) { return; } } } fMode = NOTIFY_EVENTS; if (DebugOptions.DEBUG_EVENTS) { for (DebugEvent <START> fEvent : <END> fEvents) { DebugOptions.trace(fEvent.toString()); } } for (IDebugEventSetListener iDebugEventSetListener : fEventListeners) { fListener = iDebugEventSetListener; SafeRunner.run(this); } fEvents = null; fFilter = null; fListener = null; }</code><technical_language>rename event</technical_language>

Target:
void dispatch(DebugEvent[] events) { fEvents = events; if (!fEventFilters.isEmpty()) { fMode = NOTIFY_FILTERS; for (IDebugEventFilter iDebugEventFilter : fEventFilters) { fFilter = iDebugEventFilter; SafeRunner.run(this); if (fEvents == null || fEvents.length == 0) { return; } } } fMode = NOTIFY_EVENTS; if (DebugOptions.DEBUG_EVENTS) { for (DebugEvent event : fEvents) { DebugOptions.trace(event.toString()); } } for (IDebugEventSetListener iDebugEventSetListener : fEventListeners) { fListener = iDebugEventSetListener; SafeRunner.run(this); } fEvents = null; fFilter = null; fListener = null; }
Source:
<code>public long getOldestWriteTimstamp() { if(writes.size() == 0) { return Long.MAX_VALUE; } <START> Write oldestWrite = writes.get(0); <END> return oldestWrite.getVersion(); }</code><technical_language>add explicit else block if (condition) { } else { }</technical_language>

Target:
public long getOldestWriteTimstamp() { if(writes.size() == 0) { return Long.MAX_VALUE; } else { Write oldestWrite = writes.get(0); return oldestWrite.getVersion(); } }
Source:
<code>protected WgsMetricsCollector getCollector(final int coverageCap, final IntervalList intervals) { <START> if (collector != null) throw new PicardException("A WGSMetricsCollector already exists"); <END> collector = new WgsMetricsWithNonZeroCoverageCollector(COVERAGE_CAP, intervals); return collector; }</code><technical_language>remove assertion</technical_language>

Target:
protected WgsMetricsCollector getCollector(final int coverageCap, final IntervalList intervals) { assert(coverageCap == this.collector.coverageCap); return this.collector; }
Source:
<code>public boolean updateSMSAlertWithUpdatedCourtDate(SMSAlert dailyAlert){ <START> String sql = "UPDATE sms_alerts SET court_date = :courtDate WHERE id = :smsAlertId"; <END> Map<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("courtDate", DatabaseUtilities.convertLocalDateTimeToDatabaseDate(dailyAlert.courtDate)); parameterMap.put("smsAlertId", dailyAlert.id); try{ jdbcTemplate.update(sql, parameterMap); }catch(Exception e){ LogSystem.LogDBException(e); return false; } return true; }</code><technical_language>sql</technical_language>

Target:
public boolean updateSMSAlertWithUpdatedCourtDate(SMSAlert dailyAlert){ Map<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("courtDate", DatabaseUtilities.convertLocalDateTimeToDatabaseDate(dailyAlert.courtDate)); parameterMap.put("smsAlertId", dailyAlert.id); try{ jdbcTemplate.update(getSql("SMSAlert/update-SMSAlert-courtDate.sql"), parameterMap); }catch(Exception e){ LogSystem.LogDBException(e); return false; } return true; }
Source:
<code>private OpenShiftEnvironment asOpenShiftEnv(InternalEnvironment source) throws ValidationException, InfrastructureException { if (source instanceof OpenShiftEnvironment) { return (OpenShiftEnvironment) source; } if (source instanceof DockerImageEnvironment) { return dockerImageEnvConverter.convert((DockerImageEnvironment) source); } <START> throw new ValidationException( <END> format( "Environment type '%s' is not supported. Supported environment types: %s", source.getRecipe().getType(), OpenShiftEnvironment.TYPE)); }</code><technical_language>Consider changing InternalInfrastructureException reaching of this code is in case of a developer mistake</technical_language>

Target:
private OpenShiftEnvironment asOpenShiftEnv(InternalEnvironment source) throws ValidationException, InfrastructureException { if (source instanceof OpenShiftEnvironment) { return (OpenShiftEnvironment) source; } if (source instanceof DockerImageEnvironment) { return dockerImageEnvConverter.convert((DockerImageEnvironment) source); } throw new InternalInfrastructureException( format( "Environment type '%s' is not supported. Supported environment types: %s", source.getRecipe().getType(), OpenShiftEnvironment.TYPE)); }
Source:
<code>public boolean validate() { StringTokenizer tokenizer = new StringTokenizer(inputString, "\n"); if (tokenizer.countTokens() != 2) { log.trace("putTaskStatus() - input error"); validationResponse = Response.status(400).build(); return false; } String requestTokenInput = tokenizer.nextToken(); String surlInput = tokenizer.nextToken(); if ((!requestTokenInput.startsWith("requestToken=")) || (!surlInput.startsWith("surl="))) { log.trace("putTaskStatus() - input error"); validationResponse = Response.status(400).build(); return false; } requestToken = requestTokenInput .substring(requestTokenInput.indexOf('=') + 1); String surlString = surlInput.substring(surlInput.indexOf('=') + 1); if ((requestToken.length() == 0) || (surlString.length() == 0)) { log.trace("putTaskStatus() - input error"); validationResponse = Response.status(400).build(); return false; } if(!TokenValidator.valid(requestToken)){ <START> validationResponse = Response.status(400).entity("Invalid token\n\n").build(); <END> return false; } if (!validateSurl(surlString)) { return false; } return true; }</code><technical_language>nice invalid token in output well.</technical_language>

Target:
public boolean validate() { StringTokenizer tokenizer = new StringTokenizer(inputString, "\n"); if (tokenizer.countTokens() != 2) { log.trace("putTaskStatus() - input error"); validationResponse = Response.status(400).build(); return false; } String requestTokenInput = tokenizer.nextToken(); String surlInput = tokenizer.nextToken(); if ((!requestTokenInput.startsWith("requestToken=")) || (!surlInput.startsWith("surl="))) { log.trace("putTaskStatus() - input error"); validationResponse = Response.status(400).build(); return false; } requestToken = requestTokenInput .substring(requestTokenInput.indexOf('=') + 1); String surlString = surlInput.substring(surlInput.indexOf('=') + 1); if ((requestToken.length() == 0) || (surlString.length() == 0)) { log.trace("putTaskStatus() - input error"); validationResponse = Response.status(400).build(); return false; } if(!TokenValidator.valid(requestToken)){ validationResponse = Response.status(400).entity("Invalid token: " + requestToken +" \n\n").build(); return false; } if (!validateSurl(surlString)) { return false; } return true; }
Source:
<code>public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); <START> EPerson ePerson = null; <END> try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); UUID dsoId = UUID.fromString(targetId.toString()); DSpaceObjectService<DSpaceObject> dSpaceObjectService = ContentServiceFactory.getInstance() .getDSpaceObjectService( Constants.getTypeID( targetType)); DSpaceObject dSpaceObject = dSpaceObjectService.find(context, dsoId); return authorizeService.isAdmin(context, ePerson, dSpaceObject); } catch (SQLException e) { log.error(e.getMessage(),e); } return false; }</code><technical_language>Consider checking if ePerson is a repository admin. If so, return true immediately</technical_language>

Target:
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson != null) { if (authorizeService.isAdmin(context, ePerson)) { return true; } } } catch (SQLException e) { log.error(e.getMessage(), e); } return false; }
Source:
<code>public void addRecipient(String channelName, String selectorExpression) { <START> Assert.notNull(channelName, "channelName can't be null."); <END> MessageChannel channel = this.getBeanFactory().getBean(channelName, MessageChannel.class); ExpressionEvaluatingSelector expressionEvaluatingSelector = new ExpressionEvaluatingSelector(selectorExpression); expressionEvaluatingSelector.setBeanFactory(this.getBeanFactory()); this.recipients.add(new Recipient(channel, expressionEvaluatingSelector)); }</code><technical_language>Assert.hasText(channelName, "channelName empty.");. empty channelName is bad</technical_language>

Target:
public void addRecipient(String channelName, String selectorExpression) { Assert.notNull(channelName, "channelName can't be null."); Assert.hasText(channelName, "channelName can't be empty."); Assert.notNull(selectorExpression, "selectorExpression can't be null."); Assert.hasText(selectorExpression, "selectorExpression can't be empty."); MessageChannel channel = this.getBeanFactory().getBean(channelName, MessageChannel.class); ExpressionEvaluatingSelector expressionEvaluatingSelector = new ExpressionEvaluatingSelector(selectorExpression); expressionEvaluatingSelector.setBeanFactory(this.getBeanFactory()); this.recipients.add(new Recipient(channel, expressionEvaluatingSelector)); }
Source:
<code>public void emptyErrorLog() { LogView elv = new LogView(); elv.open(); <START> elv.clearLog(); <END> new WaitWhile(new JobIsRunning()); }</code><technical_language>clear log is action delete log. want clear</technical_language>

Target:
public void emptyErrorLog() { LogView elv = new LogView(); elv.open(); elv.deleteLog(); new WaitWhile(new JobIsRunning()); }
Source:
<code>public void onDataChanged() { if (mHasQueuedInstantOps) { <START> notifyListenersOnDataChanged(); <END> mHasQueuedInstantOps = false; } }</code><technical_language>For "instant operation" batch events filed? I here, in DataRefListener</technical_language>

Target:
public void onDataChanged() { if (mHasPendingMoveOrDelete) { notifyListenersOnDataChanged(); mHasPendingMoveOrDelete = false; } }
Source:
<code>protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { Object[] changed = event.getElements(); if (changed != null) { List<Object> others = new ArrayList<Object>(); for (Object <START> element : <END> changed) { if (element == null) continue; if (_mapper != null) { if (_mapper.handlesObject(element)) { _mapper.objectChanged(element); continue; } } others.add(element); } if (others.isEmpty()) { return; } event = new LabelProviderChangedEvent((IBaseLabelProvider) event .getSource(), others.toArray()); } super.handleLabelProviderChanged(event); }</code><technical_language>rename 'changedElement'</technical_language>

Target:
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { Object[] changed = event.getElements(); if (changed != null) { List<Object> others = new ArrayList<Object>(); for (Object changedElement : changed) { if (changedElement == null) continue; if (_mapper != null) { if (_mapper.handlesObject(changedElement)) { _mapper.objectChanged(changedElement); continue; } } others.add(changedElement); } if (others.isEmpty()) { return; } event = new LabelProviderChangedEvent((IBaseLabelProvider) event .getSource(), others.toArray()); } super.handleLabelProviderChanged(event); }
Source:
<code>private ApplicationReport findApplicationReportFromAppNameOrId(String appNameOrId) { ApplicationReport app = null; <START> if (getApplication(appNameOrId) != null) { <END> app = getApplication(appNameOrId); } else if (getApplicationByName(appNameOrId) != null) { app = getApplicationByName(appNameOrId); } return app; }</code><technical_language>app = getApplication(appNameOrId) if (app == null) { app = getApplicationByName(appNameOrId) } avoid calling getApplication getApplicationByName twice</technical_language>

Target:
private ApplicationReport findApplicationReportFromAppNameOrId(String appNameOrId) { ApplicationReport app = getApplication(appNameOrId); if (app == null) { app = getApplicationByName(appNameOrId); } return app; }
Source:
<code><START> private synchronized void handshake() throws TTransportException { <END> Message message; try { message = conn.request(this.connectionSubject, null, this.connectionTimeout); } catch (IOException e) { throw new TTransportException(e); } catch (TimeoutException e) { throw new TTransportException(TTransportException.UNKNOWN, "Handshake timed out", e); } String reply = message.getReplyTo(); if (reply == null || reply.isEmpty() ) { throw new TTransportException("No reply subject on connect."); } String[] subjects = new String(message.getData()).split(" "); if (subjects.length != 3 ) { throw new TTransportException("Invalid connect message."); } String heartbeatListen = subjects[0]; String heartbeatReply = subjects[1]; int deadline; try { deadline = Integer.parseInt(subjects[2]); } catch (NumberFormatException e) { throw new TTransportException("Connection deadline not an integer.", e); } long heartbeatInterval = 0; if (deadline > 0) { heartbeatInterval = deadline; } this.heartbeatListen = heartbeatListen; this.heartbeatReply = heartbeatReply; this.heartbeatInterval = heartbeatInterval; this.listenTo = message.getSubject(); this.writeTo = reply; }</code><technical_language>open synchronized</technical_language>

Target:
private void handshake() throws TTransportException { Message message; try { message = conn.request(this.connectionSubject, null, this.connectionTimeout); } catch (IOException e) { throw new TTransportException(e); } catch (TimeoutException e) { throw new TTransportException(TTransportException.TIMED_OUT, "Handshake timed out", e); } String reply = message.getReplyTo(); if (reply == null || reply.isEmpty() ) { throw new TTransportException("No reply subject on connect."); } String[] subjects = new String(message.getData()).split(" "); if (subjects.length != 3 ) { throw new TTransportException("Invalid connect message."); } String heartbeatListen = subjects[0]; String heartbeatReply = subjects[1]; int deadline; try { deadline = Integer.parseInt(subjects[2]); } catch (NumberFormatException e) { throw new TTransportException("Connection deadline not an integer.", e); } long heartbeatInterval = 0; if (deadline > 0) { heartbeatInterval = deadline; } this.heartbeatListen = heartbeatListen; this.heartbeatReply = heartbeatReply; this.heartbeatInterval = heartbeatInterval; this.listenTo = message.getSubject(); this.writeTo = reply; }
Source:
<code>protected FilterCapabilities createFilterCapabilities() { FilterCapabilities caps = new FilterCapabilities(); caps.addAll(SQLDialect.BASE_DBMS_CAPABILITIES); caps.addType(BBOX.class); caps.addType(Contains.class); caps.addType(Crosses.class); caps.addType(Disjoint.class); caps.addType(Equals.class); caps.addType(Intersects.class); caps.addType(Overlaps.class); caps.addType(Touches.class); caps.addType(Within.class); caps.addType(DWithin.class); caps.addType(Beyond.class); caps.addType(FilterFunction_sdonn.class); caps.addType(FilterFunction_area.class); caps.addType(After.class); caps.addType(Before.class); caps.addType(Begins.class); caps.addType(BegunBy.class); caps.addType(During.class); caps.addType(TOverlaps.class); caps.addType(Ends.class); caps.addType(EndedBy.class); caps.addType(TEquals.class); <START> caps.addType(NativeFilter.class); <END> return caps; }</code><technical_language>If native filter handling in SQL is write out in SQL, add support for in SQLDialect#BASE_DBMS_CAPABILITIES instead? selected DBMS remove it, if needs (don't need)</technical_language>

Target:
protected FilterCapabilities createFilterCapabilities() { FilterCapabilities caps = new FilterCapabilities(); caps.addAll(SQLDialect.BASE_DBMS_CAPABILITIES); caps.addType(BBOX.class); caps.addType(Contains.class); caps.addType(Crosses.class); caps.addType(Disjoint.class); caps.addType(Equals.class); caps.addType(Intersects.class); caps.addType(Overlaps.class); caps.addType(Touches.class); caps.addType(Within.class); caps.addType(DWithin.class); caps.addType(Beyond.class); caps.addType(FilterFunction_sdonn.class); caps.addType(FilterFunction_area.class); caps.addType(After.class); caps.addType(Before.class); caps.addType(Begins.class); caps.addType(BegunBy.class); caps.addType(During.class); caps.addType(TOverlaps.class); caps.addType(Ends.class); caps.addType(EndedBy.class); caps.addType(TEquals.class); return caps; }
Source:
<code>public Response getItemData(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @QueryParam("metadata") @ApiParam(value = "metadata selector", required = false) @Nullable String namespaceSelector, @PathParam("itemname") @ApiParam(value = "item name", required = true) String itemname) { final Locale locale = LocaleUtil.getLocale(language); final Set<String> namespaces = namespaceSelector == null ? Collections.emptySet() <START> : Arrays.stream(namespaceSelector.split(",")) END> .filter(n -> !n.startsWith(MetadataRegistry.INTERNAL_NAMESPACE_PREFIX)) .collect(Collectors.toSet()); logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); Item item = getItem(itemname); if (item != null) { logger.debug("Received HTTP GET request at '{}'.", uriInfo.getPath()); EnrichedItemDTO dto = EnrichedItemDTOMapper.map(item, true, null, uriInfo.getBaseUri(), locale); addMetadata(dto, namespaces, null); return JSONResponse.createResponse(Status.OK, dto, null); } else { logger.info("Received HTTP GET request at '{}' for the unknown item '{}'.", uriInfo.getPath(), itemname); return getItemNotFoundResponse(itemname); } }</code><technical_language>is this block lines 216 - 218 worth a separate method</technical_language>

Target:
public Response getItemData(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @QueryParam("metadata") @ApiParam(value = "metadata selector", required = false) @Nullable String namespaceSelector, @PathParam("itemname") @ApiParam(value = "item name", required = true) String itemname) { final Locale locale = LocaleUtil.getLocale(language); final Set<String> namespaces = splitAndFilterNamespaces(namespaceSelector); logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); Item item = getItem(itemname); if (item != null) { logger.debug("Received HTTP GET request at '{}'.", uriInfo.getPath()); EnrichedItemDTO dto = EnrichedItemDTOMapper.map(item, true, null, uriInfo.getBaseUri(), locale); addMetadata(dto, namespaces, null); return JSONResponse.createResponse(Status.OK, dto, null); } else { logger.info("Received HTTP GET request at '{}' for the unknown item '{}'.", uriInfo.getPath(), itemname); return getItemNotFoundResponse(itemname); } }
Source:
<code>protected int poll() throws Exception { final Map<String, Object> args = new HashMap<>(); args.putAll(endpoint.getEndpointProperties()); endpoint.interceptProperties(args); interceptProperties(args); try { final CountDownLatch latch = new CountDownLatch(1); final Object[] result = new Object[1]; final Exception[] error = new Exception[1]; args.put(Olingo4Endpoint.RESPONSE_HANDLER_PROPERTY, new Olingo4ResponseHandler<Object>() { @Override public void onResponse(Object response, Map<String, String> responseHeaders) { result[0] = response; latch.countDown(); } @Override public void onException(Exception ex) { error[0] = ex; latch.countDown(); } @Override public void onCanceled() { error[0] = new RuntimeCamelException("OData HTTP Request cancelled"); latch.countDown(); } }); doInvokeMethod(args); latch.await(); if (error[0] != null) { throw error[0]; } <START> int processed = ApiConsumerHelper.getResultsProcessed(this, result[0], isSplitResult()); <END> if (result[0] instanceof ClientEntitySet && (((ClientEntitySet) result[0]).getEntities().isEmpty())) { return 0; } else { return processed; } } catch (Throwable t) { throw RuntimeCamelException.wrapRuntimeCamelException(t); } }</code><technical_language>moved this return processed is evaluated if needed</technical_language>

Target:
protected int poll() throws Exception { final Map<String, Object> args = new HashMap<>(); args.putAll(endpoint.getEndpointProperties()); endpoint.interceptProperties(args); interceptProperties(args); try { final CountDownLatch latch = new CountDownLatch(1); final Object[] result = new Object[1]; final Exception[] error = new Exception[1]; args.put(Olingo4Endpoint.RESPONSE_HANDLER_PROPERTY, new Olingo4ResponseHandler<Object>() { @Override public void onResponse(Object response, Map<String, String> responseHeaders) { result[0] = response; latch.countDown(); } @Override public void onException(Exception ex) { error[0] = ex; latch.countDown(); } @Override public void onCanceled() { error[0] = new RuntimeCamelException("OData HTTP Request cancelled"); latch.countDown(); } }); doInvokeMethod(args); latch.await(); if (error[0] != null) { throw error[0]; } if (result[0] instanceof ClientEntitySet && (((ClientEntitySet) result[0]).getEntities().isEmpty())) { return 0; } else { int processed = ApiConsumerHelper.getResultsProcessed(this, result[0], isSplitResult()); return processed; } } catch (Throwable t) { throw RuntimeCamelException.wrapRuntimeCamelException(t); } }
Source:
<code>public static void showSitePickerForResult(Activity activity, SiteModel site) { <START> Intent intent = createSitePickerIntent(activity, site, false); <END> activity.startActivityForResult(intent, RequestCodes.SITE_PICKER); }</code><technical_language>if currently a 2 state discrimination I enum (like SitePickerMode). Wdyt</technical_language>

Target:
public static void showSitePickerForResult(Activity activity, SiteModel site) { Intent intent = createSitePickerIntent(activity, site, SitePickerMode.NORMAL); activity.startActivityForResult(intent, RequestCodes.SITE_PICKER); }
Source:
<code>public ElevationModule(ElevationGridCoverageFactory factory) { <START> gridCoverageFactory = factory; <END> cachedElevationsFile = null; readCachedElevations = false; writeCachedElevations = false; elevationUnitMultiplier = 1; }</code><technical_language>this(factory, null, false, false, 1). if add/remove a new parameter "main" constructor he/she needs a decision do this one</technical_language>

Target:
public ElevationModule(ElevationGridCoverageFactory factory) { this( factory, null, false, false, 1, true, false ); }
Source:
<code>protected OCFile getCurrentDir() { OCFile file = getFile(); if (file != null) { if (file.isFolder()) { return file; } else if (getStorageManager() != null) { <START> String parentPath = file.getRemotePath().substring(0, <END> file.getRemotePath().lastIndexOf(file.getFileName())); return getStorageManager().getFileByPath(parentPath); } } return null; }</code><technical_language>OCFile a method getRemoteParentPath replace this block. advantage of :)</technical_language>

Target:
protected OCFile getCurrentDir() { OCFile file = getFile(); if (file != null) { if (file.isFolder()) { return file; } else if (getStorageManager() != null) { String parentPath = file.getParentRemotePath(); return getStorageManager().getFileByPath(parentPath); } } return null; }
Source:
<code><START> private int determineDay(long rangeStart, long rangeEnd) <END> { int startDay = toIntExact(Duration.ofMillis(rangeStart).toDays()); int endDay = toIntExact(Duration.ofMillis(rangeEnd).toDays()); if (startDay == endDay) { return toIntExact(startDay); } if ((endDay - startDay) > 1) { return startDay + 1; } long millisInStartDay = Duration.ofDays(endDay).toMillis() - rangeStart; long millisInEndDay = rangeEnd - Duration.ofDays(endDay).toMillis(); return (millisInStartDay >= millisInEndDay) ? startDay : endDay; }</code><technical_language>This method static</technical_language>

Target:
private static int determineDay(long rangeStart, long rangeEnd) { int startDay = toIntExact(Duration.ofMillis(rangeStart).toDays()); int endDay = toIntExact(Duration.ofMillis(rangeEnd).toDays()); if (startDay == endDay) { return toIntExact(startDay); } if ((endDay - startDay) > 1) { return startDay + 1; } long millisInStartDay = Duration.ofDays(endDay).toMillis() - rangeStart; long millisInEndDay = rangeEnd - Duration.ofDays(endDay).toMillis(); return (millisInStartDay >= millisInEndDay) ? startDay : endDay; }
Source:
<code>public void setUp() { try { GoogleCredential credential = GoogleCredential.getApplicationDefault() .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM)); iamService = new Iam.Builder( GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential) .setApplicationName("service-accounts") .build(); } catch (IOException | GeneralSecurityException e) { System.out.println("Unable to initialize service: \n" + e.toString()); return; } try { serviceAccount = new ServiceAccount(); <START> serviceAccount.setDisplayName("iam-test-account" + new Date().hashCode()); <END> CreateServiceAccountRequest request = new CreateServiceAccountRequest(); request.setAccountId("iam-test-account" + new Date().hashCode()); request.setServiceAccount(serviceAccount); serviceAccount = iamService .projects() .serviceAccounts() .create("projects/" + PROJECT_ID, request) .execute(); } catch (IOException e) { System.out.println("Unable to create service account: \n" + e.toString()); } }</code><technical_language>start 2 tests time, possible, unlikely, get of these</technical_language>

Target:
public void setUp() { try { GoogleCredential credential = GoogleCredential.getApplicationDefault() .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM)); iamService = new Iam.Builder( GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential) .setApplicationName("service-accounts") .build(); } catch (IOException | GeneralSecurityException e) { System.out.println("Unable to initialize service: \n" + e.toString()); return; } try { serviceAccount = new ServiceAccount(); String serviceAccountUuid = UUID.randomUUID().toString().split("-")[0]; serviceAccount.setDisplayName("iam-test-account" + serviceAccountUuid); CreateServiceAccountRequest request = new CreateServiceAccountRequest(); request.setAccountId("iam-test-account" + serviceAccountUuid); request.setServiceAccount(serviceAccount); serviceAccount = iamService .projects() .serviceAccounts() .create("projects/" + PROJECT_ID, request) .execute(); } catch (IOException e) { System.out.println("Unable to create service account: \n" + e.toString()); } }
Source:
<code>public void register(SystemStreamPartition systemStreamPartition, String offset) { if (started.get()) { String exceptionMessage = String.format("KafkaSystemConsumer: %s had started. Registration of ssp: %s, offset: %s failed.", this, systemStreamPartition, offset); throw new SamzaException(exceptionMessage); } if (!Objects.equals(systemStreamPartition.getSystem(), systemName)) { LOG.warn("{}: ignoring SSP {}, because this consumer's system doesn't match.", this, systemStreamPartition); return; } <START> LOG.info("{}: Registering ssp = with offset {}", this, systemStreamPartition, offset); <END> super.register(systemStreamPartition, offset); TopicPartition tp = toTopicPartition(systemStreamPartition); topicPartitionsToSSP.put(tp, systemStreamPartition); String existingOffset = topicPartitionsToOffset.get(tp); if (existingOffset == null || compareOffsets(existingOffset, offset) > 0) { topicPartitionsToOffset.put(tp, offset); } metrics.registerTopicAndPartition(toTopicAndPartition(tp)); }</code><technical_language>nit: LOG.info("{}: Registering ssp: offset: {}", this, systemStreamPartition, offset); for logging consistency</technical_language>

Target:
public void register(SystemStreamPartition systemStreamPartition, String offset) { if (started.get()) { String exceptionMessage = String.format("KafkaSystemConsumer: %s had started. Registration of ssp: %s, offset: %s failed.", this, systemStreamPartition, offset); throw new SamzaException(exceptionMessage); } if (!Objects.equals(systemStreamPartition.getSystem(), systemName)) { LOG.warn("{}: ignoring SSP {}, because this consumer's system doesn't match.", this, systemStreamPartition); return; } LOG.info("{}: Registering ssp: with offset: {}", this, systemStreamPartition, offset); super.register(systemStreamPartition, offset); TopicPartition topicPartition = toTopicPartition(systemStreamPartition); String existingOffset = topicPartitionsToOffset.get(topicPartition); if (existingOffset == null || compareOffsets(existingOffset, offset) > 0) { topicPartitionsToOffset.put(topicPartition, offset); } metrics.registerTopicAndPartition(toTopicAndPartition(topicPartition)); }
Source:
<code>private TestRunner() { this.configs = new HashMap<>(); this.inMemoryScope = RandomStringUtils.random(10, true, true); configs.put(JobConfig.JOB_NAME(), JOB_NAME); configs.put(JobConfig.PROCESSOR_ID(), "1"); configs.put(JobCoordinatorConfig.JOB_COORDINATOR_FACTORY, PassthroughJobCoordinatorFactory.class.getName()); configs.put(TaskConfig.GROUPER_FACTORY(), SingleContainerGrouperFactory.class.getName()); configs.put(JobConfig.JOB_NON_LOGGED_STORE_BASE_DIR(), <START> FileSystems.getDefault().getPath("/tmp/" + this.inMemoryScope).toAbsolutePath().toString() + File.separator); <END> configs.put(JobConfig.JOB_LOGGED_STORE_BASE_DIR(), FileSystems.getDefault().getPath("/tmp/" + this.inMemoryScope).toAbsolutePath().toString() + File.separator); addConfig(JobConfig.JOB_DEFAULT_SYSTEM(), JOB_DEFAULT_SYSTEM); addConfig(ClusterManagerConfig.CLUSTER_MANAGER_HOST_AFFINITY_ENABLED, Boolean.FALSE.toString()); addConfig(InMemorySystemConfig.INMEMORY_SCOPE, inMemoryScope); addConfig(new InMemorySystemDescriptor(JOB_DEFAULT_SYSTEM).withInMemoryScope(inMemoryScope).toConfig()); }</code><technical_language>Instead of hardcoding path, check if Files.createTempDirectory() works</technical_language>

Target:
private TestRunner() { this.configs = new HashMap<>(); this.inMemoryScope = RandomStringUtils.random(10, true, true); configs.put(JobConfig.JOB_NAME(), JOB_NAME); configs.put(JobConfig.PROCESSOR_ID(), "1"); configs.put(JobCoordinatorConfig.JOB_COORDINATOR_FACTORY, PassthroughJobCoordinatorFactory.class.getName()); configs.put(TaskConfig.GROUPER_FACTORY(), SingleContainerGrouperFactory.class.getName()); configs.put(JobConfig.JOB_NON_LOGGED_STORE_BASE_DIR(), new File(System.getProperty("java.io.tmpdir"), this.inMemoryScope).getAbsolutePath()); configs.put(JobConfig.JOB_LOGGED_STORE_BASE_DIR(), new File(System.getProperty("java.io.tmpdir"), this.inMemoryScope).getAbsolutePath()); addConfig(JobConfig.JOB_DEFAULT_SYSTEM(), JOB_DEFAULT_SYSTEM); addConfig(ClusterManagerConfig.CLUSTER_MANAGER_HOST_AFFINITY_ENABLED, Boolean.FALSE.toString()); addConfig(InMemorySystemConfig.INMEMORY_SCOPE, inMemoryScope); addConfig(new InMemorySystemDescriptor(JOB_DEFAULT_SYSTEM).withInMemoryScope(inMemoryScope).toConfig()); }
Source:
<code>private void setupJackson(Injector injector, final ObjectMapper mapper) { final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector(); <START> mapper.setInjectableValues(injector.getInstance(InjectableValues.class)); <END> mapper.setAnnotationIntrospectors( new AnnotationIntrospectorPair( guiceIntrospector, mapper.getSerializationConfig().getAnnotationIntrospector() ), new AnnotationIntrospectorPair( guiceIntrospector, mapper.getDeserializationConfig().getAnnotationIntrospector() ) ); }</code><technical_language>I changes in this file effecting functional change. I done a attempt figure out wrong, issue copy() method ObjectMapper noticed</technical_language>

Target:
private void setupJackson(Injector injector, final ObjectMapper mapper) { final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector(); mapper.setInjectableValues(new GuiceInjectableValues(injector)); mapper.setAnnotationIntrospectors( new AnnotationIntrospectorPair( guiceIntrospector, mapper.getSerializationConfig().getAnnotationIntrospector() ), new AnnotationIntrospectorPair( guiceIntrospector, mapper.getDeserializationConfig().getAnnotationIntrospector() ) ); }
Source:
<code>private boolean cacheReadRequest(ReadOptions options) { <START> if (!runtime.getParameters().isCacheDisabled() && options.isClientCacheable()) { <END> return true; } return false; }</code><technical_language>return !runtime.getParameters().isCacheDisabled() && options.isClientCacheable();</technical_language>

Target:
private boolean cacheReadRequest(ReadOptions options) { if (runtime.getParameters().isCacheDisabled() && options.isClientCacheable()) { log.warn("read: Runtime cache is disabled, but read request is requesting to cache"); } return !runtime.getParameters().isCacheDisabled() && options.isClientCacheable(); }
Source:
<code>public void downloadAllNovelInfo() { <START> touchedForDownload = language + " Light Novels information"; <END> executeDownloadTask(listItems); }</code><technical_language>Ensure language is null</technical_language>

Target:
public void downloadAllNovelInfo() { if (language != null) { touchedForDownload = language + " Light Novels information"; executeDownloadTask(listItems); } }
Source:
<code>protected boolean canStoreClassClassic(final SootClass child, final SootClass parent) { SootClass sc = child; final boolean parentIsInterface = parent.isInterface(); while (sc != null) { <START> if (sc.getName().equals(parent.getName())) { <END> return true; } if (parentIsInterface) { for (SootClass interf : sc.getInterfaces()) { if (canStoreClassClassic(interf, parent)) { return true; } } } sc = sc.getSuperclassUnsafe(); } return false; }</code><technical_language>comparing names instead of object equality SootClasses directly? This a bit safer more time consuming String equality here. classes managed Scene guaranteed unique. IMHO, if this assumption hold, issue fixed there. This BTW break other components of Soot</technical_language>

Target:
protected boolean canStoreClassClassic(final SootClass child, final SootClass parent) { SootClass sc = child; final boolean parentIsInterface = parent.isInterface(); while (sc != null) { if (sc == parent) { return true; } if (parentIsInterface) { for (SootClass interf : sc.getInterfaces()) { if (canStoreClassClassic(interf, parent)) { return true; } } } sc = sc.getSuperclassUnsafe(); } return false; }
Source:
<code>private void logBrickStatusChange(GlusterVolumeEntity vol, GlusterStatus status, GlusterBrickEntity brick) { logUtil.logAuditMessage(vol.getClusterId(), vol, null, AuditLogType.GLUSTER_BRICK_STATUS_CHANGED, <START> new HashMap<String, String>() { { put(GlusterConstants.BRICK_PATH, brick.getQualifiedName()); put(GlusterConstants.OPTION_OLD_VALUE, brick.getStatus().toString()); put(GlusterConstants.OPTION_NEW_VALUE, status.toString()); put("source", "gluster event"); } }); <END> }</code><technical_language>pls create a local instance of HashMap populate instead of creating annonynous class</technical_language>

Target:
private void logBrickStatusChange(GlusterVolumeEntity vol, GlusterStatus status, GlusterBrickEntity brick) { Map<String, String> customValues = new HashMap<>(); customValues.put(GlusterConstants.BRICK_PATH, brick.getQualifiedName()); customValues.put(GlusterConstants.OPTION_OLD_VALUE, brick.getStatus().toString()); customValues.put(GlusterConstants.OPTION_NEW_VALUE, status.toString()); customValues.put(GlusterConstants.SOURCE, GlusterConstants.SOURCE_EVENT); logUtil.logAuditMessage(vol.getClusterId(), vol, null, AuditLogType.GLUSTER_BRICK_STATUS_CHANGED, customValues); }
Source:
<code>public boolean isDeleteProtectionEnabled(AuthenticatedContext ac, DatabaseStack dbStack) { AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); AmazonRDS rdsClient = awsClient.createRdsClient(credentialView, regionName); String dbInstanceIdentifier = dbStack.getDatabaseServer().getServerId(); DescribeDBInstancesRequest describeDBInstancesRequest = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceIdentifier); DescribeDBInstancesResult describeDBInstancesResult; try { LOGGER.debug("RDS Checking if delete protection is enabled"); describeDBInstancesResult = rdsClient.describeDBInstances(describeDBInstancesRequest); } catch (DBInstanceNotFoundException ex) { <START> LOGGER.debug("DB Instance does not exists! Therefor termination protection check is not relevant anymore: {}", ex.getMessage()); <END> return false; } catch (RuntimeException ex) { throw new CloudConnectorException(ex.getMessage(), ex); } return describeDBInstancesResult.getDBInstances() .stream() .findFirst() .get().getDeletionProtection(); }</code><technical_language>1) Typo: exists => exist 2) typo: therefor is a legit word, I a meaning: for it, for that. <LINK_0> I here</technical_language>

Target:
public boolean isDeleteProtectionEnabled(AuthenticatedContext ac, DatabaseStack dbStack) { AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); AmazonRDS rdsClient = awsClient.createRdsClient(credentialView, regionName); String dbInstanceIdentifier = dbStack.getDatabaseServer().getServerId(); DescribeDBInstancesRequest describeDBInstancesRequest = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceIdentifier); DescribeDBInstancesResult describeDBInstancesResult; try { LOGGER.debug("RDS Checking if delete protection is enabled"); describeDBInstancesResult = rdsClient.describeDBInstances(describeDBInstancesRequest); } catch (DBInstanceNotFoundException ex) { LOGGER.debug("DB Instance does not exist! Therefore termination protection check is not relevant anymore: {}", ex.getMessage()); return false; } catch (RuntimeException ex) { throw new CloudConnectorException(ex.getMessage(), ex); } return describeDBInstancesResult.getDBInstances() .stream() .findFirst() .get().getDeletionProtection(); }