auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String getCustomField(String fieldName) { <START> if(customFields == null) return null; <END> for (CustomField f : customFields) { if (f.getName().equals(fieldName)) { return f.getValue(); } } return null; }</code><technical_language>init customFields empty collection avoid "==null"</technical_language>

Target:
public String getCustomField(String fieldName) { for (CustomField f : customFields) { if (f.getName().equals(fieldName)) { return f.getValue(); } } return null; }
Source:
<code>public void addSessionWithDefaultPrivileges(String sectionName, String sessionName) { verifyExistenceOfsectionName(sectionName); this.sessionLevel.get(sectionName).put(sessionName, <START> this.sectionLevel.getOrDefault(sessionName, getOverallPrivilegesForSessionsInSection(sectionName))); <END> }</code><technical_language>This is is a more ideal Java 8 method here. figure out one; in scope of this issue revert two. (yes means other places in this file converted)</technical_language>

Target:
public void addSessionWithDefaultPrivileges(String sectionName, String sessionName) { verifyExistenceOfsectionName(sectionName); if (this.sessionLevel.get(sectionName).containsKey(sessionName)) { return; } this.sessionLevel.get(sectionName).put(sessionName, getOverallPrivilegesForSessionsInSection(sectionName)); }
Source:
<code>public void testMmsPartUpdate() { Uri mmsUri = insertInToMmsTable(false, MMS_SUBJECT_ONE); assertThat(mmsUri).isNotNull(); final long mmsId = ContentUris.parseId(mmsUri); final Uri partUri = Telephony.Mms.CONTENT_URI.buildUpon() .appendPath(String.valueOf(mmsId)).appendPath("part").build(); Uri insertPartUri = insertInToMmsPartTable(true, mmsUri, partUri, mmsId, MMS_BODY); assertThat(insertPartUri).isNotNull(); Cursor cursor = mContentResolver.query(partUri, null, null, null); assertThat(cursor.getCount()).isEqualTo(1); cursor.moveToNext(); assertThat(cursor.getString(cursor.getColumnIndex(Telephony.Mms.Part.TEXT))).isEqualTo( MMS_BODY); final ContentValues updateValues = new ContentValues(); updateValues.put(Telephony.Mms.Part.TEXT, MMS_BODY_UPDATE); int cursorUpdate = mContentResolver.update(partUri, updateValues, null, null); assertThat(cursorUpdate).isEqualTo(1); Cursor cursorAfterUpdate = mContentResolver.query(partUri, null, null, null); if (cursorAfterUpdate.getCount() == 0) { return; } assertThat(cursorAfterUpdate.getCount()).isEqualTo(1); cursorAfterUpdate.moveToNext(); <START> assertThat(cursorAfterUpdate.getString(cursorAfterUpdate.getColumnIndex(Telephony.Mms.Part.TEXT))).isEqualTo( <END> MMS_BODY_UPDATE); }</code><technical_language>nit: please break line earlier</technical_language>

Target:
public void testMmsPartUpdate() { Uri mmsUri = insertIntoMmsTable(MMS_SUBJECT_ONE); assertThat(mmsUri).isNotNull(); final long mmsId = ContentUris.parseId(mmsUri); final Uri partUri = Telephony.Mms.CONTENT_URI.buildUpon() .appendPath(String.valueOf(mmsId)).appendPath("part").build(); Uri insertPartUri = insertIntoMmsPartTable(mmsUri, partUri, mmsId, MMS_BODY); assertThat(insertPartUri).isNotNull(); Cursor cursor = mContentResolver.query(partUri, null, null, null); assertThat(cursor.getCount()).isEqualTo(1); cursor.moveToNext(); assertThat(cursor.getString(cursor.getColumnIndex(Telephony.Mms.Part.TEXT))).isEqualTo( MMS_BODY); final ContentValues updateValues = new ContentValues(); updateValues.put(Telephony.Mms.Part.TEXT, MMS_BODY_UPDATE); int cursorUpdate = mContentResolver.update(partUri, updateValues, null, null); assertThat(cursorUpdate).isEqualTo(1); Cursor cursorAfterUpdate = mContentResolver.query(partUri, null, null, null); if (cursorAfterUpdate.getCount() == 0) { return; } assertThat(cursorAfterUpdate.getCount()).isEqualTo(1); cursorAfterUpdate.moveToNext(); assertThat(cursorAfterUpdate.getString(cursorAfterUpdate.getColumnIndex(Telephony.Mms.Part.TEXT))).isEqualTo( MMS_BODY_UPDATE); }
Source:
<code>protected void addDefaultMimetypeIfRequired(Blob blob) { <START> if (blob.getMimeType() == null || "".equals(blob.getMimeType().trim())) { <END> blob.setMimeType("image/jpeg"); } }</code><technical_language>I this is refactored code, please opportunity StringUtils.isBlank here</technical_language>

Target:
protected void addDefaultMimetypeIfRequired(Blob blob) { if (StringUtils.isBlank(blob.getMimeType())) { blob.setMimeType("image/jpeg"); } }
Source:
<code>public Scope getScopeForInterfaceByIfIndex(final Integer nodeId, final int ifIndex) { if (nodeId == null) { return EmptyScope.EMPTY; } final Scope metaDataScope = this.sessionUtils.withReadOnlyTransaction(() -> { final OnmsSnmpInterface snmpInterface = this.snmpInterfaceDao.findByNodeIdAndIfIndex(nodeId, ifIndex); if (snmpInterface == null) { return EmptyScope.EMPTY; } ArrayList<Scope> scopes = new ArrayList<>(); scopes.add(new ObjectScope<>(snmpInterface) <START> .map(INTERFACE, "if-alias", (i) -> Optional.ofNullable(snmpInterface.getIfAlias())) <END> .map(INTERFACE, "if-description", (i) -> Optional.ofNullable(snmpInterface.getIfDescr())) .map(INTERFACE, "phy-addr", (i) -> Optional.ofNullable(snmpInterface.getPhysAddr()))); Optional.ofNullable(snmpInterface.getPrimaryIpInterface()) .ifPresent(ipInterface -> { scopes.add(transform(ipInterface.getMetaData())); scopes.add(mapIpIntefaceKeys(new ObjectScope<>(ipInterface))); }); return new FallbackScope(scopes.toArray(new Scope[0])); }); return metaDataScope; }</code><technical_language>i.getIfAlias() here</technical_language>

