auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected int getResponseSetSize() { <START> return responses.size(); <END> }</code><technical_language>careful size() calls concurrent data structures in general. of asynchronous nature maintain a "correct" size, operations of time O(N). hash map though. for application, exact size approximation works get this limitation is size a separate variable application. This is do server concurrent skip lists. FYI</technical_language>

Target:
protected int getResponseSetSize() { return queuedResponseCount.get(); }
Source:
<code>public String toString() { <START> return MoreObjects.toStringHelper(this) <END> .add("id", id) .add("tenantId", tenantId) .add("name", name) .add("description", description) .add("securityGroupRules", securityGroupRules) .toString(); }</code><technical_language>+1: I prefer this form other string().toString(). Do plan do other Domain classes well</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("tenantId", tenantId) .add("name", name) .add("description", description) .add("securityGroupRules", rules) .toString(); }
Source:
<code>public V put(@NonNull K key, @NonNull V value) { final ByteBuf keyPayload = Unpooled.buffer(); final ByteBuf valuePayload = Unpooled.buffer(); serializer.serialize(key, keyPayload); serializer.serialize(value, valuePayload); try { rocksDb.put( keyPayload.array(), keyPayload.arrayOffset(), keyPayload.readableBytes(), valuePayload.array(), valuePayload.arrayOffset(), valuePayload.readableBytes()); } catch (RocksDBException ex) { throw new UnrecoverableCorfuError(ex); } finally { keyPayload.release(); valuePayload.release(); } <START> dataSetSize.incrementAndGet(); <END> return value; }</code><technical_language>LSM compute size of elements full merge happens. do if this is accurate? do a rocksDb.get() if exists selectively increment right? Please correct if this is handled. thanks</technical_language>

Target:
public V put(@NonNull K key, @NonNull V value) { final ByteBuf keyPayload = Unpooled.buffer(); final ByteBuf valuePayload = Unpooled.buffer(); serializer.serialize(key, keyPayload); serializer.serialize(value, valuePayload); final boolean keyExists = rocksDb.keyMayExist(keyPayload.array(), keyPayload.arrayOffset(), keyPayload.readableBytes(), new StringBuilder()); if (!keyExists) { dataSetSize.incrementAndGet(); } try { rocksDb.put( keyPayload.array(), keyPayload.arrayOffset(), keyPayload.readableBytes(), valuePayload.array(), valuePayload.arrayOffset(), valuePayload.readableBytes()); } catch (RocksDBException ex) { throw new UnrecoverableCorfuError(ex); } finally { keyPayload.release(); valuePayload.release(); } return value; }
Source:
<code>default JobExecution getLastJobExecution(JobInstance jobInstance) { <START> return null; <END> }</code><technical_language>Is null right do default do throw new UnsuportedOperationException()</technical_language>

Target:
default JobExecution getLastJobExecution(JobInstance jobInstance) { throw new UnsupportedOperationException(); }
Source:
<code>public static ResourceMapping[] getResourceMappings(IFile file, ResourceMappingContext context) { final IModelProviderDescriptor[] modelDescriptors = ModelProvider .getModelProviderDescriptors(); final Set<ResourceMapping> mappings = new LinkedHashSet<ResourceMapping>(); for (IModelProviderDescriptor candidate : modelDescriptors) { try { final IResource[] resources = candidate .getMatchingResources(new IResource[] { file, }); if (resources.length > 0) { final ModelProvider model = candidate.getModelProvider(); final ResourceMapping[] modelMappings = model.getMappings( file, context, null); for (ResourceMapping mapping : modelMappings) { mappings.add(mapping); <START> } <END> } } catch (CoreException e) { Activator.logError(e.getMessage(), e); } } return mappings.toArray(new ResourceMapping[mappings.size()]); }</code><technical_language>Style nit: braces for simple single-line blocks</technical_language>

Target:
public static ResourceMapping[] getResourceMappings(IFile file, ResourceMappingContext context) { final IModelProviderDescriptor[] modelDescriptors = ModelProvider .getModelProviderDescriptors(); final Set<ResourceMapping> mappings = new LinkedHashSet<ResourceMapping>(); for (IModelProviderDescriptor candidate : modelDescriptors) { try { final IResource[] resources = candidate .getMatchingResources(new IResource[] { file, }); if (resources.length > 0) { final ModelProvider model = candidate.getModelProvider(); final ResourceMapping[] modelMappings = model.getMappings( file, context, null); for (ResourceMapping mapping : modelMappings) mappings.add(mapping); } } catch (CoreException e) { Activator.logError(e.getMessage(), e); } } return mappings.toArray(new ResourceMapping[mappings.size()]); }
Source:
<code>private void setupSound() { if (state.soundPop == null) { state.soundPop = createMediaPlayer(R.raw.pop); } if (state.soundNewPop == null) { state.soundNewPop = createMediaPlayer(R.raw.newpop); } setVolumeControlStream(AudioManager.STREAM_MUSIC); TelephonyManager tele = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (tele != null && state.phoneState == null) { state.phoneState = new PhoneState(); final int signal_strengths = 256; try { tele.listen(state.phoneState, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_CALL_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | signal_strengths); } catch (SecurityException ex) { info("cannot get call state, will play audio over any telephone calls: " + ex); } } Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); <START> startActivityForResult(checkTTSIntent, ACTION_TTS_CODE); <END> }</code><technical_language>this block shows twice, DRY</technical_language>

