auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean onTouchEvent(MotionEvent event) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { return false; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && MotionEventCompat.getSource(event) == InputDevice.SOURCE_MOUSE) { if (onMouseEvent(event, bridge)) { return true; } viewPager.setPagingEnabled(true); } super.onTouchEvent(event); if (gestureDetector != null) { gestureDetector.onTouchEvent(event); } return true; }

Target:
public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { refreshTextFromBuffer(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && MotionEventCompat.getSource(event) == InputDevice.SOURCE_MOUSE) { if (onMouseEvent(event, bridge)) { return true; } viewPager.setPagingEnabled(true); } else if (gestureDetector != null) { gestureDetector.onTouchEvent(event); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { if (bridge.isSelectingForCopy()) { SelectionArea area = bridge.getSelectionArea(); int row = (int) Math.floor(event.getY() / bridge.charHeight); int col = (int) Math.floor(event.getX() / bridge.charWidth); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: viewPager.setPagingEnabled(false); if (area.isSelectingOrigin()) { area.setRow(row); area.setColumn(col); lastTouchedRow = row; lastTouchedCol = col; bridge.redraw(); } return true; case MotionEvent.ACTION_MOVE: if (row == lastTouchedRow && col == lastTouchedCol) return true; area.finishSelectingOrigin(); area.setRow(row); area.setColumn(col); lastTouchedRow = row; lastTouchedCol = col; bridge.redraw(); return true; case MotionEvent.ACTION_UP: if (area.getLeft() == area.getRight() && area.getTop() == area.getBottom()) { return true; } String copiedText = area.copyFrom(bridge.buffer); clipboard.setText(copiedText); Toast.makeText( context, context.getString(R.string.console_copy_done, copiedText.length()), Toast.LENGTH_LONG).show(); case MotionEvent.ACTION_CANCEL: area.reset(); bridge.setSelectingForCopy(false); bridge.redraw(); viewPager.setPagingEnabled(true); return true; } } return true; } super.onTouchEvent(event); return true; }
Source:
public AutocompleteTextareaDOMElementFactory getAutocompleteTextareaFactory() { return new AutocompleteTextareaDOMElementFactory(gridPanel, gridLayer, this, sessionManager, sessionCommandManager, newCellHasNoValueCommand(), newCellHasValueCommand()); }

Target:
public AutocompleteTextAreaDOMElementFactory getAutocompleteTextareaFactory() { return new AutocompleteTextAreaDOMElementFactory(gridPanel, gridLayer, this, sessionManager, sessionCommandManager, newCellHasNoValueCommand(), newCellHasValueCommand()); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BlobId)) { return false; } BlobId blobId = (BlobId) o; if (!version.equals(blobId.version)) { return false; } if (!flag.equals(blobId.flag)) { return false; } if (!datacenterId.equals(blobId.datacenterId)) { return false; } if (!accountId.equals(blobId.accountId)) { return false; } if (!containerId.equals(blobId.containerId)) { return false; } if (!partitionId.equals(blobId.partitionId)) { return false; } return uuid.equals(blobId.uuid); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BlobId)) { return false; } BlobId blobId = (BlobId) o; return compareTo(blobId) == 0; }
Source:
public static void quickUpdatePageAAD(byte[] pageAAD, short newPageOrdinal) { byte[] pageOrdinalBytes = shortToBytesLE(newPageOrdinal); int length = pageAAD.length; System.arraycopy(pageOrdinalBytes, 0, pageAAD, length-2, 2); }

Target:
public static void quickUpdatePageAAD(byte[] pageAAD, short newPageOrdinal) { byte[] pageOrdinalBytes = shortToBytesLE(newPageOrdinal); System.arraycopy(pageOrdinalBytes, 0, pageAAD, pageAAD.length - 2, 2); }
Source:
public void updateImpl(List<Metric> metrics) { StatsDClient statsd = new NonBlockingStatsDClient(prefix, host, port, new ErrorHandler()); LOGGER.debug("sending data"); for (Metric metric : metrics) { String aspect = namingConvention.getName(metric); if (metric.hasNumberValue()) { statsd.recordGaugeValue(aspect, metric.getNumberValue().longValue()); } else { statsd.recordSetEvent(aspect, metric.getValue().toString()); } statsd.recordExecutionTime(aspect, metric.getTimestamp() / 1000); } statsd.stop(); }

Target:
public void updateImpl(List<Metric> metrics) { StatsDClient statsd = createClient(); LOGGER.debug("sending data"); for (Metric metric : metrics) { String aspect = namingConvention.getName(metric); if (metric.getConfig().getTags().getTag(DataSourceType.COUNTER.getValue()) != null) { statsd.count(aspect, metric.getNumberValue().longValue()); } else if (metric.hasNumberValue()) { statsd.gauge(aspect, metric.getNumberValue().longValue()); } else { statsd.set(aspect, metric.getValue().toString()); } statsd.time(aspect, metric.getTimestamp() / 1000); } statsd.stop(); }
Source:
public void testOverlap1() throws Exception { TestTransaction tx = new TestTransaction(env); tx.set("bob", BALANCE, "10"); tx.set("joe", BALANCE, "20"); tx.set("jill", BALANCE, "60"); tx.done(); tx = new TestTransaction(env); Assert.assertEquals("10", tx.gets("bob", BALANCE)); Assert.assertEquals("20", tx.gets("joe", BALANCE)); tx.set("bob", BALANCE, "5"); tx.set("joe", BALANCE, "25"); TestTransaction tx2 = new TestTransaction(env); Assert.assertEquals("10", tx2.gets("bob", BALANCE)); Assert.assertEquals("60", tx2.gets("jill", BALANCE)); tx2.set("bob", BALANCE, "5"); tx2.set("jill", BALANCE, "65"); tx2.done(); assertCommitFails(tx); TestTransaction tx3 = new TestTransaction(env); Assert.assertEquals("5", tx3.gets("bob", BALANCE)); Assert.assertEquals("20", tx3.gets("joe", BALANCE)); Assert.assertEquals("65", tx3.gets("jill", BALANCE)); tx3.done(); }