Target:
public Scope getScopeForInterfaceByIfIndex(final Integer nodeId, final int ifIndex) { if (nodeId == null) { return EmptyScope.EMPTY; } return this.sessionUtils.withReadOnlyTransaction(() -> { final OnmsSnmpInterface snmpInterface = this.snmpInterfaceDao.findByNodeIdAndIfIndex(nodeId, ifIndex); if (snmpInterface == null) { return EmptyScope.EMPTY; } ArrayList<Scope> scopes = new ArrayList<>(); scopes.add(new ObjectScope<>(snmpInterface) .map(INTERFACE, "if-alias", (i) -> Optional.ofNullable(i.getIfAlias())) .map(INTERFACE, "if-description", (i) -> Optional.ofNullable(i.getIfDescr())) .map(INTERFACE, "phy-addr", (i) -> Optional.ofNullable(i.getPhysAddr()))); Optional.ofNullable(snmpInterface.getPrimaryIpInterface()) .ifPresent(ipInterface -> { scopes.add(transform(ipInterface.getMetaData())); scopes.add(mapIpInterfaceKeys(ipInterface)); }); return new FallbackScope(scopes); }); }
Source:
<code>public void csvWithNoDelimiterShouldReturnNull() { DefaultCSVMetaDataBuilder builder = new DefaultCSVMetaDataBuilder(); <START> CSVMetaDataModel model = builder.addField("name", DataType.STRING).addField("age", DataType.DECIMAL).build(); <END> Assert.assertThat(model, CoreMatchers.nullValue()); }</code><technical_language>"name" is times in this test. Extract a constant</technical_language>

Target:
public void csvWithNoDelimiterShouldReturnNull() { DefaultCSVMetaDataBuilder builder = new DefaultCSVMetaDataBuilder(); CSVMetaDataModel model = builder.addField(FIELD_NAME, DataType.STRING).addField(FIELD_AGE, DataType.DECIMAL).build(); assertThat(model, nullValue()); }
Source:
<code>public void startLastActiveRadioStream() { if (RadioStreamService.isRunning) return; int stationIndex = Settings.getLastActiveRadioStation(context); RadioStation station = null; if (stations != null) { station = stations.get(stationIndex); <START> } if (station != null) { toggleRadioStreamState(stationIndex); <END> } }</code><technical_language>This block removed</technical_language>

Target:
public void startLastActiveRadioStream() { if (RadioStreamService.isRunning) return; if (stations == null) { return; } if (stations.numAvailableStations() == 0) { showRadioStreamDialog(0); return; } int stationIndex = Settings.getLastActiveRadioStation(context); if (stations.get(stationIndex) != null) { toggleRadioStreamState(stationIndex); } }
Source:
<code>public SearchNodeHealthProvider(Props props, System2 system2, ClusterAppState clusterAppState, NetworkUtils networkUtils) { this.clusterAppState = clusterAppState; this.nodeDetails = NodeDetails.newNodeDetailsBuilder() .setType(NodeDetails.Type.SEARCH) .setName(props.nonNullValue(CLUSTER_NODE_NAME)) <START> .setHost(networkUtils.getHostname()) <END> .setPort(Integer.valueOf(props.nonNullValue(CLUSTER_NODE_PORT))) .setStartedAt(system2.now()) .build(); }</code><technical_language>of sonar.cluster.host configured in sonar.properties. localhost hostname sense in response differ configured IP</technical_language>

Target:
public SearchNodeHealthProvider(Props props, System2 system2, ClusterAppState clusterAppState, NetworkUtils networkUtils) { this.clusterAppState = clusterAppState; this.nodeDetails = NodeDetails.newNodeDetailsBuilder() .setType(NodeDetails.Type.SEARCH) .setName(props.nonNullValue(CLUSTER_NODE_NAME)) .setHost(getHost(props, networkUtils)) .setPort(Integer.valueOf(props.nonNullValue(CLUSTER_NODE_PORT))) .setStartedAt(system2.now()) .build(); }
Source:
<code>public Map<String,String> getProperties() { Map<String,String> propertyMap = new HashMap<>(); if (limitVersion) propertyMap.putAll(IteratorUtil.generateInitialTableProperties(limitVersion)); if (createOffline) propertyMap.put(Property.TABLE_OFFLINE_OPTS + "create.offline", "true"); if (createInitialSplits) { propertyMap.put(Property.TABLE_OFFLINE_OPTS + "create.initial.splits", "true"); <START> } <END> propertyMap.putAll(summarizerProps); propertyMap.putAll(samplerProps); propertyMap.putAll(properties); propertyMap.putAll(iteratorProps); propertyMap.putAll(localityProps); return Collections.unmodifiableMap(propertyMap); }</code><technical_language>Keith Properties, map keys internal constants. actions performed API set in config</technical_language>

Target:
public Map<String,String> getProperties() { Map<String,String> propertyMap = new HashMap<>(); if (limitVersion) propertyMap.putAll(IteratorUtil.generateInitialTableProperties(limitVersion)); propertyMap.putAll(summarizerProps); propertyMap.putAll(samplerProps); propertyMap.putAll(properties); propertyMap.putAll(iteratorProps); propertyMap.putAll(localityProps); return Collections.unmodifiableMap(propertyMap); }
Source:
<code>public MatchResults matchIndexEntry(ExpressionOrColumn indexEntry) { int idx; if (isDead() || isDone()) { return MatchResults.DONE_OR_DEAD; } if ( ! m_partitionByExprs.isEmpty() ) { List<AbstractExpression> moreBindings = null; for (ExpressionOrColumn eorc : m_partitionByExprs) { moreBindings = findBindingsForOneIndexedExpression(eorc, indexEntry); if (moreBindings != null) { m_orderedMatchingExpressions.add(eorc.m_expr); for (idx = 0; m_partitionByExprs.remove(eorc) && idx < MAX_LIST_REMOVAL; idx += 1) { ; } assert(idx < MAX_LIST_REMOVAL); m_bindings.addAll(moreBindings); return MatchResults.MATCHED; } } markDead(); return MatchResults.DONE_OR_DEAD; } ExpressionOrColumn nextStatementEOC = m_unmatchedOrderByExprs.get(0); if (m_sortDirection == SortDirectionType.INVALID) { m_sortDirection = nextStatementEOC.m_sortDirection; } if (nextStatementEOC.m_sortDirection != m_sortDirection) { markDead(); return MatchResults.DONE_OR_DEAD; } List<AbstractExpression> moreBindings = findBindingsForOneIndexedExpression(nextStatementEOC, indexEntry); if ( moreBindings != null ) { m_orderedMatchingExpressions.add(nextStatementEOC.m_expr); m_bindings.addAll(moreBindings); for (idx = 0; m_unmatchedOrderByExprs.remove(nextStatementEOC) && idx < MAX_LIST_REMOVAL; idx += 1) { ; } assert(idx < MAX_LIST_REMOVAL); return MatchResults.MATCHED; } assert(0 <= indexEntry.m_indexEntryNumber); if (m_isWindowFunction) { markDead(); return MatchResults.DONE_OR_DEAD; <START> } else { <END> return MatchResults.POSSIBLE_ORDER_SPOILER; } }</code><technical_language>Remove redundant else return</technical_language>