Target:
private void setupSound() { if (state.soundPop == null) { state.soundPop = createMediaPlayer(R.raw.pop); } if (state.soundNewPop == null) { state.soundNewPop = createMediaPlayer(R.raw.newpop); } setVolumeControlStream(AudioManager.STREAM_MUSIC); TelephonyManager tele = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (tele != null && state.phoneState == null) { state.phoneState = new PhoneState(); final int signal_strengths = 256; try { tele.listen(state.phoneState, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_CALL_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | signal_strengths); } catch (SecurityException ex) { info("cannot get call state, will play audio over any telephone calls: " + ex); } } ttsCheckIntent(); }
Source:
<code>public Response putBatchWifiInfo (@Auth final AccessToken token, @Valid @NotNull final List<WifiInfo> wifiInfoList){ if (wifiInfoList.size() > WifiInfoDynamoDB.MAXIMUM_BATCH_WRITE_SIZE) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(new JsonError(Response.Status.BAD_REQUEST.getStatusCode(), <START> String.format("Max batch size allow is %s", WifiInfoDynamoDB.MAXIMUM_BATCH_WRITE_SIZE))).build()); <END> } final Boolean hasPut = wifiInfoDAO.putBatch(wifiInfoList); if (!hasPut) { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to update wifi info batch"))).build()); } return Response.noContent().build(); }</code><technical_language>s/allow/allowed</technical_language>

Target:
public Response putBatchWifiInfo (@Auth final AccessToken token, @Valid @NotNull final List<WifiInfo> wifiInfoList){ if (wifiInfoList.size() > WifiInfoDynamoDB.MAXIMUM_BATCH_WRITE_SIZE) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(new JsonError(Response.Status.BAD_REQUEST.getStatusCode(), String.format("Max batch size allowed is %s", WifiInfoDynamoDB.MAXIMUM_BATCH_WRITE_SIZE))).build()); } final Boolean hasPut = wifiInfoDAO.putBatch(wifiInfoList); if (!hasPut) { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to update wifi info batch"))).build()); } return Response.noContent().build(); }
Source:
<code>@Override protected Optional<SmeltableProperty> getFor(ItemStack itemStack) { <START> if(FurnaceRecipes.instance().getSmeltingResult(itemStack) != null) { <END> return Optional.of(new SmeltableProperty(true)); } return Optional.of(new SmeltableProperty(false)); }</code><technical_language>if (</technical_language>

Target:
@Override protected Optional<SmeltableProperty> getFor(ItemStack itemStack) { return Optional.of(new SmeltableProperty(FurnaceRecipes.instance().getSmeltingResult(itemStack) != null)); }
Source:
<code>public void searchRightsByQuestionsTestLicenseWithoutFields() throws Exception { getClient().perform(get("/api/config/submissioncclicenses/search/rightsByQuestions?license=license3")) <START> .andExpect(status().isOk()) <END> .andExpect(jsonPath("$.url", is("mock-license-uri"))) .andExpect(jsonPath("$.type", is("submissioncclicenseUrl"))) .andExpect(jsonPath("$._links.self.href", is("http://localhost/api/config/submissioncclicenses/search/rightsByQuestions" + "?license=license3"))); }</code><technical_language>I asked need validate answer is provided. describe this case search licenses *without* giving answers? Is this lookup types of answers allowed? If so, enhance this test check response includes info types of answers alllowed</technical_language>

Target:
public void searchRightsByQuestionsTestLicenseWithoutFields() throws Exception { String epersonToken = getAuthToken(eperson.getEmail(), password); getClient(epersonToken) .perform(get("/api/config/submissioncclicenses/search/rightsByQuestions?license=license3")) .andExpect(status().isOk()) .andExpect(jsonPath("$.url", is("mock-license-uri"))) .andExpect(jsonPath("$.type", is("submissioncclicenseUrl"))) .andExpect(jsonPath("$._links.self.href", is("http://localhost/api/config/submissioncclicenses/search/rightsByQuestions" + "?license=license3"))); }
Source:
<code>public static ExecutorServices create(ResourceLoader loader) { URL configuration = loader.getResource(CONFIGURATION_FILE); Properties properties = null; if (configuration != null) { properties = loadProperties(configuration); } final int threadPoolSize = initIntValue(properties, THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE); final boolean debug = initBooleanValue(properties, DEBUG, false); <START> ThreadPoolType defaultType = PermissionChecker.hasPermission(new java.lang.RuntimePermission("modifyThreadGroup")) ? ThreadPoolType.FIXED <END> : ThreadPoolType.NONE; final ThreadPoolType threadPoolType = initThreadPoolType(properties, THREAD_POOL_TYPE, defaultType); final long threadPoolKeepAliveTime = initLongValue(properties, THREAD_POOL_KEEP_ALIVE_TIME, DEFAULT_KEEP_ALIVE_TIME); if (debug) { return enableDebugMode(constructExecutorServices(threadPoolType, threadPoolSize, threadPoolKeepAliveTime)); } else { return constructExecutorServices(threadPoolType, threadPoolSize, threadPoolKeepAliveTime); } }</code><technical_language>new java.lang.RuntimePermission("modifyThreadGroup") a public constant in PermissionChecker class</technical_language>

Target:
public static ExecutorServices create(ResourceLoader loader) { URL configuration = loader.getResource(CONFIGURATION_FILE); Properties properties = null; if (configuration != null) { properties = loadProperties(configuration); } final int threadPoolSize = initIntValue(properties, THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE); final boolean debug = initBooleanValue(properties, DEBUG, false); ThreadPoolType defaultType = Permissions.hasPermission(Permissions.MODIFY_THREAD_GROUP) ? ThreadPoolType.FIXED : ThreadPoolType.NONE; final ThreadPoolType threadPoolType = initThreadPoolType(properties, THREAD_POOL_TYPE, defaultType); final long threadPoolKeepAliveTime = initLongValue(properties, THREAD_POOL_KEEP_ALIVE_TIME, DEFAULT_KEEP_ALIVE_TIME); if (debug) { return enableDebugMode(constructExecutorServices(threadPoolType, threadPoolSize, threadPoolKeepAliveTime)); } else { return constructExecutorServices(threadPoolType, threadPoolSize, threadPoolKeepAliveTime); } }
Source:
<code><START> private static GitFlowRepository getRepository(Object element) { <END> GitFlowRepository repository = null; if (element instanceof GitFlowRepository) { repository = (GitFlowRepository) element; } if (element instanceof RepositoryNode) { RepositoryNode node = (RepositoryNode) element; repository = new GitFlowRepository(node.getObject()); } return repository; }</code><technical_language>mark @Nullable</technical_language>

Target:
private static @Nullable GitFlowRepository getRepository(Object element) { GitFlowRepository repository = null; if (element instanceof GitFlowRepository) { repository = (GitFlowRepository) element; } if (element instanceof RepositoryNode) { RepositoryNode node = (RepositoryNode) element; repository = new GitFlowRepository(node.getObject()); } return repository; }
Source:
<code>public void canQueryOverTwoStringFieldsNormalized() { Map<String, Object> nameOperator = new HashMap<String, Object>(); nameOperator.put("$eq", "mike"); Map<String, Object> query = new HashMap<String, Object>(); query.put("name", nameOperator); Map<String, Object> petOperator = new HashMap<String, Object>(); petOperator.put("$eq", "cat"); query.put("pet", petOperator); QueryResult queryResult = im.find(query); Assert.assertNotNull(queryResult); Assert.assertEquals(2, queryResult.size()); List<String> checkList = new ArrayList<String>(); checkList.add("mike12"); <START> checkList.add("mike72"); <END> Assert.assertEquals(2, queryResult.documentIds().size()); Assert.assertTrue(queryResult.documentIds().containsAll(checkList)); List<String> docCheckList = new ArrayList<String>(); for (DocumentRevision rev: queryResult) { Assert.assertNotNull(rev.getId()); Assert.assertNotNull(rev.getBody()); docCheckList.add(rev.getId()); } Assert.assertEquals(2, docCheckList.size()); Assert.assertTrue(docCheckList.containsAll(checkList)); }</code><technical_language>This clearer List<String> checkList = Arrays.asList("mike12", "mike72");</technical_language>

Target:
public void canQueryOverTwoStringFieldsNormalized() { Map<String, Object> nameOperator = new HashMap<String, Object>(); nameOperator.put("$eq", "mike"); Map<String, Object> query = new HashMap<String, Object>(); query.put("name", nameOperator); Map<String, Object> petOperator = new HashMap<String, Object>(); petOperator.put("$eq", "cat"); query.put("pet", petOperator); QueryResult queryResult = im.find(query); Assert.assertNotNull(queryResult); Assert.assertEquals(2, queryResult.size()); List<String> checkList = Arrays.asList("mike12", "mike72"); Assert.assertEquals(2, queryResult.documentIds().size()); Assert.assertTrue(queryResult.documentIds().containsAll(checkList)); }
Source:
<code>public Object invoke(Message message) throws Exception { checkArgument(message != null); try { Method method = this.methods.get(message.header(ServiceHeaders.METHOD)); Object result; if (method.getParameters().length == 0) { result = method.invoke(serviceObject); } else if (method.getParameters()[0].getType().isAssignableFrom(Message.class)) { <START> result = method.invoke(serviceObject, (Message) message.data()); <END> } else { result = method.invoke(serviceObject, new Object[] {message.data()}); } return result; } catch (Exception ex) { return ex; } }</code><technical_language>I logic supposed here, is message.data() is Message here</technical_language>

Target:
public Object invoke(Message message) throws Exception { checkArgument(message != null); try { Method method = this.methods.get(message.header(ServiceHeaders.METHOD)); Object result; if (method.getParameters().length == 0) { result = method.invoke(serviceObject); } else if (method.getParameters()[0].getType().isAssignableFrom(Message.class)) { result = method.invoke(serviceObject, message); } else { result = method.invoke(serviceObject, new Object[] {message.data()}); } return result; } catch (Exception ex) { return ex; } }
Source:
<code>@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { String columnName; try { <START> columnName = rsMetaData.getColumnLabel( index ); <END> } catch ( SQLException sqlException ) { throw new KettleDatabaseException( "Something went wrong trying to get the legacy column name", sqlException ); } catch ( Exception e ) { throw new KettleDatabaseException( "Something unexpected went wrong trying to get the legacy column name", e ); } return columnName; }</code><technical_language>return here? save declaring a variable return end of method? Yeah! lazy prefer write code possible</technical_language>

Target:
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { if ( dbMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) ); } if ( rsMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoRSMetaDataException" ) ); } try { return rsMetaData.getColumnLabel( index ); } catch ( Exception e ) { throw new KettleDatabaseException( String.format( "%s: %s", BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameException" ), e.getMessage() ), e ); } }
Source:
<code>public static File copyDir(File srcDir, File dstDir) throws IOException { if (!srcDir.exists()) { throw new FileNotFoundException("Directory: " + srcDir.getAbsolutePath() + " does not exist."); } if (!srcDir.isDirectory()) { throw new IOException(srcDir.getAbsolutePath() + " is not a directory."); } <START> dstDir.mkdirs(); <END> if (!dstDir.isDirectory()) { throw new IOException("Cannot create directory: " + dstDir.getAbsolutePath()); } for (File file : srcDir.listFiles()) { if (file.isDirectory()) { copyDir(file, new File(dstDir, file.getName())); } else { copyFileToDir(file, dstDir); } } return dstDir; }</code><technical_language>reason for this change</technical_language>

