auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void writeStack() throws Exception { File dir = new File(reftablePath); File stackFile = new File(reftablePath + ".stack"); dir.mkdirs(); long start = System.currentTimeMillis(); FileReftableStack stack = new FileReftableStack(stackFile, dir, null, () -> new Config()); List<Ref> refs = readLsRemote().asList(); for (Ref r : refs) { final long j = stack.getMergedReftable().maxUpdateIndex() + 1; if (!stack.addReftable(w -> { w.setMaxUpdateIndex(j).setMinUpdateIndex(j) .begin().writeRef(r); })) { throw new IOException("should succeed"); } } long dt = System.currentTimeMillis() - start; printf("%12s %10d ms avg %6d us/write", "reftable", dt, (dt * 1000)/refs.size()); }

Target:
private void writeStack() throws Exception { File dir = new File(reftablePath); File stackFile = new File(reftablePath + ".stack"); dir.mkdirs(); long start = System.currentTimeMillis(); try (FileReftableStack stack = new FileReftableStack(stackFile, dir, null, () -> new Config())) { List<Ref> refs = readLsRemote().asList(); for (Ref r : refs) { final long j = stack.getMergedReftable().maxUpdateIndex() + 1; if (!stack.addReftable(w -> { w.setMaxUpdateIndex(j).setMinUpdateIndex(j).begin() .writeRef(r); })) { throw new IOException("should succeed"); } } long dt = System.currentTimeMillis() - start; printf("%12s %10d ms avg %6d us/write", "reftable", dt, (dt * 1000) / refs.size()); } }
Source:
private void connectComponentsAndRequestSlot( JobMasterGateway jobMasterGateway, ResourceManagerGateway resourceManagerGateway, TaskExecutorGateway taskExecutorGateway, JobLeaderService jobLeaderService, CompletableFuture<SlotReport> initialSlotReportFuture, AllocationID allocationId) throws Exception { final String jobMasterAddress = "jm"; rpc.registerGateway(jobMasterAddress, jobMasterGateway); rpc.registerGateway(resourceManagerGateway.getAddress(), resourceManagerGateway); jobLeaderService.addJob(jobId, jobMasterAddress); jobManagerLeaderRetriever.notifyListener(jobMasterAddress, UUID.randomUUID()); resourceManagerLeaderRetriever.notifyListener(resourceManagerGateway.getAddress(), resourceManagerGateway.getFencingToken().toUUID()); final Optional<SlotStatus> slotStatusOptional = StreamSupport.stream(initialSlotReportFuture.get().spliterator(), false) .findAny(); assertTrue(slotStatusOptional.isPresent()); while (true) { try { taskExecutorGateway.requestSlot( slotStatusOptional.get().getSlotID(), jobId, allocationId, ResourceProfile.ZERO, jobMasterAddress, resourceManagerGateway.getFencingToken(), timeout ).get(); break; } catch (Exception e) { Thread.sleep(50); } } }

Target:
private void connectComponentsAndRequestSlot( JobMasterGateway jobMasterGateway, ResourceManagerGateway resourceManagerGateway, TaskExecutorGateway taskExecutorGateway, JobLeaderService jobLeaderService, CompletableFuture<SlotReport> initialSlotReportFuture, AllocationID allocationId) throws Exception { final String jobMasterAddress = "jm"; RPC_SERVICE_RESOURCE.getTestingRpcService().registerGateway(jobMasterAddress, jobMasterGateway); RPC_SERVICE_RESOURCE.getTestingRpcService().registerGateway(resourceManagerGateway.getAddress(), resourceManagerGateway); jobLeaderService.addJob(jobId, jobMasterAddress); jobManagerLeaderRetriever.notifyListener(jobMasterAddress, UUID.randomUUID()); resourceManagerLeaderRetriever.notifyListener(resourceManagerGateway.getAddress(), resourceManagerGateway.getFencingToken().toUUID()); final Optional<SlotStatus> slotStatusOptional = StreamSupport.stream(initialSlotReportFuture.get().spliterator(), false) .findAny(); assertTrue(slotStatusOptional.isPresent()); taskExecutorGateway.requestSlot( slotStatusOptional.get().getSlotID(), jobId, allocationId, ResourceProfile.ZERO, jobMasterAddress, resourceManagerGateway.getFencingToken(), timeout ).get(); }
Source:
public static org.kie.dmn.model.api.Definitions dmnFromWB(final Definitions wb) { if (wb == null) { return null; } org.kie.dmn.model.api.Definitions result = new org.kie.dmn.model.v1_1.TDefinitions(); String defaultId = (wb.getId() != null) ? wb.getId().getValue() : UUID.uuid(); String defaulName = (wb.getName() != null) ? wb.getName().getValue() : UUID.uuid(8); String defaultNamespace = (wb.getNamespace() != null) ? wb.getNamespace() : "<LINK_0>"; result.setId(defaultId); result.setName(defaulName); result.setNamespace(defaultNamespace); result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); result.getNsContext().putAll(wb.getNsContext()); result.getNsContext().put(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(), DMNModelInstrumentedBase.Namespace.DEFAULT.getUri()); for (ItemDefinition itemDef : wb.getItemDefinition()) { org.kie.dmn.model.api.ItemDefinition itemDefConvered = ItemDefinitionPropertyConverter.dmnFromWB(itemDef); result.getItemDefinition().add(itemDefConvered); } if (!result.getPrefixForNamespaceURI(DMNDiagram.DMNV11_DD).isPresent()) { result.getNsContext().put("dmndi", DMNDiagram.DMNV11_DD); } if (!result.getPrefixForNamespaceURI(DMNDiagram.DMNV11_DC).isPresent()) { result.getNsContext().put("dc", DMNDiagram.DMNV11_DC); } if (!result.getPrefixForNamespaceURI(DMNDiagram.DMNV11_DI).isPresent()) { result.getNsContext().put("di", DMNDiagram.DMNV11_DI); } for (Import i : wb.getImport()) { result.getImport().add(ImportConverter.dmnFromNode(i)); } return result; }