Target:
public MatchResults matchIndexEntry(ExpressionOrColumn indexEntry) { int idx; if (isDead() || isDone()) { return MatchResults.DONE_OR_DEAD; } if ( ! m_partitionByExprs.isEmpty() ) { List<AbstractExpression> moreBindings = null; for (ExpressionOrColumn eorc : m_partitionByExprs) { moreBindings = findBindingsForOneIndexedExpression(eorc, indexEntry); if (moreBindings != null) { m_orderedMatchingExpressions.add(eorc.m_expr); while (m_partitionByExprs.remove(eorc)) { ; } m_bindings.addAll(moreBindings); return MatchResults.MATCHED; } } markDead(); return MatchResults.DONE_OR_DEAD; } ExpressionOrColumn nextStatementEOC = m_unmatchedOrderByExprs.get(0); if (m_sortDirection == SortDirectionType.INVALID) { m_sortDirection = nextStatementEOC.m_sortDirection; } if (nextStatementEOC.m_sortDirection != m_sortDirection) { markDead(); return MatchResults.DONE_OR_DEAD; } List<AbstractExpression> moreBindings = findBindingsForOneIndexedExpression(nextStatementEOC, indexEntry); if ( moreBindings != null ) { m_orderedMatchingExpressions.add(nextStatementEOC.m_expr); m_bindings.addAll(moreBindings); while (m_unmatchedOrderByExprs.remove(nextStatementEOC)) { ; } return MatchResults.MATCHED; } assert(0 <= indexEntry.m_indexKeyComponentPosition); if (isWindowFunction()) { markDead(); return MatchResults.DONE_OR_DEAD; } return MatchResults.POSSIBLE_ORDER_SPOILER; }
Source:
<code>public static <T extends Annotation> List<T> findAnnotations(Class<?> clazz, Class<T> annotationClass) { List<T> anns = new ArrayList<>(); T ann = clazz.getAnnotation(annotationClass); if (ann != null) { anns.add(ann); } ann = clazz.getPackage().getAnnotation(annotationClass); if (ann != null) { anns.add(ann); } if (clazz.getSuperclass() != Object.class) { <START> anns.addAll(findAnnotations(clazz.getSuperclass(), annotationClass)); <END> } return anns; }</code><technical_language>if call findAnnotations(Object.class,...), recursive call ends NPE</technical_language>

Target:
public static <T extends Annotation> List<T> findAnnotations(Class<?> clazz, Class<T> annotationClass) { List<T> anns = new ArrayList<>(); List<Class<?>> classes = new ArrayList<>(); classes.add(clazz); classes.addAll(ClassUtils.getAllSuperclasses(clazz)); classes.addAll(ClassUtils.getAllInterfaces(clazz)); for (Class<?> aClass : classes) { T ann = aClass.getAnnotation(annotationClass); if (ann != null) { anns.add(ann); } ann = aClass.getPackage().getAnnotation(annotationClass); if (ann != null) { anns.add(ann); } } return anns; }
Source:
<code>private void initializeFrom(URL resource, Properties properties) { InputStreamReader input = null; try { input = new InputStreamReader(resource.openStream()); properties.load(input); input.close(); } catch (Exception e) { <START> logger.log(Level.INFO, "Could not load properties file"+resource.toExternalForm(), e); <END> } finally { IOUtils.closeQuietly(input); } }</code><technical_language>Is idea presence of a cucumber-guice.properties file is optional? If case, users annoying logging message? If intention is a cucumber-guice.properties file is mandatory exception caught, thrown up</technical_language>

Target:
private void initializeFrom(URL resource, Properties properties) { InputStreamReader input = null; try { input = new InputStreamReader(resource.openStream()); properties.load(input); } catch (Exception e) { String message = MessageFormat.format("Could not load properties from ''{0}''", resource.toExternalForm()); throw new LoadingPropertiesFileFailed(message, e); } finally { closeQuietly(input); } }
Source:
<code>public void importMrrtReportTemplate(InputStream in) throws IOException { final File tmp = File.createTempFile(java.util.UUID.randomUUID() .toString(), java.util.UUID.randomUUID() .toString()); OpenmrsUtil.copyFile(in, new FileOutputStream(tmp)); <START> MrrtReportTemplate template = parser.parse(new FileInputStream(tmp)); <END> final File destinationFile = new File(radiologyProperties.getReportTemplateHome(), java.util.UUID.randomUUID() .toString()); template.setPath(destinationFile.getAbsolutePath()); saveMrrtReportTemplate(template); OpenmrsUtil.copyFile(new FileInputStream(tmp), new FileOutputStream(destinationFile)); in.close(); }</code><technical_language>@ivange94 final</technical_language>

Target:
public void importMrrtReportTemplate(InputStream in) throws IOException { final File tmp = File.createTempFile(java.util.UUID.randomUUID() .toString(), java.util.UUID.randomUUID() .toString()); OpenmrsUtil.copyFile(in, new FileOutputStream(tmp)); final MrrtReportTemplate template = parser.parse(new FileInputStream(tmp)); final File destinationFile = new File(radiologyProperties.getReportTemplateHome(), java.util.UUID.randomUUID() .toString()); template.setPath(destinationFile.getAbsolutePath()); saveMrrtReportTemplate(template); OpenmrsUtil.copyFile(new FileInputStream(tmp), new FileOutputStream(destinationFile)); in.close(); }
Source:
<code>private void updateDataFileChangeListeners() { <START> if (dataFileChangeListeners == null) { <END> return; } for (DataFileChangeListener listener : dataFileChangeListeners) { listener.onColumnsChange(this); } }</code><technical_language>If field final I suggest above, this null here</technical_language>