Target:
public static File copyDir(File srcDir, File dstDir) throws IOException { if (!srcDir.exists()) { throw new FileNotFoundException("Directory: " + srcDir.getAbsolutePath() + " does not exist."); } if (!srcDir.isDirectory()) { throw new IOException(srcDir.getAbsolutePath() + " is not a directory."); } dstDir.mkdir(); if (!dstDir.isDirectory()) { throw new IOException("Cannot create directory: " + dstDir.getAbsolutePath()); } for (File file : srcDir.listFiles()) { if (file.isDirectory()) { copyDir(file, new File(dstDir, file.getName())); } else { copyFileToDir(file, dstDir); } } return dstDir; }
Source:
<code>private Token nextIsASimpleValue(ConfigOrigin baseOrigin, int lineNumber) { if (lastTokenWasSimpleValue) { if (whitespace.length() > 0) { Token t = Tokens.newUnquotedText( lineOrigin(baseOrigin, lineNumber), whitespace.toString()); whitespace.setLength(0); return t; } else { return null; } } else { lastTokenWasSimpleValue = true; if (whitespace.length() > 0) { Token t = Tokens.newIgnoredWhitespace(lineOrigin(baseOrigin, lineNumber), whitespace.toString()); whitespace.setLength(0); return t; <START> } <END> return null; } }</code><technical_language>this block of code is in places, split a method</technical_language>