Target:
public static org.kie.dmn.model.api.Definitions dmnFromWB(final Definitions wb) { if (wb == null) { return null; } org.kie.dmn.model.api.Definitions result = new org.kie.dmn.model.v1_2.TDefinitions(); String defaultId = (wb.getId() != null) ? wb.getId().getValue() : UUID.uuid(); String defaulName = (wb.getName() != null) ? wb.getName().getValue() : UUID.uuid(8); String defaultNamespace = !StringUtils.isEmpty(wb.getNamespace()) ? wb.getNamespace() : DMNModelInstrumentedBase.Namespace.DEFAULT.getUri() + UUID.uuid(); result.setId(defaultId); result.setName(defaulName); result.setNamespace(defaultNamespace); result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription())); result.getNsContext().putAll(wb.getNsContext()); result.getNsContext().put(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(), defaultNamespace); for (ItemDefinition itemDef : wb.getItemDefinition()) { org.kie.dmn.model.api.ItemDefinition itemDefConvered = ItemDefinitionPropertyConverter.dmnFromWB(itemDef); itemDefConvered.setParent(result); result.getItemDefinition().add(itemDefConvered); } for (Import i : wb.getImport()) { result.getImport().add(ImportConverter.dmnFromWb(i)); } return result; }
Source:
public SplitTransition create(AttributeTransitionData data) { String platformTypeString = data.attributes().get(PlatformRule.PLATFORM_TYPE_ATTR_NAME, STRING); String minimumOsVersionString = data.attributes().get(PlatformRule.MINIMUM_OS_VERSION, STRING); PlatformType platformType; Optional<DottedVersion> minimumOsVersion; try { platformType = getPlatformType(platformTypeString); if (Strings.isNullOrEmpty(minimumOsVersionString)) { minimumOsVersion = Optional.absent(); } else { minimumOsVersion = Optional.of(DottedVersion.fromString(minimumOsVersionString)); } } catch (IllegalArgumentException | DottedVersion.InvalidDottedVersionError exception) { platformType = PlatformType.IOS; minimumOsVersion = Optional.absent(); } return new AppleBinaryTransition(platformType, minimumOsVersion); }

Target:
public SplitTransition create(AttributeTransitionData data) { String platformTypeString = data.attributes().get(PlatformRule.PLATFORM_TYPE_ATTR_NAME, STRING); String minimumOsVersionString = data.attributes().get(PlatformRule.MINIMUM_OS_VERSION, STRING); PlatformType platformType; Optional<DottedVersion> minimumOsVersion; try { platformType = getPlatformType(platformTypeString); if (Strings.isNullOrEmpty(minimumOsVersionString)) { minimumOsVersion = Optional.absent(); } else { minimumOsVersion = Optional.of(DottedVersion.fromString(minimumOsVersionString)); } } catch (ApplePlatform.UnsupportedPlatformTypeException | DottedVersion.InvalidDottedVersionException exception) { platformType = PlatformType.IOS; minimumOsVersion = Optional.absent(); } return new AppleBinaryTransition(platformType, minimumOsVersion); }
Source:
private static Stream<Symbol.MethodSymbol> getAllMembers(Symbol.TypeSymbol symbol, boolean isEnclosed, Set<Symbol> visitedSymbols) { if (!visitedSymbols.add(symbol) || "java.lang.Object".equals(symbol.type().fullyQualifiedName())) { return Stream.empty(); } Stream<Symbol.MethodSymbol> members = Stream.empty(); if (!isEnclosed) { members = symbol.memberSymbols().stream().filter(Symbol::isMethodSymbol).map(Symbol.MethodSymbol.class::cast); } Type superClass = symbol.superClass(); if (superClass != null) { members = Stream.concat(members, getAllMembers(superClass.symbol(), isEnclosed, visitedSymbols)); } Stream<Symbol.MethodSymbol> defaultMethodsFromInterfaces = symbol.interfaces().stream() .flatMap(i -> getAllMembers(i.symbol(), false)) .filter(m -> ((JavaSymbol.MethodJavaSymbol) m).isDefault()); members = Stream.concat(members, defaultMethodsFromInterfaces); for (Symbol s : symbol.memberSymbols()) { if (isNested(s) || isPublicStaticConcrete(s)) { members = Stream.concat(members, getAllMembers((Symbol.TypeSymbol) s, false, visitedSymbols)); } } return members; }

Target:
private static Stream<Symbol.MethodSymbol> getAllMembers(Symbol.TypeSymbol symbol, boolean isEnclosed, Set<Symbol> visitedSymbols) { if (!visitedSymbols.add(symbol) || symbol.type().is("java.lang.Object")) { return Stream.empty(); } Stream<Symbol.MethodSymbol> members = Stream.empty(); if (!isEnclosed) { members = symbol.memberSymbols().stream().filter(Symbol::isMethodSymbol).map(Symbol.MethodSymbol.class::cast); } Type superClass = symbol.superClass(); if (superClass != null) { members = Stream.concat(members, getAllMembers(superClass.symbol(), isEnclosed, visitedSymbols)); } Stream<Symbol.MethodSymbol> defaultMethodsFromInterfaces = symbol.interfaces().stream() .flatMap(i -> getAllMembers(i.symbol(), false)) .filter(m -> ((JavaSymbol.MethodJavaSymbol) m).isDefault()); members = Stream.concat(members, defaultMethodsFromInterfaces); for (Symbol s : symbol.memberSymbols()) { if (isNested(s) || isPublicStaticConcrete(s)) { members = Stream.concat(members, getAllMembers((Symbol.TypeSymbol) s, false, visitedSymbols)); } } return members; }
Source:
static LinkedList<RuntimeException> executeAll(final Runnable... actions) { LinkedList<RuntimeException> suppressed = null; for (final Runnable action : actions) { try { action.run(); } catch (final RuntimeException exception) { if (suppressed == null) { suppressed = new LinkedList<>(); } suppressed.add(exception); } } return suppressed; }