Target:
private void updateDataFileChangeListeners() { if (this.isAttached()) { for (DataFileChangeListener listener : dataFileChangeListeners) { listener.onColumnsChange(this); } } }
Source:
<code>public boolean consumeItem(EntityRef player, Prefab prefab) { <START> OreonSpawnComponent oreonSpawnComponent = prefab.getComponent(OreonSpawnComponent.class); <END> HashMap<String, Integer> itemsHashMap = oreonSpawnComponent.itemsToConsume; if (oreonSpawnComponent.itemsToConsume != null) { ArrayList<String> neededItemList = new ArrayList(itemsHashMap.keySet()); int numberOfItems = neededItemList.size(); if (player.hasComponent(InventoryComponent.class)) { ArrayList<Integer> requiredSlots = getSlotsForRequiredItems(itemsHashMap, player); if (requiredSlots.size() != numberOfItems) { logger.info("Could not find all required items in inventory"); return false; } for (int slotNumber = 0; slotNumber < numberOfItems; slotNumber++) { if(!removeNeededItem(itemsHashMap, requiredSlots.get(slotNumber), player)) { return false; } } logger.info("Found all items required for spawning, creating your Oreon"); return true; } logger.info("No inventory to source material from, cannot spawn"); return false; } logger.info("No item required to spawn, spawning your Oreon"); return true; }</code><technical_language>guarantee oreonSpawnComponent is non-null</technical_language>

Target:
private boolean consumeItem(EntityRef player, Prefab prefab) { OreonSpawnComponent oreonSpawnComponent = prefab.getComponent(OreonSpawnComponent.class); if (oreonSpawnComponent == null) { logger.info(prefab.getName() + " is not spawnable."); return false; } Map<String, Integer> itemsHashMap = oreonSpawnComponent.itemsToConsume; int numberOfItems = itemsHashMap.size(); if (numberOfItems != 0) { if (player.hasComponent(InventoryComponent.class)) { List<Integer> requiredSlots = getSlotsForRequiredItems(itemsHashMap, player); if (requiredSlots.size() != numberOfItems) { logger.info("Could not find all required items in inventory"); return false; } for (int slotNumber = 0; slotNumber < numberOfItems; slotNumber++) { if (!removeNeededItem(itemsHashMap, requiredSlots.get(slotNumber), player)) { return false; } } logger.info("Found all items required for spawning, creating your Oreon"); return true; } logger.info("No inventory to source material from, cannot spawn"); return false; } logger.info("No item required to spawn, spawning your Oreon"); return true; }
Source:
<code>private Response createResponse(HotRodHeader h, OperationStatus st, byte[] prev) { if (hasFlag(h, ProtocolFlag.ForceReturnPreviousValue)) { switch (st) { case Success: switch (h.op) { case PUT: <START> case PUT_MULTIMAP: <END> case REPLACE: case REMOVE_IF_UNMODIFIED: case REMOVE: case REPLACE_IF_UNMODIFIED: return new ResponseWithPrevious(h.version, h.messageId, h.cacheName, h.clientIntel, h.op, OperationStatus.SuccessWithPrevious, h.topologyId, Optional.ofNullable(prev)); } break; case OperationNotExecuted: switch (h.op) { case PUT_IF_ABSENT: case REPLACE_IF_UNMODIFIED: case REMOVE_IF_UNMODIFIED: return new ResponseWithPrevious(h.version, h.messageId, h.cacheName, h.clientIntel, h.op, OperationStatus.NotExecutedWithPrevious, h.topologyId, Optional.ofNullable(prev)); } break; } } return new EmptyResponse(h.version, h.messageId, h.cacheName, h.clientIntel, h.op, st, h.topologyId); }</code><technical_language>I belongs here</technical_language>

Target:
private Response createResponse(HotRodHeader h, OperationStatus st, byte[] prev) { if (hasFlag(h, ProtocolFlag.ForceReturnPreviousValue)) { switch (st) { case Success: switch (h.op) { case PUT: case REPLACE: case REMOVE_IF_UNMODIFIED: case REMOVE: case REPLACE_IF_UNMODIFIED: return new ResponseWithPrevious(h.version, h.messageId, h.cacheName, h.clientIntel, h.op, OperationStatus.SuccessWithPrevious, h.topologyId, Optional.ofNullable(prev)); } break; case OperationNotExecuted: switch (h.op) { case PUT_IF_ABSENT: case REPLACE_IF_UNMODIFIED: case REMOVE_IF_UNMODIFIED: return new ResponseWithPrevious(h.version, h.messageId, h.cacheName, h.clientIntel, h.op, OperationStatus.NotExecutedWithPrevious, h.topologyId, Optional.ofNullable(prev)); } break; } } return new EmptyResponse(h.version, h.messageId, h.cacheName, h.clientIntel, h.op, st, h.topologyId); }
Source:
<code>public static boolean isVisible(MCoreExpression exp, final ExpressionContext eContext) { final Expression ref; if (exp.getCoreExpression() instanceof Expression) { ref = (Expression) exp.getCoreExpression(); } else { ref = new ReferenceExpression(exp.getCoreExpressionId()); exp.setCoreExpression(ref); } ExpressionInfo info = ref.computeExpressionInfo(); String[] names = info.getAccessedPropertyNames(); for (String name : names) { eContext.getVariable(name + ".evaluationServiceLink"); } <START> final boolean[] ret = new boolean[1]; <END> ret[0] = false; try { ret[0] = ref.evaluate(eContext) != EvaluationResult.FALSE; } catch (Exception e) { trace("isVisible exception", e); } return ret[0]; }</code><technical_language>This array needed anymore, turned a boolean. I this method called frequently, worth allocating array</technical_language>

Target:
public static boolean isVisible(MCoreExpression exp, final ExpressionContext eContext) { final Expression ref; if (exp.getCoreExpression() instanceof Expression) { ref = (Expression) exp.getCoreExpression(); } else { ref = new ReferenceExpression(exp.getCoreExpressionId()); exp.setCoreExpression(ref); } ExpressionInfo info = ref.computeExpressionInfo(); String[] names = info.getAccessedPropertyNames(); for (String name : names) { eContext.getVariable(name + ".evaluationServiceLink"); } boolean ret = false; try { ret = ref.evaluate(eContext) != EvaluationResult.FALSE; } catch (Exception e) { trace("isVisible exception", e); } return ret; }
Source:
<code>public void doStuff() { int x = 1; switch (x) { case 0: { break; } case (1+0): { break; } case 2: { break; } default: { break; } case 3: case 4: x++; <START> { END> } break; } switch (x) { case 0: { break; } default: } }</code><technical_language>if is first, x++? treated a standalone block. please add options</technical_language>