Target:
private Token nextIsASimpleValue(ConfigOrigin baseOrigin, int lineNumber) { Token t = createWhitespaceTokenFromSaver(baseOrigin, lineNumber); if (!lastTokenWasSimpleValue) { lastTokenWasSimpleValue = true; } return t; }
Source:
<code>private Map<String, Map<String, String>> getPluginConfigValues() { Map<String, Map<String, String>> pluginConfigValues = new HashMap<>(pluginConfigWidgets.size()); for (Entry<String, Map<String, FocusWidget>> e : pluginConfigWidgets.entrySet()) { Map<String, String> values = new HashMap<String, String>(e.getValue().size()); pluginConfigValues.put(e.getKey(), values); for (Entry<String, FocusWidget> e2 : e.getValue().entrySet()) { FocusWidget widget = e2.getValue(); if (widget instanceof TextBox) { values.put(e2.getKey(), ((TextBox) widget).getValue().trim()); } else if (widget instanceof CheckBox) { values.put(e2.getKey(), Boolean.toString(((CheckBox) widget).getValue())); } else if (widget instanceof ListBox) { ListBox listBox = (ListBox) widget; String value = listBox.getSelectedIndex() > 0 ? listBox.getValue(listBox.getSelectedIndex()) : null; values.put(e2.getKey(), value); } else if (widget instanceof NpTextArea) { NpTextArea txtArea = (NpTextArea) widget; values.put(e2.getKey(), txtArea.getText().trim()); } else { throw new <START> UnsupportedOperationException("unupported widget <END> type"); } } } return pluginConfigValues; }</code><technical_language>s/unupported/unsupported</technical_language>

Target:
private Map<String, Map<String, String>> getPluginConfigValues() { Map<String, Map<String, String>> pluginConfigValues = new HashMap<>(pluginConfigWidgets.size()); for (Entry<String, Map<String, FocusWidget>> e : pluginConfigWidgets.entrySet()) { Map<String, String> values = new HashMap<String, String>(e.getValue().size()); pluginConfigValues.put(e.getKey(), values); for (Entry<String, FocusWidget> e2 : e.getValue().entrySet()) { FocusWidget widget = e2.getValue(); if (widget instanceof TextBox) { values.put(e2.getKey(), ((TextBox) widget).getValue().trim()); } else if (widget instanceof CheckBox) { values.put(e2.getKey(), Boolean.toString(((CheckBox) widget).getValue())); } else if (widget instanceof ListBox) { ListBox listBox = (ListBox) widget; String value = listBox.getSelectedIndex() > 0 ? listBox.getValue(listBox.getSelectedIndex()) : null; values.put(e2.getKey(), value); } else if (widget instanceof NpTextArea) { NpTextArea txtArea = (NpTextArea) widget; values.put(e2.getKey(), txtArea.getText().trim()); } else { throw new UnsupportedOperationException("unsupported widget type"); } } } return pluginConfigValues; }
Source:
<code>public Set<RuntimeIdentity> findIdentities() throws InternalInfrastructureException { try { <START> return docker.listContainers(ListContainersParams.create().withAll(false)) <END> .stream() .map(container -> Labels.newDeserializer(container.getLabels()).runtimeId()) .filter(id -> !Strings.isNullOrEmpty(id.getWorkspaceId())) .collect(Collectors.toSet()); } catch (IOException x) { throw new InternalInfrastructureException(x.getMessage(), x); } }</code><technical_language>considered filtering in Docker API</technical_language>

Target:
public Set<RuntimeIdentity> findIdentities() throws InternalInfrastructureException { return listNonStoppedContainers(Labels.LABEL_WORKSPACE_ID, Labels.LABEL_WORKSPACE_ID, Labels.LABEL_WORKSPACE_OWNER) .stream() .map(e -> Labels.newDeserializer(e.getLabels()).runtimeId()) .collect(Collectors.toSet()); }
Source:
<code>public void testThrowing() { XLogger logger = XLoggerFactory.getXLogger("UnitTest"); Throwable t = new UnsupportedOperationException("Test"); assertEquals(t, logger.throwing(t)); assertEquals(t, logger.throwing(XLogger.Level.DEBUG,t)); assertEquals(2, listAppender.list.size()); <START> if (listAppender.list.get(0).getThrowableStrRep() == null) { <END> return; } verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t); LoggingEvent event = (LoggingEvent)listAppender.list.get(1); verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t); }</code><technical_language>this change</technical_language>

Target:
public void testThrowing() { XLogger logger = XLoggerFactory.getXLogger("UnitTest"); Throwable t = new UnsupportedOperationException("Test"); assertEquals(t, logger.throwing(t)); assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t)); assertEquals(2, listAppender.list.size()); verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t); LoggingEvent event = (LoggingEvent) listAppender.list.get(1); verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t); }
Source:
<code>public void testDoubleClaim() throws CloudnameException, InterruptedException { final Coordinate c = Coordinate.parse("2.service.user.cell"); final CountDownLatch okCounter = new CountDownLatch(1); final CountDownLatch failCounter = new CountDownLatch(1); final CoordinateListener listener = new CoordinateListener() { @Override public void onCoordinateEvent(Event event, String message) { switch (event) { case COORDINATE_OK: okCounter.countDown(); break; case NOT_OWNER: failCounter.countDown(); default: assert(false); break; } } }; Cloudname cn = null; try { cn = makeLocalZkCloudname(); } catch (CloudnameException e) { fail("connecting to localhost failed."); } try { cn.createCoordinate(c); } catch (CoordinateExistsException e) { fail("should not happen."); } <START> ServiceHandle handle1 = cn.claim(c); <END> assert(handle1.waitForCoordinateOkSeconds(4)); handle1.registerCoordinateListener(listener); ServiceHandle handle2 = cn.claim(c); assertFalse(handle2.waitForCoordinateOkSeconds(1)); handle2.registerCoordinateListener(listener); assert(okCounter.await(4, TimeUnit.SECONDS)); assert(failCounter.await(2, TimeUnit.SECONDS)); }</code><technical_language>final</technical_language>