Target:
static LinkedList<RuntimeException> executeAll(final Runnable... actions) { final LinkedList<RuntimeException> suppressed = new LinkedList<>(); for (final Runnable action : actions) { try { action.run(); } catch (final RuntimeException exception) { suppressed.add(exception); } } return suppressed; }
Source:
public O evaluate(IotasEvent iotasEvent) throws ScriptException { LOG.debug("Evaluating with [{}]", expression, iotasEvent); groovy.lang.Script parsedScript = getParsedScript(); O evaluatedResult = null; if (iotasEvent != null) { final Map<String, Object> fieldsToValues = iotasEvent.getFieldsAndValues(); if (fieldsToValues != null) { try { Binding binding = new Binding(fieldsToValues); parsedScript.setBinding(binding); LOG.debug("Set script binding to [{}]", fieldsToValues); evaluatedResult = (O) parsedScript.run(); LOG.debug("Expression evaluated to [{}]", expression, evaluatedResult); } catch (groovy.lang.MissingPropertyException e) { throw new ScriptException(e); } } } return evaluatedResult; }

Target:
public O evaluate(IotasEvent iotasEvent) throws ScriptException { LOG.debug("Evaluating with [{}]", expression, iotasEvent); groovy.lang.Script parsedScript = getParsedScript(); O evaluatedResult = null; if (iotasEvent != null) { final Map<String, Object> fieldsToValues = iotasEvent.getFieldsAndValues(); if (fieldsToValues != null) { try { Binding binding = new Binding(fieldsToValues); parsedScript.setBinding(binding); LOG.debug("Set script binding to [{}]", fieldsToValues); evaluatedResult = (O) parsedScript.run(); LOG.debug("Expression evaluated to [{}]", expression, evaluatedResult); } catch (groovy.lang.MissingPropertyException e) { LOG.debug("Missing property: Expression params [{}]", expression, fieldsToValues); throw new ScriptException(e); } } } return evaluatedResult; }
Source:
public List<RichResource> extractData(ResultSet rs) throws SQLException, DataAccessException { Map<Integer, RichResource> map = new HashMap<>(); RichResource myObject; while (rs.next()) { Integer id = rs.getInt("resources_id"); myObject = map.get(id); if(myObject == null){ myObject = RICH_RESOURCE_MAPPER.mapRow(rs, rs.getRow()); map.put(id, myObject); } ResourceTag tag = RESOURCE_TAG_MAPPER.mapRow(rs, rs.getRow()); if (tag != null && tag.getId() != 0 && myObject != null) { myObject.addResourceTag(tag); } } return new ArrayList<>(map.values()); }

Target:
public List<RichResource> extractData(ResultSet rs) throws SQLException, DataAccessException { Map<Integer, RichResource> map = new HashMap<>(); RichResource myObject; while (rs.next()) { Integer id = rs.getInt("resources_id"); myObject = map.get(id); if(myObject == null){ myObject = RICH_RESOURCE_MAPPER.mapRow(rs, rs.getRow()); if (myObject == null) { log.warn("RICH_RESOURCE_MAPPER returned null during extraction of data."); continue; } map.put(id, myObject); } ResourceTag tag = RESOURCE_TAG_MAPPER.mapRow(rs, rs.getRow()); if (tag != null && tag.getId() != 0) { myObject.addResourceTag(tag); } } return new ArrayList<>(map.values()); }
Source:
public Response awaitResponse() throws Exception { Future<Response> future = remoteFuture; if (future == null) { throw new NullPointerException("Should not happen!"); } return future.get(); }

Target:
public Response awaitResponse() throws Exception { return Objects.requireNonNull(remoteFuture).get(); }
Source:
public static FeedRangeInternal tryParse(final String jsonString) { checkNotNull(jsonString, "Argument 'jsonString' must not be null"); final ObjectMapper mapper = Utils.getSimpleObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); JsonNode rangeNode = rootNode.get(Constants.Properties.RANGE); if (rangeNode != null && rangeNode.isObject()) { Range<String> range = new Range<>((ObjectNode)rangeNode); return new FeedRangeEpkImpl(range); } JsonNode pkNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY); if (pkNode != null && pkNode.isArray()) { PartitionKeyInternal pk = mapper.convertValue(pkNode, PartitionKeyInternal.class); return new FeedRangePartitionKeyImpl(pk); } JsonNode pkRangeIdNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID); if (pkRangeIdNode != null && pkRangeIdNode.isTextual()) { return new FeedRangePartitionKeyRangeImpl(pkRangeIdNode.asText()); } return null; } catch (final IOException ioError) { LOGGER.debug("Failed to parse feed range JSON %s", jsonString, ioError); return null; } }

Target:
public static FeedRangeInternal tryParse(final String jsonString) { checkNotNull(jsonString, "Argument 'jsonString' must not be null"); final ObjectMapper mapper = Utils.getSimpleObjectMapper(); try { JsonNode rootNode = mapper.readTree(jsonString); JsonNode rangeNode = rootNode.get(Constants.Properties.RANGE); if (rangeNode != null && rangeNode.isObject()) { Range<String> range = new Range<>((ObjectNode)rangeNode); return new FeedRangeEpkImpl(range); } JsonNode pkNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY); if (pkNode != null && pkNode.isArray()) { PartitionKeyInternal pk = mapper.convertValue(pkNode, PartitionKeyInternal.class); return new FeedRangePartitionKeyImpl(pk); } JsonNode pkRangeIdNode = rootNode.get(Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID); if (pkRangeIdNode != null && pkRangeIdNode.isTextual()) { return new FeedRangePartitionKeyRangeImpl(pkRangeIdNode.asText()); } return null; } catch (final IOException ioError) { LOGGER.debug("Failed to parse feed range JSON {}", jsonString, ioError); return null; } }
Source:
public static double jaccardIndex(KHyperLogLog a, KHyperLogLog b) { int sizeOfSmallerSet = Math.min(a.minhash.size(), b.minhash.size()); LongSortedSet minUnion = new LongRBTreeSet(a.minhash.keySet()); minUnion.addAll(b.minhash.keySet()); int intersection = 0; int i = 0; for (long key : minUnion) { if (a.minhash.containsKey(key) && b.minhash.containsKey(key)) { intersection++; } i++; if (i >= sizeOfSmallerSet) { break; } } return intersection / (double) sizeOfSmallerSet; }

