auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void onBarcodeResult(BarcodeScanListener barcodeScanListener, int requestCode, int resultCode, Intent intent) { if (BuildConfig.DEBUG && !(requestCode == BARCODE_FETCH)) { throw new AssertionError("requestCode should be BARCODE_FETCH!"); } if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra(SCAN_RESULT).trim(); barcodeScanListener.onBarcodeFetch(result, intent); } }

Target:
public static void onBarcodeResult(BarcodeScanListener barcodeScanListener, int requestCode, int resultCode, Intent intent) { if (BuildConfig.DEBUG && !(requestCode == BARCODE_FETCH)) { throw new AssertionError("requestCode should be BARCODE_FETCH!"); } if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra(SCAN_RESULT); if (result != null){ result = result.trim(); } barcodeScanListener.onBarcodeFetch(result, intent); } }
Source:
public QuotaProgressBar() { super(); tooltip = new WidgetTooltip(this); }

Target:
public QuotaProgressBar() { tooltip = new WidgetTooltip(this); }
Source:
private String replaceDiskSourceFile(String xmlDesc, String isoPath, String vmName) throws IOException, SAXException, ParserConfigurationException, TransformerException { InputStream in = IOUtils.toInputStream(xmlDesc); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(in); Node domainNode = doc.getFirstChild(); NodeList domainChildNodes = domainNode.getChildNodes(); for (int i = 0; i < domainChildNodes.getLength(); i++) { Node domainChildNode = domainChildNodes.item(i); if ("devices".equals(domainChildNode.getNodeName())) { NodeList devicesChildNodes = domainChildNode.getChildNodes(); for (int x = 0; x < devicesChildNodes.getLength(); x++) { Node deviceChildNode = devicesChildNodes.item(x); if ("disk".equals(deviceChildNode.getNodeName())) { Node diskNode = deviceChildNode; String sourceText = getSourceText(diskNode); NodeList diskChildNodes = diskNode.getChildNodes(); for (int z = 0; z < diskChildNodes.getLength(); z++) { Node diskChildNode = diskChildNodes.item(z); if ("source".equals(diskChildNode.getNodeName())) { Node sourceNode = diskChildNode; NamedNodeMap sourceNodeAttributes = sourceNode.getAttributes(); Node sourceNodeAttribute = sourceNodeAttributes.getNamedItem("file"); if ( sourceNodeAttribute.getNodeValue().contains(vmName)) { diskNode.removeChild(diskChildNode); Element newChildSourceNode = doc.createElement("source"); newChildSourceNode.setAttribute("file", isoPath); diskNode.appendChild(newChildSourceNode); } } } } } } } return getXml(doc); }

Target:
private String replaceDiskSourceFile(String xmlDesc, String isoPath, String vmName) throws IOException, SAXException, ParserConfigurationException, TransformerException { InputStream in = IOUtils.toInputStream(xmlDesc); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(in); Node domainNode = doc.getFirstChild(); NodeList domainChildNodes = domainNode.getChildNodes(); for (int i = 0; i < domainChildNodes.getLength(); i++) { Node domainChildNode = domainChildNodes.item(i); if ("devices".equals(domainChildNode.getNodeName())) { NodeList devicesChildNodes = domainChildNode.getChildNodes(); if (findDiskNode(doc, devicesChildNodes, vmName, isoPath)) { break; } } } return getXml(doc); }
Source:
public static Object invokeInstanceMethod(Object instance, Method method, Object[] args) { Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length != args.length) { handleException("Provided argument count does not match method the " + "parameter count of method '" + method.getName() + "'. Argument count = " + args.length + ", method parameter count = " + paramTypes.length); } Object[] processedArgs = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; ++i) { if (args[i] == null || paramTypes[i].isAssignableFrom(args[i].getClass())) { processedArgs[i] = args[i]; } else if (SimpleTypeMapper.isSimpleType(paramTypes[i])) { try { processedArgs[i] = SimpleTypeMapper.getSimpleTypeObject(paramTypes[i], AXIOMUtil.stringToOM("<a>" + args[i] + "</a>")); } catch (XMLStreamException e) { handleException("XMLStreamException ", e); } } else { handleException("Incompatible argument found in " + i + "th argument " + "for '" + method.getName() + "' method."); } } try { return method.invoke(instance, processedArgs); } catch (IllegalAccessException e) { handleException("Error while invoking '" + method.getName() + "' method " + "via reflection.", e); } catch (InvocationTargetException e) { handleException("Error while invoking '" + method.getName() + "' method " + "via reflection.", e); } return null; }

Target:
public static Object invokeInstanceMethod(Object instance, Method method, Object[] args) { Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length != args.length) { handleException("Provided argument count does not match method the " + "parameter count of method '" + method.getName() + "'. Argument count = " + args.length + ", method parameter count = " + paramTypes.length); } Object[] processedArgs = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; ++i) { if (args[i] == null || paramTypes[i].isAssignableFrom(args[i].getClass())) { processedArgs[i] = args[i]; } else if (SimpleTypeMapper.isSimpleType(paramTypes[i])) { try { processedArgs[i] = SimpleTypeMapper.getSimpleTypeObject(paramTypes[i], AXIOMUtil.stringToOM("<a>" + args[i] + "</a>")); } catch (XMLStreamException e) { handleException("XMLStreamException ", e); } } else { handleException("Incompatible argument found in " + i + "th argument " + "for '" + method.getName() + "' method."); } } try { return method.invoke(instance, processedArgs); } catch (IllegalAccessException |InvocationTargetException e ) { handleException("Error while invoking '" + method.getName() + "' method " + "via reflection.", e); } return null; }
Source:
public boolean hasNext() { if (currentEpisodes != null && episodes.hasNext()) { currentEpisodes = episodes.next().iterator(); if (currentEpisodes.hasNext()) { return true; } else { return false; } } else if (currentEpisodes.hasNext()) { return true; } else if (episodes.hasNext()) { currentEpisodes = episodes.next().iterator(); if (currentEpisodes.hasNext()) { return true; } else { return false; } } else { return false; } }

