auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
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(); assertThat(cursorAfterUpdate.getString(cursorAfterUpdate.getColumnIndex(Telephony.Mms.Part.TEXT))).isEqualTo( MMS_BODY_UPDATE); }

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:
protected void addDefaultMimetypeIfRequired(Blob blob) { if (blob.getMimeType() == null || "".equals(blob.getMimeType().trim())) { blob.setMimeType("image/jpeg"); } }

Target:
protected void addDefaultMimetypeIfRequired(Blob blob) { if (StringUtils.isBlank(blob.getMimeType())) { blob.setMimeType("image/jpeg"); } }
Source:
protected List retrieveTransactions() { List groupedTransactions = new ArrayList(); List transactions = (List) businessObjectService.findMatchingOrderBy(CorporateBilledCorporatePaidTransaction.class, new HashMap(), KFSPropertyConstants.TRANSACTION_CREDIT_CARD_NUMBER, true); boolean singleTransaction = parameterService.getParameterValueAsBoolean(ProcurementCardCreateDocumentsStep.class, SINGLE_TRANSACTION_IND_PARM_NM); List documentTransactions = new ArrayList(); if (singleTransaction) { for (Iterator iter = transactions.iterator(); iter.hasNext(); ) { documentTransactions.add(iter.next()); groupedTransactions.add(documentTransactions); documentTransactions = new ArrayList(); } } else { Map cardTransactionsMap = new HashMap(); for (Iterator iter = transactions.iterator(); iter.hasNext(); ) { CorporateBilledCorporatePaidTransaction transaction = (CorporateBilledCorporatePaidTransaction) iter.next(); if (!cardTransactionsMap.containsKey(transaction.getTransactionCreditCardNumber())) { cardTransactionsMap.put(transaction.getTransactionCreditCardNumber(), new ArrayList()); } ((List) cardTransactionsMap.get(transaction.getTransactionCreditCardNumber())).add(transaction); } for (Iterator iter = cardTransactionsMap.values().iterator(); iter.hasNext(); ) { groupedTransactions.add(iter.next()); } } return groupedTransactions; }

Target:
protected List retrieveTransactions() { List<List<CorporateBilledCorporatePaidTransaction>> groupedTransactions = new ArrayList<List<CorporateBilledCorporatePaidTransaction>>(); List<CorporateBilledCorporatePaidTransaction> cbcpTransactions = (List<CorporateBilledCorporatePaidTransaction>) businessObjectService.findMatchingOrderBy(CorporateBilledCorporatePaidTransaction.class, new HashMap<String, String>(), KFSPropertyConstants.TRANSACTION_CREDIT_CARD_NUMBER, true); boolean singleTransaction = parameterService.getParameterValueAsBoolean(ProcurementCardCreateDocumentsStep.class, SINGLE_TRANSACTION_IND_PARM_NM); if (singleTransaction) { List<CorporateBilledCorporatePaidTransaction> documentTransactions = new ArrayList<CorporateBilledCorporatePaidTransaction>(); for (CorporateBilledCorporatePaidTransaction transaction : cbcpTransactions) { documentTransactions.add(transaction); groupedTransactions.add(documentTransactions); documentTransactions = new ArrayList<CorporateBilledCorporatePaidTransaction>(); } } else { Map<String, List<CorporateBilledCorporatePaidTransaction>> cardTransactionsMap = new HashMap<String, List<CorporateBilledCorporatePaidTransaction>>(); for (CorporateBilledCorporatePaidTransaction transaction : cbcpTransactions) { if (!cardTransactionsMap.containsKey(transaction.getTransactionCreditCardNumber())) { cardTransactionsMap.put(transaction.getTransactionCreditCardNumber(), new ArrayList<CorporateBilledCorporatePaidTransaction>()); } cardTransactionsMap.get(transaction.getTransactionCreditCardNumber()).add(transaction); } for (List<CorporateBilledCorporatePaidTransaction> cbcpTransaction : cardTransactionsMap.values()) { groupedTransactions.add(cbcpTransaction); } } return groupedTransactions; }
Source:
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) .map(INTERFACE, "if-alias", (i) -> Optional.ofNullable(snmpInterface.getIfAlias())) .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; }

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:
public void csvWithNoDelimiterShouldReturnNull() { DefaultCSVMetaDataBuilder builder = new DefaultCSVMetaDataBuilder(); CSVMetaDataModel model = builder.addField("name", DataType.STRING).addField("age", DataType.DECIMAL).build(); Assert.assertThat(model, CoreMatchers.nullValue()); }

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:
public void startLastActiveRadioStream() { if (RadioStreamService.isRunning) return; int stationIndex = Settings.getLastActiveRadioStation(context); RadioStation station = null; if (stations != null) { station = stations.get(stationIndex); } if (station != null) { toggleRadioStreamState(stationIndex); } }

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:
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(networkUtils.getHostname()) .setPort(Integer.valueOf(props.nonNullValue(CLUSTER_NODE_PORT))) .setStartedAt(system2.now()) .build(); }

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:
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"); } propertyMap.putAll(summarizerProps); propertyMap.putAll(samplerProps); propertyMap.putAll(properties); propertyMap.putAll(iteratorProps); propertyMap.putAll(localityProps); return Collections.unmodifiableMap(propertyMap); }

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:
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; } else { return MatchResults.POSSIBLE_ORDER_SPOILER; } }

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:
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) { anns.addAll(findAnnotations(clazz.getSuperclass(), annotationClass)); } return anns; }

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:
private void initializeFrom(URL resource, Properties properties) { InputStreamReader input = null; try { input = new InputStreamReader(resource.openStream()); properties.load(input); input.close(); } catch (Exception e) { logger.log(Level.INFO, "Could not load properties file"+resource.toExternalForm(), e); } finally { IOUtils.closeQuietly(input); } }

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:
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)); 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(); }

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:
private void updateDataFileChangeListeners() { if (dataFileChangeListeners == null) { return; } for (DataFileChangeListener listener : dataFileChangeListeners) { listener.onColumnsChange(this); } }