Target:
public void testDoubleClaim() throws CloudnameException, InterruptedException { final Coordinate c = Coordinate.parse("2.service.user.cell"); final CountDownLatch okCounter = new CountDownLatch(1); final CountDownLatch failCounter = new CountDownLatch(1); final CoordinateListener listener = new CoordinateListener() { @Override public void onCoordinateEvent(Event event, String message) { switch (event) { case COORDINATE_OK: okCounter.countDown(); break; case NOT_OWNER: failCounter.countDown(); default: assert(false); break; } } }; final Cloudname cn; try { cn = makeLocalZkCloudname(); } catch (CloudnameException e) { fail("connecting to localhost failed."); return; } try { cn.createCoordinate(c); } catch (CoordinateExistsException e) { fail("should not happen."); } final ServiceHandle handle1 = cn.claim(c); assert(handle1.waitForCoordinateOkSeconds(4)); handle1.registerCoordinateListener(listener); ServiceHandle handle2 = cn.claim(c); assertFalse(handle2.waitForCoordinateOkSeconds(1)); handle2.registerCoordinateListener(listener); assert(okCounter.await(4, TimeUnit.SECONDS)); assert(failCounter.await(2, TimeUnit.SECONDS)); }
Source:
<code>private void initListeners() { Set<Class<? extends ITestNGListener>> listenerClasses = Sets.newHashSet(); Class<? extends ITestNGListenerFactory> listenerFactoryClass = null; for (IClass cls : getTestClasses()) { Class<?> realClass = cls.getRealClass(); TestListenerHelper.ListenerHolder listenerHolder = TestListenerHelper.findAllListeners(realClass, m_annotationFinder); if (listenerFactoryClass == null) { listenerFactoryClass = listenerHolder.getListenerFactoryClass(); } listenerClasses.addAll(listenerHolder.getListenerClasses()); } ITestNGListenerFactory factory = TestListenerHelper.createListenerFactory(m_testClassFinder, listenerFactoryClass); for (Class<? extends ITestNGListener> c : listenerClasses) { if (IClassListener.class.isAssignableFrom(c) && m_classListeners.containsKey(c)) { continue; } <START> ITestNGListener listener = TestListenerHelper.createListener(factory, c); <END> addListener(listener); } }</code><technical_language>factory.createListener(c) factory null (TestListenerHelper.createListenerFactory return a default factory)</technical_language>

Target:
private void initListeners() { Set<Class<? extends ITestNGListener>> listenerClasses = Sets.newHashSet(); Class<? extends ITestNGListenerFactory> listenerFactoryClass = null; for (IClass cls : getTestClasses()) { Class<?> realClass = cls.getRealClass(); TestListenerHelper.ListenerHolder listenerHolder = TestListenerHelper.findAllListeners(realClass, m_annotationFinder); if (listenerFactoryClass == null) { listenerFactoryClass = listenerHolder.getListenerFactoryClass(); } listenerClasses.addAll(listenerHolder.getListenerClasses()); } if (listenerFactoryClass == null) { listenerFactoryClass = DefaultListenerFactory.class; } ITestNGListenerFactory factory = TestListenerHelper.createListenerFactory(m_testClassFinder, listenerFactoryClass); for (Class<? extends ITestNGListener> c : listenerClasses) { if (IClassListener.class.isAssignableFrom(c) && m_classListeners.containsKey(c)) { continue; } ITestNGListener listener = factory.createListener(c); addListener(listener); } }
Source:
<code>TopicMetadataLoadingJob(TopicMetadataLoadingRunner topicMetadataLoadingRunner, int intervalSeconds) { this.topicMetadataLoadingRunner = topicMetadataLoadingRunner; this.intervalSeconds = intervalSeconds; ThreadFactory threadFactory = new ThreadFactoryBuilder() <START> .setNameFormat("TopicMetadataLoadingExecutor-%d").build(); <END> this.executorService = Executors.newSingleThreadScheduledExecutor(threadFactory); }</code><technical_language>BTW, name TopicMetadataLoadingJob</technical_language>

Target:
TopicMetadataLoadingJob(TopicMetadataLoadingRunner topicMetadataLoadingRunner, int intervalSeconds) { this.topicMetadataLoadingRunner = topicMetadataLoadingRunner; this.intervalSeconds = intervalSeconds; ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("TopicMetadataLoadingJob-%d").build(); this.executorService = Executors.newSingleThreadScheduledExecutor(threadFactory); }
Source:
<code><START> public Object applyUpdateUnsafe(SMRRecord record) { <END> log.trace("Apply[{}] of {}@{} ({})", this, record.getSMRMethod(), Address.isAddress(record.getGlobalAddress()) ? record.getGlobalAddress() : "OPT", record.getSMRArguments()); ICorfuSMRUpcallTarget<T> target = upcallTargetMap.get(record.getSMRMethod()); if (target == null) { throw new RuntimeException("Unknown upcall " + record.getSMRMethod()); } if (!record.isUndoable() || !Address.isAddress(record.getGlobalAddress())) { IUndoRecordFunction<T> undoRecordTarget = undoRecordFunctionMap.get(record.getSMRMethod()); if (undoRecordTarget != null) { record.setUndoRecord(undoRecordTarget .getUndoRecord(object, record.getSMRArguments())); log.trace("Apply[{}] Undo->{}", this, record.getUndoRecord()); } else if (resetSet.contains(record.getSMRMethod())) { record.setUndoRecord(object); object = newObjectFn.get(); log.trace("Apply[{}] Undo->RESET", this); } } return target.upcall(object, record.getSMRArguments()); }</code><technical_language>public</technical_language>

