auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void processImageChooserResponse(Intent intent) { Uri selectedImage = intent.getData(); File originalImage = new File(FileUtils.getPath(this, selectedImage)); if (originalImage.exists()) { File unscaledFinalImage = moveAndScaleImage(originalImage, true); ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, unscaledFinalImage.getName()); values.put(Images.Media.DISPLAY_NAME, unscaledFinalImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, unscaledFinalImage.getAbsolutePath()); Uri imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(TAG, "Inserting image returned uri = " + imageURI.toString()); ((ODKView) mCurrentView).setBinaryData(imageURI); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } else { CommCareActivity.createErrorDialog(this, Localization.get("invalid.image.selection"), false); } refreshCurrentView(); }

Target:
private void processImageChooserResponse(Intent intent) { Uri selectedImage = intent.getData(); File originalImage = new File(FileUtils.getPath(this, selectedImage)); if (originalImage.exists()) { try { File unscaledFinalImage = moveAndScaleImage(originalImage, true); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.selection.not.saved"), Toast.LENGTH_LONG); } } else { showCustomToast(Localization.get("invalid.image.selection"), Toast.LENGTH_LONG); } }
Source:
public long getLastAddConfirmed() { return entries.size() - 1; }

Target:
public long getLastAddConfirmed() { return entries.get(entries.size() - 1).getEntryId(); }
Source:
public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName) { this(keepStrings, cDataTagName, false); }

Target:
public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName) { this.keepStrings = keepStrings; this.cDataTagName = cDataTagName; this.convertNilAttributeToNull = false; }
Source:
public void testExpandableItemStatusAfterOpening() { SWTBotVSMEditor odesignEditor = openViewpointSpecificationModel(VSM); SWTBotTreeItem[] treeItem = odesignEditor.bot().tree().getAllItems(); assertEquals(1, treeItem.length); SWTBotTreeItem resourceItem = treeItem[0]; assertEquals(1, resourceItem.getItems().length); SWTBotTreeItem groupItem = resourceItem.getItems()[0]; assertEquals(6, groupItem.getItems().length); SWTBotTreeItem viewpointItem = groupItem.getItems()[0]; assertEquals(7, viewpointItem.getItems().length); SWTBotTreeItem entitiesDiagramItem = viewpointItem.getItems()[0]; assertEquals(1, entitiesDiagramItem.getItems().length); SWTBotTreeItem viewpointItem2 = groupItem.getItems()[2]; assertEquals(4, viewpointItem2.getItems().length); SWTBotTreeItem entitiesDiagramItem2 = viewpointItem2.getItems()[0]; assertEquals(1, entitiesDiagramItem2.getItems().length); SWTBotTreeItem expandedEntitiesDiagramItem2 = entitiesDiagramItem2.expand(); assertEquals(2, expandedEntitiesDiagramItem2.getItems().length); SWTBotTreeItem expandedEntitiesDiagramItem = entitiesDiagramItem.expand(); assertEquals(9, expandedEntitiesDiagramItem.getItems().length); }

Target:
public void testExpandableItemStatusAfterOpening() { SWTBotVSMEditor odesignEditor = openViewpointSpecificationModel(VSM); SWTBotTreeItem[] treeItem = odesignEditor.bot().tree().getAllItems(); assertEquals("There should be only one group node under resource node", 1, treeItem.length); SWTBotTreeItem resourceItem = treeItem[0]; assertEquals("There should be only one viewpoint node under group node", resourceItem.getItems().length); SWTBotTreeItem groupItem = resourceItem.getItems()[0]; assertEquals("The level 2 node should be expanded with 6 sub items", 6, groupItem.getItems().length); SWTBotTreeItem viewpointItem = groupItem.getItems()[0]; assertEquals("The level 3 node should be expanded with 7 sub items", 7, viewpointItem.getItems().length); SWTBotTreeItem viewpointItem2 = groupItem.getItems()[2]; assertEquals("The level 3 node should be expanded with 4 sub items", 4, viewpointItem2.getItems().length); SWTBotTreeItem entitiesDiagramItem2 = viewpointItem2.getItems()[0]; assertEquals("The level 4 node should not be expanded. It should contains only the empty node.", 1, entitiesDiagramItem2.getItems().length); SWTBotTreeItem entitiesDiagramItem = viewpointItem.getItems()[0]; assertEquals("The level 4 node should not be expanded. It should contains only the empty node.", 1, entitiesDiagramItem.getItems().length); SWTBotTreeItem expandedEntitiesDiagramItem2 = entitiesDiagramItem2.expand(); assertEquals("The level 4 node should have 2 sub elements when expanded.", 2, expandedEntitiesDiagramItem2.getItems().length); SWTBotTreeItem expandedEntitiesDiagramItem = entitiesDiagramItem.expand(); assertEquals("The level 4 node should have 9 sub elements when expanded.", 9, expandedEntitiesDiagramItem.getItems().length); }
Source:
public static YamlNode load(InputStream inputStream, String rootName) { try { Object document = getLoad().loadFromInputStream(inputStream); inputStream.close(); return buildDom(rootName, document); } catch (Exception ex) { throw new YamlException("An error occurred while loading and parsing the YAML stream", ex); } }

Target:
public static YamlNode load(InputStream inputStream, String rootName) { try { Object document = getLoad().loadFromInputStream(inputStream); return buildDom(rootName, document); } catch (Exception ex) { throw new YamlException("An error occurred while loading and parsing the YAML stream", ex); } }
Source:
private void carryOntoHistory(RevCommit c, int carry) { stack = null; for (;;) { carryOntoHistoryInnerLoop(c, carry); CarryStack s = stack; if (s != null) { stack = s.prev; c = s.c; carry = s.carry; continue; } break; } }

Target:
private void carryOntoHistory(RevCommit c, int carry) { stack = null; for (;;) { carryOntoHistoryInnerLoop(c, carry); if (stack != null) { c = stack.c; carry = stack.carry; stack = stack.prev; continue; } break; } }
Source:
public CoordinatorDynamicConfig( @JsonProperty("millisToWaitBeforeDeleting") long millisToWaitBeforeDeleting, @JsonProperty("mergeBytesLimit") long mergeBytesLimit, @JsonProperty("mergeSegmentsLimit") int mergeSegmentsLimit, @JsonProperty("maxSegmentsToMove") int maxSegmentsToMove, @JsonProperty("replicantLifetime") int replicantLifetime, @JsonProperty("replicationThrottleLimit") int replicationThrottleLimit, @JsonProperty("balancerComputeThreads") int balancerComputeThreads, @JsonProperty("emitBalancingStats") boolean emitBalancingStats, @JsonProperty("killDataSourceWhitelist") Object killDataSourceWhitelist ) { this.maxSegmentsToMove = maxSegmentsToMove; this.millisToWaitBeforeDeleting = millisToWaitBeforeDeleting; this.mergeSegmentsLimit = mergeSegmentsLimit; this.mergeBytesLimit = mergeBytesLimit; this.replicantLifetime = replicantLifetime; this.replicationThrottleLimit = replicationThrottleLimit; this.emitBalancingStats = emitBalancingStats; this.balancerComputeThreads = Math.max(balancerComputeThreads, 1); if (killDataSourceWhitelist instanceof String) { String[] tmp = ((String) killDataSourceWhitelist).split(","); this.killDataSourceWhitelist = new HashSet<>(); for (int i = 0; i < tmp.length; i++) { if (!tmp[i].isEmpty()) { this.killDataSourceWhitelist.add(tmp[i]); } } } else if (killDataSourceWhitelist instanceof Collection){ this.killDataSourceWhitelist = ImmutableSet.copyOf(((Collection) killDataSourceWhitelist)); } else { this.killDataSourceWhitelist = ImmutableSet.of(); } }

Target:
public CoordinatorDynamicConfig( @JsonProperty("millisToWaitBeforeDeleting") long millisToWaitBeforeDeleting, @JsonProperty("mergeBytesLimit") long mergeBytesLimit, @JsonProperty("mergeSegmentsLimit") int mergeSegmentsLimit, @JsonProperty("maxSegmentsToMove") int maxSegmentsToMove, @JsonProperty("replicantLifetime") int replicantLifetime, @JsonProperty("replicationThrottleLimit") int replicationThrottleLimit, @JsonProperty("balancerComputeThreads") int balancerComputeThreads, @JsonProperty("emitBalancingStats") boolean emitBalancingStats, @JsonProperty("killDataSourceWhitelist") Object killDataSourceWhitelist ) { this.maxSegmentsToMove = maxSegmentsToMove; this.millisToWaitBeforeDeleting = millisToWaitBeforeDeleting; this.mergeSegmentsLimit = mergeSegmentsLimit; this.mergeBytesLimit = mergeBytesLimit; this.replicantLifetime = replicantLifetime; this.replicationThrottleLimit = replicationThrottleLimit; this.emitBalancingStats = emitBalancingStats; this.balancerComputeThreads = Math.max(balancerComputeThreads, 1); if (killDataSourceWhitelist instanceof String) { String[] tmp = ((String) killDataSourceWhitelist).split(","); this.killDataSourceWhitelist = new HashSet<>(); for (int i = 0; i < tmp.length; i++) { String trimmed = tmp[i].trim(); if (!trimmed.isEmpty()) { this.killDataSourceWhitelist.add(trimmed); } } } else if (killDataSourceWhitelist instanceof Collection){ this.killDataSourceWhitelist = ImmutableSet.copyOf(((Collection) killDataSourceWhitelist)); } else { this.killDataSourceWhitelist = ImmutableSet.of(); } }
Source:
public void onClick(final ClickEvent e) { final Object ele = getTarget(e); if (Objects.equals(ele, checkbox)) { return; } if (HiddenHelper.isHidden(itemsContainer)) { showElement(itemsContainer); } else { hideElement(itemsContainer); } }

Target:
public void onClick(final ClickEvent e) { final Object target = getTarget(e); if (Objects.equals(target, checkbox)) { return; } if (HiddenHelper.isHidden(itemsContainer)) { showElement(itemsContainer); } else { hideElement(itemsContainer); } }
Source:
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doPost"); int idx = Integer.parseInt(request.getParameter("idx"), 10); String source = request.getParameter("source"); String target = request.getParameter("target"); log.debug("Removing entry with at {}",source, target, idx); InputStream is = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE).adaptTo(InputStream.class); List<String> lines = IOUtils.readLines(is); log.debug("Loaded lines", lines.size()); lines.add(idx, source+" "+target); log.debug("Added entry..."); ModifiableValueMap mvm = request.getResource().getChild(RedirectMapModel.MAP_FILE_NODE) .getChild(JcrConstants.JCR_CONTENT).adaptTo(ModifiableValueMap.class); mvm.put(JcrConstants.JCR_DATA, StringUtils.join(lines, "\n")); request.getResourceResolver().commit(); request.getResourceResolver().refresh(); log.debug("Changes saved..."); super.doGet(request, response); }

Target:
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doPost"); int idx = Integer.parseInt(request.getParameter("idx"), 10); String source = request.getParameter("source"); String target = request.getParameter("target"); log.debug("Removing entry with at {}", source, target, idx); List<String> lines = RedirectEntriesUtils.readEntries(request); lines.add(idx, source + " " + target); log.debug("Added entry..."); RedirectEntriesUtils.updateRedirectMap(request, lines); RedirectEntriesUtils.writeEntriesToResponse(request, response); }
Source:
public void testCompilerLogWithCustomComilerArgsAndLog() throws Exception { File basedir = getBasedir("projects/logs/customCompilerArgsAndLog"); List<MavenProject> projects = getSortedProjects(basedir, null); MavenProject project = projects.get(0); try { getMojo(projects, project).execute(); fail(); } catch (MojoExecutionException e) { assertThat(e.getMessage(), containsString("Compiler logging is configured by the 'log' compiler" + " plugin parameter and the custom compiler argument '-log'. Only either of them is allowed.")); } }

Target:
public void testCompilerLogWithCustomComilerArgsAndLog() throws Exception { File basedir = getBasedir("projects/logs/customCompilerArgsAndLog"); List<MavenProject> projects = getSortedProjects(basedir, null); MavenProject project = projects.get(0); try { lookupConfiguredMojo(project, "compile").execute(); fail(); } catch (MojoFailureException e) { assertThat(e.getMessage(), containsString("Compiler logging is configured by the 'log' compiler" + " plugin parameter and the custom compiler argument '-log'. Only either of them is allowed.")); } }
Source:
public void onFeatureClicked(int featureId) { showSummary(featureId); }

Target:
public void onFeatureClicked(int featureId) { FormMapViewModel.MappableFormInstance mappableFormInstance = instancesByFeatureId.get(featureId); if (mappableFormInstance != null) { map.zoomToPoint(new MapPoint(mappableFormInstance.getLatitude(), mappableFormInstance.getLongitude()), map.getZoom(), true); setUpSummarySheet(mappableFormInstance); summarySheet.setState(BottomSheetBehavior.STATE_EXPANDED); } }
Source:
public void disableTableReplication(String tableName) throws IOException { TableName tn = tableInfoFactory.getTableInfo(tableName); try { HTableDescriptor htd = admin.getTableDescriptor(tn); if (admin.isTableEnabled(tn)) { admin.disableTable(tn); } for (HColumnDescriptor hcd : htd.getFamilies()) { hcd.setScope(HConstants.REPLICATION_SCOPE_LOCAL); } admin.modifyTable(tn, htd); SpliceLogUtils.info(LOG, "disabled replication for table %s", tn); } finally { if (tn != null && !admin.isTableEnabled(tn)) { admin.enableTable(tn); } } }

Target:
public void disableTableReplication(String tableName) throws IOException { TableName tn = tableInfoFactory.getTableInfo(tableName); boolean tableEnabled = admin.isTableEnabled(tn); try { HTableDescriptor htd = admin.getTableDescriptor(tn); if (tableEnabled) { admin.disableTable(tn); } for (HColumnDescriptor hcd : htd.getFamilies()) { hcd.setScope(HConstants.REPLICATION_SCOPE_LOCAL); } admin.modifyTable(tn, htd); SpliceLogUtils.info(LOG, "disabled replication for table %s", tn); } finally { if (tn != null && !admin.isTableEnabled(tn) && tableEnabled) { admin.enableTable(tn); } } }
Source:
private void setProgress() { if (supervisor != null) { int checked = state.equals(ImageGeneratorStep.GENERATE_IMAGES) ? getMode().equals(GenerationMode.ALL) ? 1 : sources.size() : 0; int generated = getMode().equals(GenerationMode.ALL) && state.equals(ImageGeneratorStep.DETERMINE_WHICH_IMAGES_NEED_TO_BE_GENERATED) ? 0 : getPosition(); int total = sources.size() + (getMode().equals(GenerationMode.ALL) ? 1 : getContentToBeGenerated().size()) + 1; supervisor.setProgress(100d * (1 + checked + generated) / total); } }

Target:
private void setProgress() { if (Objects.nonNull(supervisor)) { int checked = state.equals(ImageGeneratorStep.GENERATE_IMAGES) ? getMode().equals(GenerationMode.ALL) ? 1 : sources.size() : 0; int generated = getMode().equals(GenerationMode.ALL) && state.equals(ImageGeneratorStep.DETERMINE_WHICH_IMAGES_NEED_TO_BE_GENERATED) ? 0 : getPosition(); int total = sources.size() + (getMode().equals(GenerationMode.ALL) ? 1 : getContentToBeGenerated().size()) + 1; supervisor.setProgress(100d * (1 + checked + generated) / total); } }
Source:
public void run() { List<Throwable> errors = new LinkedList<>(); for ( Runnable o : operations ) { try { o.run(); } catch ( RuntimeException e ) { errors.add( e ); } } if ( !errors.isEmpty() ) { RuntimeException exception = new RuntimeException(); errors.forEach( exception::addSuppressed ); throw exception; } }

Target:
public void run() { List<Throwable> errors = new ArrayList<>(); for ( Runnable o : operations ) { try { o.run(); } catch ( RuntimeException e ) { errors.add( e ); } } if ( !errors.isEmpty() ) { RuntimeException exception = new RuntimeException(); errors.forEach( exception::addSuppressed ); throw exception; } }
Source:
public void startup(Application application, ComponentStartupStatus ss) { Pattern pattern = Pattern.compile("^(topic|queues)/(.*)$"); Matcher matcher = pattern.matcher(brokerDestination); if (matcher.find()) { String destinationType = matcher.group(1).equals("topic") ? "topic" : "queue"; String destinationName = matcher.group(2); String destinationBinding = String.format("%s.%s", destinationType, brokerDestination); Properties properties = new Properties(); properties.put(INITIAL_CONTEXT_FACTORY, factoryInitial); properties.put(PROVIDER_URL, providerURL); properties.put(destinationBinding, destinationName); try { InitialContext ic = new InitialContext(properties); ConnectionFactory cf = (ConnectionFactory) ic.lookup(connectionFactory); Destination destination = (Destination) ic.lookup(brokerDestination); Connection connection = cf.createConnection(brokerUsername, brokerPassword); session = connection.createSession(Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); ss.info(String.format("Connected to %s at %s", brokerDestination, providerURL)); } catch (NamingException | JMSException e) { ss.warning(String.format("Failed to connect to %s at %s", brokerDestination, providerURL), e); } } else { ss.warning(String.format("%s is not a valid broker destination", brokerDestination)); } }

Target:
public void startup(Application application, ComponentStartupStatus ss) { Pattern pattern = Pattern.compile("^.*/(.*)$"); Matcher matcher = pattern.matcher(brokerDestination); if (matcher.find()) { String destinationName = matcher.group(1); String destinationBinding = String.format("%s.%s", brokerType, brokerDestination); Properties properties = new Properties(); properties.put(INITIAL_CONTEXT_FACTORY, factoryInitial); properties.put(PROVIDER_URL, providerURL); properties.put(destinationBinding, destinationName); try { InitialContext ic = new InitialContext(properties); ConnectionFactory cf = (ConnectionFactory) ic.lookup(connectionFactory); Destination destination = (Destination) ic.lookup(brokerDestination); Connection connection = cf.createConnection(brokerUsername, brokerPassword); session = connection.createSession(Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); ss.info(String.format("Connected to %s at %s", brokerDestination, providerURL)); } catch (NamingException | JMSException e) { ss.warning(String.format("Failed to connect to %s at %s", brokerDestination, providerURL), e); } } else { ss.warning(String.format("%s is not a valid broker destination", brokerDestination)); } }
Source:
public void timestampFiltersAreAdapted() { TimestampsFilter filter = new TimestampsFilter(ImmutableList.of(1L, 10L, 20L)); Filters.Filter expected = filterAdapter.adapt(emptyScanContext, filter); Assert.assertEquals(3, expected.toProto().getInterleave().getFiltersCount()); Assert.assertEquals( 10000L, expected.toProto() .getInterleave() .getFilters(1) .getTimestampRangeFilter() .getStartTimestampMicros()); Assert.assertEquals( 11000L, expected.toProto() .getInterleave() .getFilters(1) .getTimestampRangeFilter() .getEndTimestampMicros()); }

Target:
public void timestampFiltersAreAdapted() { TimestampsFilter filter = new TimestampsFilter(ImmutableList.of(1L, 10L, 20L)); Filters.Filter expected = filterAdapter.adapt(emptyScanContext, filter); Interleave expectedInterleaveFilter = expected.toProto().getInterleave(); Assert.assertEquals(3, expectedInterleaveFilter.getFiltersCount()); Assert.assertEquals( 10000L, expectedInterleaveFilter .getFilters(1) .getTimestampRangeFilter() .getStartTimestampMicros()); Assert.assertEquals( 11000L, expectedInterleaveFilter .getFilters(1) .getTimestampRangeFilter() .getEndTimestampMicros()); }
Source:
public File gitPrefix() { Holder<File> p = gitPrefix; if (p == null) { String overrideGitPrefix = System.getProperty("jgit.gitprefix"); if (overrideGitPrefix != null) p = new Holder<File>(new File(overrideGitPrefix)); else p = new Holder<File>(discoverGitPrefix()); gitPrefix = p; } return p.value; }

Target:
public File gitPrefix() { Holder<File> p = gitPrefix; if (p == null) { String overrideGitPrefix = SystemReader.getInstance().getProperty( "jgit.gitprefix"); if (overrideGitPrefix != null) p = new Holder<File>(new File(overrideGitPrefix)); else p = new Holder<File>(discoverGitPrefix()); gitPrefix = p; } return p.value; }
Source:
public static void commitJob(String domainName, JobConf conf) throws IOException { Path outputPath = new Path(DomainBuilderProperties.getOutputPath(domainName, conf)); Path tmpOutputPath = new Path(DomainBuilderProperties.getTmpOutputPath(domainName, conf)); FileSystem fs = outputPath.getFileSystem(conf); fs.mkdirs(outputPath); LOG.info("Moving temporary output files from: " + tmpOutputPath + " to final output path: " + outputPath); FileStatus[] partitions = fs.listStatus(tmpOutputPath); final int nThreads = 10; final ExecutorService executor = Executors.newFixedThreadPool(nThreads); final List<PartitionCopier> partitionCopiers = new ArrayList<PartitionCopier>(); for (FileStatus partition : partitions) { PartitionCopier partitionCopier = new PartitionCopier(partition, fs, outputPath); partitionCopiers.add(partitionCopier); executor.execute(partitionCopier); } executor.shutdown(); final long waitSeconds = 10000; try { executor.awaitTermination(waitSeconds, TimeUnit.SECONDS); } catch (InterruptedException exc) { throw new RuntimeException("executor interrupted"); } for (PartitionCopier partitionCopier : partitionCopiers) { if (partitionCopier.exception != null) { throw new IOException("Partition copying failed for " + partitionCopier.partition, partitionCopier.exception); } } cleanupJob(domainName, conf); }

Target:
public static void commitJob(String domainName, JobConf conf) throws IOException { Path outputPath = new Path(DomainBuilderProperties.getOutputPath(domainName, conf)); Path tmpOutputPath = new Path(DomainBuilderProperties.getTmpOutputPath(domainName, conf)); FileSystem fs = outputPath.getFileSystem(conf); fs.mkdirs(outputPath); LOG.info("Moving temporary output files from: " + tmpOutputPath + " to final output path: " + outputPath); FileStatus[] partitions = fs.listStatus(tmpOutputPath); final ExecutorService executor = Executors.newFixedThreadPool(N_THREADS); final List<PartitionCopier> partitionCopiers = new ArrayList<PartitionCopier>(); for (FileStatus partition : partitions) { if (!IGNORE_PATHS.contains(partition.getPath().getName()) && partition.isDir()) { PartitionCopier partitionCopier = new PartitionCopier(partition, outputPath, fs); partitionCopiers.add(partitionCopier); executor.execute(partitionCopier); } } executor.shutdown(); try { boolean allCopiersFinished = false; while (!allCopiersFinished) { allCopiersFinished = executor.awaitTermination(WAIT_CYCLE_SECONDS, TimeUnit.SECONDS); } } catch (InterruptedException e) { throw new IOException("Executor interrupted", e); } for (PartitionCopier partitionCopier : partitionCopiers) { if (partitionCopier.exception != null) { throw new IOException("Partition copying failed for " + partitionCopier.partition, partitionCopier.exception); } } cleanupJob(domainName, conf); }
Source:
public void processResponse(final CopyResult copyResult) throws PathIOException { }

Target:
public void processResponse(final CopyResult copyResult) throws PathIOException { String newRevisionId = policy.getRevisionId(copyResult); LOG.debug("Copy result {}: {}", policy.getSource(), newRevisionId); if (newRevisionId == null && policy.isRequireVersion()) { throw new NoVersionAttributeException(uri, String.format( "Change detection policy requires %s", policy.getSource())); } }
Source:
public FileStatus getFileStatus(Path path) throws IOException { if (path.getName().isEmpty()) { if (getS3ObjectMetadata(path) != null) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } ObjectMetadata metadata = getS3ObjectMetadata(path); if (metadata == null) { Iterator<LocatedFileStatus> iterator = listPrefix(path); if (iterator.hasNext()) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } return new FileStatus( getObjectSize(path, metadata), metadata.getContentType().equals(S3_DIRECTORY_OBJECT_CONTENT_TYPE), 1, BLOCK_SIZE.toBytes(), lastModifiedTime(metadata), qualifiedPath(path)); }

Target:
public FileStatus getFileStatus(Path path) throws IOException { if (path.getName().isEmpty()) { if (getS3ObjectMetadata(path) != null) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } ObjectMetadata metadata = getS3ObjectMetadata(path); if (metadata == null) { Iterator<LocatedFileStatus> iterator = listPrefix(path); if (iterator.hasNext()) { return new FileStatus(0, true, 1, 0, 0, qualifiedPath(path)); } throw new FileNotFoundException("File does not exist: " + path); } return new FileStatus( getObjectSize(path, metadata), S3_DIRECTORY_OBJECT_CONTENT_TYPE.equals(metadata.getContentType()), 1, BLOCK_SIZE.toBytes(), lastModifiedTime(metadata), qualifiedPath(path)); }
Source:
protected void restartDeadTasks() { synchronized (_runningTasks) { if (_runningTasks.isEmpty()) { _logger.info("Connector received no datastreams tasks yet."); return; } _logger.info("Checking the status of running connector tasks.", _runningTasks.size()); Set<DatastreamTask> deadDatastreamTasks = new HashSet<>(); _runningTasks.forEach((datastreamTask, connectorTaskEntry) -> { if (isTaskDead(connectorTaskEntry)) { _logger.warn("Detected that the kafka connector task is not running for datastream task {}. Restarting it", datastreamTask); boolean stopped = stopTask(datastreamTask, connectorTaskEntry); if (stopped) { deadDatastreamTasks.add(datastreamTask); } else { _logger.error("Connector task for datastream task could not be stopped.", datastreamTask); } } else { _logger.info("Connector task for datastream task is healthy", datastreamTask); } }); deadDatastreamTasks.forEach(datastreamTask -> { _logger.warn("Creating a new connector task for the datastream task {}", datastreamTask); _runningTasks.put(datastreamTask, createKafkaConnectorTask(datastreamTask)); }); _dynamicMetricsManager.createOrUpdateCounter(MODULE, NUM_TASK_RESTARTS, deadDatastreamTasks.size()); } }

Target:
protected void restartDeadTasks() { synchronized (_runningTasks) { if (_runningTasks.isEmpty()) { _logger.info("Connector received no datastreams tasks yet."); return; } _logger.info("Checking the status of running connector tasks.", _runningTasks.size()); Set<DatastreamTask> deadDatastreamTasks = new HashSet<>(); _runningTasks.forEach((datastreamTask, connectorTaskEntry) -> { if (isTaskDead(connectorTaskEntry)) { _logger.warn("Detected that the kafka connector task is not running for datastream task {}. Restarting it", datastreamTask); boolean stopped = stopTask(datastreamTask, connectorTaskEntry); if (stopped) { deadDatastreamTasks.add(datastreamTask); } else { _logger.error("Connector task for datastream task could not be stopped.", datastreamTask); } } else { _logger.info("Connector task for datastream task is healthy", datastreamTask); } }); deadDatastreamTasks.forEach(datastreamTask -> { _logger.warn("Creating a new connector task for the datastream task {}", datastreamTask); _runningTasks.put(datastreamTask, createKafkaConnectorTask(datastreamTask)); }); _numTaskRestarts = deadDatastreamTasks.size(); } }
Source:
public void onCreate() { if (DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog().build()); } super.onCreate(); try{ DatabaseHelper.init(this.getApplicationContext()); } catch (Exception e) { LogUtils.logD("Database initialize error! \n" + e.getMessage()); } }