Target:
public boolean hasNext() { return episodesIterator.hasNext(); }
Source:
public void log(IStatus status) { if (status.getSeverity() < minStatus) return; if (writer != null) { writer.start(STATUS_ELEMENT); switch (status.getSeverity()) { case IStatus.OK : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "OK"); break; case IStatus.INFO : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "INFO"); break; case IStatus.WARNING : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "WARNING"); break; case IStatus.ERROR : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "ERROR"); break; case IStatus.CANCEL : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "CANCEL"); break; default : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, status.getSeverity()); } writer.attribute(STATUS_MESSAGE_ATTRIBUTE, status.getMessage()); } else System.out.println(status); IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus nestedStatu : nestedStatus) { log(nestedStatu); } if (writer != null) writer.end(); }

Target:
public void log(IStatus status) { if (status.getSeverity() < minStatus) return; if (writer != null) { writer.start(STATUS_ELEMENT); switch (status.getSeverity()) { case IStatus.OK : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "OK"); break; case IStatus.INFO : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "INFO"); break; case IStatus.WARNING : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "WARNING"); break; case IStatus.ERROR : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "ERROR"); break; case IStatus.CANCEL : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, "CANCEL"); break; default : writer.attribute(STATUS_SEVERITY_ATTRIBUTE, status.getSeverity()); } writer.attribute(STATUS_MESSAGE_ATTRIBUTE, status.getMessage()); } else System.out.println(status); IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus s : nestedStatus) { log(s); } if (writer != null) writer.end(); }
Source:
private void verifyServiceDeclaration() { final PackageManager packageManager = mContext.getPackageManager(); final Intent intent = new Intent(mContext, BeaconService.class); List<ResolveInfo> resolveInfo = packageManager.queryIntentServices(intent, PackageManager.MATCH_DEFAULT_ONLY); if (resolveInfo != null && resolveInfo.size() == 0) { throw new ServiceNotDeclaredException(); } }

Target:
private void verifyServiceDeclaration() { final PackageManager packageManager = mContext.getPackageManager(); final Intent intent = new Intent(mContext, BeaconService.class); List<ResolveInfo> resolveInfo = packageManager.queryIntentServices(intent, PackageManager.MATCH_DEFAULT_ONLY); if (resolveInfo != null && resolveInfo.isEmpty()) { throw new ServiceNotDeclaredException(); } }
Source:
private void updateMap(WfsLayerInfo wfsLayerInfo) { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); mLoadingView.setVisibility(View.VISIBLE); mMapView.getMap().getOperationalLayers().clear(); WfsFeatureTable featureTable = new WfsFeatureTable(wfsLayerInfo); featureTable.setAxisOrder(mAxisCheckbox.isChecked() ? OgcAxisOrder.SWAP : OgcAxisOrder.NO_SWAP); featureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.MANUAL_CACHE); ListenableFuture<FeatureQueryResult> featureQueryResultFuture = featureTable .populateFromServiceAsync(new QueryParameters(), false, null); new Thread(() -> { try { featureQueryResultFuture.get(); FeatureLayer featureLayer = new FeatureLayer(featureTable); featureLayer.setRenderer(getRandomRendererForTable(featureTable)); runOnUiThread(() -> { mMapView.getMap().getOperationalLayers().add(featureLayer); mMapView.setViewpointGeometryAsync(featureLayer.getFullExtent(), 50); }); } catch (InterruptedException | ExecutionException e) { runOnUiThread( () -> logErrorToUser( getString(R.string.error_feature_table_populate_from_service_failure, e.getMessage()))); } finally { runOnUiThread(() -> mLoadingView.setVisibility(View.GONE)); } }).start(); }

Target:
private void updateMap(WfsLayerInfo wfsLayerInfo) { mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); mLoadingView.setVisibility(View.VISIBLE); mMapView.getMap().getOperationalLayers().clear(); WfsFeatureTable featureTable = new WfsFeatureTable(wfsLayerInfo); featureTable.setAxisOrder(mAxisCheckbox.isChecked() ? OgcAxisOrder.SWAP : OgcAxisOrder.NO_SWAP); featureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.MANUAL_CACHE); FeatureLayer featureLayer = new FeatureLayer(featureTable); featureLayer.setRenderer(getRandomRendererForTable(featureTable)); mMapView.getMap().getOperationalLayers().add(featureLayer); ListenableFuture<FeatureQueryResult> featureQueryResultFuture = featureTable .populateFromServiceAsync(new QueryParameters(), false, null); featureQueryResultFuture.addDoneListener(() -> { mMapView.setViewpointGeometryAsync(featureLayer.getFullExtent(), 50); mLoadingView.setVisibility(View.GONE); }); }
Source:
void restartSessionIfNeeded() { long resetTime = sessionTime != null ? System.currentTimeMillis() - sessionTime : HALF_MIN_IN_MILLIS; if (resetTime < HALF_MIN_IN_MILLIS) return; OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "Session restarted"); cleanSession(); onSessionStarted(); if (sessionListener != null) sessionListener.onSessionRestarted(); }

Target:
void restartSessionIfNeeded() { if (OneSignal.getAppEntryState().isNotificationClick()) return; JSONArray lastNotifications = getLastNotificationsReceivedIds(); if (lastNotifications.length() > 0) setSession(Session.INDIRECT, null, lastNotifications); else setSession(Session.UNATTRIBUTED, null, null); }
Source:
public void initForViewByQuestion(InstructorAttributes instructor, String selectedSection, String showStats, String groupByTeam) { viewType = ViewType.QUESTION; this.instructor = instructor; this.selectedSection = selectedSection; this.showStats = showStats; this.groupByTeam = groupByTeam; Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> questionToResponseMap = bundle.getQuestionResponseMap(); questionPanels = new ArrayList<InstructorFeedbackResultsQuestionTable>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : questionToResponseMap.entrySet()) { FeedbackQuestionAttributes question = entry.getKey(); List<FeedbackResponseAttributes> responses = entry.getValue(); questionPanels.add(buildQuestionTableAndResponseRows(question, responses, "")); } }