Target:
private Object applyUpdateUnsafe(SMRRecord record) { log.trace("Apply[{}] of {}@{} ({})", this, record.getSMRMethod(), Address.isAddress(record.getGlobalAddress()) ? record.getGlobalAddress() : "OPT", record.getSMRArguments()); ICorfuSMRUpcallTarget<T> target = upcallTargetMap.get(record.getSMRMethod()); if (target == null) { throw new RuntimeException("Unknown upcall " + record.getSMRMethod()); } if (!record.isUndoable() || !Address.isAddress(record.getGlobalAddress())) { IUndoRecordFunction<T> undoRecordTarget = undoRecordFunctionMap.get(record.getSMRMethod()); if (undoRecordTarget != null) { record.setUndoRecord(undoRecordTarget .getUndoRecord(object, record.getSMRArguments())); log.trace("Apply[{}] Undo->{}", this, record.getUndoRecord()); } else if (resetSet.contains(record.getSMRMethod())) { record.setUndoRecord(object); object = newObjectFn.get(); log.trace("Apply[{}] Undo->RESET", this); } } return target.upcall(object, record.getSMRArguments()); }
Source:
<code>public void run() { int exitCode = waitForExit(); ji.setExitCode(exitCode); ReentrantReadWriteLock rwl = PersistenceManager.getDbLock(); try { rwl.writeLock().lock(); JobInfoElement dbJI = pm.getEntity(ji.getJobID(), JobInfoElement.class); if ((dbJI.getStatus() != null) && !dbJI.getStatus().equalsIgnoreCase("KILLED")) { GenieNodeStatistics stats = GenieNodeStatistics.getInstance(); if (exitCode != SubprocessStatus.SUCCESS.code()) { logger.error("Failed to execute job, exit code: " + exitCode); String errMsg = Types.SubprocessStatus.message(exitCode); if ((errMsg == null) || (errMsg.isEmpty())) { errMsg = "Please look at job's stderr for more details"; } ji.setJobStatus(JobStatus.FAILED, "Failed to execute job, Error Message: " + errMsg); stats.incrGenieFailedJobs(); } else { ji.setJobStatus(JobStatus.SUCCEEDED, "Job finished successfully"); stats.incrGenieSuccessfulJobs(); } if (!ji.getDisableLogArchival()) { ji.setArchiveLocation(NetUtil.getArchiveURI(ji.getJobID())); } pm.updateEntity(ji); rwl.writeLock().unlock(); } else { logger.debug("Job has been killed - will not update DB: " + ji.getJobID()); rwl.writeLock().unlock(); } if (config.getBoolean("netflix.genie.server.mail.enable", false)) { logger.info("Sending Job Completion Email to user"); if (sendEmail() != 0) { <START> logger.warn("Failed to Send Email.Will not fail job."); <END> } } else { logger.info("Email Sending is disabled"); } } finally { if (rwl.writeLock().isHeldByCurrentThread()) { rwl.writeLock().unlock(); } } }</code><technical_language>I this, setting statusMsg. minor grammar nazi - capitalize words do (prefer latter), space a period :)</technical_language>

Target:
public void run() { GenieNodeStatistics stats = GenieNodeStatistics.getInstance(); int exitCode = waitForExit(); ji.setExitCode(exitCode); ReentrantReadWriteLock rwl = PersistenceManager.getDbLock(); try { rwl.writeLock().lock(); JobInfoElement dbJI = pm.getEntity(ji.getJobID(), JobInfoElement.class); if ((dbJI.getStatus() != null) && !dbJI.getStatus().equalsIgnoreCase("KILLED")) { if (exitCode != SubprocessStatus.SUCCESS.code()) { logger.error("Failed to execute job, exit code: " + exitCode); String errMsg = Types.SubprocessStatus.message(exitCode); if ((errMsg == null) || (errMsg.isEmpty())) { errMsg = "Please look at job's stderr for more details"; } ji.setJobStatus(JobStatus.FAILED, "Failed to execute job, Error Message: " + errMsg); stats.incrGenieFailedJobs(); } else { ji.setJobStatus(JobStatus.SUCCEEDED, "Job finished successfully"); stats.incrGenieSuccessfulJobs(); } if (!ji.getDisableLogArchival()) { ji.setArchiveLocation(NetUtil.getArchiveURI(ji.getJobID())); } pm.updateEntity(ji); rwl.writeLock().unlock(); } else { logger.debug("Job has been killed - will not update DB: " + ji.getJobID()); rwl.writeLock().unlock(); } } finally { if (rwl.writeLock().isHeldByCurrentThread()) { rwl.writeLock().unlock(); } } String emailTo = ji.getUserEmail(); if (emailTo != null) { logger.info("User email address: " + emailTo); if (sendEmail(emailTo)) { stats.incrSuccessfulEmailCount(); } else { logger.warn("Failed to send email."); stats.incrFailedEmailCount(); } } }
Source:
<code>private List<String> parseChipsetPrefixedList(String line, ChipsetType chipset) { List<String> values = new ArrayList<>(); if (StringUtils.isEmpty(line)) { <START> return values; <END> } for (String element : line.split(",")) { Pair<String, String> pair = parseSlashSeparatedPair(element); if (pair == null) { String value = element.trim(); if (!value.isEmpty()) { values.add(value); } } else if (chipset != null && chipset.getChipsetName().equalsIgnoreCase(pair.getFirst())) { values.add(pair.getSecond()); } } return values; }</code><technical_language>returning Collections.emptyList() move #344 this if-statement</technical_language>

Target:
private List<String> parseChipsetPrefixedList(String line, ChipsetType chipset) { if (StringUtils.isEmpty(line)) { return Collections.emptyList(); } List<String> values = new ArrayList<>(); for (String element : line.split(",")) { Pair<String, String> pair = parseSlashSeparatedPair(element); if (pair == null) { String value = element.trim(); if (!value.isEmpty()) { values.add(value); } } else if (chipset != null && chipset.getChipsetName().equalsIgnoreCase(pair.getFirst())) { values.add(pair.getSecond()); } } return values; }
Source:
<code>private void fetchNameNodeTokenInternal(final String renewer, final Credentials cred, final String userToProxy, final URI uri) throws IOException, HadoopSecurityManagerException { FileSystem fs = null; try { if (uri == null) { fs = FileSystem.newInstance(conf); } else { <START> fs = FileSystem.newInstance(uri, conf); <END> } logger.info("Getting DFS token from " + fs.getUri()); try { final Token<?>[] fsTokens = fs.addDelegationTokens(renewer, cred); for (int i = 0; i < fsTokens.length; i++) { final Token<?> fsToken = fsTokens[i]; logger.info(String.format( "DFS token from namenode pre-fetched, token kind: %s, token service: %s", fsToken.getKind(), fsToken.getService())); } } catch (Exception e) { logger.error("Failed to fetch DFS token for "); throw new HadoopSecurityManagerException( "Failed to fetch DFS token for " + userToProxy); } } finally { if (fs != null) { fs.close(); } } }</code><technical_language>is this URI change needed</technical_language>