Target:
public static double jaccardIndex(KHyperLogLog a, KHyperLogLog b) { int sizeOfSmallerSet = Math.min(a.minhash.size(), b.minhash.size()); LongSortedSet minUnion = new LongRBTreeSet(a.minhash.keySet()); minUnion.addAll(b.minhash.keySet()); int intersection = 0; int i = 0; LongIterator iterator = minUnion.iterator(); while (iterator.hasNext()) { long key = iterator.nextLong(); if (a.minhash.containsKey(key) && b.minhash.containsKey(key)) { intersection++; } i++; if (i >= sizeOfSmallerSet) { break; } } return intersection / (double) sizeOfSmallerSet; }
Source:
public <C> Expression rewriteWith(RewriterProvider<C> rewriterProvider, Expression expression, C context) { if (expression instanceof LambdaExpression) { LambdaExpression lambdaExpression = (LambdaExpression) expression; return new LambdaExpression(lambdaExpression.getArguments(), rewriteWith(rewriterProvider, lambdaExpression.getBody(), context)); } Map<NodeRef<Expression>, Type> types = getExpressionTypes( session, metadata, sqlParser, typeProvider, expression, emptyList(), WarningCollector.NOOP); return ExpressionTreeRewriter.rewriteWith(rewriterProvider.get(types), expression, context); }

Target:
public <C> Expression rewriteWith(RewriterProvider<C> rewriterProvider, Expression expression, C context) { if (expression instanceof LambdaExpression) { LambdaExpression lambdaExpression = (LambdaExpression) expression; return new LambdaExpression(lambdaExpression.getArguments(), rewriteWith(rewriterProvider, lambdaExpression.getBody(), context)); } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, typeProvider, expression, emptyList(), WarningCollector.NOOP); return ExpressionTreeRewriter.rewriteWith(rewriterProvider.get(expressionTypes), expression, context); }
Source:
public static void registerBendingWorldGuardFlag() { final FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); try { registry.register(new StateFlag("bending", false)); } catch (final Exception e) { ProjectKorra.log.severe("Unable to register bending WorldGuard Flag"); } }

Target:
public static void registerBendingWorldGuardFlag() { final FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); try { registry.register(new StateFlag("bending", false)); } catch (final Exception e) { ProjectKorra.log.severe("Unable to register bending WorldGuard flag: " + e); } }
Source:
private ArrayList<String> split(String str) { if (StringHelper.isNullOrEmpty(str)) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }

Target:
private ArrayList<String> split(String str) { if (StringUtils.isEmpty(str)) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }
Source:
private List<String> buildJarFiles(MutableRef<String> primaryJarRef) throws IOException { final List<String> list = new ArrayList<>(); final Path directoryPath = new Path(_jarDirectoryPath); final RemoteIterator<LocatedFileStatus> files = _fileSystem.listFiles(directoryPath, false); while (files.hasNext()) { final LocatedFileStatus file = files.next(); final Path path = file.getPath(); final String filename = path.getName(); boolean primaryJar = false; for (String prefix : PRIMARY_JAR_FILENAME_PREFIXES) { if (filename.startsWith(prefix)) { primaryJarRef.set(path.toString()); break; } } if (!primaryJar) { list.add(path.toString()); } } if (primaryJarRef.get() == null) { throw new IllegalArgumentException("Failed to find primary jar (starting with '" + PRIMARY_JAR_FILENAME_PREFIXES[0] + "') in JAR file directory: " + _jarDirectoryPath); } return list; }

Target:
private List<String> buildJarFiles(MutableRef<String> primaryJarRef) throws IOException { final List<String> list = new ArrayList<>(); final Path directoryPath = new Path(_jarDirectoryPath); final RemoteIterator<LocatedFileStatus> files = _fileSystem.listFiles(directoryPath, false); while (files.hasNext()) { final LocatedFileStatus file = files.next(); final Path path = file.getPath(); final String filename = path.getName(); boolean primaryJar = false; for (String prefix : PRIMARY_JAR_FILENAME_PREFIXES) { if (filename.startsWith(prefix)) { primaryJarRef.set(path.toString()); primaryJar = true; break; } } if (!primaryJar) { list.add(path.toString()); } } if (primaryJarRef.get() == null) { throw new IllegalArgumentException("Failed to find primary jar (starting with '" + PRIMARY_JAR_FILENAME_PREFIXES[0] + "') in JAR file directory: " + _jarDirectoryPath); } return list; }
Source:
public List<Job> get(final List<String> jids) throws IOException { final List<Job> jobList = new ArrayList<>(); for (final String jid : jids) { jobList.add(this.get(jid)); } return jobList; }

Target:
public List<Job> get(final List<String> jids) throws IOException { final Object result = this.client.call( LuaCommand.MULTIGET.toString(), jids); final InjectableValues inject = new InjectableValues.Std().addValue( "client", this.client); final JavaType javaType = new ObjectMapper().getTypeFactory() .constructCollectionType(ArrayList.class, Job.class); return JsonUtils.parse(result.toString(), javaType, inject); }
Source:
public void saveOrder_shouldSetOrderTypeOfTestOrderToTestOrderIfNotSetAndConceptNotMapped() throws Exception { TestOrder testOrder = new TestOrder(); testOrder.setPatient(patientService.getPatient(7)); testOrder.setConcept(conceptService.getConcept(113)); testOrder.setOrderer(providerService.getProvider(1)); testOrder.setCareSetting(orderService.getCareSetting(1)); Encounter encounter = encounterService.getEncounter(3); testOrder.setEncounter(encounter); testOrder.setStartDate(encounter.getEncounterDatetime()); testOrder.setClinicalHistory("Patient had a negative reaction to the test in the past"); testOrder.setFrequency(orderService.getOrderFrequency(3)); testOrder.setSpecimenSource(conceptService.getConcept(22)); testOrder.setNumberOfRepeats(3); orderService.saveOrder(testOrder,null); Assert.assertNotNull(testOrder.getOrderType()); Assert.assertEquals(orderService.getOrderTypeByUuid(OrderType.TEST_ORDER_TYPE_UUID),testOrder.getOrderType()); }