Target:
public void initForViewByQuestion(InstructorAttributes instructor, String selectedSection, String showStats, String groupByTeam) { Assumption.assertNotNull(bundle); this.viewType = ViewType.QUESTION; this.sortType = ViewType.QUESTION.toString(); this.instructor = instructor; this.selectedSection = selectedSection; this.showStats = showStats; this.groupByTeam = groupByTeam; Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> questionToResponseMap = bundle.getQuestionResponseMap(); questionPanels = new ArrayList<InstructorFeedbackResultsQuestionTable>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : questionToResponseMap.entrySet()) { FeedbackQuestionAttributes question = entry.getKey(); List<FeedbackResponseAttributes> responses = entry.getValue(); questionPanels.add(buildQuestionTableAndResponseRows(question, responses, "")); } }
Source:
public List<String> getExamples() { return Lists.newArrayList( "# Create a schema for Kite's Format class:", "org.kitesdk.data.Format", "# Create a schema for a class in a jar:", "com.example.MyRecord --jar my-application.jar", "# Save the schema for Kite's Format class to format.avsc:", "org.kitesdk.data.Format -o format.avsc" ); }

Target:
public List<String> getExamples() { return Lists.newArrayList( "# Create a schema for an example User class:", "org.kitesdk.cli.example.User", "# Create a schema for a class in a jar:", "com.example.MyRecord --jar my-application.jar", "# Save the schema for the example User class to user.avsc:", "org.kitesdk.cli.example.User -o user.avsc" ); }
Source:
protected void updateUIForOrientation() { final int orientation = getResources().getConfiguration().orientation; try { if (orientation == Configuration.ORIENTATION_LANDSCAPE && youTubePlayer != null) { youTubePlayer.setFullscreen(true); } else if (youTubePlayer != null) { youTubePlayer.setFullscreen(false); } updateUI(orientation); } catch (IllegalStateException e) { return; } }

Target:
protected void updateUIForOrientation() { final int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE && allowFullScreen) { LinearLayout playerContainer = getView().findViewById(R.id.player_container); if (playerContainer != null) { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); float screenHeight = displayMetrics.heightPixels; playerContainer.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, (int) screenHeight)); playerContainer.requestLayout(); } if (youTubePlayer != null) { youTubePlayer.setFullscreen(true); } } else { LinearLayout playerContainer = getView().findViewById(R.id.player_container); if (playerContainer != null) { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); float screenWidth = displayMetrics.widthPixels; float ideaHeight = screenWidth * 9 / 16; playerContainer.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, (int) ideaHeight)); playerContainer.requestLayout(); } if (youTubePlayer != null) { youTubePlayer.setFullscreen(false); } } updateUI(orientation); }
Source:
public void testHttpsClientDisableCNCheckFalse() { String url = "https://url"; AssertionType assertion = new AssertionType(); assertion.setTransactionTimeout(-1); CONNECTClient<TestServicePortType> endpoint = null; try { PropertyAccessor.getInstance().setProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.DISABLE_CN_CHECK, "false"); boolean disableCNCheck = PropertyAccessor.getInstance() .getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.DISABLE_CN_CHECK); endpoint = createClient(url, assertion); Client client = ClientProxy.getClient(endpoint.getPort()); HTTPConduit conduit = (HTTPConduit) client.getConduit(); TLSClientParameters tlsPara = conduit.getTlsClientParameters(); Assert.assertFalse("disableCNCheck==false", tlsPara.isDisableCNCheck()); } catch (PropertyAccessException ex) { System.out.println("Unable to set in memory property for disable-CN-Check."); } }

Target:
public void testHttpsClientDisableCNCheckFalse() { String url = "https://url"; AssertionType assertion = new AssertionType(); assertion.setTransactionTimeout(-1); CONNECTClient<TestServicePortType> endpoint = null; try { PropertyAccessor.getInstance().setProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.DISABLE_CN_CHECK, "false"); boolean disableCNCheck = PropertyAccessor.getInstance() .getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.DISABLE_CN_CHECK); endpoint = createClient(url, assertion); Client client = ClientProxy.getClient(endpoint.getPort()); HTTPConduit conduit = (HTTPConduit) client.getConduit(); TLSClientParameters tlsPara = conduit.getTlsClientParameters(); Assert.assertFalse("disableCNCheck==false", tlsPara.isDisableCNCheck()); } catch (PropertyAccessException ex) { Assert.fail("Unable to set in memory property for disable-CN-Check."); } }
Source:
public static String convert(char... chars) { if (chars.length == 0) { throw new IllegalArgumentException("empty character array"); } StringBuilder builder = new StringBuilder(chars.length * 2 - 1); builder.append(chars[0]); for (int i = 1; i < chars.length; i++) { builder.append(' ').append(chars[i]); } return builder.toString(); }

Target:
public static String convert(char... chars) { if (chars.length == 0) { throw new IllegalArgumentException("empty character array"); } StringBuilder builder = new StringBuilder(chars.length * 2 - 1); builder.append(chars[0]); for (int i = 1; i < chars.length; i++) { if (Character.isWhitespace(chars[i])) { throw new IllegalArgumentException("whitespace character present: " + ((int)chars[i])); } builder.append(' ').append(chars[i]); } return builder.toString(); }
Source:
private static Certificate[] getCertificatesFromString(String pemFileString) throws IOException, CertificateException { Matcher matcher = CERT_PATTERN.matcher(pemFileString); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); List<Certificate> certList = new ArrayList<>(); while (matcher.find()) { Certificate certificate; try (InputStream stream = new ByteArrayInputStream(matcher.group(0).getBytes(Charsets.UTF_8))) { certificate = certFactory.generateCertificate(stream); } certList.add(certificate); } return certList.toArray(new Certificate[certList.size()]); }