Target:
private void fetchNameNodeTokenInternal(final String renewer, final Credentials cred, final String userToProxy, final URI uri) throws IOException, HadoopSecurityManagerException { FileSystem fs = null; try { if (uri == null) { fs = FileSystem.newInstance(conf); } else { fs = FileSystem.newInstance(uri, conf); } logger.info("Getting DFS token from " + fs.getUri()); try { final Token<?>[] fsTokens = fs.addDelegationTokens(renewer, cred); for (int i = 0; i < fsTokens.length; i++) { final Token<?> fsToken = fsTokens[i]; logger.info(String.format( "DFS token from namenode pre-fetched, token kind: %s, token service: %s", fsToken.getKind(), fsToken.getService())); } } catch (Exception e) { logger.error("Failed to fetch DFS token for " + userToProxy); throw new HadoopSecurityManagerException( "Failed to fetch DFS token for " + userToProxy); } } finally { if (fs != null) { fs.close(); } } }
Source:
<code>public static int getRawDataType(final VariableIF variable) { VariableDS ds = (VariableDS) variable; <START> final DataType type = ds.getDataType(); <END> return transcodeNetCDFDataType(type,variable.isUnsigned()); }</code><technical_language>system property check influences dataType too</technical_language>

Target:
public static int getRawDataType(final VariableIF variable) { VariableDS ds = (VariableDS) variable; final DataType type; if (Boolean.getBoolean(ENHANCE_SCALE_MISSING)) { type = ds.getDataType(); } else { type = ds.getOriginalDataType(); } return transcodeNetCDFDataType(type,variable.isUnsigned()); }
Source:
<code>private Observable<CoreOperation> createCoreOperation(@NonNull final CoreValue<U> value) { switch (value.type()) { <START> case UPDATE: <END> return createCoreOperation((CoreUpdateValue<U>) value); case DELETE: return createCoreOperation((CoreDeleteValue<U>) value); default: throw new IllegalStateException("Unknown value type " + value.type()); } }</code><technical_language>return values in delete update same, case UPDATE: case DELETE: another return line</technical_language>

Target:
private Observable<CoreOperation> createCoreOperation(@NonNull final CoreValue<U> value) { Observable<CoreOperation> valueObservable; switch (value.type()) { case PUT: valueObservable = createCoreOperation((CoreValuePut<U>) value); break; case DELETE: valueObservable = createCoreOperation((CoreValueDelete<U>) value); break; default: throw new IllegalStateException("Unknown value type " + value.type()); } return valueObservable .onErrorReturn(__ -> value.noOperation()) .doOnNext(this::releaseIfNoOp) .filter(CoreOperation::isValid); }
Source:
<code>public ScalarFunctionImplementation getScalarFunctionImplementation(Signature signature) { checkArgument(signature.getKind() == SCALAR, "%s is not a scalar function", signature); checkArgument(signature.getTypeVariableConstraints().isEmpty(), "%s has unbound type parameters", signature); try { return specializedScalarCache.getUnchecked(getSpecializedFunctionKey(signature)); } catch (UncheckedExecutionException e) { if (e.getCause() instanceof ByteCodeException) { <START> throw new PrestoException(StandardErrorCode.NOT_SUPPORTED, e.getCause()); <END> } throwIfUnchecked(e.getCause()); throw new RuntimeException(e.getCause()); } }</code><technical_language>This throw original message, some problems: * mentions 255, this is internal detail inaccurate for user. For example, if generate a class method, of parameters this. * hit this condition in other cases generating projections, in case message is completely wrong</technical_language>

Target:
public ScalarFunctionImplementation getScalarFunctionImplementation(Signature signature) { checkArgument(signature.getKind() == SCALAR, "%s is not a scalar function", signature); checkArgument(signature.getTypeVariableConstraints().isEmpty(), "%s has unbound type parameters", signature); try { return specializedScalarCache.getUnchecked(getSpecializedFunctionKey(signature)); } catch (UncheckedExecutionException e) { throw Throwables.propagate(e.getCause()); } }
Source:
<code>public boolean filterOut(final SAMRecord first, final SAMRecord second) { <START> return (values.contains(first.getAttribute(tag)) && values.contains(second.getAttribute(tag))) != includeReads; <END> }</code><technical_language>hmmm. this right thing... if includeReads==false, tag/value other doesn't...should pair filtered not? rate...this tested. I tested...but should. please</technical_language>

Target:
public boolean filterOut(final SAMRecord first, final SAMRecord second) { if (includeReads) { return !(values.contains(first.getAttribute(tag)) || values.contains(second.getAttribute(tag))); } else { return values.contains(first.getAttribute(tag)) && values.contains(second.getAttribute(tag)); } }
Source:
<code>private AttributeType extractAttributeTypeFromJsonValue(JsonValue value) { if (value.isNumber()) { try { <START> value.asLong(); <END> return AttributeType.LONG; } catch (NumberFormatException e) { return AttributeType.DOUBLE; } } else if (value.isBoolean()) { return AttributeType.BOOLEAN; } else if (value.isString()) { return AttributeType.STRING; } throw new HazelcastSerializationException("Unknown Json type: " + value); }</code><technical_language>Minor: check if number contains decimal point instead</technical_language>