Target:
public void onCreate() { if (DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog().build()); } super.onCreate(); try{ DatabaseHelper.init(this); } catch (Exception e) { LogUtils.logD("Database initialize error! " + e.getMessage()); } }
Source:
public BasicCallbackHandler(String username, char[] password) { this.username = username; this.password = password; this.realm = null; }

Target:
public BasicCallbackHandler(String username, char[] password) { this(username, null, password); }
Source:
protected void connectServiceUpIsRunning() { HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(CouchbaseSyncGateway.ADMIN_REST_API_PORT)); String managementUri = String.format("http://%s:%s", hp.getHostText(), hp.getPort()); setAttribute(MANAGEMENT_URL, managementUri); httpFeed = HttpFeed.builder() .entity(this) .period(200) .baseUri(managementUri) .poll(new HttpPollConfig<Boolean>(SERVICE_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200))) .build(); }

Target:
protected void connectServiceUpIsRunning() { HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(CouchbaseSyncGateway.ADMIN_REST_API_PORT)); String managementUri = String.format("http://%s:%s", hp.getHostText(), hp.getPort()); setAttribute(MANAGEMENT_URL, managementUri); httpFeed = HttpFeed.builder() .entity(this) .period(200) .baseUri(managementUri) .poll(new HttpPollConfig<Boolean>(SERVICE_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(false))) .build(); }
Source:
public void writeRecording() throws IOException { if (replay) { throw new PrestoException(CONFIGURATION_INVALID, "Cannot write recording in replay mode"); } Recording recording = new Recording( allDatabases, toPairsList(databaseCache), toPairsList(tableCache), toPairsList(supportedColumnStatisticsCache), toPairsList(tableStatisticsCache), toPairsList(partitionStatisticsCache), toPairsList(allTablesCache), toPairsList(allViewsCache), toPairsList(partitionCache), toPairsList(partitionNamesCache), toPairsList(partitionNamesByPartsCache), toPairsList(partitionsByNamesCache), toPairsList(rolesCache), toPairsList(databasePrivilegesCache), toPairsList(tablePrivilegesCache)); new ObjectMapperProvider().get() .writerWithDefaultPrettyPrinter() .writeValue(new File(recordingPath), recording); }