Target:
private static List<Certificate> getCertificatesFromString(String pemFileString) throws IOException, CertificateException { Matcher matcher = CERT_PATTERN.matcher(pemFileString); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); List<Certificate> certList = new ArrayList<>(); while (matcher.find()) { Certificate certificate; try (InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8))) { certificate = certFactory.generateCertificate(stream); } certList.add(certificate); } return certList; }
Source:
public void stop() { if (executor != null) { try { cleanup.shutdownNow(); List<Runnable> pending = executor.shutdownNow(); if (executor.awaitTermination(15, TimeUnit.MINUTES)) { if (pending != null && !pending.isEmpty()) { log.info(String.format("Finishing %d disk cache updates", pending.size())); for (Runnable update : pending) { update.run(); } } } else { log.info("Timeout waiting for disk cache to close"); } } catch (InterruptedException e) { log.warn("Interrupted waiting for disk cache to shutdown"); } } for (H2CacheImpl<?, ?> cache : caches) { cache.stop(); } }

Target:
public void stop() { if (executor != null) { try { cleanup.shutdownNow(); List<Runnable> pending = executor.shutdownNow(); if (executor.awaitTermination(15, TimeUnit.MINUTES)) { if (pending != null && !pending.isEmpty()) { log.info(String.format("Finishing %d disk cache updates", pending.size())); for (Runnable update : pending) { update.run(); } } } else { log.info("Timeout waiting for disk cache to close"); } } catch (InterruptedException e) { log.warn("Interrupted waiting for disk cache to shutdown"); } } synchronized (caches) { for (H2CacheImpl<?, ?> cache : caches) { cache.stop(); } } }
Source:
public void testObservableDirectory_dontChangeAnything_ObservableOnlyNotifiedOnce() throws InterruptedException { final File temporaryDirectory = Files.createTempDir(); try (DirectoryWatcherFiles directoryWatcherFiles = new DirectoryWatcherFiles(mockExecutorService, temporaryDirectory, CHECK_INTERVAL)) { Consumer<List<File>> mockConsumer = mock(Consumer.class); directoryWatcherFiles.setOnChange(mockConsumer); Thread.sleep(2 * CHECK_INTERVAL); temporaryDirectory.delete(); verify(mockConsumer, times(1)).accept(any(List.class)); } }

Target:
public void testObservableDirectory_dontChangeAnything_ObservableOnlyNotifiedOnce() throws InterruptedException { final File temporaryDirectory = Files.createTempDir(); try (DirectoryWatcherFiles directoryWatcherFiles = new DirectoryWatcherFiles(mockExecutorService, temporaryDirectory, CHECK_INTERVAL)) { final Consumer<List<File>> mockConsumer = mock(Consumer.class); directoryWatcherFiles.setOnChange(mockConsumer); Thread.sleep(2 * CHECK_INTERVAL); temporaryDirectory.delete(); verify(mockConsumer, times(1)).accept(any(List.class)); } }
Source:
public static IProject[] getProjectsContaining(Repository repository, Collection<String> fileList) throws CoreException { Set<IProject> result = new HashSet<IProject>(); Set<String> handledPaths = new TreeSet<String>(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String member : fileList) { File file = new File(repository.getWorkTree(), member); if (!file.exists()) continue; if (file.isFile()) file = file.getParentFile(); String absPath = file.getAbsolutePath(); if (handledPaths.contains(absPath)) continue; IContainer[] containers = root.findContainersForLocationURI(file .toURI()); for (IContainer container : containers) if (container instanceof IProject) result.add((IProject) container); handledPaths.add(absPath); } return result.toArray(new IProject[result.size()]); }

Target:
public static IProject[] getProjectsContaining(Repository repository, Collection<String> fileList) throws CoreException { Set<IProject> result = new HashSet<IProject>(); Set<String> handledPaths = new TreeSet<String>(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String member : fileList) { File file = new File(repository.getWorkTree(), member); if (!file.exists() || file.isFile()) file = file.getParentFile(); String absPath = file.getAbsolutePath(); if (handledPaths.contains(absPath)) continue; IContainer[] containers = root.findContainersForLocationURI(file .toURI()); for (IContainer container : containers) if (container instanceof IProject) result.add((IProject) container); handledPaths.add(absPath); } return result.toArray(new IProject[result.size()]); }
Source:
public void migrateVM(List<Guid> initialHosts, Guid vmToMigrate) { MigrateVmParameters parameters = new MigrateVmParameters(false, vmToMigrate); parameters.setInitialHosts(new ArrayList<Guid>(initialHosts)); Backend.getInstance().runInternalAction(VdcActionType.MigrateVm, parameters, ExecutionHandler.createInternalJobContext()); }

Target:
public void migrateVM(List<Guid> initialHosts, Guid vmToMigrate) { MigrateVmParameters parameters = new MigrateVmParameters(false, vmToMigrate); parameters.setInitialHosts(new ArrayList<Guid>(initialHosts)); backendInternal.runInternalAction(VdcActionType.MigrateVm, parameters, ExecutionHandler.createInternalJobContext()); }
Source:
protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { final org.kie.workbench.common.stunner.core.graph.Graph graph = getGraph(context); final Collection<RuleViolation> cardinalityRuleViolations = doEvaluate(context, RuleContextBuilder.GraphContexts.cardinality(graph, getCandidate(), CardinalityContext.Operation.ADD)); return new GraphCommandResultBuilder(cardinalityRuleViolations).build(); }

Target:
protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { final Graph graph = getGraph(context); final Collection<RuleViolation> cardinalityRuleViolations = doEvaluate(context, RuleContextBuilder.GraphContexts.cardinality(graph, getCandidate(), CardinalityContext.Operation.ADD)); return new GraphCommandResultBuilder(cardinalityRuleViolations).build(); }
Source:
public void tearDown() throws Exception { TestUtils.deleteProjects(brickClass.getSimpleName()); }