Target:
public void doStuff() { int x = 1; switch (x) { case 0: { break; } case (1+0): { break; } case 2: { break; } default: { break; } case 3: case 4: x++; { } break; case 5: { } break; case (5 +1): { break; } case 7 : { break; } } switch (x) { case 0: { break; } default: } }
Source:
<code>Map<String, Object> callWithExecutionId(final String host, final int port, final String action, final Integer executionId, final String user, final Pair<String, String>... params) throws ExecutorManagerException { try { final List<Pair<String, String>> paramList = new ArrayList<>(); if (params != null) { paramList.addAll(Arrays.asList(params)); } paramList .add(new Pair<>(ConnectorParams.ACTION_PARAM, action)); paramList.add(new Pair<>(ConnectorParams.EXECID_PARAM, String .valueOf(executionId))); paramList.add(new Pair<>(ConnectorParams.USER_PARAM, user)); <START> final Map<String, Object> jsonResponse = <END> callForJsonObjectMap(host, port, "/executor", paramList); return jsonResponse; } catch (final IOException e) { throw new ExecutorManagerException(e); } }</code><technical_language>return directly</technical_language>

Target:
Map<String, Object> callWithExecutionId(final String host, final int port, final String action, final Integer executionId, final String user, final Pair<String, String>... params) throws ExecutorManagerException { try { final List<Pair<String, String>> paramList = new ArrayList<>(); if (params != null) { paramList.addAll(Arrays.asList(params)); } paramList .add(new Pair<>(ConnectorParams.ACTION_PARAM, action)); paramList.add(new Pair<>(ConnectorParams.EXECID_PARAM, String .valueOf(executionId))); paramList.add(new Pair<>(ConnectorParams.USER_PARAM, user)); return callForJsonObjectMap(host, port, "/executor", paramList); } catch (final IOException e) { throw new ExecutorManagerException(e); } }
Source:
<code>public static RepoIO createApplicationRepoIO() { return new RepoIO(isTestMode() ? Optional.of(new DummySource()) : Optional.empty(), <START> isTestJSONEnabled() ? Optional.of(new JSONStoreStub()) : Optional.empty(), <END> isTestMode() ? Optional.of(RepoStore.TEST_DIRECTORY) : Optional.empty()); }</code><technical_language>I confused this line. In original, if isTestJSONEnabled() is true, Optional.empty. Otherwise, stub. This holds true if is in test mode. I this close original more readable this if (isTestMode()) { return new RepoIO(Optional.of(new DummySource()), isTestJSONEnabled() ? Optional.empty() : Optional.of(new JSONStoreStub()), Optional.of(RepoStore.TEST_DIRECTORY)); } else { return new RepoIO(Optional.empty(), Optional.empty(), Optional.empty()); } safe if test json command line option is set true, i.e. isTestJSONEnabled() is true, isTestMode() return true. if developer forgot put test mode true testing json is set true, real JSONs messed up</technical_language>

Target:
public static RepoIO createApplicationRepoIO() { if (isTestMode()) { return createTestingRepoIO(isTestJSONEnabled() ? Optional.of(new JSONStoreStub()) : Optional.empty()); } else { return new RepoIO(Optional.empty(), Optional.empty(), Optional.empty()); } }
Source:
<code>protected String extractShareName(URI uri) throws FileSystemException { String s = uri.getPath().startsWith("/") ? uri.getPath().substring(1) : uri.getPath(); String[] pathParts = s.split("/"); String share = pathParts[0]; if (share == null || share.equals("")) { throw new FileSystemException("vfs.provider.smb2/missing-share-name.error", uri.toString()); } <START> <END> return pathParts[0]; }</code><technical_language>Please remove this extra line</technical_language>

Target:
protected String extractShareName(URI uri) throws FileSystemException { String path = uri.getPath(); path = path.startsWith("/") ? path.substring(1) : path; String[] pathParts = path.split("/"); String share = pathParts[0]; if (share == null || share.isEmpty()) { throw new FileSystemException("vfs.provider.smb2/missing-share-name.error", uri.toString()); } return pathParts[0]; }
Source:
<code>public void testES6ImportOfCJS() { args.add("--process_common_js_modules"); args.add("--entry_point=app"); args.add("--dependency_mode=STRICT"); args.add("--language_in=ECMASCRIPT6"); setFilename(0, "foo.js"); setFilename(1, "app.js"); test(new String[] { <START> " function Foo () {}" + <END> "Foo.prototype.bar = function() { console.log('bar'); };" + "module.exports = Foo;", "import * as FooBar from './foo';" + "var baz = new FooBar();" + "console.log(baz.bar());" }, new String[] { "function Foo$$module$foo(){}" + "Foo$$module$foo.prototype.bar=function(){console.log(\"bar\")};" + "var module$foo=Foo$$module$foo;", "var module$app={}," + "baz$$module$app$$module$app=new module$foo();" + "console.log(baz$$module$app$$module$app.bar());" }); }</code><technical_language>pull out a join method takes varargs String... joins a line break (using Joiner)? That'd this code more readable error messages code produce. I vaguely remember writing in another file, longer remember - for Joiner in test files</technical_language>