Target:
public void testOverlap1() throws Exception { TestTransaction tx = new TestTransaction(env); tx.set("bob", BALANCE, "10"); tx.set("joe", BALANCE, "20"); tx.set("jill", BALANCE, "60"); tx.done(); tx = new TestTransaction(env); Assert.assertEquals("10", tx.gets("bob", BALANCE)); Assert.assertEquals("20", tx.gets("joe", BALANCE)); TestUtil.increment(tx, "bob", BALANCE, -5); TestUtil.increment(tx, "joe", BALANCE, 5); TestTransaction tx2 = new TestTransaction(env); Assert.assertEquals("10", tx2.gets("bob", BALANCE)); Assert.assertEquals("60", tx2.gets("jill", BALANCE)); TestUtil.increment(tx2, "bob", BALANCE, -5); TestUtil.increment(tx2, "jill", BALANCE, 5); tx2.done(); assertCommitFails(tx); TestTransaction tx3 = new TestTransaction(env); Assert.assertEquals("5", tx3.gets("bob", BALANCE)); Assert.assertEquals("20", tx3.gets("joe", BALANCE)); Assert.assertEquals("65", tx3.gets("jill", BALANCE)); tx3.done(); }
Source:
public void setTracerRegistry(TracerRegistry tracerRegistry) { this.m_tracerRegistry = tracerRegistry; }

Target:
public void setTracerRegistry(TracerRegistry tracerRegistry) { m_tracerRegistry = tracerRegistry; }
Source:
private void validatePropertyNodeXorLiteralPropertyNode() { Validate.isTrue(propertyNode != null ^ literalPropertyNode != null); }

Target:
private void validatePropertyNodeXorLiteralPropertyNode() { Validate.isTrue( propertyNode != null ^ literalPropertyNode != null, "The property node must be non-null xor the literal property node must be non-null"); }
Source:
public void onGetTotalNumberOfPages() { final QueryAllImpl<Category, CategoryQuery> query = QueryAllImpl.of(CategoryQuery.of(), 2); long totalNumberOfPages = query.getTotalNumberOfPages(10); assertThat(totalNumberOfPages).isEqualTo(5); totalNumberOfPages = query.getTotalNumberOfPages(7); assertThat(totalNumberOfPages).isEqualTo(4); }

Target:
public void onGetTotalNumberOfPages() { final QueryAllImpl query1 = QueryAllImpl.of(CategoryQuery.of(), 1); assertThat(query1.getTotalNumberOfPages(0)).isEqualTo(0); assertThat(query1.getTotalNumberOfPages(1)).isEqualTo(1); assertThat(query1.getTotalNumberOfPages(2)).isEqualTo(2); assertThat(query1.getTotalNumberOfPages(3)).isEqualTo(3); assertThat(query1.getTotalNumberOfPages(4)).isEqualTo(4); final QueryAllImpl query2 = QueryAllImpl.of(CategoryQuery.of(), 2); assertThat(query2.getTotalNumberOfPages(0)).isEqualTo(0); assertThat(query2.getTotalNumberOfPages(1)).isEqualTo(1); assertThat(query2.getTotalNumberOfPages(2)).isEqualTo(1); assertThat(query2.getTotalNumberOfPages(3)).isEqualTo(2); assertThat(query2.getTotalNumberOfPages(7)).isEqualTo(4); assertThat(query2.getTotalNumberOfPages(9)).isEqualTo(5); assertThat(query2.getTotalNumberOfPages(10)).isEqualTo(5); assertThat(query2.getTotalNumberOfPages(11)).isEqualTo(6); final QueryAllImpl query7 = QueryAllImpl.of(CategoryQuery.of(), 7); assertThat(query7.getTotalNumberOfPages(0)).isEqualTo(0); assertThat(query7.getTotalNumberOfPages(1)).isEqualTo(1); assertThat(query7.getTotalNumberOfPages(6)).isEqualTo(1); assertThat(query7.getTotalNumberOfPages(7)).isEqualTo(1); assertThat(query7.getTotalNumberOfPages(8)).isEqualTo(2); assertThat(query7.getTotalNumberOfPages(9)).isEqualTo(2); assertThat(query7.getTotalNumberOfPages(699)).isEqualTo(100); assertThat(query7.getTotalNumberOfPages(700)).isEqualTo(100); assertThat(query7.getTotalNumberOfPages(701)).isEqualTo(101); assertThat(query7.getTotalNumberOfPages(702)).isEqualTo(101); final QueryAllImpl queryMax = QueryAllImpl.of(CategoryQuery.of(), Integer.MAX_VALUE); assertThat(queryMax.getTotalNumberOfPages(0)).isEqualTo(0); assertThat(queryMax.getTotalNumberOfPages(1)).isEqualTo(1); assertThat(queryMax.getTotalNumberOfPages(Integer.MAX_VALUE - 1)).isEqualTo(1); assertThat(queryMax.getTotalNumberOfPages(Integer.MAX_VALUE)).isEqualTo(1); }
Source:
private void parseProperties() { for(String arg : getUsageArguments()) { ParserArgument argument = new ParserArgument(); argument.setName( getArgAttrValue(arg, "name") ); if (argument.getName() == null) { throw new IllegalArgumentException( String.format("Invalid configuration. Parameter '%1$s' has no name", arg) ); } argument.setMetavar( getArgAttrValue(arg, "metavar") ); argument.setHelp( getArgAttrValue(arg, "help") ); argument.setDefaultValue( getArgAttrValue(arg, "default") ); argument.setMultivalue( Boolean.parseBoolean( getArgAttrValue(arg, "multivalue") ) ); argument.setMandatory( Boolean.parseBoolean( getArgAttrValue(arg, "mandatory") ) ); argument.setType( ParametersParser.ArgumentType.valueOf( getArgAttrValue(arg, "type") ) ); argument.setMatcher( Pattern.compile( getArgAttrValue(arg, "matcher") ) ); try { argument.setConvert( argument.getType() != ArgumentType.no_argument ? Boolean.class : Class.forName( getArgAttrValue(arg, "convert"), true, Thread.currentThread().getContextClassLoader() ) ); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( String.format("Can't convert argument: '%1$s'. Please check convert class in properties file.", arg) ); } if (argument.isMandatory()) { mandatory.add(argument.getName()); } if (argument.getDefaultValue() != null) { defaults.add(String.format("%1$s%2$s=%3$s", LONG_PREFIX, argument.getName(), argument.getDefaultValue())); } arguments.put(argument.getName(), argument); } }