Target:
public void tearDown() throws Exception { Intents.release(); resetFormulaFields(); baseActivityTestRule.finishActivity(); TestUtils.deleteProjects(VisualPlacementBrickTest.class.getSimpleName()); }
Source:
public String getImagePath(DefinitionImageType definitionImageType) { switch (definitionImageType) { case PALETTE_ICON_32X32: return NAME + "_icon32.png"; case SVG_ICON: return null; } return null; }

Target:
public String getImagePath(DefinitionImageType definitionImageType) { switch (definitionImageType) { case PALETTE_ICON_32X32: return NAME + "_icon32.png"; default: return null; } }
Source:
public void journalBootstrapTest() throws StoreException, IOException { if (state.getMaxInMemElements() <= 1) { fail("This test can work only if the max in mem elements config > 1"); } if (state.index.getIndexSegments().lastEntry().getValue().getNumberOfItems() <= 1) { state.addPutEntries(1, PUT_RECORD_SIZE, Utils.Infinite_Time); } assertTrue("There should be more than one element in the last index segment for this test to work", state.index.getIndexSegments().lastEntry().getValue().getNumberOfItems() > 1); state.properties.put("store.index.max.number.of.inmem.elements", "1"); state.reloadIndex(true, false); int entriesInJournal = state.index.journal.getCurrentNumberOfEntries(); assertEquals("Number of entries in the journal should be equal to the number of elements in the last index segment", state.index.getIndexSegments().lastEntry().getValue().getNumberOfItems(), state.index.journal.getCurrentNumberOfEntries()); state.addPutEntries(3, PUT_RECORD_SIZE, Utils.Infinite_Time); assertEquals("Number of entries in the journal should not have changed", entriesInJournal, state.index.journal.getCurrentNumberOfEntries()); state.reloadIndex(true, false); assertEquals("Number of entries in the journal should be exactly 1", 1, state.index.journal.getCurrentNumberOfEntries()); }

Target:
public void journalBootstrapTest() throws StoreException, IOException { if (state.getMaxInMemElements() <= 1) { fail("This test can work only if the max in mem elements config > 1"); } if (state.index.getIndexSegments().lastEntry().getValue().getNumberOfItems() <= 1) { state.addPutEntries(1, PUT_RECORD_SIZE, Utils.Infinite_Time); } assertTrue("There should be more than one element in the last index segment for this test to work", state.index.getIndexSegments().lastEntry().getValue().getNumberOfItems() > 1); state.properties.put("store.index.max.number.of.inmem.elements", "1"); state.reloadIndex(true, false); int entriesInJournal = state.index.journal.getCurrentNumberOfEntries(); assertEquals("Number of entries in the journal should be equal to the number of elements in the last index segment", state.index.getIndexSegments().lastEntry().getValue().getNumberOfItems(), entriesInJournal); state.addPutEntries(1, PUT_RECORD_SIZE, Utils.Infinite_Time); assertEquals("Number of entries in the journal should not have changed", entriesInJournal, state.index.journal.getCurrentNumberOfEntries()); state.reloadIndex(true, false); assertEquals("Number of entries in the journal should be exactly 1", 1, state.index.journal.getCurrentNumberOfEntries()); }
Source:
public static String convertToSimpleDate(String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = DateUtil.convertToDate(date); String formattedDate = dateFormat.format(startDate); return formattedDate; } catch (Exception e) { logger.error(e); return ""; } }

Target:
public static String convertToSimpleDate(String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = DateUtil.convertToDate(date); return dateFormat.format(startDate); } catch (Exception e) { logger.error(e); } return ""; }
Source:
public TupleHashTable(final Schema schema, final int[] keyColumns) { this.keyColumns = keyColumns; data = new MutableTupleBuffer(schema); keyHashCodesToIndices = new IntObjectHashMap<IntArrayList>(); int numIntegers = 0, numLongs = 0, numStrings = 0; for (Type t : schema.getColumnTypes()) { if (t == Type.INT_TYPE || t == Type.FLOAT_TYPE) { numIntegers += 1; } if (t == Type.LONG_TYPE || t == Type.DOUBLE_TYPE) { numLongs += 1; } if (t == Type.STRING_TYPE) { numStrings += 1; } } stats = new HashMap<String, Integer>(); stats.put("numIntegers", numIntegers); stats.put("numLongs", numLongs); stats.put("numStrings", numStrings); stats.put("sumStrings", 0); }

Target:
public TupleHashTable(final Schema schema, final int[] keyColumns) { this.keyColumns = keyColumns; data = new MutableTupleBuffer(schema); keyHashCodesToIndices = new IntObjectHashMap<IntArrayList>(); int num32BitTypes = 0, num64BitTypes = 0, numStrings = 0; for (Type t : schema.getColumnTypes()) { if (t == Type.INT_TYPE || t == Type.FLOAT_TYPE) { num32BitTypes += 1; } if (t == Type.LONG_TYPE || t == Type.DOUBLE_TYPE) { num64BitTypes += 1; } if (t == Type.STRING_TYPE) { numStrings += 1; } } stats = new HashMap<String, Integer>(); stats.put("num32BitTypes", num32BitTypes); stats.put("num64BitTypes", num64BitTypes); stats.put("numStrings", numStrings); stats.put("sumStrings", 0); }
Source:
private void raiseViolationOnMissingAriaLabel(List<TagNode> nodes) { List<TagNode> matches = nodes.stream().filter(node -> !hasAriaLabel(node)).collect(Collectors.toList()); raiseViolationOnSize(matches); }