Target:
public void writeRecording() throws IOException { if (replay) { throw new IllegalStateException("Cannot write recording in replay mode"); } Recording recording = new Recording( allDatabases, toPairs(databaseCache), toPairs(tableCache), toPairs(supportedColumnStatisticsCache), toPairs(tableStatisticsCache), toPairs(partitionStatisticsCache), toPairs(allTablesCache), toPairs(allViewsCache), toPairs(partitionCache), toPairs(partitionNamesCache), toPairs(partitionNamesByPartsCache), toPairs(partitionsByNamesCache), toPairs(rolesCache), toPairs(databasePrivilegesCache), toPairs(tablePrivilegesCache)); new ObjectMapperProvider().get() .writerWithDefaultPrettyPrinter() .writeValue(new File(recordingPath), recording); }
Source:
protected void executeQueryCommand() { Function<Guid, DiskImage> getAncestor = (Guid imageId) -> diskImageDao.getAncestor(imageId, getUserID(), getParameters().isFiltered()); Set<Guid> haveNullAncestor = new HashSet<>(); Predicate<Pair<Guid, DiskImage>> ancestorNotNull = (Pair<Guid, DiskImage> pair) -> { if (pair.getSecond() == null) { haveNullAncestor.add(pair.getFirst()); return false; } return true; }; Map<Guid, DiskImage> haveValidAncestor = getParameters().getIds().stream() .map(guid -> new Pair<>(guid, getAncestor.apply(guid))) .filter(ancestorNotNull) .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond)); if (!haveNullAncestor.isEmpty()) { log.warn("Ancestor is missing for the following guid(s): {}", StringUtils.join(haveNullAncestor, ',')); } getQueryReturnValue().setReturnValue(haveValidAncestor); }