Target:
public void testES6ImportOfCJS() { args.add("--process_common_js_modules"); args.add("--entry_point=app"); args.add("--dependency_mode=STRICT"); args.add("--language_in=ECMASCRIPT6"); setFilename(0, "foo.js"); setFilename(1, "app.js"); test(new String[] { " function Foo () {}" + "Foo.prototype.bar = function() { console.log('bar'); };" + "module.exports = Foo;", "import * as FooBar from './foo';" + "var baz = new FooBar();" + "console.log(baz.bar());" }, new String[] { "function Foo$$module$foo(){}" + "Foo$$module$foo.prototype.bar=function(){console.log(\"bar\")};" + "var module$foo=Foo$$module$foo;", "var module$app={}," + "baz$$module$app$$module$app=new Foo$$module$foo();" + "console.log(baz$$module$app$$module$app.bar());" }); }
Source:
<code>public void testEmptyStringPathParameter() { ConjureRuntime runtime = DefaultConjureRuntime.builder().build(); Channel channel = mock(Channel.class); Response response = mock(Response.class); when(response.body()).thenReturn(new ByteArrayInputStream(new byte[0])); when(response.code()).thenReturn(204); when(response.headers()).thenReturn(ImmutableListMultimap.of()); when(channel.execute(any(Endpoint.class), any(Request.class))).thenReturn(Futures.immediateFuture(response)); StubService service = JaxRsClient.create(StubService.class, channel, runtime); service.innerPath(""); ArgumentCaptor<Endpoint> endpointCaptor = ArgumentCaptor.forClass(Endpoint.class); ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class); verify(channel).execute(endpointCaptor.capture(), requestCaptor.capture()); UrlBuilder urlBuilder = mock(UrlBuilder.class); endpointCaptor.getValue().renderPath(ImmutableMap.of(), urlBuilder); verify(urlBuilder).pathSegment("foo"); verify(urlBuilder).pathSegment("begin"); verify(urlBuilder).pathSegment(""); verify(urlBuilder).pathSegment("end"); <START> } <END></code><technical_language>set code in tests, I find a hard read. extract mock channel setup a function</technical_language>

Target:
public void testEmptyStringPathParameter() { Channel channel = stubNoContentResponseChannel(); StubService service = JaxRsClient.create(StubService.class, channel, runtime); service.innerPath(""); ArgumentCaptor<Endpoint> endpointCaptor = ArgumentCaptor.forClass(Endpoint.class); ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class); verify(channel).execute(endpointCaptor.capture(), requestCaptor.capture()); UrlBuilder urlBuilder = mock(UrlBuilder.class); endpointCaptor.getValue().renderPath(ImmutableMap.of(), urlBuilder); verify(urlBuilder).pathSegment("foo"); verify(urlBuilder).pathSegment("begin"); verify(urlBuilder).pathSegment(""); verify(urlBuilder).pathSegment("end"); }
Source:
<code>void setForegroundColor (GdkColor color) { super.setForegroundColor (color); setForegroundColor (fixedHandle, color); if (labelHandle != 0) setForegroundColor (labelHandle, color); if (imageHandle != 0) setForegroundColor (imageHandle, color); <START> if (OS.GTK_VERSION >= OS.VERSION(3, 10, 0) && (style & (SWT.CHECK | SWT.RADIO)) != 0) { <END> gtk_swt_set_border_color (color); } }</code><technical_language>Please version guard this check < 3.16.0. Playing css esp. theme 3.16.0 is css is dangerous</technical_language>

Target:
void setForegroundColor (GdkColor color) { super.setForegroundColor (color); setForegroundColor (fixedHandle, color); if (labelHandle != 0) setForegroundColor (labelHandle, color); if (imageHandle != 0) setForegroundColor (imageHandle, color); if (OS.GTK_VERSION >= OS.VERSION(3, 10, 0) && OS.GTK_VERSION < OS.VERSION (3, 16, 0) && (style & (SWT.CHECK | SWT.RADIO)) != 0) { gtk_swt_set_border_color (color); } }
Source:
<code><START> public Download call() throws IOException { <END> File stagingDir = DownloadUtility.createDownloadStagingArea(); LOG.info("Staging item download at location for item {}", stagingDir.getAbsolutePath(), itemId); Item item; try (ItemManager itemManager = new ItemManager()) { item = itemManager.load(itemId); } if (item == null) { throw new IOException(MessageFormat.format("Item {0} does not exist", itemId)); } Download download; try (DownloadManager downloadManager = new DownloadManager()) { download = downloadManager.load(itemId); if (download == null) { LOG.info("Beginning staging item {}", itemId); download = new Download(); download.setItemId(itemId); downloadManager.save(download); } } boolean staged = DownloadUtility.stageItemDownload(item, stagingDir); if (staged) { LOG.info("Item has been staged", itemId); try { download = DownloadUtility.zipStagingAreaForDownload(stagingDir, download); } catch (IOException ioe) { LOG.warn("Download could not be staged", ioe); FileUtils.forceDelete(stagingDir); download.setProblem(true); } } else { LOG.warn("Staging item has run into a problem.", itemId); download.setProblem(true); } try (DownloadManager downloadManager = new DownloadManager()) { downloadManager.update(download); } return download; }</code><technical_language>I idea of smaller try-blocks, in practice I is making code harder read</technical_language>

Target:
public Download call() throws IOException { File stagingDir = DownloadUtility.createDownloadStagingArea(); LOG.info("Staging item download at location for item {}", stagingDir.getAbsolutePath(), itemId); Item item; try (ItemManager itemManager = new ItemManager()) { item = itemManager.load(itemId); } if (item == null) { throw new IOException(MessageFormat.format("Item {0} does not exist", itemId)); } Download download = null; try (DownloadManager downloadManager = new DownloadManager()) { download = downloadManager.load(itemId); if (download == null) { LOG.info("Beginning staging item {}", itemId); download = new Download(); download.setItemId(itemId); downloadManager.save(download); } } boolean staged = DownloadUtility.stageItemDownload(item, stagingDir); if (staged) { LOG.info("Item has been staged", itemId); try { download = DownloadUtility.zipStagingAreaForDownload(stagingDir, download); } catch (IOException ioe) { LOG.warn("Download could not be staged", ioe); FileUtils.forceDelete(stagingDir); download.setProblem(true); } } else { LOG.warn("Staging item has run into a problem.", itemId); download.setProblem(true); } try (DownloadManager downloadManager = new DownloadManager()) { downloadManager.update(download); } return download; }
Source:
<code><START> private void saveDataToModelGraph(String selected) { <END> model.setGraph(selected); setKeyEnablement( GraphFactory.isKeyRequired(model.getGraphID(), model.getDataSet()), GraphFactory.isKeyOptional(model.getGraphID(), model.getDataSet())); }</code><technical_language>Yeah... systemtap code is in great shape try improve bits touch little</technical_language>