Target:
private void raiseViolationOnMissingAriaLabel(List<TagNode> nodes) { if (nodes.size() > 1) { nodes.stream().filter(node -> !hasAriaLabel(node)).forEach(node -> createViolation(node.getStartLinePosition(), "Add an \"aria-label\" or \"aria-labbelledby\" attribute to this element.")); } }
Source:
public abstract long maxUpdateIndex() throws IOException; public abstract RefCursor allRefs() throws IOException; public abstract RefCursor seekRef(String refName) throws IOException; public abstract RefCursor seekRefsWithPrefix(String prefix) throws IOException; public abstract RefCursor byObjectId(AnyObjectId id) throws IOException; abstract public boolean hasObjectMap() throws IOException; public abstract LogCursor allLogs() throws IOException; public LogCursor seekLog(String refName) throws IOException { return seekLog(refName, Long.MAX_VALUE); }

Target:
public abstract long maxUpdateIndex() throws IOException; public abstract RefCursor allRefs() throws IOException; public abstract RefCursor seekRef(String refName) throws IOException; public abstract RefCursor seekRefsWithPrefix(String prefix) throws IOException; public abstract RefCursor byObjectId(AnyObjectId id) throws IOException; public abstract boolean hasObjectMap() throws IOException; public abstract LogCursor allLogs() throws IOException; public LogCursor seekLog(String refName) throws IOException { return seekLog(refName, Long.MAX_VALUE); }
Source:
public void dispose() { this.jmxRegistration.unregisterMBean(MBEAN_NAME); for (MentionsConsumer consumer : this.consumers) { consumer.halt(); this.queue.add(new MentionsData().stop()); } }

Target:
public void dispose() { this.jmxRegistration.unregisterMBean(MBEAN_NAME); for (MentionsConsumer consumer : this.consumers) { consumer.halt(); this.queue.add(MentionsData.STOP); } }
Source:
public HTMLPanel getSizeWidget(ChangeInfo c) { int largeChangeSize = Gerrit.getConfig().getLargeChangeSize(); int changedLines = c.insertions() + c.deletions(); int p = 100; if (changedLines < largeChangeSize) { p = Math.round(changedLines * 100 / largeChangeSize); } int width = Math.max(2, 70 * p / 100); int red = p > 50 ? 255 : (int) Math.round((p) * 5.12); int green = p < 50 ? 255 : (int) Math.round(256 - (p - 50) * 5.12); SafeHtmlBuilder sb = new SafeHtmlBuilder(); sb.openDiv() .setStyleName(Gerrit.RESOURCES.css().changeSize()) .setAttribute("style", "width:" + width + "px; " + "background-color: #" + toHex(red) + toHex(green) + "00;") .closeDiv(); HTMLPanel panel = new HTMLPanel(sb); panel.setTitle(Util.M.insertionsAndDeletions(c.insertions(), c.deletions())); return panel; }

Target:
private static Widget getSizeWidget(ChangeInfo c) { int largeChangeSize = Gerrit.getConfig().getLargeChangeSize(); int changedLines = c.insertions() + c.deletions(); int p = 100; if (changedLines < largeChangeSize) { p = Math.round(changedLines * 100 / largeChangeSize); } int width = Math.max(2, 70 * p / 100); int red = p > 50 ? 255 : (int) Math.round((p) * 5.12); int green = p < 50 ? 255 : (int) Math.round(256 - (p - 50) * 5.12); String bg = "#" + toHex(red) + toHex(green) + "00"; SimplePanel panel = new SimplePanel(); panel.setStyleName(Gerrit.RESOURCES.css().changeSize()); panel.setWidth(width + "px"); panel.getElement().getStyle().setBackgroundColor(bg); panel.setTitle(Util.M.insertionsAndDeletions(c.insertions(), c.deletions())); return panel; }
Source:
public Map<List<Object>, Integer> processMessage(Message<?> message) { if (this.routingSlip == null) { synchronized (this) { if (this.routingSlip == null) { List<Object> routingSlipValues = new ArrayList<Object>(this.routingSlipPath.size()); for (String path : this.routingSlipPath) { if (this.beanFactory.containsBean(path)) { Object bean = this.beanFactory.getBean(path); Assert.state(bean instanceof MessageChannel || bean instanceof RoutingSlipRouteStrategy, "The RotingSlip can contain only bean names of MessageChannel or " + "RoutingSlipRouteStrategy: " + bean); routingSlipValues.add(path); } else { ExpressionEvaluationRoutingSlipRouteStrategy strategy = new ExpressionEvaluationRoutingSlipRouteStrategy(path); strategy.setIntegrationEvaluationContext(this.evaluationContext); routingSlipValues.add(strategy); } } this.routingSlip = Collections.singletonMap(Collections.unmodifiableList(routingSlipValues), 0); } } } return this.routingSlip; }

Target:
public Map<List<Object>, Integer> processMessage(Message<?> message) { if (this.routingSlip == null) { synchronized (this) { if (this.routingSlip == null) { List<Object> routingSlipValues = new ArrayList<Object>(this.routingSlipPath.size()); for (String path : this.routingSlipPath) { if (this.beanFactory.containsBean(path)) { Object bean = this.beanFactory.getBean(path); Assert.state(bean instanceof MessageChannel || bean instanceof RoutingSlipRouteStrategy, "The RoutingSlip can contain only bean names of MessageChannel or " + "RoutingSlipRouteStrategy: " + bean); routingSlipValues.add(path); } else { ExpressionEvaluationRoutingSlipRouteStrategy strategy = new ExpressionEvaluationRoutingSlipRouteStrategy(path); strategy.setIntegrationEvaluationContext(this.evaluationContext); routingSlipValues.add(strategy); } } this.routingSlip = Collections.singletonMap(Collections.unmodifiableList(routingSlipValues), 0); } } } return this.routingSlip; }
Source:
public static int searchResultCount(Context context, String query) throws SQLException { String dbquery = "%"+query.toLowerCase()+"%"; Long count; Integer int_param; try { int_param = Integer.valueOf(query); } catch (NumberFormatException e) { int_param = Integer.valueOf(-1); } TableRow row = DatabaseManager.querySingle(context, "SELECT count(*) as epcount FROM eperson " + "WHERE eperson_id = ? OR " + "LOWER((select text_value from metadatavalue where resource_id=? and resource_type_id=? and metadata_field_id=?)) LIKE LOWER(?) " + "OR LOWER((select text_value from metadatavalue where resource_id=? and resource_type_id=? and metadata_field_id=?)) LIKE LOWER(?) " + "OR LOWER(eperson.email) LIKE LOWER(?)", new Object[] { int_param, int_param, Constants.EPERSON, MetadataField.findByElement(context, MetadataSchema.find(context, "eperson").getSchemaID(), "firstname", null).getFieldID(), dbquery, int_param, Constants.EPERSON, MetadataField.findByElement(context, MetadataSchema.find(context, "eperson").getSchemaID(), "lastname", null).getFieldID(), dbquery, dbquery }); if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { count = Long.valueOf(row.getIntColumn("epcount")); } else { count = Long.valueOf(row.getLongColumn("epcount")); } return count.intValue(); }