Target:
protected void executeQueryCommand() { Set<Guid> haveInvalidAncestor = new HashSet<>(); Function<Guid, DiskImage> getAncestor = (Guid imageId) -> { DiskImage ancestor = diskImageDao.getAncestor(imageId, getUserID(), getParameters().isFiltered()); if (ancestor == null) { haveInvalidAncestor.add(imageId); } return ancestor; }; Map<Guid, DiskImage> haveValidAncestor = getParameters().getIds().stream() .map(guid -> new Pair<>(guid, getAncestor.apply(guid))) .filter(pair -> pair.getSecond() != null) .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond)); if (!haveInvalidAncestor.isEmpty()) { log.warn("Ancestor is missing for the following guid(s): {}", StringUtils.join(haveInvalidAncestor, ',')); } getQueryReturnValue().setReturnValue(haveValidAncestor); }
Source:
@Test public void testCheckQueueIntegrityOn2xLongCorruptedElement() throws IOException { QueueFile queueFile = new QueueFile(file); final byte[] a = { 1, 2 }; queueFile.add(a); final byte[] b = { 3, 4, 5 }; queueFile.add(b); final int positionOfElementB = QueueFile.HEADER_LENGTH + Element.HEADER_LENGTH + 2; queueFile.raf.seek(positionOfElementB); int doubleFileSize = (int)queueFile.raf.length() * 2; final byte[] intBuffer = new byte[4]; QueueFile.writeInt(intBuffer, 0, doubleFileSize); queueFile.raf.write(intBuffer); try { queueFile.checkQueueIntegrity(); fail("Should have complained about wrong element lengths."); } catch (IOException ex) { final String message = ex.getMessage(); assertThat(message).contains("corruption"); } }