Target:
private void parseProperties() { for(String arg : getUsageArguments()) { ParserArgument argument = new ParserArgument(); argument.setName( getArgAttrValue(arg, "name") ); if (argument.getName() == null) { throw new IllegalArgumentException( String.format("Invalid configuration. Parameter '%1$s' has no name", arg) ); } argument.setMetavar( getArgAttrValue(arg, "metavar") ); argument.setHelp( getArgAttrValue(arg, "help") ); argument.setDefaultValue( getArgAttrValue(arg, "default") ); argument.setMultivalue( Boolean.parseBoolean( getArgAttrValue(arg, "multivalue") ) ); argument.setValue( Boolean.parseBoolean( getArgAttrValue(arg, "value") ) ); argument.setMandatory( Boolean.parseBoolean( getArgAttrValue(arg, "mandatory") ) ); argument.setType( ParametersParser.ArgumentType.valueOf( getArgAttrValue(arg, "type") ) ); argument.setMatcher( Pattern.compile( getArgAttrValue(arg, "matcher") ) ); try { argument.setConvert( Class.forName( getArgAttrValue(arg, "convert"), true, Thread.currentThread().getContextClassLoader() ) ); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( String.format("Can't convert argument: '%1$s'. Please check convert class in properties file.", arg) ); } if (argument.isMandatory()) { mandatory.add(argument.getName()); } arguments.put(argument.getName(), argument); } }
Source:
private boolean hasPermission(String sid, Permission p, RoleType roleType, AccessControlled controlledItem) { for(Role role : getRolesHavingPermission(p)) { if(this.grantedRoles.get(role).contains(sid)) { if (Macro.isMacro(role)) { Macro macro = RoleMacroExtension.getMacro(role.getName()); if (macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType) && macroExtension.hasPermission(sid, p, roleType, controlledItem, macro)) { return true; } } } else { return true; } } else { try { UserDetails userDetails = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(sid); for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(role.getName())) { return true; } } } catch (Exception e) } } return false; }

Target:
private boolean hasPermission(String sid, Permission p, RoleType roleType, AccessControlled controlledItem) { for(Role role : getRolesHavingPermission(p)) { if(this.grantedRoles.get(role).contains(sid)) { if (Macro.isMacro(role)) { Macro macro = RoleMacroExtension.getMacro(role.getName()); if (macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType) && macroExtension.hasPermission(sid, p, roleType, controlledItem, macro)) { return true; } } } else { return true; } } else { try { UserDetails userDetails = cache.getIfPresent(sid); if (userDetails == null) { userDetails = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(sid); cache.put(sid, userDetails); } for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(role.getName())) { return true; } } } catch (BadCredentialsException e) { LOGGER.log(Level.FINE, "Bad credentials", e); } catch (DataAccessException e) { LOGGER.log(Level.FINE, "failed to access the data", e); } } } return false; }
Source:
public int deleteEventsBefore(long time) { final SQLiteDatabase db = this.helper.getWritableDatabase(); final String whereClause = "date < ?"; final int endDay = this.getDay(time); final String dayString = Integer.toString(endDay, 10); final String[] whereArgs = new String[] {dayString}; int numRowsDeleted = db.delete(EVENTS_TEXTUAL, whereClause, whereArgs); numRowsDeleted += db.delete(EVENTS_INTEGER, whereClause, whereArgs); return numRowsDeleted; }

Target:
public int deleteEventsBefore(long time) { final SQLiteDatabase db = this.helper.getWritableDatabase(); final String whereClause = "date < ?"; final int endDay = this.getDay(time); final String dayString = Integer.toString(endDay, 10); final String[] whereArgs = new String[] {dayString}; int numRowsDeleted = 0; db.beginTransaction(); try { numRowsDeleted += db.delete(EVENTS_TEXTUAL, whereClause, whereArgs); numRowsDeleted += db.delete(EVENTS_INTEGER, whereClause, whereArgs); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return numRowsDeleted; }
Source:
private void formatAllowableHeaders(Set<String> allowedHeaderNames, HttpHeaders requestResponseHeaders, ClientLogger logger) { if (!allowedHeaderNames.isEmpty()) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : requestResponseHeaders) { sb.append(header.getName()).append(":"); if (allowedHeaderNames.contains(header.getName())) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); } }

Target:
private void formatAllowableHeaders(Set<String> allowedHeaderNames, HttpHeaders requestResponseHeaders, ClientLogger logger) { if (!allowedHeaderNames.isEmpty()) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : requestResponseHeaders) { sb.append(header.getName()).append(":"); if (allowedHeaderNames.stream().anyMatch(header.getName()::equalsIgnoreCase)) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); } }
Source:
private boolean parsePath(Parser parser, List<Class<? extends Edge>> path) { boolean accept = false; int currentState = 0; for (Class<? extends Edge> edgeClass : path) { State state = mock(State.class); Edge edge = mock(edgeClass); when(state.getBackEdge()).thenReturn(edge); int terminal = parser.terminalFor(state); currentState = parser.transition(currentState, terminal); if (currentState == AutomatonState.REJECT) { return false; } } if (parser.accepts(currentState)) { accept = true; } return accept; }