Target:
public static int searchResultCount(Context context, String query) throws SQLException { String dbquery = "%"+query.toLowerCase()+"%"; Long count; Integer int_param; try { int_param = Integer.valueOf(query); } catch (NumberFormatException e) { int_param = Integer.valueOf(-1); } TableRow row = DatabaseManager.querySingle(context, "SELECT count(*) as epcount FROM eperson " + "WHERE eperson_id = ? OR " + "LOWER((select text_value from metadatavalue where resource_id=? and resource_type_id=? and metadata_field_id=?)) LIKE LOWER(?) " + "OR LOWER((select text_value from metadatavalue where resource_id=? and resource_type_id=? and metadata_field_id=?)) LIKE LOWER(?) " + "OR LOWER(eperson.email) LIKE LOWER(?)", new Object[] { int_param, int_param, Constants.EPERSON, MetadataField.findByElement(context, MetadataSchema.find(context, "eperson").getSchemaID(), "firstname", null).getFieldID(), dbquery, int_param, Constants.EPERSON, MetadataField.findByElement(context, MetadataSchema.find(context, "eperson").getSchemaID(), "lastname", null).getFieldID(), dbquery, dbquery }); if (DatabaseManager.isOracle()) { count = Long.valueOf(row.getIntColumn("epcount")); } else { count = Long.valueOf(row.getLongColumn("epcount")); } return count.intValue(); }
Source:
public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { ObjectHelper.notNull(endpoint, "endpoint"); if (endpoint.isAutoCreate() && !endpoint.getFile().exists()) { LOG.trace("Building starting directory: {}", endpoint.getFile()); buildDirectory(endpoint.getFile(), endpoint.getDirectoryPermissions(), absolute); } if (ObjectHelper.isEmpty(directory)) { return true; } File endpointPath = endpoint.getFile(); File target = new File(directory); boolean isPath = Math.max(directory.lastIndexOf("/"), directory.lastIndexOf("\\")) != -1; File path; if (absolute) { path = target; } else if (endpointPath.equals(target)) { path = endpointPath; } else if (isPath) { String afterRoot = StringHelper.after(directory, endpointPath.getPath() + File.separator); if (ObjectHelper.isNotEmpty(afterRoot)) { path = new File(endpoint.getFile(), afterRoot); } else { path = new File(directory); } } else { path = new File(endpoint.getFile(), directory); } synchronized (this) { if (path.isDirectory() && path.exists()) { return true; } else { LOG.trace("Building directory: {}", path); return buildDirectory(path, endpoint.getDirectoryPermissions(), absolute); } } }

Target:
public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { ObjectHelper.notNull(endpoint, "endpoint"); if (endpoint.isAutoCreate() && !endpoint.getFile().exists()) { LOG.trace("Building starting directory: {}", endpoint.getFile()); buildDirectory(endpoint.getFile(), endpoint.getDirectoryPermissions(), absolute); } if (ObjectHelper.isEmpty(directory)) { return true; } File endpointPath = endpoint.getFile(); File target = new File(directory); boolean isPath = directory.contains("/") || directory.contains("\\"); File path; if (absolute) { path = target; } else if (endpointPath.equals(target)) { path = endpointPath; } else if (isPath) { String afterRoot = StringHelper.after(directory, endpointPath.getPath() + File.separator); if (ObjectHelper.isNotEmpty(afterRoot)) { path = new File(endpoint.getFile(), afterRoot); } else { path = new File(directory); } } else { path = new File(endpoint.getFile(), directory); } synchronized (this) { if (path.isDirectory() && path.exists()) { return true; } else { LOG.trace("Building directory: {}", path); return buildDirectory(path, endpoint.getDirectoryPermissions(), absolute); } } }
Source:
public static int toCoapCode(int lwm2mCode) { int codeClass = lwm2mCode / 100; int codeDetail = lwm2mCode % 100; if (codeClass > 7 || codeDetail > 31) throw new IllegalArgumentException("Could not be translate in a valid CoAP code"); return codeClass << 5 | codeDetail; }

Target:
public static int toCoapCode(int lwm2mCode) { int codeClass = lwm2mCode / 100; int codeDetail = lwm2mCode % 100; if (codeClass > 7 || codeDetail > 31) throw new IllegalArgumentException("Could not be translated into a valid COAP code"); return codeClass << 5 | codeDetail; }
Source:
public Slice regexpReplace( @SqlType("varchar") Slice source, @SqlType(Re2JRegexpType.NAME) Re2JRegexp pattern, @SqlType("function(array(varchar), varchar(x))") UnaryFunctionInterface replaceFunction) { if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); Matcher matcher = pattern.re2jPattern.matcher(source); SliceOutput output = new DynamicSliceOutput(source.length()); int groupCount = matcher.groupCount(); int appendPos = 0; while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (appendPos < start) { output.writeBytes(source, appendPos, start - appendPos); } appendPos = end; for (int i = 1; i <= groupCount; i++) { Slice matchedGroupSlice = matcher.group(i); if (matchedGroupSlice != null) { VARCHAR.writeSlice(blockBuilder, matchedGroupSlice, 0, matchedGroupSlice.length()); } else { blockBuilder.appendNull(); } } pageBuilder.declarePositions(groupCount); Block target = blockBuilder.getRegion(blockBuilder.getPositionCount() - groupCount, groupCount); Slice replaced = (Slice) replaceFunction.apply(target); if (replaced == null) { return null; } output.appendBytes(replaced); } output.writeBytes(source, appendPos, source.length() - appendPos); return output.slice(); }