Target:
public void saveOrder_shouldSetOrderTypeOfTestOrderToTestOrderIfNotSetAndConceptNotMapped() throws Exception { TestOrder testOrder = new TestOrder(); testOrder.setPatient(patientService.getPatient(7)); Concept unmappedConcept = conceptService.getConcept(113); Assert.assertNull(orderService.getOrderTypeByConcept(unmappedConcept)); testOrder.setConcept(unmappedConcept); testOrder.setOrderer(providerService.getProvider(1)); testOrder.setCareSetting(orderService.getCareSetting(1)); Encounter encounter = encounterService.getEncounter(3); testOrder.setEncounter(encounter); testOrder.setStartDate(encounter.getEncounterDatetime()); testOrder.setClinicalHistory("Patient had a negative reaction to the test in the past"); testOrder.setFrequency(orderService.getOrderFrequency(3)); testOrder.setSpecimenSource(conceptService.getConcept(22)); testOrder.setNumberOfRepeats(3); orderService.saveOrder(testOrder,null); Assert.assertNotNull(testOrder.getOrderType()); Assert.assertEquals(orderService.getOrderTypeByUuid(OrderType.TEST_ORDER_TYPE_UUID),testOrder.getOrderType()); }
Source:
public AnnotateWidget(Context context, QuestionDetails prompt) { super(context, prompt); imageClickHandler = new DrawImageClickHandler(DrawActivity.OPTION_ANNOTATE, RequestCodes.ANNOTATE_IMAGE, R.string.annotate_image); imageCaptureHandler = new ImageCaptureHandler(); setUpLayout(); addCurrentImageToLayout(); if (errorLoadingImage) { annotateButton.setEnabled(false); } addAnswerView(answerLayout, WidgetViewUtils.getStandardMargin(context)); }

Target:
public AnnotateWidget(Context context, QuestionDetails prompt) { super(context, prompt); imageClickHandler = new DrawImageClickHandler(DrawActivity.OPTION_ANNOTATE, RequestCodes.ANNOTATE_IMAGE, R.string.annotate_image); imageCaptureHandler = new ImageCaptureHandler(); setUpLayout(); addCurrentImageToLayout(); adjustAnnotateButtonAvailability(); addAnswerView(answerLayout, WidgetViewUtils.getStandardMargin(context)); }
Source:
public void validate(String s) { NumberRepresentation br = new NumberRepresentation( s, true, true, false ) { @Override void parse(String val, int radix) { if ( radix == 10 ) { Long.parseLong( val, radix ); } else { if ( new BigInteger( val, radix ).bitLength() > 64 ) { throw new NumberFormatException( "integer number too large" ); } } } }; br.validate(); }

Target:
public void validate(String s) { NumberRepresentation br = new NumberRepresentation( s, true, true, false ) { @Override void parse(String val, int radix) { if ( radix == 10 ) { Long.parseLong( val, radix ); } else if ( new BigInteger( val, radix ).bitLength() > 64 ) { throw new NumberFormatException( "integer number too large" ); } } }; br.validate(); }
Source:
InternationalFixedDate plusYears(final long yearsToAdd) { if (yearsToAdd == 0) { return this; } int newYear = (int) Math.addExact(getProlepticYear(), yearsToAdd); if (isYearDay()) { return create(newYear, false, true); } int day = getDayOfMonth(); int newMonth = getCalculatedMonth(); if (isLeapDay()) { if ((yearsToAdd & 3) == 0) { return create(newYear, true, false); } day = 1; } return create(newYear, newMonth, day); }

Target:
InternationalFixedDate plusYears(final long yearsToAdd) { if (yearsToAdd == 0) { return this; } int newYear = YEAR_RANGE.checkValidIntValue(Math.addExact(this.prolepticYear, yearsToAdd), ChronoField.YEAR); return resolvePreviousValid(newYear, this.month, this.day); }
Source:
public void after() { fTrace.dispose(); }

Target:
public void after() { if (fTrace == null) { fTrace.dispose(); } }
Source:
private List<File> loadFiles(File workingDir) { System.out.println(workingDir.getAbsolutePath()); List<File> dataFile = new ArrayList<File>(); if (workingDir.exists()) { File[] files = workingDir.listFiles(); for (File eachFile : files) { if (eachFile.isDirectory()) { dataFile.addAll(loadFiles(eachFile)); } else if (eachFile.getName().endsWith(".yaml")) { dataFile.add(eachFile); } } } return dataFile; }

Target:
private List<File> loadFiles(File workingDir) { List<File> dataFile = new ArrayList<File>(); if (workingDir.exists()) { File[] files = workingDir.listFiles(); for (File eachFile : files) { if (eachFile.isDirectory()) { dataFile.addAll(loadFiles(eachFile)); } else if (eachFile.getName().endsWith(".yaml")) { dataFile.add(eachFile); } } } return dataFile; }
Source:
public static Map<Integer, List<IntermediateEntry>> hashByKey(List<IntermediateEntry> entries) { Map<Integer, List<IntermediateEntry>> hashed = new HashMap<>(); for (IntermediateEntry entry : entries) { if (hashed.containsKey(entry.getPartId())) { hashed.get(entry.getPartId()).add(entry); } else { List inputList = new ArrayList<>(); inputList.addAll(Arrays.asList(entry)); hashed.put(entry.getPartId(), inputList); } } return hashed; }

Target:
public static Map<Integer, List<IntermediateEntry>> hashByKey(List<IntermediateEntry> entries) { Map<Integer, List<IntermediateEntry>> hashed = new HashMap<>(); for (IntermediateEntry entry : entries) { if (hashed.containsKey(entry.getPartId())) { hashed.get(entry.getPartId()).add(entry); } else { hashed.put(entry.getPartId(), Arrays.asList(entry)); } } return hashed; }
Source:
public void addStreamEventUptoMaxSize(StreamEvent streamEvent) { int sizeAfterAdding = 0; ComplexEventChunk<StreamEvent> addEventsLimitCopy = new ComplexEventChunk<>(true); StreamEvent streamEventIter; while (true) { sizeAfterAdding++; streamEventIter = streamEvent.getNext(); if (sizeAfterAdding == maxSize || streamEventIter.getNext() == null) { streamEventIter.setNext(null); break; } } addEventsLimitCopy.add(streamEvent); readWriteLock.writeLock().lock(); try { this.add(addEventsLimitCopy); } finally { readWriteLock.writeLock().unlock(); } }