Target:
private void saveDataToModelGraph(String selected) { model.setGraph(selected); }
Source:
<code>public void testExecuteAndPostProcess() { ______TS("Typical case for adding template question 1"); InstructorAttributes instructor1ofCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor1ofCourse1.googleId); FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("session1InCourse1"); String[] params = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), Const.ParamsNames.FEEDBACK_QUESTION_TEMPLATE_NUMBER, "1" }; InstructorFeedbackTemplateQuestionAddAction action = getAction(params); RedirectResult result = getRedirectResult(action); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_FEEDBACK_EDIT_PAGE, instructor1ofCourse1.courseId, "First+feedback+session", instructor1ofCourse1.googleId, false), result.getDestinationWithParams()); assertEquals(Const.StatusMessages.FEEDBACK_QUESTION_ADDED, result.getStatusMessage()); String expectedLogMessage = "TEAMMATESLOG|||instructorFeedbackTemplateQuestionAdd|||" + "instructorFeedbackTemplateQuestionAdd|||true|||" + "Instructor|||Instructor 1 of Course 1|||" + "idOfInstructor1OfCourse1|||instr1@course1.tmt|||" + "Added Feedback Template Question for Feedback Session:<span class=\"bold\">" + "(First feedback session)</span> for Course " + "<span class=\"bold\">[idOfTypicalCourse1]</span>" + " created.<br><span class=\"bold\">Team contribution question:</span> " + "Your estimate of how much each team member has contributed.|||" + "/page/instructorFeedbackTemplateQuestionAdd"; AssertHelper.assertLogMessageEquals(expectedLogMessage, action.getLogMessage()); <START> Logic logic = new Logic(); <END> FeedbackQuestionAttributes fqa = logic.getFeedbackQuestion(fs.getFeedbackSessionName(), fs.getCourseId(), 1); assertNotNull(fqa); }</code><technical_language>Init FeedbackQuestionsLogic enough</technical_language>

Target:
public void testExecuteAndPostProcess() { }
Source:
<code>protected <T extends VisitableCommand> InvocationStage retryWhenDone( CompletableFuture<Void> future, int topologyId, InvocationContext ctx, T command, Consumer<ConsistentHash> consistentHashConsumer) throws Throwable { if (future.isDone()) { getLog().tracef("Retrying command %s for topology %d", command, topologyId); return invokeNext(ctx, command); } else { CancellableRetry<T> cancellableRetry = new CancellableRetry<>(command, topologyId, stateTransferManager, consistentHashConsumer); CompletableFuture<Void> retryFuture = future.handleAsync(cancellableRetry, remoteExecutor); ScheduledFuture<?> timeoutFuture = timeoutExecutor.schedule(() -> { <START> TimeoutException timeoutException = new TimeoutException("Timed out waiting for topology " + topologyId); <END> if (cancellableRetry.cancel(timeoutException)) { retryFuture.completeExceptionally(timeoutException); } }, transactionDataTimeout, TimeUnit.MILLISECONDS); retryFuture.whenComplete((nil, throwable) -> timeoutFuture.cancel(false)); return invokeNextAsync(ctx, command, retryFuture); } }</code><technical_language>CancellableRetry topology id, create exception there</technical_language>

Target:
protected <T extends VisitableCommand> InvocationStage retryWhenDone( CompletableFuture<Void> future, int topologyId, InvocationContext ctx, T command, Consumer<ConsistentHash> consistentHashConsumer) throws Throwable { if (future.isDone()) { getLog().tracef("Retrying command %s for topology %d", command, topologyId); return invokeNext(ctx, command); } else { CancellableRetry<T> cancellableRetry = new CancellableRetry<>(command, topologyId, stateTransferManager, consistentHashConsumer); CompletableFuture<Void> retryFuture = future.handleAsync(cancellableRetry, remoteExecutor); cancellableRetry.setRetryFuture(retryFuture); ScheduledFuture<?> timeoutFuture = timeoutExecutor.schedule(cancellableRetry, transactionDataTimeout, TimeUnit.MILLISECONDS); cancellableRetry.setTimeoutFuture(timeoutFuture); return invokeNextAsync(ctx, command, retryFuture); } }
Source:
<code>public static List<Long> indexes(final MutableBitSet bits) { <START> List indexes = new ArrayList(); <END> for (long i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) { indexes.add(i); } return indexes; }</code><technical_language>initialize cardinality of bits, e.g. List<Long> indexes = new ArrayList<Long>((int) bits.cardinality());</technical_language>

Target:
public static List<Long> indexes(final MutableBitSet bits) { List<Long> indexes = new ArrayList<>((int) bits.cardinality()); for (long i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) { indexes.add(i); } return indexes; }
Source:
<code>static boolean isExpired(LocalDateTime expiry) { val now = LocalDateTime.now(); log.trace("Now DateTime: %s%n", now); log.trace("Specified Expiry: %s%n", expiry); if (expiry.isBefore(now)) { <START> System.out.println("Expired!"); <END> } else { System.out.println("Not expired; still " + ChronoUnit.SECONDS.between(now, expiry) + " seconds to go"); } return expiry.isBefore(now); }</code><technical_language>this stderr Terminal</technical_language>

Target:
static boolean isExpired(LocalDateTime expiry) { val now = LocalDateTime.now(); log.trace("Now DateTime: %s%n", now); log.trace("Specified Expiry: %s%n", expiry); return expiry.isBefore(now); }
Source:
<code>public static Bytes addTriplePrefixAndConvertToBytes(byte[] tripleBytes) { BytesBuilder builder = Bytes.builder(); <START> return builder.append(TRIPLE_PREFIX_BYTES).append(tripleBytes).toBytes(); <END> }</code><technical_language>requireNonNull(tripleBytes)</technical_language>

Target:
public static Bytes addTriplePrefixAndConvertToBytes(byte[] tripleBytes) { checkNotNull(tripleBytes); BytesBuilder builder = Bytes.builder(); return builder.append(TRIPLE_PREFIX_BYTES).append(tripleBytes).toBytes(); }
Source:
<code>public EmbeddedTransaction(TransactionManager transactionManager, Transaction nativeTransaction, Type type) { super(transactionManager); <START> if (nativeTransaction instanceof PlaceboTransaction) { <END> LOGGER.debug("placebo Transaction"); } this.nativeTransaction = nativeTransaction; this.type = type; }</code><technical_language>Development fragment</technical_language>

Target:
public EmbeddedTransaction(TransactionManager transactionManager, Transaction nativeTransaction, Type type) { super(transactionManager); this.nativeTransaction = nativeTransaction; this.type = type; }
Source:
<code>private String getCompatVersion() { int version = Integer.parseInt(getStoragePool().getStoragePoolFormatType().getValue()); if (version >= 4) { return VDSM_COMPAT_VERSION_1_1; } <START> return VDSM_COMPAT_DEFAULT_VERSION; <END> }</code><technical_language>explicitly this version is leaving before</technical_language>