Target:
private boolean parsePath(Parser parser, List<Class<? extends Edge>> path) { boolean accepted = false; int currentState = AutomatonState.START; for (Class<? extends Edge> edgeClass : path) { State state = mock(State.class); Edge edge = mock(edgeClass); when(state.getBackEdge()).thenReturn(edge); int terminal = parser.terminalFor(state); currentState = parser.transition(currentState, terminal); if (currentState == AutomatonState.REJECT) { return false; } } if (parser.accepts(currentState)) { accepted = true; } return accepted; }
Source:
private Instant convertToDateTime(Object value) { try { return value != null ? Instant.ofEpochMilli(Double.valueOf(value.toString()).longValue()) : null; } catch (NumberFormatException e) { throw new ValueConversionException(value, DATE_TIME, e); } }

Target:
private Instant convertToDateTime(Object value) { try { return value != null ? Instant.ofEpochMilli(Double.valueOf(value.toString()).longValue()) : null; } catch (NumberFormatException e) { throw new AlgorithmValueConversionException(value, DATE_TIME, e); } }
Source:
public Response start(Action action) { RunVmOnceParams params = map(get(), new RunVmOnceParams(guid)); if (action.isSetVm()) { validateEnums(VM.class, action.getVm()); VM vm = action.getVm(); params = map(vm, params); if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetHost()) { validateParameters(vm.getPlacementPolicy(), "host.id|name"); params.setDestinationVdsId(getHostId(vm.getPlacementPolicy().getHost())); } } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } return doAction(VdcActionType.RunVmOnce, setReinitializeSysPrep(params), action); }

Target:
public Response start(Action action) { RunVmOnceParams params = map(map(getEntity(entityType, VdcQueryType.GetVmByVmId, new GetVmByVmIdParameters(guid), id, true), new VM()), new RunVmOnceParams(guid)); if (action.isSetVm()) { validateEnums(VM.class, action.getVm()); VM vm = action.getVm(); params = map(vm, params); if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetHost()) { validateParameters(vm.getPlacementPolicy(), "host.id|name"); params.setDestinationVdsId(getHostId(vm.getPlacementPolicy().getHost())); } } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } return doAction(VdcActionType.RunVmOnce, setReinitializeSysPrep(params), action); }
Source:
public void testConfigValidations() { final KafkaSystemConsumer consumer = setupConsumer(FETCH_THRESHOLD_MSGS, FETCH_THRESHOLD_BYTES); consumer.start(); }

Target:
public void testConfigValidations() { final KafkaSystemConsumer consumer = createConsumer(FETCH_THRESHOLD_MSGS, FETCH_THRESHOLD_BYTES); consumer.start(); }
Source:
public String getDisplayName() { if (isAttributeExist(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) { return LambdaExceptionUtils.rethrowSupplier( () -> ((SimpleAttribute) attributeList.get(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) .getStringValue()).get(); } else { return null; } }

Target:
public String getDisplayName() { if (isAttributeExist(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) { return LambdaExceptionUtils.rethrowSupplier( () -> ((SimpleAttribute) attributeList.get(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) .getStringValue()).get(); } return null; }
Source:
public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) { boolean isHA = (rmId != null); rmId = isHA ? ("." + rmId) : ""; if (isHA) { conf = getYarnConfiguration(conf); conf.set(ConfigUtils.RM_HA_ID, rmId); } InetSocketAddress address; if (sslEnabled) { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT); } else { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT); } if (isHA) { conf.unset(ConfigUtils.RM_HA_ID); } LOG.info("rm webapp address setting {}", address); LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS)); InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address); InetAddress resolved = resolvedSocketAddress.getAddress(); if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) { try { resolvedSocketAddress = InetSocketAddress.createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort()); } catch (UnknownHostException e) { } } return resolvedSocketAddress; }

Target:
public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) { boolean isHA = (rmId != null); if (isHA) { conf = getYarnConfiguration(conf); conf.set(ConfigUtils.RM_HA_ID, rmId); } InetSocketAddress address; if (sslEnabled) { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT); } else { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT); } if (isHA) { conf.unset(ConfigUtils.RM_HA_ID); } LOG.info("rm webapp address setting {}", address); LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS)); InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address); InetAddress resolved = resolvedSocketAddress.getAddress(); if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) { try { resolvedSocketAddress = InetSocketAddress.createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort()); } catch (UnknownHostException e) { } } return resolvedSocketAddress; }
Source:
private static String getLocalCanonicalHostName() { try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(Locale.US); } catch (UnknownHostException e) { throw new RuntimeException(e); } }

Target:
private static String getLocalCanonicalHostName() { try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(Locale.US); } catch (UnknownHostException e) { throw new UncheckedIOException(e); } }
Source:
public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, MiddlewareQueryException, FieldbookException { return this.namingConventionService.advanceNursery(advanceInfo, workbook); }

Target:
public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, FieldbookException { return this.namingConventionService.advanceNursery(advanceInfo, workbook); }
Source:
public void testFollow() { TmfTraceManager traceManager = TmfTraceManager.getInstance(); ITmfTrace ust = traceManager.getActiveTrace(); assertNotNull(ust); ITmfTrace kernelTest = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.CONTEXT_SWITCHES_KERNEL); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, kernelTest.getPath(), TRACETYPE_ID); SWTBotEditor kernelEditor = SWTBotUtils.activateEditor(fBot, kernelTest.getName()); fBot.editorByTitle(kernelTest.getName()); ITmfTrace kernel = traceManager.getActiveTrace(); assertNotNull(kernel); SWTBotTable kernelEventTable = kernelEditor.bot().table(); SWTBotTableItem kernelEvent = kernelEventTable.getTableItem(5); kernelEvent.contextMenu("Follow time updates from other traces").click(); SWTBotUtils.activateEditor(fBot, ust.getName()); TmfTimeRange r = updateTimeRange(ust, UST_START + SECOND, UST_START + 2 * SECOND); IWorkbenchPart part = fOriginalViewBot.getViewReference().getPart(false); assertTrue(part instanceof AbstractTimeGraphView); AbstractTimeGraphView abstractTimeGraphView = (AbstractTimeGraphView) part; fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, ust, r)); SWTBotUtils.activateEditor(fBot, kernel.getName()); fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, kernel, r)); kernelTest.dispose(); }