Target:
private AttributeType extractAttributeTypeFromJsonValue(JsonValue value) { if (value.isNumber()) { if (value.toString().contains(".")) { return AttributeType.DOUBLE; } else { return AttributeType.LONG; } } else if (value.isBoolean()) { return AttributeType.BOOLEAN; } else if (value.isString()) { return AttributeType.STRING; } throw new HazelcastSerializationException("Unknown Json type: " + value); }
Source:
<code>public void validateEnums(StorageDomain storageDomain) { if (storageDomain != null) { if (storageDomain.isSetType()) { validateEnum(StorageDomainType.class, storageDomain.getType(), true); } if (storageDomain.isSetStorage() && storageDomain.getStorage().isSetType()) { validateEnum(StorageType.class, storageDomain.getStorage().getType(), true); } if (storageDomain.isSetFormat()) { validateEnum(StorageFormat.class, storageDomain.getStorageFormat(), true); } if (storageDomain.isSetStorage() && storageDomain.getStorage().isSetNfsVersion()) { validateEnum(NfsVersion.class, storageDomain.getStorage().getNfsVersion(), true); } if (storageDomain.isSetExternalStatus()) { <START> validateEnum(EntityExternalStatus.class, storageDomain.getExternalStatus().getState().toUpperCase()); <END> } } }</code><technical_language>call "getState().toUpperCase()" generate a NPE. need check a befor it</technical_language>

Target:
public void validateEnums(StorageDomain storageDomain) { if (storageDomain != null) { if (storageDomain.isSetType()) { validateEnum(StorageDomainType.class, storageDomain.getType(), true); } if (storageDomain.isSetStorage() && storageDomain.getStorage().isSetType()) { validateEnum(StorageType.class, storageDomain.getStorage().getType(), true); } if (storageDomain.isSetFormat()) { validateEnum(StorageFormat.class, storageDomain.getStorageFormat(), true); } if (storageDomain.isSetStorage() && storageDomain.getStorage().isSetNfsVersion()) { validateEnum(NfsVersion.class, storageDomain.getStorage().getNfsVersion(), true); } if (storageDomain.isSetExternalStatus() && storageDomain.getExternalStatus().getState() != null) { validateEnum(EntityExternalStatus.class, storageDomain.getExternalStatus().getState().toUpperCase()); } } }
Source:
<code>public void testDeserializeFileMessage() throws Exception { File tempFile = getTempTestFile(); Messenger messenger = new Messenger(File.createTempFile("test", "").getParentFile()); FileMessage testMessage = new FileMessage(); testMessage.setFilePath(tempFile.getCanonicalPath()); InputStream is = simulateSendAndReceive(testMessage); assertTrue(messenger.deserializeMessage(is)); IMessage message = messenger.getReceivedMessages().get(0); assertNotNull(message); assertTrue(message instanceof FileMessage); <START> assertFalse(tempFile.getCanonicalPath().equals(((FileMessage)message).getFilePath())); <END> assertFileEquals(tempFile, new File(((FileMessage)message).getFilePath())); assertEquals(0, is.available()); }</code><technical_language>matter file paths different</technical_language>

Target:
public void testDeserializeFileMessage() throws Exception { File tempFile = MessageTestUtil.getTempTestFile(20); Messenger messenger = new Messenger(File.createTempFile("test", "").getParentFile()); FileMessage testMessage = new FileMessage(); testMessage.setFilePath(tempFile.getCanonicalPath()); int packetSize = 1024; List<PacketFormat> packets = simulateSendAndReceive(testMessage, packetSize); boolean received = false; for (PacketFormat packet : packets) { assertFalse(received); InputBuffer buffer = new InputBuffer(); packet.serialize(buffer); received = messenger.deserializeMessage(buffer.getInputStream()); } assertTrue(received); IMessage message = messenger.getReceivedMessages().get(0); assertNotNull(message); assertTrue(message instanceof FileMessage); assertFalse(tempFile.getCanonicalPath().equals(((FileMessage)message).getFilePath())); CustomAssert.assertChecksumsMatch(tempFile.getCanonicalPath(), ((FileMessage)message).getFilePath()); }
Source:
<code>public PersistentResource getRelation(String relation, String id) { Optional<FilterExpression> filterExpression; boolean skipNew = false; Class<?> entityType = dictionary.getParameterizedType(getResourceClass(), relation); if (requestScope.isMutatingMultipleEntities() && requestScope.getObjectById(dictionary.getJsonAliasFor(entityType), id) != null) { <START> if (!this.checkRelation(relation)) { <END> throw new ForbiddenAccessException("oops"); } Object entity = requestScope.getObjectById(dictionary.getJsonAliasFor(entityType), id); PersistentResource resource = requestScope.getNewPersistentResources().stream() .filter(r -> r.getObject() == entity).findFirst().orElse(null); resource.checkFieldAwarePermissions(ReadPermission.class); return resource; } else { if (entityType == null) { throw new InvalidAttributeException(relation, type); } Class<?> idType = dictionary.getIdType(entityType); Object idVal = CoerceUtil.coerce(id, idType); String idField = dictionary.getIdFieldName(entityType); filterExpression = Optional.of(new FilterPredicate( new FilterPredicate.PathElement( entityType, relation, idType, idField), Operator.IN, Collections.singletonList(idVal))); } Set<PersistentResource> resources = filter(ReadPermission.class, (Set) getRelationChecked(relation, filterExpression), skipNew); for (PersistentResource childResource : resources) { if (childResource.matchesId(id)) { return childResource; } } throw new InvalidObjectIdentifierException(id, relation); }</code><technical_language>remove skipNew this is place this is set</technical_language>

Target:
public PersistentResource getRelation(String relation, String id) { Optional<FilterExpression> filterExpression; boolean skipNew = false; Class<?> entityType = dictionary.getParameterizedType(getResourceClass(), relation); if (requestScope.isMutatingMultipleEntities() && requestScope.getObjectById(dictionary.getJsonAliasFor(entityType), id) != null) { filterExpression = Optional.empty(); skipNew = true; } else { if (entityType == null) { throw new InvalidAttributeException(relation, type); } Class<?> idType = dictionary.getIdType(entityType); Object idVal = CoerceUtil.coerce(id, idType); String idField = dictionary.getIdFieldName(entityType); filterExpression = Optional.of(new FilterPredicate( new FilterPredicate.PathElement( entityType, relation, idType, idField), Operator.IN, Collections.singletonList(idVal))); } Set<PersistentResource> resources = filter(ReadPermission.class, (Set) getRelationChecked(relation, filterExpression), skipNew); for (PersistentResource childResource : resources) { if (childResource.matchesId(id)) { return childResource; } } throw new InvalidObjectIdentifierException(id, relation); }