Target:
@Test public void testCheckQueueIntegrityOn2xLongCorruptedElement() throws IOException { QueueFile queueFile = new QueueFile(file); final byte[] a = { 1, 2 }; queueFile.add(a); final byte[] b = { 3, 4, 5 }; queueFile.add(b); final int positionOfElementB = QueueFile.HEADER_LENGTH + Element.HEADER_LENGTH + 2; queueFile.raf.seek(positionOfElementB); int doubleFileSize = (int)queueFile.raf.length() * 2; final byte[] intBuffer = new byte[4]; QueueFile.writeInt(intBuffer, 0, doubleFileSize); queueFile.raf.write(intBuffer); try { queueFile.checkQueueIntegrity(); fail("Should have complained about wrong element lengths."); } catch (IOException ex) { String message = ex.getMessage(); assertThat(message).contains("corruption"); } }
Source:
public byte[] encrypt(byte[] message) { if (publicKey == null) throw new RuntimeException("Encryption failed. Public key not available."); byte[] ct = new byte[message.length + SEAL_BYTES]; isValid(sodium().crypto_box_seal( ct, message, message.length, publicKey), "Encryption failed"); return ct; }

Target:
public byte[] encrypt(byte[] message) { byte[] ct = new byte[message.length + SEAL_BYTES]; if (sodium().crypto_box_seal(ct, message, message.length, mPublicKey) != 0) { throw new IllegalArgumentException("Failed to encrypt"); } return ct; }
Source:
public List<SecretSeriesAndContent> getSecretsByName(List<String> names) { checkArgument(!names.isEmpty()); SecretContentDAO secretContentDAO = secretContentDAOFactory.using(dslContext.configuration()); SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(dslContext.configuration()); List<SecretSeries> multipleseries = secretSeriesDAO.getSecretsSeriesByName(names); Iterator siter = multipleseries.iterator(); List<SecretSeriesAndContent> ret = new ArrayList<SecretSeriesAndContent>(); while (siter.hasNext()) { SecretSeries series = (SecretSeries) siter.next(); if (series.currentVersion().isPresent()) { long secretContentId = series.currentVersion().get(); Optional<SecretContent> secretContent = secretContentDAO.getSecretContentById(secretContentId); if (secretContent.isPresent()) { ret.add(SecretSeriesAndContent.of(series, secretContent.get())); } else { } } } return ret; }