Target:
private String getCompatVersion() { int version = Integer.parseInt(getStoragePool().getStoragePoolFormatType().getValue()); if (version >= 4 && getVm().getOrigin() != OriginType.KVM) { return VDSM_COMPAT_VERSION_1_1; } return null; }
Source:
<code>public void testNullFileByFileName() { try { byte[] nullContents = LoadFileUtils.safelyLoadFileBytes(StringUtils.EMPTY); } catch (RuntimeException re) { assertTrue(true); return; } <START> assertTrue("An empty file name should throw a run time axpection as the file can't be found ", false); <END> }</code><technical_language>Another method assertions simplified (remove always-succeeding assertion, replace always-failing assertTrue() fail(), etc.). Also, please fix error message typo (should "exception" instead of "axpection")</technical_language>

Target:
public void testNullFileByFileName() { try { byte[] nullContents = LoadFileUtils.safelyLoadFileBytes(StringUtils.EMPTY); fail("An empty file name should throw a run time exception as the file can't be found "); } catch (RuntimeException re) { } }
Source:
<code>private DefaultScanResult scanDependencies() { if ( getDependenciesToScan() == null ) { return null; } else { try { DefaultScanResult scanResult = new DefaultScanResult( Collections.EMPTY_LIST ); List<String> dependenciesToScanList = new ArrayList( Arrays.asList( getDependenciesToScan() ) ); TestListResolver includedAndExcludedTests = getIncludedAndExcludedTests(); for ( MavenProject mavenProject : session.getSortedProjects() ) { <START> String groupArtifactId = new StringBuilder( mavenProject.getGroupId() ).append( ":" ) <END> .append( mavenProject.getArtifactId() ).toString(); if ( dependenciesToScanList.removeAll( Collections.singleton( groupArtifactId ) ) ) { File outputDirectoryFile = new File( mavenProject.getBuild().getOutputDirectory() ); DirectoryScanner scanner = new DirectoryScanner( outputDirectoryFile, includedAndExcludedTests ); scanResult = scanResult.append( scanner.scan() ); } } @SuppressWarnings( "unchecked" ) List<File> dependenciesToScanFileList = DependencyScanner.filter( project.getTestArtifacts(), dependenciesToScanList ); DependencyScanner scanner = new DependencyScanner( dependenciesToScanFileList, includedAndExcludedTests ); return scanResult.append( scanner.scan() ); } catch ( Exception e ) { throw new RuntimeException( e ); } } }</code><technical_language>Pls concatenate mavenProject.getGroupId() + ":" + mavenProject.getArtifactId(). This is simple javac compile StringBuilder anyway, longer in sources</technical_language>

Target:
private DefaultScanResult scanDependencies() { if ( getDependenciesToScan() == null ) { return null; } else { try { @SuppressWarnings( "unchecked" ) List<File> dependenciesToScan = DependencyScanner.filter( project.getTestArtifacts(), Arrays.asList( getDependenciesToScan() ) ); DependencyScanner scanner = new DependencyScanner( dependenciesToScan, getIncludedAndExcludedTests() ); return scanner.scan(); } catch ( Exception e ) { throw new RuntimeException( e ); } } }
Source:
<code><START> public synchronized CryptoService getCryptoService() { <END> if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; }</code><technical_language>if this needs synchronized</technical_language>

Target:
public CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; }
Source:
<code><START> public int getDisplayExecutionPageSize() { <END> return displayExecutionPageSize; }</code><technical_language>need introduce public here? package-access is good enough</technical_language>

Target:
protected int getDisplayExecutionPageSize() { return displayExecutionPageSize; }
Source:
<code>public Object get(DataFetchingEnvironment environment) { GeometryFactory gf = new GeometryFactory(); List<Shape> shapes = new ArrayList<>(); Map<String, Object> parentFeedMap = environment.getSource(); String namespace = (String) parentFeedMap.get("namespace"); Connection connection = null; try { connection = GTFSGraphQL.getConnection(); Statement statement = connection.createStatement(); String sql = String.format( "select shape_id, shape_pt_lon, shape_pt_lat from %s.shapes order by shape_id", namespace ); LOG.info("SQL: {}", sql); <START> if (statement.execute(sql)) { <END> ResultSet result = statement.getResultSet(); String currentShapeId = null; String nextShapeId; List<Point> shapePoints = new ArrayList<>(); while (result.next()) { nextShapeId = result.getString(1); double lon = result.getDouble(2); double lat = result.getDouble(3); if (currentShapeId != null && !nextShapeId.equals(currentShapeId)) { shapes.add(new Shape(currentShapeId, shapePoints)); shapePoints = new ArrayList<>(); } currentShapeId = nextShapeId; shapePoints.add(gf.createPoint(new Coordinate(lon, lat))); } shapes.add(new Shape(currentShapeId, shapePoints)); } } catch (SQLException e) { throw new RuntimeException(e); } finally { DbUtils.closeQuietly(connection); } return shapes; }</code><technical_language>this fetch single shape do filtering shape_id bounding box. logic implemented here, args in GraphQL schema removed</technical_language>

Target:
public Object get(DataFetchingEnvironment environment) { Map<String, Object> parentFeedMap = environment.getSource(); String namespace = (String) parentFeedMap.get("namespace"); Connection connection = null; try { List<Shape> shapes = new ArrayList<>(); connection = GTFSGraphQL.getConnection(); Set<String> shapeIds = new HashSet<>(); String getShapeIdsSql = String.format("select distinct shape_id from %s.shapes", namespace); LOG.info(getShapeIdsSql); ResultSet shapeIdsResult = connection.createStatement().executeQuery(getShapeIdsSql); while (shapeIdsResult.next()) { shapeIds.add(shapeIdsResult.getString(1)); } PreparedStatement shapePointsStatement = connection.prepareStatement(String.format( "select shape_pt_lon, shape_pt_lat from %s.shapes where shape_id = ? order by shape_pt_sequence", namespace )); for (String shapeId : shapeIds) { shapePointsStatement.setString(1, shapeId); ResultSet result = shapePointsStatement.executeQuery(); List<Point> shapePoints = new ArrayList<>(); while (result.next()) { double lon = result.getDouble(1); double lat = result.getDouble(2); shapePoints.add(gf.createPoint(new Coordinate(lon, lat))); } shapes.add(new Shape(shapeId, shapePoints)); } return shapes; } catch (SQLException e) { throw new RuntimeException(e); } finally { DbUtils.closeQuietly(connection); } }