Target:
public void addStreamEventUptoMaxSize(StreamEvent streamEvent) { int sizeAfterAdding = this.size(); ComplexEventChunk<StreamEvent> addEventsLimitCopy = new ComplexEventChunk<>(true); while (sizeAfterAdding < maxSize && streamEvent != null) { sizeAfterAdding++; addEventsLimitCopy.add((StreamEvent) generateEventWithRequiredFields(streamEvent, siddhiAppContext, cacheExpiryEnabled)); streamEvent = streamEvent.getNext(); } readWriteLock.writeLock().lock(); try { this.add(addEventsLimitCopy); } finally { readWriteLock.writeLock().unlock(); } }
Source:
@Test void testDeserializeInvalidOperatorName() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .project( builder.field("JOB"), builder.field("SAL")) .aggregate( builder.groupKey("JOB"), builder.max("max_sal", builder.field("SAL")), builder.min("min_sal", builder.field("SAL"))) .project( builder.field("max_sal"), builder.field("min_sal")) .build(); final RelJsonWriter jsonWriter = new RelJsonWriter(); rel.explain(jsonWriter); String relJson = jsonWriter.asString().replace("\"name\": \"MAX\"", "\"name\": \"MAXS\""); try { deserializeAndDumpToTextFormat(getSchema(rel), relJson); fail(); } catch (Exception e) { assertThat(e.getMessage(), isLinux("org.apache.calcite.runtime.CalciteException: " + "No operator for 'MAXS' with kind: 'MAX', syntax: 'FUNCTION'")); } }

Target:
@Test void testDeserializeInvalidOperatorName() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .project( builder.field("JOB"), builder.field("SAL")) .aggregate( builder.groupKey("JOB"), builder.max("max_sal", builder.field("SAL")), builder.min("min_sal", builder.field("SAL"))) .project( builder.field("max_sal"), builder.field("min_sal")) .build(); final RelJsonWriter jsonWriter = new RelJsonWriter(); rel.explain(jsonWriter); String relJson = jsonWriter.asString().replace("\"name\": \"MAX\"", "\"name\": \"MAXS\""); assertThrows(RuntimeException.class, () -> deserializeAndDumpToTextFormat(getSchema(rel), relJson), "org.apache.calcite.runtime.CalciteException: " + "No operator for 'MAXS' with kind: 'MAX', syntax: 'FUNCTION' during JSON deserialization"); }
Source:
private static void assertCompilationDiagnostingOn(Kind expectedDiagnosticKind, File expectedErrorClassFile, String expectedContentInError, CompileResult result) throws IOException { String expectedErrorPath = expectedErrorClassFile.toURI().toString(); for (Diagnostic<? extends JavaFileObject> diagnostic : result.diagnostics) { if (diagnostic.getKind() == expectedDiagnosticKind) { JavaFileObject source = diagnostic.getSource(); if (source != null) { if (expectedErrorPath.endsWith(source.toUri().toString())) { CharSequence sourceContent = source.getCharContent(true); if (diagnostic.getPosition() != Diagnostic.NOPOS) { CharSequence contentInError = sourceContent.subSequence((int) diagnostic.getStartPosition(), (int) diagnostic.getEndPosition()); String contentInErrorString = contentInError.toString(); int parenIndex = contentInErrorString.indexOf("("); if (parenIndex != -1) { contentInErrorString = contentInErrorString.substring(0, parenIndex); } if (expectedContentInError.equals(contentInErrorString)) { return; } } } } } } fail("Expected a compilation " + expectedDiagnosticKind + " in " + expectedErrorClassFile.toString() + " on " + expectedContentInError + ", diagnostics: " + result.diagnostics); }

Target:
private static void assertCompilationDiagnostingOn(Kind expectedDiagnosticKind, File expectedErrorClassFile, String expectedContentInError, CompileResult result) throws IOException { String expectedErrorPath = expectedErrorClassFile.toURI().toString(); for (Diagnostic<? extends JavaFileObject> diagnostic : result.diagnostics) { if (diagnostic.getKind() == expectedDiagnosticKind) { JavaFileObject source = diagnostic.getSource(); if (source != null) { if (expectedErrorPath.endsWith(source.toUri().toString())) { CharSequence sourceContent = source.getCharContent(true); if (diagnostic.getPosition() != Diagnostic.NOPOS) { CharSequence contentInError = sourceContent.subSequence((int) diagnostic.getStartPosition(), (int) diagnostic.getEndPosition()); if (contentInError.toString().contains(expectedContentInError)) { return; } } } } } } fail("Expected a compilation " + expectedDiagnosticKind + " in " + expectedErrorClassFile.toString() + " on " + expectedContentInError + ", diagnostics: " + result.diagnostics); }
Source:
public void testGetSubscriptionNotFound() throws IOException { final EventType eventType = createEventType(); createSubscription(eventType); given() .get(format(CURSORS_URL, "UNKNOWN_SUB_ID")) .then() .statusCode(HttpStatus.SC_NOT_FOUND); }

Target:
public void testGetSubscriptionNotFound() throws IOException { given() .get(format(CURSORS_URL, "UNKNOWN_SUB_ID")) .then() .statusCode(HttpStatus.SC_NOT_FOUND); }
Source:
static BlobId getBlobIdFromString(String blobIdString, ClusterMap clusterMap) throws RouterException { BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); logger.trace("BlobId created " + blobId + " with partition " + blobId.getPartition()); } catch (Exception e) { logger.trace("Caller passed in invalid BlobId " + blobIdString); throw new RouterException("BlobId is invalid " + blobIdString, RouterErrorCode.InvalidBlobId); } return blobId; }

Target:
static BlobId getBlobIdFromString(String blobIdString, ClusterMap clusterMap) throws RouterException { BlobId blobId; try { blobId = new BlobId(blobIdString, clusterMap); logger.trace("BlobId created with partitionId {}", blobId, blobId.getPartition()); } catch (Exception e) { logger.trace("Caller passed in invalid BlobId {}", blobIdString); throw new RouterException("BlobId is invalid " + blobIdString, RouterErrorCode.InvalidBlobId); } return blobId; }
Source:
private void processRefundEvent(RefundHistory refundHistory, RefundTransactionEntity refundTransactionEntity) { if (refundTransactionEntity.getTransactionEvents() .stream() .noneMatch(refundEvent -> refundEvent.getStatus().equals(refundHistory.getStatus()))) { logger.info("Adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); RefundTransactionEventEntity refundTransactionEventEntity = new RefundTransactionEventEntity(); refundTransactionEventEntity.setStatus(refundHistory.getStatus()); refundTransactionEventEntity.setUpdated(refundHistory.getCreatedDate()); refundTransactionEntity.getTransactionEvents().add(refundTransactionEventEntity); refundTransactionEventEntity.setTransaction(refundTransactionEntity); } else { logger.info("Not adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); } }