Target:
public List<SecretSeriesAndContent> getSecretsByName(List<String> names) { checkArgument(!names.isEmpty()); SecretContentDAO secretContentDAO = secretContentDAOFactory.using(dslContext.configuration()); SecretSeriesDAO secretSeriesDAO = secretSeriesDAOFactory.using(dslContext.configuration()); List<SecretSeries> multipleSeries = secretSeriesDAO.getMultipleSecretSeriesByName(names); List<SecretSeriesAndContent> ret = new ArrayList<SecretSeriesAndContent>(); for (SecretSeries series : multipleSeries) { if (series.currentVersion().isPresent()) { long secretContentId = series.currentVersion().get(); Optional<SecretContent> secretContent = secretContentDAO.getSecretContentById(secretContentId); if (secretContent.isPresent()) { ret.add(SecretSeriesAndContent.of(series, secretContent.get())); } else { throw new NotFoundException("Secret not found."); } } } return ret; }
Source:
public SkyValue compute(SkyKey skyKey, Environment env) throws SkyFunctionException, InterruptedException { RepositoryName nameFromRule = (RepositoryName) skyKey.argument(); SkyKey repositoryKey = RepositoryDirectoryValue.key(nameFromRule); RepositoryDirectoryValue repository = (RepositoryDirectoryValue) env.getValue(repositoryKey); if (repository == null) { return null; } if (!repository.repositoryExists()) { return RepositoryValue.notFound(nameFromRule); } RootedPath workspaceFilePath; try { workspaceFilePath = WorkspaceFileHelper .getWorkspaceRootedFile(Root.fromPath(repository.getPath()), env); if (workspaceFilePath == null) { return null; } } catch (IOException e) { throw new RepositoryLoaderFunctionException( new IOException("Could not determine workspace file (WORKSPACE.bazel / WORKSPACE): " + e.getMessage()), Transience.PERSISTENT); } SkyKey workspaceKey = WorkspaceFileValue.key(workspaceFilePath); WorkspaceFileValue workspacePackage = (WorkspaceFileValue) env.getValue(workspaceKey); if (workspacePackage == null) { return null; } RepositoryName workspaceName; try { String workspaceNameStr = workspacePackage.getPackage().getWorkspaceName(); workspaceName = workspaceNameStr.isEmpty() ? RepositoryName.create("") : RepositoryName.create("@" + workspaceNameStr); } catch (LabelSyntaxException e) { throw new IllegalStateException(e); } return RepositoryValue.success(nameFromRule, repository); }