Target:
public void testFollow() { TmfTraceManager traceManager = TmfTraceManager.getInstance(); ITmfTrace ust = traceManager.getActiveTrace(); assertNotNull(ust); ITmfTrace kernelTest = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.CONTEXT_SWITCHES_KERNEL); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, kernelTest.getPath(), TRACETYPE_ID); SWTBotEditor kernelEditor = SWTBotUtils.activateEditor(fBot, kernelTest.getName()); fBot.editorByTitle(kernelTest.getName()); ITmfTrace kernel = traceManager.getActiveTrace(); assertNotNull(kernel); SWTBotTable kernelEventTable = kernelEditor.bot().table(); SWTBotTableItem kernelEvent = kernelEventTable.getTableItem(5); kernelEvent.contextMenu("Follow time updates from other traces").click(); SWTBotUtils.activateEditor(fBot, ust.getName()); TmfSignalManager.dispatchSignal(new TmfWindowRangeUpdatedSignal(this, RANGE, ust)); IWorkbenchPart part = fOriginalViewBot.getViewReference().getPart(false); assertTrue(part instanceof AbstractTimeGraphView); AbstractTimeGraphView abstractTimeGraphView = (AbstractTimeGraphView) part; fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, ust, RANGE)); SWTBotUtils.activateEditor(fBot, kernel.getName()); fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, kernel, RANGE)); kernelTest.dispose(); }
Source:
public boolean isCorrectRequiredValue(ValueResult result) { if (result == null || !result.isValueDefined()) { return false; } final String value = result.getValueObject(); final boolean correct; final TextAreaType type = TextAreaType.fromCode(getType()); if (type == TextAreaType.DATE) { correct = isCorrectRequiredDateValue(value); } else if (type == TextAreaType.NUMBER) { correct = isCorrectRequiredNumberValue(value); } else { correct = isCorrectRequiredStringValue(value); } return correct; }

Target:
public boolean isCorrectRequiredValue(ValueResult result) { if (result == null || !result.isValueDefined()) { return false; } final String value = result.getValueObject(); final boolean correct; final TextAreaType type = TextAreaType.fromCode(getType()); if (type != null) switch (type) { case DATE: correct = isCorrectRequiredDateValue(value); break; case NUMBER: correct = isCorrectRequiredNumberValue(value); break; case PARAGRAPH: case TEXT: correct = isCorrectRequiredStringValue(value); break; default: throw new UnsupportedOperationException("Given type '" + type + "' is not supported yet."); } else { Log.warn("No textarea type is specified for the textarea element '" + getLabel() + "'. Using paragraph instead."); correct = isCorrectRequiredStringValue(value); } return correct; }
Source:
public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; }

Target:
public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { if (buffer == null || sessionProposedCapacity < 0) { return buffer; } if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; }
Source:
protected void addWorkerToIdleChain(Worker worker) { while (true) { Worker casWorker = idleWorker.get(); worker.nextIdleWorker = casWorker; if (idleWorker.compareAndSet(casWorker, worker)) { break; } } }

Target:
protected void addWorkerToIdleChain(Worker worker) { idleWorkerCount.incrementAndGet(); while (true) { Worker casWorker = idleWorker.get(); worker.nextIdleWorker = casWorker; if (idleWorker.compareAndSet(casWorker, worker)) { break; } } }
Source:
public void send(DatastreamProducerRecord record, SendCallback sendCallback) { try { validateEventRecord(record); record.serializeEvents(_datastreamTask.getDestinationSerDes()); String destination = record.getDestination().orElse(_datastreamTask.getDatastreamDestination().getConnectionString()); record.setEventsSendTimestamp(System.currentTimeMillis()); _transportProvider.send(destination, record, (metadata, exception) -> onSendCallback(metadata, exception, sendCallback, record)); } catch (Exception e) { String errorMessage = String.format("Failed send the event %s exception %s", record, e); _logger.warn(errorMessage, e); if (_skipBadMessagesEnabled) { _logger.error("Skipping Message. task: ; error: {}", _datastreamTask, e); _dynamicMetricsManager.createOrUpdateCounter(MODULE, _datastreamName, SKIPPED_BAD_MESSAGES_RATE, 1); } else { throw new DatastreamRuntimeException(errorMessage, e); } } if (Instant.now().isAfter(_lastFlushTime.plus(_flushInterval))) { flush(); } }

Target:
public void send(DatastreamProducerRecord record, SendCallback sendCallback) { try { validateEventRecord(record); record.serializeEvents(_datastreamTask.getDestinationSerDes()); String destination = record.getDestination().orElse(_datastreamTask.getDatastreamDestination().getConnectionString()); record.setEventsSendTimestamp(System.currentTimeMillis()); _transportProvider.send(destination, record, (metadata, exception) -> onSendCallback(metadata, exception, sendCallback, record)); } catch (Exception e) { String errorMessage = String.format("Failed send the event %s exception %s", record, e); _logger.warn(errorMessage, e); if (_skipBadMessagesEnabled) { _logger.error("Skipping Message. task: ; error: {}", _datastreamTask, e); _dynamicMetricsManager.createOrUpdateCounter(MODULE, _datastreamName, SKIPPED_BAD_MESSAGES_COUNTER, 1); } else { throw new DatastreamRuntimeException(errorMessage, e); } } if (Instant.now().isAfter(_lastFlushTime.plus(_flushInterval))) { flush(); } }
Source:
public void cancelSetupTotp() throws Exception { doAIA(); loginPage.login("test-user@localhost", "password"); totpPage.assertCurrent(); totpPage.cancel(); assertRedirectSuccess(); }