Target:
private void updateDataFileChangeListeners() { if (this.isAttached()) { for (DataFileChangeListener listener : dataFileChangeListeners) { listener.onColumnsChange(this); } } }
Source:
public boolean consumeItem(EntityRef player, Prefab prefab) { OreonSpawnComponent oreonSpawnComponent = prefab.getComponent(OreonSpawnComponent.class); 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; }

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:
private Response createResponse(HotRodHeader h, OperationStatus st, byte[] prev) { if (hasFlag(h, ProtocolFlag.ForceReturnPreviousValue)) { switch (st) { case Success: switch (h.op) { case PUT: case PUT_MULTIMAP: 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); }

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:
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"); } final boolean[] ret = new boolean[1]; ret[0] = false; try { ret[0] = ref.evaluate(eContext) != EvaluationResult.FALSE; } catch (Exception e) { trace("isVisible exception", e); } return ret[0]; }

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:
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; } switch (x) { case 0: { break; } default: } }

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:
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)); final Map<String, Object> jsonResponse = callForJsonObjectMap(host, port, "/executor", paramList); return jsonResponse; } catch (final IOException e) { throw new ExecutorManagerException(e); } }

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:
public static RepoIO createApplicationRepoIO() { return new RepoIO(isTestMode() ? Optional.of(new DummySource()) : Optional.empty(), isTestJSONEnabled() ? Optional.of(new JSONStoreStub()) : Optional.empty(), isTestMode() ? Optional.of(RepoStore.TEST_DIRECTORY) : Optional.empty()); }

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:
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()); } return pathParts[0]; }

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:
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 module$foo();" + "console.log(baz$$module$app$$module$app.bar());" }); }

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:
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"); }

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:
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) && (style & (SWT.CHECK | SWT.RADIO)) != 0) { gtk_swt_set_border_color (color); } }

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:
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; 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; }

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:
private void saveDataToModelGraph(String selected) { model.setGraph(selected); setKeyEnablement( GraphFactory.isKeyRequired(model.getGraphID(), model.getDataSet()), GraphFactory.isKeyOptional(model.getGraphID(), model.getDataSet())); }

Target:
private void saveDataToModelGraph(String selected) { model.setGraph(selected); }
Source:
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()); Logic logic = new Logic(); FeedbackQuestionAttributes fqa = logic.getFeedbackQuestion(fs.getFeedbackSessionName(), fs.getCourseId(), 1); assertNotNull(fqa); }

Target:
public void testExecuteAndPostProcess() { }
Source:
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(() -> { TimeoutException timeoutException = new TimeoutException("Timed out waiting for topology " + topologyId); if (cancellableRetry.cancel(timeoutException)) { retryFuture.completeExceptionally(timeoutException); } }, transactionDataTimeout, TimeUnit.MILLISECONDS); retryFuture.whenComplete((nil, throwable) -> timeoutFuture.cancel(false)); return invokeNextAsync(ctx, command, retryFuture); } }

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:
public static List<Long> indexes(final MutableBitSet bits) { List indexes = new ArrayList(); for (long i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) { indexes.add(i); } return indexes; }

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:
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)) { System.out.println("Expired!"); } else { System.out.println("Not expired; still " + ChronoUnit.SECONDS.between(now, expiry) + " seconds to go"); } return expiry.isBefore(now); }

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:
public static Bytes addTriplePrefixAndConvertToBytes(byte[] tripleBytes) { BytesBuilder builder = Bytes.builder(); return builder.append(TRIPLE_PREFIX_BYTES).append(tripleBytes).toBytes(); }

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