Target:
public SkyValue compute(SkyKey skyKey, Environment env) throws SkyFunctionException, InterruptedException { RepositoryName nameFromRule = (RepositoryName) skyKey.argument(); SkyKey repositoryKey = RepositoryDirectoryValue.key(nameFromRule); RepositoryDirectoryValue repository = (RepositoryDirectoryValue) env.getValue(repositoryKey); if (repository == null) { return null; } if (!repository.repositoryExists()) { return RepositoryValue.notFound(nameFromRule); } RootedPath workspaceFilePath; try { workspaceFilePath = WorkspaceFileHelper .getWorkspaceRootedFile(Root.fromPath(repository.getPath()), env); if (workspaceFilePath == null) { return null; } } catch (IOException e) { throw new RepositoryLoaderFunctionException( new IOException( "Could not determine workspace file (\"WORKSPACE.bazel\" or \"WORKSPACE\"): " + e.getMessage()), Transience.PERSISTENT); } SkyKey workspaceKey = WorkspaceFileValue.key(workspaceFilePath); WorkspaceFileValue workspacePackage = (WorkspaceFileValue) env.getValue(workspaceKey); if (workspacePackage == null) { return null; } RepositoryName workspaceName; try { String workspaceNameStr = workspacePackage.getPackage().getWorkspaceName(); workspaceName = workspaceNameStr.isEmpty() ? RepositoryName.create("") : RepositoryName.create("@" + workspaceNameStr); } catch (LabelSyntaxException e) { throw new IllegalStateException(e); } return RepositoryValue.success(nameFromRule, repository); }
Source:
protected void executeCommand() { if (getVmTemplate().isBaseTemplate()) { shiftBaseTemplateToSuccessor(); } List<Disk> templateImages = DbFacade.getInstance().getDiskDao().getAllForVm(getVmTemplateId()); final List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(templateImages); final List<DiskImage> diskImages = ImagesHandler.filterImageDisks(templateImages, false, false, true); VmTemplateHandler.lockVmTemplateInTransaction(getVmTemplateId(), getCompensationContext()); TransactionSupport.executeInNewTransaction(() -> { if (!diskImages.isEmpty() || !cinderDisks.isEmpty()) { if (!diskImages.isEmpty() && removeVmTemplateImages()) { VmHandler.removeVmInitFromDB(getVmTemplate()); setSucceeded(true); } if (!cinderDisks.isEmpty()) { removeCinderDisks(cinderDisks); setSucceeded(true); } } removeTemplateFromDb(); return null; }); }

Target:
protected void executeCommand() { if (getVmTemplate().isBaseTemplate()) { shiftBaseTemplateToSuccessor(); } List<Disk> templateImages = DbFacade.getInstance().getDiskDao().getAllForVm(getVmTemplateId()); final List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(templateImages); final List<DiskImage> diskImages = ImagesHandler.filterImageDisks(templateImages, false, false, true); VmTemplateHandler.lockVmTemplateInTransaction(getVmTemplateId(), getCompensationContext()); TransactionSupport.executeInNewTransaction(() -> { if (!diskImages.isEmpty() || !cinderDisks.isEmpty()) { if (!diskImages.isEmpty() && removeVmTemplateImages()) { VmHandler.removeVmInitFromDB(getVmTemplate()); setSucceeded(true); } if (!cinderDisks.isEmpty()) { removeCinderDisks(cinderDisks); setSucceeded(true); } } return null; }); if (noAsyncOperations()) { handleEndAction(); } }
Source:
public DDLCompiler(VoltCompiler compiler, HSQLInterface hsql, VoltDDLElementTracker tracker, ClassLoader classLoader) { assert(compiler != null); assert(hsql != null); assert(tracker != null); m_hsql = hsql; m_compiler = compiler; m_tracker = tracker; m_classLoader = classLoader; m_mvProcessor = new MaterializedViewProcessor(m_compiler, m_hsql); m_voltStatementProcessor = new VoltDBStatementProcessor(this); m_voltStatementProcessor.addNextProcessor(new CreateAggregateFunctionFromClass(this)) .addNextProcessor(new CreateProcedureFromClass(this)) .addNextProcessor(new CreateProcedureAsScript(this)) .addNextProcessor(new CreateProcedureAsSQL(this)) .addNextProcessor(new CreateFunctionFromMethod(this)) .addNextProcessor(new DropAggregateFunction(this)) .addNextProcessor(new DropFunction(this)) .addNextProcessor(new DropProcedure(this)) .addNextProcessor(new PartitionStatement(this)) .addNextProcessor(new ReplicateTable(this)) .addNextProcessor(new CreateRole(this)) .addNextProcessor(new DropRole(this)) .addNextProcessor(new DropStream(this)) .addNextProcessor(new DRTable(this)) .addNextProcessor(new SetGlobalParam(this)) .addNextProcessor(new CatchAllVoltDBStatement(this, m_voltStatementProcessor)); }