Target:
public Slice regexpReplace( @SqlType("varchar") Slice source, @SqlType(Re2JRegexpType.NAME) Re2JRegexp pattern, @SqlType("function(array(varchar), varchar(x))") UnaryFunctionInterface replaceFunction) { Matcher matcher = pattern.re2jPattern.matcher(source); if (!matcher.find()) { return source; } SliceOutput output = new DynamicSliceOutput(source.length()); if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0); int groupCount = matcher.groupCount(); int appendPosition = 0; do { int start = matcher.start(); int end = matcher.end(); if (appendPosition < start) { output.writeBytes(source, appendPosition, start - appendPosition); } appendPosition = end; for (int i = 1; i <= groupCount; i++) { Slice matchedGroupSlice = matcher.group(i); if (matchedGroupSlice != null) { VARCHAR.writeSlice(blockBuilder, matchedGroupSlice); } else { blockBuilder.appendNull(); } } pageBuilder.declarePositions(groupCount); Block target = blockBuilder.getRegion(blockBuilder.getPositionCount() - groupCount, groupCount); Slice replaced = (Slice) replaceFunction.apply(target); if (replaced == null) { return null; } output.appendBytes(replaced); } while (matcher.find()); output.writeBytes(source, appendPosition, source.length() - appendPosition); return output.slice(); }
Source:
private AuthenticationProvider getAuthenticationProvider(OAuth2Authentication oauth2User) { if (oauth2User.getName().startsWith("S-")) { return AuthenticationProvider.BOSCH; } return AuthenticationProvider.GITHUB; }

Target:
private String getAuthenticationProvider(OAuth2Authentication oauth2User) { if (oauth2User.getName().startsWith("S-")) { return AuthenticationProvider.BOSCH.name(); } return AuthenticationProvider.GITHUB.name(); }
Source:
public void setTimerServiceProvider(InternalTimeServiceManager.Provider timerServiceProvider) { this.timerServiceProvider = timerServiceProvider; }

Target:
public void setTimerServiceProvider(InternalTimeServiceManager.Provider timerServiceProvider) { this.timerServiceProvider = checkNotNull(timerServiceProvider); }
Source:
public Iterable<DocumentRevsList> bulkReadDocsWithOpenRevisions(List<BulkGetRequest> request, boolean pullAttachmentsInline) { Map<String, Object> options = new HashMap<String, Object>(); options.put("revs", true); if (pullAttachmentsInline) { options.put("attachments", true); } else { options.put("attachments", false); options.put("att_encoding_info", true); } URI bulkGet = this.uriHelper.documentUri("_bulk_get", options); HttpConnection connection = Http.POST(bulkGet, "application/json"); Map<String, List<BulkGetRequest>> jsonRequest = new HashMap<String, List<BulkGetRequest>>(); jsonRequest.put("docs", request); connection.setRequestBody(jsonHelper.toJson(jsonRequest)); BulkGetResponse response = executeToJsonObjectWithRetry(connection, BulkGetResponse.class); Map<String,ArrayList<DocumentRevs>> revsMap = new HashMap<String,ArrayList<DocumentRevs>>(); for (BulkGetResponse.Result result : response.results) { for (BulkGetResponse.Doc doc : result.docs) { if (doc.ok != null){ String id = doc.ok.getId(); if (!revsMap.containsKey(id)) { revsMap.put(id, new ArrayList<DocumentRevs>()); } revsMap.get(id).add(doc.ok); } else { @SuppressWarnings("unchecked") String id = (String)doc.error.get("id"); DocumentRevs revs = new DocumentRevs(); revs.setId(id); revs.setRev((String)doc.error.get("rev")); if (!revsMap.containsKey(id)) { revsMap.put(id, new ArrayList<DocumentRevs>()); } revsMap.get(id).add(revs); } } } List<DocumentRevsList> allRevs = new ArrayList<DocumentRevsList>(); for (ArrayList<DocumentRevs> value : revsMap.values()) { allRevs.add(new DocumentRevsList(value)); } return allRevs; }

Target:
public Iterable<DocumentRevsList> bulkReadDocsWithOpenRevisions(List<BulkGetRequest> request, boolean pullAttachmentsInline) { Map<String, Object> options = new HashMap<String, Object>(); options.put("revs", true); if (pullAttachmentsInline) { options.put("attachments", true); } else { options.put("attachments", false); options.put("att_encoding_info", true); } URI bulkGet = this.uriHelper.documentUri("_bulk_get", options); HttpConnection connection = Http.POST(bulkGet, "application/json"); Map<String, List<BulkGetRequest>> jsonRequest = new HashMap<String, List<BulkGetRequest>>(); jsonRequest.put("docs", request); connection.setRequestBody(jsonHelper.toJson(jsonRequest)); BulkGetResponse response = executeToJsonObjectWithRetry(connection, BulkGetResponse.class); Map<String,ArrayList<DocumentRevs>> revsMap = new HashMap<String,ArrayList<DocumentRevs>>(); for (BulkGetResponse.Result result : response.results) { for (BulkGetResponse.Doc doc : result.docs) { if (doc.ok != null) { String id = doc.ok.getId(); if (!revsMap.containsKey(id)) { revsMap.put(id, new ArrayList<DocumentRevs>()); } revsMap.get(id).add(doc.ok); } } } List<DocumentRevsList> allRevs = new ArrayList<DocumentRevsList>(); for (ArrayList<DocumentRevs> value : revsMap.values()) { allRevs.add(new DocumentRevsList(value)); } return allRevs; }