Target:
public void cancelSetupTotp() throws Exception { doAIA(); loginPage.login("test-user@localhost", "password"); totpPage.assertCurrent(); totpPage.cancel(); assertRedirectSuccess(); assertCancelMessage(); }
Source:
Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> resolve(EngineDiscoveryRequest request, Predicate<Class<?>> classFilter) { Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> filteredTestClasses = new LinkedHashMap<>(); BiConsumer<Class<?>, RunnerTestDescriptorAwareFilter> addFilter = (testClass, filter) -> filteredTestClasses.computeIfAbsent(testClass, key -> new LinkedList<>()).add(filter); methodSelectorResolver.resolve(request, classFilter, addFilter); uniqueIdSelectorResolver.resolve(request, classFilter, addFilter); return filteredTestClasses; }

Target:
Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> resolve(EngineDiscoveryRequest request, Predicate<Class<?>> classFilter) { Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> filteredTestClasses = new LinkedHashMap<>(); BiConsumer<Class<?>, RunnerTestDescriptorAwareFilter> addFilter = (testClass, filter) -> filteredTestClasses.computeIfAbsent(testClass, key -> new ArrayList<>()).add(filter); methodSelectorResolver.resolve(request, classFilter, addFilter); uniqueIdSelectorResolver.resolve(request, classFilter, addFilter); return filteredTestClasses; }
Source:
public void testOnActiveFilterAdded() { ActiveFilterItem testActiveFilterItem = new ActiveFilterItem(Constants.INSTANCE.State(), "test lable", null, Arrays.asList("Active"), null); presenter.onActiveFilterAdded(testActiveFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.State(), "Active"); ActiveFilterItem activeWithErrorsFilterItem = new ActiveFilterItem("errorCount", "test lable", null, Arrays.asList("0"), null); presenter.onActiveFilterAdded(activeWithErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "true"); ActiveFilterItem activeWithoutErrorsFilterItem = new ActiveFilterItem("errorCount", "test lable", null, Arrays.asList("1"), null); presenter.onActiveFilterAdded(activeWithoutErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "false"); }

Target:
public void testOnActiveFilterAdded() { ActiveFilterItem testActiveFilterItem = new ActiveFilterItem(Constants.INSTANCE.State(), "test label", null, Arrays.asList("Active"), null); presenter.onActiveFilterAdded(testActiveFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.State(), "Active"); ActiveFilterItem activeWithErrorsFilterItem = new ActiveFilterItem("errorCount", "test label", null, Arrays.asList("0"), null); presenter.onActiveFilterAdded(activeWithErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "0"); ActiveFilterItem activeWithoutErrorsFilterItem = new ActiveFilterItem("errorCount", "test label", null, Arrays.asList("1"), null); presenter.onActiveFilterAdded(activeWithoutErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "1"); }
Source:
public String toString() { String version = ""; if (major != null) { version += String.valueOf(major); } if (minor != null) { String minorInString = String.valueOf(minor); if (minorInString.length() < 2) { minorInString = "0" + minorInString; } version += "." + minorInString; } if (patch != null) { version += "." + patch; } return version; }

Target:
public String toString() { return originalRepresentation.replace('-', '.'); }
Source:
public Map<String, Object> getMetadata(@NonNull String section) { if (section != null) { return impl.getMetadata(section); } else { error("getMetadata"); return null; } }

Target:
public Map<String, Object> getMetadata(@NonNull String section) { if (section != null) { return impl.getMetadata(section); } else { logNull("getMetadata"); return null; } }
Source:
public HadoopDruidIndexerConfig getHadoopDruidIndexerConfig() { if(config == null) { try { if (argumentSpec.startsWith("{")) { config = HadoopDruidIndexerConfig.fromString(argumentSpec); } else { URI argumentSpecUri = new URI(argumentSpec); String argumentSpecScheme = argumentSpecUri.getScheme(); if ((argumentSpecScheme == null) || argumentSpecScheme.equals("file")) { config = HadoopDruidIndexerConfig.fromFile(new File(argumentSpecUri.getPath())); } else { config = HadoopDruidIndexerConfig.fromDistributedFileSystem(argumentSpec); } } } catch (Exception e) { throw Throwables.propagate(e); } } return config; }

Target:
public HadoopDruidIndexerConfig getHadoopDruidIndexerConfig() { if(config == null) { try { if (argumentSpec.startsWith("{")) { config = HadoopDruidIndexerConfig.fromString(argumentSpec); } else { File localConfigFile = null; try { final URI argumentSpecUri = new URI(argumentSpec); final String argumentSpecScheme = argumentSpecUri.getScheme(); if (argumentSpecScheme == null || argumentSpecScheme.equals("file")) { localConfigFile = new File(argumentSpecUri.getPath()); } } catch (URISyntaxException e) { localConfigFile = new File(argumentSpec); } if (localConfigFile != null) { config = HadoopDruidIndexerConfig.fromFile(localConfigFile); } else { config = HadoopDruidIndexerConfig.fromDistributedFileSystem(argumentSpec); } } } catch (Exception e) { throw Throwables.propagate(e); } } return config; }
Source:
public TimelineSyncImpl(final ZooKeeperHolder zooKeeperHolder, final UUIDGenerator uuidGenerator) { this.thisId = uuidGenerator.randomUUID().toString(); this.log = LoggerFactory.getLogger("timelines.sync." + thisId); this.zooKeeperHolder = zooKeeperHolder; this.initializeZkStructure(); }

Target:
public TimelineSyncImpl(final ZooKeeperHolder zooKeeperHolder, final UUIDGenerator uuidGenerator) throws InterruptedException { this.nodeId = uuidGenerator.randomUUID().toString(); this.zooKeeperHolder = zooKeeperHolder; this.initializeZkStructure(); }
Source:
public SourceConfiguration build() { final Set<String> remainingParams = new HashSet(); requiredParameters.stream() .filter(s -> !configMap.containsKey(s)) .forEach(s -> remainingParams.add(s)); if (!remainingParams.isEmpty()) { final StringBuilder stringBuilder = new StringBuilder("Missing Configuration for " + this.getClass().getName()); stringBuilder.append(": ["); remainingParams.stream() .forEach(s -> stringBuilder.append(s + ", ")); stringBuilder.append("]"); throw new IllegalStateException(stringBuilder.toString()); } return new DefaultSourceConfigurationImpl(configMap); }