Target:
public EmbeddedTransaction(TransactionManager transactionManager, Transaction nativeTransaction, Type type) { super(transactionManager); this.nativeTransaction = nativeTransaction; this.type = type; }
Source:
private String getCompatVersion() { int version = Integer.parseInt(getStoragePool().getStoragePoolFormatType().getValue()); if (version >= 4) { return VDSM_COMPAT_VERSION_1_1; } return VDSM_COMPAT_DEFAULT_VERSION; }

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:
public void testNullFileByFileName() { try { byte[] nullContents = LoadFileUtils.safelyLoadFileBytes(StringUtils.EMPTY); } catch (RuntimeException re) { assertTrue(true); return; } assertTrue("An empty file name should throw a run time axpection as the file can't be found ", false); }

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:
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() ) { String groupArtifactId = new StringBuilder( mavenProject.getGroupId() ).append( ":" ) .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 ); } } }

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:
public synchronized CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; }

Target:
public CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } return cryptoService; }
Source:
TwitterImpl(Configuration conf, Authorization auth) { super(conf, auth); INCLUDE_MY_RETWEET = new HttpParameter("include_my_retweet", conf.isIncludeMyRetweetEnabled()); if (implicitParamsMap.containsKey(conf)) { this.IMPLICIT_PARAMS = implicitParamsMap.get(conf); this.IMPLICIT_PARAMS_STR = implicitParamsStrMap.get(conf); } else { String implicitParamsStr = conf.isIncludeEntitiesEnabled() ? "include_entities=" + true : ""; boolean contributorsEnabled = conf.getContributingTo() != -1L; if (contributorsEnabled) { if (!"".equals(implicitParamsStr)) { implicitParamsStr += "?"; } implicitParamsStr += "contributingto=" + conf.getContributingTo(); } List<HttpParameter> params = new ArrayList<HttpParameter>(3); if (conf.isIncludeEntitiesEnabled()) { params.add(new HttpParameter("include_entities", "true")); } if (contributorsEnabled) { params.add(new HttpParameter("contributingto", conf.getContributingTo())); } if (conf.isTrimUserEnabled()) { params.add(new HttpParameter("trim_user", "1")); } if (conf.isIncludeExtAltTextEnabled()) { params.add(new HttpParameter("include_ext_alt_text", "true")); } if (conf.isTweetModeExtended()) { params.add(new HttpParameter("tweet_mode", "extended")); } HttpParameter[] implicitParams = params.toArray(new HttpParameter[params.size()]); implicitParamsStrMap.putIfAbsent(conf, implicitParamsStr); implicitParamsMap.putIfAbsent(conf, implicitParams); this.IMPLICIT_PARAMS = implicitParams; this.IMPLICIT_PARAMS_STR = implicitParamsStr; } }

Target:
TwitterImpl(Configuration conf, Authorization auth) { super(conf, auth); INCLUDE_MY_RETWEET = new HttpParameter("include_my_retweet", conf.isIncludeMyRetweetEnabled()); if (implicitParamsMap.containsKey(conf)) { this.IMPLICIT_PARAMS = implicitParamsMap.get(conf); this.IMPLICIT_PARAMS_STR = implicitParamsStrMap.get(conf); } else { String implicitParamsStr = conf.isIncludeEntitiesEnabled() ? "include_entities=" + true : ""; boolean contributorsEnabled = conf.getContributingTo() != -1L; if (contributorsEnabled) { if (!"".equals(implicitParamsStr)) { implicitParamsStr += "&"; } implicitParamsStr += "contributingto=" + conf.getContributingTo(); } if (conf.isTweetModeExtended()) { if (!"".equals(implicitParamsStr)) { implicitParamsStr += "&"; } implicitParamsStr += "tweet_mode=extended"; } List<HttpParameter> params = new ArrayList<HttpParameter>(3); if (conf.isIncludeEntitiesEnabled()) { params.add(new HttpParameter("include_entities", "true")); } if (contributorsEnabled) { params.add(new HttpParameter("contributingto", conf.getContributingTo())); } if (conf.isTrimUserEnabled()) { params.add(new HttpParameter("trim_user", "1")); } if (conf.isIncludeExtAltTextEnabled()) { params.add(new HttpParameter("include_ext_alt_text", "true")); } if (conf.isTweetModeExtended()) { params.add(new HttpParameter("tweet_mode", "extended")); } HttpParameter[] implicitParams = params.toArray(new HttpParameter[params.size()]); implicitParamsStrMap.putIfAbsent(conf, implicitParamsStr); implicitParamsMap.putIfAbsent(conf, implicitParams); this.IMPLICIT_PARAMS = implicitParams; this.IMPLICIT_PARAMS_STR = implicitParamsStr; } }
Source:
public int getDisplayExecutionPageSize() { return displayExecutionPageSize; }

Target:
protected int getDisplayExecutionPageSize() { return displayExecutionPageSize; }
Source:
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); if (statement.execute(sql)) { 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; }

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); } }