Target:
private void processRefundEvent(RefundHistory refundHistory, RefundTransactionEntity refundTransactionEntity) { if (refundTransactionEntity.getTransactionEvents() .stream() .noneMatch(refundEvent -> refundEvent.getStatus().equals(refundHistory.getStatus()))) { logger.info("Adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); RefundTransactionEventEntity refundTransactionEventEntity = new RefundTransactionEventEntity(); refundTransactionEventEntity.setStatus(refundHistory.getStatus()); refundTransactionEventEntity.setUpdated(refundHistory.getHistoryStartDate()); refundTransactionEntity.getTransactionEvents().add(refundTransactionEventEntity); refundTransactionEventEntity.setTransaction(refundTransactionEntity); } else { logger.info("Not adding refund event for [" + refundTransactionEntity.getId() + "] for status [" + refundHistory.getStatus() + "]"); } }
Source:
public void testAllColumns() { assertStatement("select *, t.*, \"table\".*", new Query( Optional.empty(), new QuerySpecification( selectList( new AllColumns(), new AllColumns(QualifiedName.of("t")), new AllColumns(QualifiedName.of("table"))), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()), Optional.empty(), Optional.empty())); }

Target:
public void testAllColumns() { assertStatement( "select *, t.*, \"table\".*", simpleQuery(selectList(new AllColumns(), new AllColumns(QualifiedName.of("t")), new AllColumns(QualifiedName.of("table"))))); }
Source:
private void sendParameters(Transfer transfer) throws IOException { int len = parameters.size(); transfer.writeInt(len); for (ParameterInterface p : parameters) { Value pVal = p.getParamValue(); if (pVal == null && cmdType == EXPLAIN) pVal = ValueString.get("PARAMETER_NOT_SET"); transfer.writeValue(pVal); } }

Target:
private void sendParameters(Transfer transfer) throws IOException { int len = parameters.size(); transfer.writeInt(len); for (ParameterInterface p : parameters) { Value pVal = p.getParamValue(); if (pVal == null && cmdType == EXPLAIN) pVal = ValueNull.INSTANCE; transfer.writeValue(pVal); } }
Source:
private void storeExecutionParameters() { metaData.put("uuid", UUID.randomUUID().toString()); Map<String, String> meta = new HashMap<String, String>(); meta.put("dsmode", "local"); meta.put("essential", "false"); meta.put("role", "server"); metaData.put("meta", meta); metaData.put("launch_index", "0"); metaData.put("availability_zone", "nova"); userData.put("user", "root"); Map<String, String> output = new HashMap<String, String>(); output.put("all", ">> /var/log/cloud-init-output.log"); userData.put("output", output); List<String> bootcmd = new ArrayList<String>(); bootcmd.add("sed -i '/^disable_root: /d' /etc/cloud/cloud.cfg"); bootcmd.add("echo 'disable_root: 0' >> /etc/cloud/cloud.cfg"); bootcmd.add("sed -i '/^datasource_list: /d' /etc/cloud/cloud.cfg"); bootcmd.add("echo 'datasource_list: [\"NoCloud\", \"ConfigDrive\"]' >> /etc/cloud/cloud.cfg"); userData.put("bootcmd", bootcmd); Map<String, Object> opts = new HashMap<String, Object>(); opts.put("expire", false); userData.put("chpasswd", opts); userData.put("ssh_pwauth", true); }

Target:
private void storeExecutionParameters() { metaData.put("uuid", UUID.randomUUID().toString()); Map<String, String> meta = new HashMap<String, String>(); meta.put("dsmode", "local"); meta.put("essential", "false"); meta.put("role", "server"); metaData.put("meta", meta); metaData.put("launch_index", "0"); metaData.put("availability_zone", "nova"); userData.put("user", "root"); Map<String, String> output = new HashMap<String, String>(); output.put("all", ">> /var/log/cloud-init-output.log"); userData.put("output", output); List<String> bootcmd = new ArrayList<String>(); bootcmd.add("sed -i -e '/^disable_root: /d' -e '/^datasource_list: /d' -e '$ a disable_root: 0' -e '$ a datasource_list: [\"NoCloud\", \"ConfigDrive\"]' /etc/cloud/cloud.cfg"); userData.put("bootcmd", bootcmd); Map<String, Object> opts = new HashMap<String, Object>(); opts.put("expire", false); userData.put("chpasswd", opts); userData.put("ssh_pwauth", true); }
Source:
public final void closeSession() { logger.entering(); if (this.isStarted && Grid.driver() != null) { new SauceLabsHelper().embedSauceLabsJobUrlToTestReport(); Grid.driver().quit(); } Grid.getThreadLocalWebDriver().set(null); Grid.getThreadLocalTestSession().set(null); this.isStarted = false; logger.exiting(); }

Target:
public final void closeSession() { logger.entering(); if ((isStarted()) && (Grid.driver() != null)) { new SauceLabsHelper().embedSauceLabsJobUrlToTestReport(); Grid.driver().quit(); } Grid.getThreadLocalWebDriver().set(null); Grid.getThreadLocalTestSession().set(null); this.isStarted = false; logger.exiting(); }
Source:
public void startService() { super.startService(); load(); if (vision == null) { vision = new Vision(); vision.init(); } vision.instance = this; if (speechRecognition == null) { speechRecognition = new SpeechRecognition(); speechRecognition.init(); } speechRecognition.instance = this; if (speechSynthesizer == null) { speechSynthesizer = new SpeechSynthesizer(); speechSynthesizer.init(); } speechSynthesizer.instance = this; languages.put("en-US", "English - United States"); languages.put("fr-FR", "French - France"); languages.put("es-ES", "Spanish - Spain"); languages.put("de-DE", "German - Germany"); languages.put("nl-NL", "Dutch - Netherlands"); languages.put("ru-RU", "Russian"); languages.put("hi-IN", "Hindi - India"); languages.put("it-IT", "Italian - Italia"); languages.put("fi-FI", "Finnish - Finland"); languagesIndex = new ArrayList<String>(languages.keySet()); this.language = getLanguage(); python = getPython(); languagePack.load(language); Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); }

Target:
public void startService() { super.startService(); if (vision == null) { vision = new Vision(); vision.init(); } vision.instance = this; languages.put("en-US", "English - United States"); languages.put("fr-FR", "French - France"); languages.put("es-ES", "Spanish - Spain"); languages.put("de-DE", "German - Germany"); languages.put("nl-NL", "Dutch - Netherlands"); languages.put("ru-RU", "Russian"); languages.put("hi-IN", "Hindi - India"); languages.put("it-IT", "Italian - Italia"); languages.put("fi-FI", "Finnish - Finland"); languagesIndex = new ArrayList<String>(languages.keySet()); this.language = getLanguage(); python = getPython(); languagePack.load(language); Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); }
Source:
private void examineNode(Node node, boolean attributesOnly) { NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); storeAttribute((Attr) attribute); } if (!attributesOnly) { NodeList chields = node.getChildNodes(); for (int i = 0; i < chields.getLength(); i++) { Node chield = chields.item(i); if (chield.getNodeType() == Node.ELEMENT_NODE) { examineNode(chield, false); } } } }