Target:
public SourceConfiguration build() { Stream<String> missingParams = requiredParameters.stream() .filter(s -> !configMap.containsKey(s)); if (missingParams.count() > 0) { final StringBuilder stringBuilder = new StringBuilder("Missing Configuration for " + this.getClass().getName()); stringBuilder.append(": ["); missingParams .forEach(s -> stringBuilder.append(s + ", ")); stringBuilder.append("]"); throw new IllegalStateException(stringBuilder.toString()); } return new DefaultSourceConfigurationImpl(configMap); }
Source:
public Response commitBranch(long branchUuid, long destinationBranchUuid, BranchCommitOptions options) { BranchReadable srcBranch = getBranchById(branchUuid); BranchReadable destBranch = getBranchById(destinationBranchUuid); ArtifactReadable committer = getArtifactById(COMMON_ID, options.getCommitterId()); Callable<TransactionReadable> op = getBranchOps().commitBranch(committer, srcBranch, destBranch); TransactionReadable tx = executeCallable(op); if (options.isArchive()) { Callable<?> op2 = getBranchOps().archiveUnarchiveBranch(srcBranch, ArchiveOperation.ARCHIVE); executeCallable(op2); } UriInfo uriInfo = getUriInfo(); URI location = getTxLocation(uriInfo, tx); activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Commit Branch {branchUUID: %s srcBranch: %s destBranch: %s accountId: %s serverId: %s clientId: %s}", branchUuid, srcBranch.toString(), destBranch.toString(), accountId, serverId, clientId)); return Response.created(location).entity(asTransaction(tx)).build(); }

Target:
public Response commitBranch(long branchUuid, long destinationBranchUuid, BranchCommitOptions options) { BranchReadable srcBranch = getBranchById(branchUuid); BranchReadable destBranch = getBranchById(destinationBranchUuid); ArtifactReadable committer = getArtifactById(COMMON_ID, options.getCommitterId()); Callable<TransactionReadable> op = getBranchOps().commitBranch(committer, srcBranch, destBranch); TransactionReadable tx = executeCallable(op); if (options.isArchive()) { Callable<?> op2 = getBranchOps().archiveUnarchiveBranch(srcBranch, ArchiveOperation.ARCHIVE); executeCallable(op2); } UriInfo uriInfo = getUriInfo(); URI location = getTxLocation(uriInfo, tx); try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Commit Branch {branchUUID: %s srcBranch: %s destBranch: %s accountId: %s serverId: %s clientId: %s}", branchUuid, srcBranch.toString(), destBranch.toString(), RestUtil.getAccountId(httpHeaders), RestUtil.getServerId(httpHeaders), RestUtil.getClientId(httpHeaders))); } catch (OseeCoreException ex) { OseeLog.log(ActivityLog.class, OseeLevel.SEVERE_POPUP, ex); } return Response.created(location).entity(asTransaction(tx)).build(); }
Source:
protected void removeChildVisual(final EditPart childEditPart) { boolean visible = true; if (childEditPart.getModel() instanceof AdapterDeclaration) { visible = isVarVisible(); } if (childEditPart instanceof InterfaceEditPart){ if (((InterfaceEditPart) childEditPart).getModel().isIsInput()) { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); if (((InterfaceEditPart) childEditPart).isEvent()) { getLeftEventInterfaceContainer().remove(child); } else { if (visible) { getLeftVarInterfaceContainer().remove(child); } else{ getLeftInterfaceContainer().remove(child); } } } else { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); if (((InterfaceEditPart) childEditPart).isEvent()) { getRightEventInterfaceContainer().remove(child); } else { if (visible) { getRightVarInterfaceContainer().remove(child); } else { getRightInterfaceContainer().remove(child); } } } } else { super.removeChildVisual(childEditPart); } }

Target:
protected void removeChildVisual(final EditPart childEditPart) { if (childEditPart instanceof InterfaceEditPart) { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); getChildVisualContainer(childEditPart).remove(child); } else { super.removeChildVisual(childEditPart); } }
Source:
public ResponseEntity<?> getAppList() { org.geoserver.platform.resource.Resource appRoot = scriptManager.app(); List<Resource> apps = Resources.list(appRoot, Resources.DirectoryFilter.INSTANCE); JSONArray array = new JSONArray(); for (org.geoserver.platform.resource.Resource f : apps) { array.add(f.name()); } JSONObject obj = new JSONObject(); obj.put("scripts", array); return new ResponseEntity<String>(obj.toString(2), HttpStatus.OK); }

Target:
public ResponseEntity<?> getAppList() { Resource appRoot = scriptManager.app(); List<Resource> apps = Resources.list(appRoot, Resources.DirectoryFilter.INSTANCE); JSONArray array = new JSONArray(); for (Resource f : apps) { array.add(f.name()); } JSONObject obj = new JSONObject(); obj.put("scripts", array); return new ResponseEntity<String>(obj.toString(2), HttpStatus.OK); }
Source:
protected void execute() { chassis.moveCartesian(controller.getX(), controller.getY(), controller.getTurnSpeed()); motorSpeeds = chassis.getMotorSpeeds(); StringBuilder motorSpeedsString = new StringBuilder(); motorSpeedsString.append("Motor speeds: "); for (int i = 0; i < motorSpins.length; i++) { LogKitten.d(Double.toString(motorSpeeds[i])); motorSpins[i].set(motorSpeeds[i]); motorSpeedsString.append(motorSpeeds[i]); motorSpeedsString.append(' '); } LogKitten.d("ChassisMove executing"); LogKitten.d(motorSpeedsString.toString()); }