Target:
public DDLCompiler(VoltCompiler compiler, HSQLInterface hsql, VoltDDLElementTracker tracker, ClassLoader classLoader) { assert(compiler != null); assert(hsql != null); assert(tracker != null); m_hsql = hsql; m_compiler = compiler; m_tracker = tracker; m_classLoader = classLoader; m_mvProcessor = new MaterializedViewProcessor(m_compiler, m_hsql); m_voltStatementProcessor = new VoltDBStatementProcessor(this); m_voltStatementProcessor.addNextProcessor(new CreateProcedureFromClass(this)) .addNextProcessor(new CreateProcedureAsScript(this)) .addNextProcessor(new CreateProcedureAsSQL(this)) .addNextProcessor(new CreateAggregateFunctionFromClass(this)) .addNextProcessor(new CreateFunctionFromMethod(this)) .addNextProcessor(new DropAggregateFunction(this)) .addNextProcessor(new DropFunction(this)) .addNextProcessor(new DropProcedure(this)) .addNextProcessor(new PartitionStatement(this)) .addNextProcessor(new ReplicateTable(this)) .addNextProcessor(new CreateRole(this)) .addNextProcessor(new DropRole(this)) .addNextProcessor(new DropStream(this)) .addNextProcessor(new DRTable(this)) .addNextProcessor(new SetGlobalParam(this)) .addNextProcessor(new CatchAllVoltDBStatement(this, m_voltStatementProcessor)); }
Source:
public static List<IProject> selectionToProjects(IStructuredSelection selection) { if (selection == null) { return Collections.emptyList(); } List<IProject> resources = new ArrayList<>(); Iterator<?> iter = selection.iterator(); while (iter.hasNext()) { Object curr = iter.next(); if (curr instanceof IWorkingSet) { IWorkingSet workingSet = (IWorkingSet) curr; if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) { continue; } IAdaptable[] elements = workingSet.getElements(); for (IAdaptable element : elements) { IProject project = element.getAdapter(IProject.class); if (project != null) { resources.add(project); } } } else if (curr instanceof IAdaptable) { IProject resource = ((IAdaptable) curr).getAdapter(IProject.class); if (resource != null) { resources.add(resource); } } } return resources; }

Target:
private static List<IProject> selectionToProjects(IStructuredSelection selection) { if (selection == null) { return Collections.emptyList(); } List<IProject> resources = new ArrayList<>(); Iterator<?> selectionIterator = selection.iterator(); while (selectionIterator.hasNext()) { Object currentObject = selectionIterator.next(); if (currentObject instanceof IWorkingSet) { IWorkingSet workingSet = (IWorkingSet) currentObject; for (IAdaptable element : workingSet.getElements()) { IProject project = element.getAdapter(IProject.class); if (project != null) { resources.add(project); } } } else if (currentObject instanceof IAdaptable) { IProject resource = ((IAdaptable) currentObject).getAdapter(IProject.class); if (resource != null) { resources.add(resource); } } } return resources; }
Source:
public void addToWhitelist(String clientID) { whitelistedIDs.add(clientID); }

Target:
public void addToWhitelist(String clientID) { whitelistedIDs.add(clientID); saveLists(); }
Source:
public void findOldestPasswordShouldFindOldestPasswordHistoryForUserWithThreePasswordHistory() { UserEntity user = this.userRepository.findByUserName(TEST_USERNAME_WITH_THREE_PASSWORD_HISTORY); Date nearNow = currentDateMinus(5); PasswordHistoryEntity pwHistory = this.repository.findOldestPassword(TEST_USER_ID_WITH_THREE_PASSWORD_HISTORY); assertThat(pwHistory, notNullValue()); assertPasswordHistoryEntity(pwHistory, user, ACTUAL_PASSWORD_FOR_USER_WITH_THREE_PASSWORD_HISTORY, nearNow); }

Target:
public void findOldestPasswordShouldFindOldestPasswordHistoryForUserWithThreePasswordHistory() { UserEntity user = this.userRepository.findByUserName(TEST_USERNAME_WITH_THREE_PASSWORD_HISTORY); Long testUserIdWithThreePasswordHistory = user.getId(); Date nearNow = currentDateMinus(5); PasswordHistoryEntity pwHistory = this.repository.findOldestPassword(testUserIdWithThreePasswordHistory); assertThat(pwHistory, notNullValue()); assertPasswordHistoryEntity(pwHistory, user, ACTUAL_PASSWORD_FOR_USER_WITH_THREE_PASSWORD_HISTORY, nearNow); }
Source:
public void testGetGraphIndex() throws Exception { final Edge edge = mock(Edge.class); when(edge.getTargetNode()).thenReturn(child); when(parent.getOutEdges()).thenReturn(Collections.singletonList(edge)); assertEquals(0, CaseManagementCommandUtil.getChildGraphIndex(parent, child)); }

Target:
public void testGetGraphIndex() { final Edge edge = mock(Edge.class); when(edge.getTargetNode()).thenReturn(child); when(parent.getOutEdges()).thenReturn(Collections.singletonList(edge)); assertEquals(0, CaseManagementCommandUtil.getChildGraphIndex(parent, child)); }
Source:
public void applyFieldFacet(SolrQuery query, String fieldName, String fieldValuePrefix) { Preconditions.checkNotNull(query); Preconditions.checkNotNull(fieldName); Preconditions.checkArgument(StringUtils.isNotBlank(fieldName)); query.setFacet(true); query.add(FacetParams.FACET_SORT, FacetParams.FACET_SORT_INDEX); query.add(FacetParams.FACET_FIELD, fieldName); if (!StringUtils.isBlank(fieldValuePrefix)) { query.add(FacetParams.FACET_PREFIX, fieldValuePrefixAdder.prefixWithSeparator(fieldValuePrefix)); } }

Target:
public void applyFieldFacet(SolrQuery query, String fieldName, String fieldValuePrefix) { Preconditions.checkNotNull(query); Preconditions.checkNotNull(fieldName); Preconditions.checkArgument(StringUtils.isNotBlank(fieldName)); String fieldParamPrefix = "f." + fieldName + "."; query.setFacet(true); query.add(fieldParamPrefix + FacetParams.FACET_SORT, FacetParams.FACET_SORT_INDEX); query.add(FacetParams.FACET_FIELD, fieldName); if (!StringUtils.isBlank(fieldValuePrefix)) { query.add(fieldParamPrefix + FacetParams.FACET_PREFIX, fieldValuePrefixAdder.prefixWithSeparator(fieldValuePrefix)); } }