Target:
private void examineNode(Node node, boolean attributesOnly) { NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); storeAttribute((Attr) attribute); } if (!attributesOnly) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { examineNode(child, false); } } } }
Source:
public void stop(boolean forceDisconnect) { logoutAllSessions(forceDisconnect); stopSessionTimer(); if (!forceDisconnect) { waitForLogout(); } stopInitiators(); eventHandlingStrategy.stopDispatcherThreads(); Session.unregisterSessions(getSessions()); }

Target:
public void stop(boolean forceDisconnect) { logoutAllSessions(forceDisconnect); stopInitiators(); eventHandlingStrategy.stopDispatcherThreads(); Session.unregisterSessions(getSessions()); }
Source:
public User getUserDetailsByUsername(final String username) throws MiddlewareQueryException { try { if (username != null) { final Criteria criteria = this.getSession().createCriteria(User.class).add(Restrictions.eq("name", username)); @SuppressWarnings("unchecked") final List<User> users = criteria.list(); return !users.isEmpty() ? users.get(0) : null; } } catch (final HibernateException e) { this.logAndThrowException("Error with getByUsernameAndPassword(username=" + username + ") query from User: " + e.getMessage(), e); } return null; }

Target:
public User getUserDetailsByUsername(final String username) throws MiddlewareQueryException { try { if (username != null) { final Criteria criteria = this.getSession().createCriteria(User.class).add(Restrictions.eq("name", username)); @SuppressWarnings("unchecked") final List<User> users = criteria.list(); return !users.isEmpty() ? users.get(0) : null; } } catch (final HibernateException e) { final String message = "Error with getByUsernameAndPassword(username=" + username + ") query from User: " + e.getMessage(); UserDAO.LOG.error(message, e); throw new MiddlewareQueryException(message, e); } return null; }
Source:
public static CDKHypervisor getDefaultHypervisor() { switch(CDKRuntimeOS.get().getRuntimeName()) { case "linux": return KVM; case "darwin": return XHYVE; case "win": return HYPERV; default: return null; } }

Target:
public static CDKHypervisor getDefaultHypervisor() { String os = CDKRuntimeOS.get().getRuntimeName(); switch(os) { case "linux": return KVM; case "darwin": return XHYVE; case "win": return HYPERV; default: throw new CDKException("This OS: " + os + " does not have defined default hypervisor"); } }
Source:
public static boolean equal( final String desc1, RelDataType type1, final String desc2, RelDataType type2, Litmus litmus) { if (!areRowTypesEqual(type1, type2, false)) { return litmus.fail("Type mismatch:\n{}:\n{}\n{}:\n{}\ndifference:\n{}", desc1, type1.getFullTypeString(), desc2, type2.getFullTypeString(), getFullTypeDifferenceString(type1, type2)); } return litmus.succeed(); }

Target:
public static boolean equal( final String desc1, RelDataType type1, final String desc2, RelDataType type2, Litmus litmus) { if (!areRowTypesEqual(type1, type2, false)) { return litmus.fail(getFullTypeDifferenceString(desc1, type1, desc2, type2)); } return litmus.succeed(); }
Source:
protected void configure() { final SchemaFactory<ReviewDb> schema = dbInjector.getInstance( Key.get(new TypeLiteral<SchemaFactory<ReviewDb>>() {})); final List<ReviewDb> dbs = Collections.synchronizedList( Lists.<ReviewDb> newArrayListWithCapacity(threads)); final ThreadLocal<ReviewDb> localDb = new ThreadLocal<ReviewDb>(); bind(ReviewDb.class).toProvider(new Provider<ReviewDb>() { @Override public ReviewDb get() { ReviewDb db = localDb.get(); if (db == null) { try { db = schema.open(); dbs.add(db); localDb.set(db); } catch (OrmException e) { throw new ProvisionException("unable to open ReviewDb", e); } } return db; } }); listener().toInstance(new LifecycleListener() { @Override public void start() { } @Override public void stop() { for (ReviewDb db : dbs) { db.close(); } } }); }

Target:
protected void configure() { final SchemaFactory<ReviewDb> schema = dbInjector.getInstance( Key.get(new TypeLiteral<SchemaFactory<ReviewDb>>() {})); final List<ReviewDb> dbs = Collections.synchronizedList( Lists.<ReviewDb> newArrayListWithCapacity(threads + 1)); final ThreadLocal<ReviewDb> localDb = new ThreadLocal<ReviewDb>(); bind(ReviewDb.class).toProvider(new Provider<ReviewDb>() { @Override public ReviewDb get() { ReviewDb db = localDb.get(); if (db == null) { try { db = schema.open(); dbs.add(db); localDb.set(db); } catch (OrmException e) { throw new ProvisionException("unable to open ReviewDb", e); } } return db; } }); listener().toInstance(new LifecycleListener() { @Override public void start() { } @Override public void stop() { for (ReviewDb db : dbs) { db.close(); } } }); }