Target:
protected void execute() { chassis.moveCartesian(controller.getX(), controller.getY(), controller.getTurnSpeed()); motorSpeeds = chassis.getMotorSpeeds(); StringBuilder motorSpeedsString = new StringBuilder(); motorSpeedsString.append("Motor speeds:"); for (int i = 0; i < motorSpins.length; i++) { LogKitten.d(Double.toString(motorSpeeds[i])); motorSpins[i].set(motorSpeeds[i]); motorSpeedsString.append(' '); motorSpeedsString.append(motorSpeeds[i]); } LogKitten.d("ChassisMove executing"); LogKitten.d(motorSpeedsString.toString()); }
Source:
private int openSocket(final int port) throws IOException { serverSocket = new ServerSocket(port); String threadName = String.format("elasticjob-snapshot-service-%d", port); new Thread(() -> { while (!closed) { try { process(serverSocket.accept()); } catch (final IOException ex) { if (isIgnoredException()) { return; } log.error("ElasticJob: Snapshot service open socket failure, error is: ", ex); } } }, threadName).start(); return serverSocket.getLocalPort(); }

Target:
private int openSocket(final int port) throws IOException { serverSocket = new ServerSocket(port); int localPort = serverSocket.getLocalPort(); String threadName = String.format("elasticjob-snapshot-service-%d", localPort); new Thread(() -> { while (!closed) { try { process(serverSocket.accept()); } catch (final IOException ex) { if (isIgnoredException()) { return; } log.error("ElasticJob: Snapshot service open socket failure, error is: ", ex); } } }, threadName).start(); return localPort; }
Source:
public Object evaluateOn(Object o, FunctionWithArgs f, boolean deepEvaluation) { if (f.getArgs()==null) throw new IllegalStateException("Invalid function-only expression '"+f.getFunction()+"'"); Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>)o; } else { clazz = o.getClass(); } if (!(clazz.getPackage().getName().startsWith(BrooklynDslCommon.class.getPackage().getName()))) throw new IllegalArgumentException("Not permitted to invoke function on '"+clazz+"' (outside allowed package scope)"); String fn = f.getFunction(); fn = Strings.removeFromStart(fn, "$brooklyn:"); if (fn.startsWith("function.")) { for (Class<?> c : clazz.getClasses()) { if (c.equals(BrooklynDslCommon.Functions.class)) { if (o instanceof Class) { o = c; } break; } } fn = Strings.removeFromStart(fn, "function."); } try { List<Object> args = new ArrayList<Object>(); for (Object arg: f.getArgs()) { args.add( deepEvaluation ? evaluate(arg, true) : arg ); } Optional<Object> v = Reflections.invokeMethodWithArgs(o, fn, args); if (v.isPresent()) return v.get(); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw Exceptions.propagate(new InvocationTargetException(e, "Error invoking '"+fn+"' on '"+o+"'")); } throw new IllegalArgumentException("No such function '"+fn+"' on "+o); }

Target:
public Object evaluateOn(Object o, FunctionWithArgs f, boolean deepEvaluation) { if (f.getArgs()==null) throw new IllegalStateException("Invalid function-only expression '"+f.getFunction()+"'"); Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>)o; } else { clazz = o.getClass(); } if (!(clazz.getPackage().getName().startsWith(BrooklynDslCommon.class.getPackage().getName()))) throw new IllegalArgumentException("Not permitted to invoke function on '"+clazz+"' (outside allowed package scope)"); String fn = f.getFunction(); fn = Strings.removeFromStart(fn, "$brooklyn:"); if (fn.startsWith("function.")) { o = BrooklynDslCommon.Functions.class; fn = Strings.removeFromStart(fn, "function."); } try { List<Object> args = new ArrayList<>(); for (Object arg: f.getArgs()) { args.add( deepEvaluation ? evaluate(arg, true) : arg ); } Optional<Object> v = Reflections.invokeMethodWithArgs(o, fn, args); if (v.isPresent()) return v.get(); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw Exceptions.propagate(new InvocationTargetException(e, "Error invoking '"+fn+"' on '"+o+"'")); } throw new IllegalArgumentException("No such function '"+fn+"' on "+o); }
Source:
public void signalConnectionLost(final RtuDevice rtu) { LOGGER.info("Sending connection lost signal for device {}.", rtu.getDeviceIdentification()); final GetDataResponseDto dataResponse = new GetDataResponseDto(Arrays.asList(new GetDataSystemIdentifierDto( SYSTEM_ID, SYSTEM_TYPE, Arrays.asList(new MeasurementDto(MEASUREMENT_ID, MEASUREMENT_NODE, 0, new DateTime(DateTimeZone.UTC), 1.0))))); final String correlationUid = this.createCorrelationUid(rtu); final String organisationIdentification = rtu.getOwner().getOrganisationIdentification(); final String deviceIdentification = rtu.getDeviceIdentification(); this.adHocManagementService.handleGetDataResponse(dataResponse, deviceIdentification, organisationIdentification, correlationUid, DeviceFunction.GET_DATA.toString(), ResponseMessageResultType.OK, null); }

Target:
public void signalConnectionLost(final RtuDevice rtu) { LOGGER.info("Sending connection lost signal for device {}.", rtu.getDeviceIdentification()); final GetDataResponseDto dataResponse = new GetDataResponseDto(Arrays.asList(new GetDataSystemIdentifierDto( SYSTEM_ID, SYSTEM_TYPE, Arrays.asList(new MeasurementDto(MEASUREMENT_ID, MEASUREMENT_NODE, 0, new DateTime(DateTimeZone.UTC), MEASUREMENT_VALUE_ALARM_ON))))); final String correlationUid = this.createCorrelationUid(rtu); final String organisationIdentification = rtu.getOwner().getOrganisationIdentification(); final String deviceIdentification = rtu.getDeviceIdentification(); this.adHocManagementService.handleGetDataResponse(dataResponse, deviceIdentification, organisationIdentification, correlationUid, DeviceFunction.GET_DATA.toString(), ResponseMessageResultType.OK, null); }