auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String getCountryName(String countryCode) { try { Locale l = new Locale("", countryCode); String displayCountry = l.getDisplayCountry(); return displayCountry.equals(countryCode) ? "Unknown" : displayCountry; } catch (NullPointerException e) { return "Unknown"; } }

Target:
public static String getCountryName(String countryCode) { if (countryCode == null){ countryCode = ""; } Locale l = new Locale("", countryCode); String displayCountry = l.getDisplayCountry(); return displayCountry.equals(countryCode) ? UNKNOWN_VALUE : displayCountry; }
Source:
private void setWikidataEditCount() { String userName = sessionManager.getUserName(); if (StringUtils.isBlank(userName)) { return; } compositeDisposable.add(okHttpJsonApiClient .getWikidataEdits(userName) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(edits -> { numberOfEdits += edits; wikidataEditsText.setText(String.valueOf(edits)); }, e -> { Timber.e("Error:" + e); })); }

Target:
private void setWikidataEditCount() { String userName = sessionManager.getUserName(); if (StringUtils.isBlank(userName)) { return; } compositeDisposable.add(okHttpJsonApiClient .getWikidataEdits(userName) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(edits -> { numberOfEdits = edits; wikidataEditsText.setText(String.valueOf(edits)); }, e -> { Timber.e("Error:" + e); })); }
Source:
public void accept(FrameworkMember member, TestRule value) { ClassRule rule = member.getAnnotation(ClassRule.class); if (rule != null) { RuleContainer.recordRuleOrder(value, rule.order()); } result.add(value); }

Target:
public void accept(FrameworkMember member, TestRule value) { ClassRule rule = member.getAnnotation(ClassRule.class); entries.add(new RuleContainer.RuleEntry(value, RuleContainer.RuleEntry.TYPE_TEST_RULE, rule != null ? rule.order() : null)); }
Source:
public VoltTable[] run(SystemProcedureExecutionContext ctx, String selector) throws VoltAbortException { VoltTable[] results; if (selector.toUpperCase().equals("OVERVIEW")) { results = getOverviewInfo(); } else if (selector.toUpperCase().equals("DEPLOYMENT")) { results = getDeploymentInfo(); } else if (selector.toUpperCase().equals("LICENSE")) { results = getLicenseInfo(); } else { throw new VoltAbortException(String.format("Invalid @SystemInformation selector %s.", selector)); } return results; }

Target:
public VoltTable[] run(SystemProcedureExecutionContext ctx, String selector) throws VoltAbortException { VoltTable[] results; if ("OVERVIEW".equalsIgnoreCase(selector.toString())) { results = getOverviewInfo(); } else if ("DEPLOYMENT".equalsIgnoreCase(selector.toString())) { results = getDeploymentInfo(); } else if ("LICENSE".equalsIgnoreCase(selector.toString())) { results = getLicenseInfo(); } else { throw new VoltAbortException(String.format("Invalid @SystemInformation selector %s.", selector)); } return results; }
Source:
public Resolution findMethod(Env env, String name, List<JavaType> argTypes, List<JavaType> typeParamTypes) { Resolution bestSoFar = unresolved(); Env env1 = env; while (env1.outer != null) { Resolution res = findMethod(env1, env1.enclosingClass.getType(), env1.enclosingClass.getType(), name, argTypes, typeParamTypes); if (res.symbol.kind < JavaSymbol.ERRONEOUS) { return res; } else if (res.symbol.kind < bestSoFar.symbol.kind) { bestSoFar = res; } env1 = env1.outer; } JavaSymbol sym = findInStaticImport(env, name, JavaSymbol.MTH); if (sym.kind < JavaSymbol.ERRONEOUS) { return Resolution.resolution(sym); } else if (sym.kind < bestSoFar.symbol.kind) { bestSoFar = Resolution.resolution(sym); } return bestSoFar; }

Target:
public Resolution findMethod(Env env, String name, List<JavaType> argTypes, List<JavaType> typeParamTypes) { Resolution bestSoFar = unresolved(); Env env1 = env; while (env1.outer != null) { Resolution res = findMethod(env1, env1.enclosingClass.getType(), name, argTypes, typeParamTypes); if (res.symbol.kind < JavaSymbol.ERRONEOUS) { return res; } else if (res.symbol.kind < bestSoFar.symbol.kind) { bestSoFar = res; } env1 = env1.outer; } JavaSymbol sym = findInStaticImport(env, name, JavaSymbol.MTH); if (sym.kind < JavaSymbol.ERRONEOUS) { return Resolution.resolution(sym); } else if (sym.kind < bestSoFar.symbol.kind) { bestSoFar = Resolution.resolution(sym); } return bestSoFar; }
Source:
private static void saveCoverageFromLcovFiles(SensorContext context, List<File> lcovFiles) { LOG.info("Analysing {}", lcovFiles); FileSystem fileSystem = context.fileSystem(); FilePredicate mainFilePredicate = fileSystem.predicates().and( fileSystem.predicates().hasType(Type.MAIN), fileSystem.predicates().hasLanguages(JavaScriptLanguage.KEY, TypeScriptLanguage.KEY)); FileLocator fileLocator = new FileLocator(fileSystem.inputFiles(mainFilePredicate)); LCOVParser parser = LCOVParser.create(context, lcovFiles, fileLocator); Map<InputFile, NewCoverage> coveredFiles = parser.coverageByFile(); for (InputFile inputFile : fileSystem.inputFiles(mainFilePredicate)) { NewCoverage fileCoverage = coveredFiles.get(inputFile); if (fileCoverage != null) { fileCoverage.save(); } } List<String> unresolvedPaths = parser.unresolvedPaths(); if (!unresolvedPaths.isEmpty()) { LOG.warn(String.format("Could not resolve %d file paths in %s", unresolvedPaths.size(), lcovFiles)); if (LOG.isDebugEnabled()) { LOG.debug("Unresolved paths:\n" + String.join("\n", unresolvedPaths)); } else { LOG.warn("First unresolved path: " + unresolvedPaths.get(0)); } } int inconsistenciesNumber = parser.inconsistenciesNumber(); if (inconsistenciesNumber > 0) { LOG.warn("Found inconsistencies in coverage report. Re-run analyse in debug mode to see details.", inconsistenciesNumber); } }

Target:
private static void saveCoverageFromLcovFiles(SensorContext context, List<File> lcovFiles) { LOG.info("Analysing {}", lcovFiles); FileSystem fileSystem = context.fileSystem(); FilePredicate mainFilePredicate = fileSystem.predicates().and( fileSystem.predicates().hasType(Type.MAIN), fileSystem.predicates().hasLanguages(JavaScriptLanguage.KEY, TypeScriptLanguage.KEY)); FileLocator fileLocator = new FileLocator(fileSystem.inputFiles(mainFilePredicate)); LCOVParser parser = LCOVParser.create(context, lcovFiles, fileLocator); Map<InputFile, NewCoverage> coveredFiles = parser.coverageByFile(); for (InputFile inputFile : fileSystem.inputFiles(mainFilePredicate)) { NewCoverage fileCoverage = coveredFiles.get(inputFile); if (fileCoverage != null) { fileCoverage.save(); } } List<String> unresolvedPaths = parser.unresolvedPaths(); if (!unresolvedPaths.isEmpty()) { LOG.warn(String.format("Could not resolve %d file paths in %s", unresolvedPaths.size(), lcovFiles)); if (LOG.isDebugEnabled()) { LOG.debug("Unresolved paths:\n" + String.join("\n", unresolvedPaths)); } else { LOG.warn("First unresolved path: " + unresolvedPaths.get(0) + " (Run in DEBUG mode to get full list of unresolved paths)"); } } int inconsistenciesNumber = parser.inconsistenciesNumber(); if (inconsistenciesNumber > 0) { LOG.warn("Found inconsistencies in coverage report. Re-run analyse in debug mode to see details.", inconsistenciesNumber); } }
Source:
public void updateListFragment(List<Place> placeList) { adapterFactory.updateAdapterData(placeList, (RVRendererAdapter<Place>) rvNearbyList.getAdapter()); if (placeList.size() <= 0) { noResultsView.setVisibility(View.VISIBLE); } else { noResultsView.setVisibility(View.GONE); } }

Target:
public void updateListFragment(List<Place> placeList) { adapterFactory.updateAdapterData(placeList, (RVRendererAdapter<Place>) rvNearbyList.getAdapter()); noResultsView.setVisibility(placeList.size() <= 0 ? View.VISIBLE : View.GONE); }
Source:
private void updateCounterOrMeter(Iterable<MetricResult<Long>> counters) { for (MetricResult<Long> metricResult : counters) { if (!isUserMetric(metricResult)) { continue; } String flinkMetricIdentifier = getFlinkMetricIdentifierString(metricResult.getKey()); ArrayList<String> scopeComponents = getNameSpaceArray(metricResult.getKey()); if ((scopeComponents.size() % 2) != 0) { Meter meter; if (flinkMeterCache.containsKey(flinkMetricIdentifier)) { meter = flinkMeterCache.get(flinkMetricIdentifier); } else { int timeSpanInSeconds = Integer.valueOf(scopeComponents.get(scopeComponents.size() - 1)); MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); meter = metricGroup.meter( metricResult.getKey().metricName().getName(), new MeterView(timeSpanInSeconds)); flinkMeterCache.put(flinkMetricIdentifier, meter); } Long update = metricResult.getAttempted(); meter.markEvent(update); } else { Counter counter; if (flinkCounterCache.containsKey(flinkMetricIdentifier)) { counter = flinkCounterCache.get(flinkMetricIdentifier); } else { MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); counter = metricGroup.counter(metricResult.getKey().metricName().getName()); flinkCounterCache.put(flinkMetricIdentifier, counter); } Long update = metricResult.getAttempted(); counter.inc(update - counter.getCount()); } } }

Target:
private void updateCounterOrMeter(Iterable<MetricResult<Long>> counters) { for (MetricResult<Long> metricResult : counters) { if (!isUserMetric(metricResult)) { continue; } String flinkMetricIdentifier = getFlinkMetricIdentifierString(metricResult.getKey()); ArrayList<String> scopeComponents = getNameSpaceArray(metricResult.getKey()); if ((scopeComponents.size() % 2) != 0) { Meter meter = flinkMeterCache.get(flinkMetricIdentifier); if (null == meter) { int timeSpanInSeconds = Integer.parseInt(scopeComponents.get(scopeComponents.size() - 1)); MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); meter = metricGroup.meter( metricResult.getKey().metricName().getName(), new MeterView(timeSpanInSeconds)); flinkMeterCache.put(flinkMetricIdentifier, meter); } Long update = metricResult.getAttempted(); meter.markEvent(update); } else { Counter counter = flinkCounterCache.get(flinkMetricIdentifier); if (null == counter) { MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); counter = metricGroup.counter(metricResult.getKey().metricName().getName()); flinkCounterCache.put(flinkMetricIdentifier, counter); } Long update = metricResult.getAttempted(); counter.inc(update - counter.getCount()); } } }
Source:
private KafkaConsumer<byte[], byte[]> getKafkaConsumer() { final Properties props = new Properties(); props.setProperty("metadata.max.age.ms", "10000"); props.setProperty("group.id", StringUtils.format("kafka-supervisor-%s", getRandomId())); props.setProperty("max.poll.records", "1"); KafkaIndexTask.addConsumerPropertiesFromConfig(props, sortingMapper, consumerProperties); props.setProperty("enable.auto.commit", "false"); ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); return new KafkaConsumer<>(props, new ByteArrayDeserializer(), new ByteArrayDeserializer()); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }

Target:
private KafkaConsumer<byte[], byte[]> getKafkaConsumer() { final Properties props = new Properties(); props.setProperty("metadata.max.age.ms", "10000"); props.setProperty("group.id", StringUtils.format("kafka-supervisor-%s", RandomIdUtils.getRandomId())); addConsumerPropertiesFromConfig(props, sortingMapper, consumerProperties); props.setProperty("enable.auto.commit", "false"); ClassLoader currCtxCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); return new KafkaConsumer<>(props, new ByteArrayDeserializer(), new ByteArrayDeserializer()); } finally { Thread.currentThread().setContextClassLoader(currCtxCl); } }
Source:
public RepositoryIndexer addRepositoryIndexer(String contextId, RepositoryIndexer value) { logger.debug( "RepositoryIndexManager = [{}]. Adding repository indexer. ContextId = [{}], RepositoryIndexer = [{}]", this, contextId, value); return indexes.put(contextId, value); }

Target:
public RepositoryIndexer addRepositoryIndexer(String contextId, RepositoryIndexer value) { return indexes.put(contextId, value); }
Source:
public void testScalabilityDialogNotDismissedInadvertently() throws Exception { String file= "/ceditor/src/large_main.cpp"; fCProject= EditorTestHelper.createCProject("ceditor", "resources/ceditor", false, false); IWorkbenchWindow window = EditorTestHelper.getActiveWorkbenchWindow(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(window.getShell()); dialog.open(); setUpEditor(file); dialog.close(); boolean scalabilityDialogFound = false; Shell[] shells = Display.getCurrent().getShells(); for (Shell shell : shells) { scalabilityDialogFound |= shell.getText().equals(CEditorMessages.Scalability_info); } assertTrue(scalabilityDialogFound); EditorTestHelper.closeEditor(fEditor); }

Target:
public void testScalabilityDialogNotDismissedInadvertently() throws Exception { fCProject= EditorTestHelper.createCProject("ceditor", "resources/ceditor", false, false); String originalFile = "/ceditor/src/main.cpp"; String file= "/ceditor/src/large_main.cpp"; ResourceTestHelper.copy(originalFile, file); setUpEditor(file); StringBuilder buffer = new StringBuilder(fDocument.get()); buffer.append("unsigned long c[250000] = {\n"); for (int i = 0; i < 12499; i++) buffer.append(" 0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,\n"); buffer.append(" 0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1,0x0,0x1\n};\n"); fDocument.set(buffer.toString()); fEditor.doSave(new NullProgressMonitor()); EditorTestHelper.closeEditor(fEditor); IWorkbenchWindow window = EditorTestHelper.getActiveWorkbenchWindow(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(window.getShell()); dialog.open(); setUpEditor(file); dialog.close(); Shell scalabilityDialog = null; Shell[] shells = Display.getCurrent().getShells(); for (Shell shell : shells) { if (shell.getText().equals(CEditorMessages.Scalability_info)) { scalabilityDialog = shell; break; } } assertNotNull(scalabilityDialog); scalabilityDialog.close(); EditorTestHelper.closeEditor(fEditor); }
Source:
private static String typedNull(String prestoType) { return format("CAST(null AS %s)", prestoType); }

Target:
private static String typedNull(String prestoType) { return format("CAST(NULL AS %s)", prestoType); }
Source:
public InputStream writeObject(final VelocityResourceKey key) throws DotStateException, DotDataException, DotSecurityException { long language = new Long(key.language); ContentletVersionInfo info = APILocator.getVersionableAPI().getContentletVersionInfo(key.id1, language); if ((info == null || key.mode.showLive && info.getLiveInode() == null) && language != defaultLang && APILocator.getLanguageAPI().canDefaultContentToDefaultLanguage()) { info = APILocator.getVersionableAPI().getContentletVersionInfo(key.id1, defaultLang); } if (info == null || key.mode.showLive && info.getLiveInode() == null) { throw new ResourceNotFoundException("cannot find content for: " + key); } Contentlet contentlet = (key.mode.showLive) ? APILocator.getContentletAPI().find(info.getLiveInode(), APILocator.systemUser(), false) : APILocator.getContentletAPI().find(info.getWorkingInode(), APILocator.systemUser(), false); Logger.debug(this, "DotResourceLoader:\tWriting out contentlet inode = " + contentlet.getInode()); if (null == contentlet) { throw new ResourceNotFoundException("cannot find content for: " + key); } return buildVelocity(contentlet, key.mode, key.path); }

Target:
public InputStream writeObject(final VelocityResourceKey key) throws DotStateException, DotDataException, DotSecurityException { long language = new Long(key.language); ContentletVersionInfo info = APILocator.getVersionableAPI().getContentletVersionInfo(key.id1, language); if (!isLiveVersionAvailable(key, info) && language != defaultLang && APILocator.getLanguageAPI().canDefaultContentToDefaultLanguage()) { info = APILocator.getVersionableAPI().getContentletVersionInfo(key.id1, defaultLang); } if (!isLiveVersionAvailable(key, info)) { throw new ResourceNotFoundException("cannot find content for: " + key); } Contentlet contentlet = (key.mode.showLive) ? APILocator.getContentletAPI().find(info.getLiveInode(), APILocator.systemUser(), false) : APILocator.getContentletAPI().find(info.getWorkingInode(), APILocator.systemUser(), false); Logger.debug(this, "DotResourceLoader:\tWriting out contentlet inode = " + contentlet.getInode()); if (null == contentlet) { throw new ResourceNotFoundException("cannot find content for: " + key); } return buildVelocity(contentlet, key.mode, key.path); }
Source:
public void testConvertsPcOdToBrandIosUri() { map.put("dc:relation.programmeId", "338672-002"); Assert.assertThat( C4AtomApi.iOsUriFromPcUri("<LINK_0>", map), is("all4://views/brands?brand=come-dine-with-me&programme=338672-002")); }

Target:
public void testConvertsPcOdToBrandIosUri() { map.put("dc:relation.programmeId", "338672-002"); assertThat( C4AtomApi.iOsUriFromPcUri("<LINK_0>", map), is("all4://views/brands?brand=come-dine-with-me&programme=338672-002")); }
Source:
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { StackEntry oldEntry = peek(); if (oldEntry != null) { oldEntry.blank = false; if (oldEntry.isPWrapper) { if (!isOnlyInline(localName)) { ByteArrayOutputStream contents = popAndGetContents(); writePWrapper(oldEntry, contents); oldEntry = peek(); } } } if (oldEntry != null && oldEntry.needsPWrapping && isOnlyInline(localName)) { pushPWrapper(); } push(uri, localName, qName, atts); }

Target:
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { StackEntry oldEntry = peek(); if (oldEntry != null) { oldEntry.blank = false; if (oldEntry.isPWrapper && !isOnlyInline(localName)) { ByteArrayOutputStream contents = popAndGetContents(); writePWrapper(oldEntry, contents); oldEntry = peek(); } } if (oldEntry != null && oldEntry.needsPWrapping && isOnlyInline(localName)) { pushPWrapper(); } push(uri, localName, qName, atts); }
Source:
public void dispose() { super.dispose(); DockerConnectionManager.getInstance().removeConnectionManagerListener(this); ((EnvironmentVariablesPageModel)envModel).dispose(); connection = null; project = null; dockerConnection = null; projects.clear(); volumes.clear(); portSpecs.clear(); if(imagePorts != null) { imagePorts.clear(); } }

Target:
public void dispose() { super.dispose(); DockerConnectionManager.getInstance().removeConnectionManagerListener(this); ((EnvironmentVariablesPageModel)envModel).dispose(); connection = null; project = null; dockerConnection = null; projects.clear(); volumes.clear(); portSpecs.clear(); if(imagePorts != null) { imagePorts.clear(); imagePorts = null; } }
Source:
private ByteArrayOutputStream getZipEntryContent( ZipInputStream zipStream, ZipEntry entry ) throws IOException { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] bytes = new byte[(int) entry.getSize()]; int read; while ((read = zipStream.read(bytes, 0, bytes.length)) != -1) { content.write(bytes, 0, read); } content.flush(); return content; }

Target:
private ByteArrayOutputStream getZipEntryContent( ZipInputStream zipStream, ZipEntry entry ) throws IOException { try (ByteArrayOutputStream content = new ByteArrayOutputStream()) { byte[] bytes = new byte[(int) entry.getSize()]; int read; while ((read = zipStream.read(bytes, 0, bytes.length)) != -1) { content.write(bytes, 0, read); } return content; } }
Source:
protected void onStart() { super.onStart(); if (!isSdkConfigured()) { new AlertDialog.Builder(this) .setTitle(R.string.configuration_incomplete_title) .setMessage(R.string.configuration_incomplete_message) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(ListExamplesActivity.this, SettingsActivity.class)); } }).show(); return; } }

Target:
protected void onStart() { super.onStart(); if (!isSdkConfigured()) { new AlertDialog.Builder(this) .setTitle(R.string.configuration_incomplete_title) .setMessage(R.string.configuration_incomplete_message) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(ListExamplesActivity.this, SettingsActivity.class)); } }).show(); return; } }
Source:
private String getSpanName(ProcessKind processKind) { String spanName = "Eventhubs."; switch (processKind) { case SEND: spanName += "send"; break; case MESSAGE: spanName += "message"; break; case PROCESS: spanName += "process"; break; default: logger.warning("Unknown processKind type: {}", processKind); break; } return spanName; }

Target:
private String getSpanName(ProcessKind processKind) { String spanName = "EventHubs."; switch (processKind) { case SEND: spanName += "send"; break; case MESSAGE: spanName += "message"; break; case PROCESS: spanName += "process"; break; default: logger.warning("Unknown processKind type: {}", processKind); break; } return spanName; }
Source:
public String toString() { return "WechatToken{" + super.toString() + " " + "openid='" + openid + '\'' + ", unionid='" + unionid + '\'' + '}'; }

Target:
public String toString() { return CommonHelper.toNiceString(WechatToken.class, "accessToken", getAccessToken(), "openid", openid, "unionid", unionid); }
Source:
public ThrottleCategory(String categoryName, Integer maxConcurrentPerNode, Integer maxConcurrentTotal, String blockingCategories, List<NodeLabeledPair> nodeLabeledPairs) { this.maxConcurrentPerNode = maxConcurrentPerNode == null ? 0 : maxConcurrentPerNode; this.maxConcurrentTotal = maxConcurrentTotal == null ? 0 : maxConcurrentTotal; this.categoryName = categoryName; this.blockingCategories = blockingCategories; this.nodeLabeledPairs = nodeLabeledPairs == null ? new ArrayList<NodeLabeledPair>() : nodeLabeledPairs; convertCategoriesToList(blockingCategories); }

Target:
public ThrottleCategory(String categoryName, Integer maxConcurrentPerNode, Integer maxConcurrentTotal, String blockingCategories, List<NodeLabeledPair> nodeLabeledPairs) { this(categoryName, maxConcurrentPerNode, maxConcurrentTotal, nodeLabeledPairs); this.blockingCategories = blockingCategories; convertCategoriesToList(blockingCategories); }
Source:
private String createCSVFile(String in_path) throws IOException, TasteException { File csv = new File("movies.csv"); if (!csv.exists()) { csv.createNewFile(); FileInputStream fileInput = new FileInputStream(path); GZIPInputStream gzis = new GZIPInputStream(fileInput); FileOutputStream fileOutput = new FileOutputStream(csv); byte[] buffer = new byte[1024]; int length; while ((length = gzis.read(buffer)) > 0) fileOutput.write(buffer, 0, length); fileInput.close(); gzis.close(); fileOutput.close(); } return csv.getAbsolutePath(); }

Target:
private String createCSVFile(String in_path) throws IOException, TasteException { File csv = new File("movies.csv"); if (csv.exists()) csv.delete(); csv.createNewFile(); FileInputStream fileInput = new FileInputStream(path); GZIPInputStream gzis = new GZIPInputStream(fileInput); FileOutputStream fileOutput = new FileOutputStream(csv); byte[] buffer = new byte[1024]; int length; while ((length = gzis.read(buffer)) > 0) fileOutput.write(buffer, 0, length); fileInput.close(); gzis.close(); fileOutput.close(); return csv.getAbsolutePath(); }
Source:
public void testCompare() { ASCII ascii = new ASCII(true); String s0 = "abc"; String s1 = "xyz"; int returnedValue1 = ascii.compare(s0, s1); int returnedValue2 = ascii.compare(s1, s0); int returnedValue3 = ascii.compare(null, null); int returnedValue4 = ascii.compare(s0, null); int returnedValue5 = ascii.compare(null, s1); assertEquals(returnedValue1, -1); assertEquals(returnedValue2, 1); assertEquals(returnedValue3, 0); assertEquals(returnedValue4, 1); assertEquals(returnedValue5, -1); }

Target:
public void testCompare() { ASCII ascii = new ASCII(true); String s0 = "abc"; String s1 = "xyz"; int returnedValue1 = ascii.compare(s0, s1); int returnedValue2 = ascii.compare(s1, s0); int returnedValue3 = ascii.compare(null, null); int returnedValue4 = ascii.compare(s0, null); int returnedValue5 = ascii.compare(null, s1); assertEquals(-1, returnedValue1); assertEquals(1, returnedValue2); assertEquals(0, returnedValue3); assertEquals(1, returnedValue4); assertEquals(-1, returnedValue5); }
Source:
private Integer prerequirementImgResource(String group) { if (group.equalsIgnoreCase(AssignmentPrerequirement.RANK.toString())) { return R.drawable.rank_prerequirement; } else if (group.equalsIgnoreCase(AssignmentPrerequirement.MISSION.toString())) { return R.drawable.group_prerequirement; } else { return R.drawable.empty; } }

Target:
private int prerequirementImgResource(String group) { if (group.equalsIgnoreCase(AssignmentPrerequirement.RANK.toString())) { return R.drawable.rank_prerequirement; } else if (group.equalsIgnoreCase(AssignmentPrerequirement.MISSION.toString())) { return R.drawable.group_prerequirement; } else { return R.drawable.empty; } }
Source:
private void prepareResults(ProjectSearchResponseDto response) { List<SearchResultDto> results = response.getItemReferences(); results.sort( (o1, o2) -> { String ext1 = getFileExtension(o1.getItemReference().getName()); String ext2 = getFileExtension(o2.getItemReference().getName()); return ext1.compareToIgnoreCase(ext2); }); view.showItems(results); }

Target:
private void prepareResults(ProjectSearchResponseDto response) { List<SearchResultDto> results = response.getItemReferences(); results.sort(SEARCH_COMPARATOR); view.showItems(results); }
Source:
public Content update(Content content, ResolvedContent resolved) { Content resolvedContent = (Content)resolved.get(content.getCanonicalUri()).requireValue(); if (content instanceof Item) { Item resolvedItem = (Item)resolvedContent; Item contentItem = (Item)content; if (resolvedItem.getContainer() != null) { contentItem.setParentRef(resolvedItem.getContainer()); } contentWriter.createOrUpdate(ContentMerger.merge(resolvedItem, contentItem)); return resolvedItem; } else { if (!Strings.nullToEmpty(resolvedContent.getDescription()) .equals(Strings.nullToEmpty(resolvedContent.getDescription())) || !resolvedContent.getImages().equals(resolvedContent.getImages())) { ContentMerger.merge((Container)resolvedContent, (Container) content); contentWriter.createOrUpdate((Container)resolvedContent); } return resolvedContent; } }

Target:
public Content update(Content content, ResolvedContent resolved) { Content resolvedContent = (Content)resolved.get(content.getCanonicalUri()).requireValue(); if (content instanceof Item) { Item resolvedItem = (Item)resolvedContent; Item contentItem = (Item)content; if (resolvedItem.getContainer() != null) { contentItem.setParentRef(resolvedItem.getContainer()); } contentWriter.createOrUpdate(ContentMerger.merge(resolvedItem, contentItem)); return resolvedItem; } else { return resolvedContent; } }
Source:
public void handleDataChanged(DataChangedEvent... events) { if (!isEnabled()) { return; } for (DataChangedEvent e : events) { if (e.getUpdateState() != UpdateState.onlyInEditor) { handleChangedPo(e.getPo(), e.getDataState(), e.getUpdateState()); } } }

Target:
public void handleDataChanged(DataChangedEvent... events) { if (!isEnabled()) { return; } boolean isUpdateInEditor = true; for (DataChangedEvent e : events) { if (e.getUpdateState() != UpdateState.onlyInEditor) { handleChangedPo(e.getPo(), e.getDataState(), e.getUpdateState()); isUpdateInEditor = false; } } if (!isUpdateInEditor) { refresh(); addTeststyleProblems(); ProblemPropagator.INSTANCE.propagate(); } }
Source:
public static Collection<Integer> getThreadIds(KernelAnalysisModule module) { ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return Collections.EMPTY_SET; } int threadQuark; try { threadQuark = ss.getQuarkAbsolute(Attributes.THREADS); Set<@NonNull Integer> tids = new TreeSet<>(); for (Integer quark : ss.getSubAttributes(threadQuark, false)) { final @NonNull String attributeName = ss.getAttributeName(quark); tids.add(attributeName.startsWith(Attributes.THREAD_0_PREFIX) ? 0 : Integer.parseInt(attributeName)); } return tids; } catch (AttributeNotFoundException e) { } return Collections.EMPTY_SET; }

Target:
public static Collection<Integer> getThreadIds(KernelAnalysisModule module) { ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return Collections.emptySet(); } int threadQuark; try { threadQuark = ss.getQuarkAbsolute(Attributes.THREADS); Set<@NonNull Integer> tids = new TreeSet<>(); for (Integer quark : ss.getSubAttributes(threadQuark, false)) { final @NonNull String attributeName = ss.getAttributeName(quark); tids.add(attributeName.startsWith(Attributes.THREAD_0_PREFIX) ? 0 : Integer.parseInt(attributeName)); } return tids; } catch (AttributeNotFoundException e) { } return Collections.emptySet(); }
Source:
public void doOnTerminateSuccess() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); Single.just(1).doOnTerminate(new Action() { @Override public void run() throws Exception { atomicBoolean.set(true); } }).subscribe(); assertTrue(atomicBoolean.get()); }

Target:
public void doOnTerminateSuccess() { final AtomicBoolean atomicBoolean = new AtomicBoolean(); Single.just(1).doOnTerminate(new Action() { @Override public void run() throws Exception { atomicBoolean.set(true); } }) .test() .assertResult(1); assertTrue(atomicBoolean.get()); }
Source:
public void shouldInheritRepartitionTopicPartitionNumberFromUpstreamTopicWhenNumberOfPartitionsIsNotSpecified() throws InterruptedException, ExecutionException { final String repartitionName = "new-topic"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .repartition(Repartitioned.<Integer, String>as(repartitionName)) .groupByKey() .count() .toStream() .to(outputTopic); startStreams(builder); validateReceivedMessages( new IntegerDeserializer(), new LongDeserializer(), Arrays.asList( new KeyValue<>(1, 1L), new KeyValue<>(2, 1L) ) ); final String repartitionTopicName = toRepartitionTopicName(repartitionName); assertTrue(topicExists(repartitionTopicName)); assertEquals(4, getNumberOfPartitionsForTopic(repartitionTopicName)); }

Target:
public void shouldInheritRepartitionTopicPartitionNumberFromUpstreamTopicWhenNumberOfPartitionsIsNotSpecified() throws Exception { final String repartitionName = "new-topic"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .repartition(Repartitioned.as(repartitionName)) .groupByKey() .count() .toStream() .to(outputTopic); startStreams(builder); validateReceivedMessages( new IntegerDeserializer(), new LongDeserializer(), Arrays.asList( new KeyValue<>(1, 1L), new KeyValue<>(2, 1L) ) ); final String repartitionTopicName = toRepartitionTopicName(repartitionName); assertTrue(topicExists(repartitionTopicName)); assertEquals(4, getNumberOfPartitionsForTopic(repartitionTopicName)); }
Source:
private void saveToDisk(SaveRequest saveRequest) { saveTask = new SaveTask(saveRequest, formSaver, formController, this, new SaveTask.Listener() { @Override public void onProgressPublished(String progress) { saveResult.setValue(new SaveResult(SaveResult.State.SAVING, saveRequest, progress)); } @Override public void onComplete(SaveToDiskResult saveToDiskResult) { handleTaskResult(saveToDiskResult, saveRequest); } }, analytics).execute(); }

Target:
private void saveToDisk(SaveRequest saveRequest) { saveTask = new SaveTask(saveRequest, formSaver, formController, mediaUtils, new SaveTask.Listener() { @Override public void onProgressPublished(String progress) { saveResult.setValue(new SaveResult(SaveResult.State.SAVING, saveRequest, progress)); } @Override public void onComplete(SaveToDiskResult saveToDiskResult) { handleTaskResult(saveToDiskResult, saveRequest); clearMediaFiles(); } }, analytics, new ArrayList<>(originalFiles.values())).execute(); }
Source:
public ValueMatcher makeValueMatcher(final BaseDoubleColumnValueSelector selector, final String value) { final Double matchVal = DimensionHandlerUtils.convertObjectToDouble(value, false); if (matchVal == null) { return BooleanValueMatcher.of(false); } final long matchValLongBits = Double.doubleToLongBits(matchVal); return new ValueMatcher() { @Override public boolean matches() { return Double.doubleToLongBits(selector.getDouble()) == matchValLongBits; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; }

Target:
public ValueMatcher makeValueMatcher(final BaseDoubleColumnValueSelector selector, final String value) { final Double matchVal = DimensionHandlerUtils.convertObjectToDouble(value); if (matchVal == null) { return BooleanValueMatcher.of(false); } final long matchValLongBits = Double.doubleToLongBits(matchVal); return new ValueMatcher() { @Override public boolean matches() { return Double.doubleToLongBits(selector.getDouble()) == matchValLongBits; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; }
Source:
public void getResourceUsage(final long queryId, final PipedOutputStream writerOutput) throws DbException { Schema schema = Schema.appendColumn(MyriaConstants.RESOURCE_SCHEMA, Type.INT_TYPE, "workerId"); TupleBuffer tb = new TupleBuffer(schema); TupleWriter writer = new CsvTupleWriter(writerOutput); boolean found = false; for (SubQueryId subQueryId : resourceUsage.keySet()) { if (subQueryId.getQueryId() == queryId) { found = true; Map<Integer, List<ResourceStats>> workerStats = resourceUsage.get(subQueryId); for (Integer workerId : workerStats.keySet()) { List<ResourceStats> statsList = workerStats.get(workerId); for (ResourceStats stats : statsList) { tb.putLong(0, stats.timestamp); tb.putInt(1, stats.opId); tb.putString(2, stats.measurement); tb.putLong(3, stats.value); tb.putLong(4, stats.queryId); tb.putLong(5, stats.subqueryId); tb.putInt(6, workerId); } } } } if (found) { try { writer.writeColumnHeaders(schema.getColumnNames()); writer.writeTuples(tb); writer.done(); } catch (IOException e) { throw new DbException(e); } return; } getResourceLog(queryId, writer); }

Target:
public void getResourceUsage(final long queryId, final PipedOutputStream writerOutput) throws DbException { Schema schema = Schema.appendColumn(MyriaConstants.RESOURCE_SCHEMA, Type.INT_TYPE, "workerId"); TupleBuffer tb = new TupleBuffer(schema); TupleWriter writer = new CsvTupleWriter(writerOutput); if (queryManager.getResourceUsage(queryId, tb)) { try { writer.writeColumnHeaders(schema.getColumnNames()); writer.writeTuples(tb); writer.done(); } catch (IOException e) { throw new DbException(e); } return; } getResourceLog(queryId, writer); }
Source:
protected PathAddress getAddress(){ return address; }

Target:
PathAddress getAddress(){ return address; }
Source:
public boolean equals(Object o) { if (o instanceof EventSubprocess) { EventSubprocess other = (EventSubprocess) o; return super.equals(other) && isAsync.equals(other.isAsync) && processData.equals(other.processData); } return false; }

Target:
public boolean equals(Object o) { if (o instanceof EventSubprocess) { EventSubprocess other = (EventSubprocess) o; return super.equals(other) && Objects.equals(isAsync, other.isAsync) && Objects.equals(processData, other.processData) && Objects.equals(labels, other.labels); } return false; }
Source:
protected void enhanceSearchField() { addContent(getUserAccountData().getPerson().getFirstname()); addContent(getUserAccountData().getPerson().getLastname()); addContent(getUserAccountData().getLogin().getUsername()); addContent(getUserAccountData().getEmail()); addContent(getTenant().fetchValue().getTenantData().getName()); addContent(getTenant().fetchValue().getTenantData().getAccountNumber()); }

Target:
protected void enhanceSearchField() { addContent(getUserAccountData().getPerson().getFirstname()); addContent(getUserAccountData().getPerson().getLastname()); addContent(getUserAccountData().getLogin().getUsername()); addContent(getUserAccountData().getEmail()); tenants.fetchCachedTenant(getTenant()).ifPresent(tenant -> { addContent(tenant.getTenantData().getName()); addContent(tenant.getTenantData().getAccountNumber()); }); }
Source:
private void streamData(String pidString, String datastream, boolean asAttachment, HttpServletRequest request, HttpServletResponse response) { PID pid = PIDs.get(pidString); AccessGroupSet principals = getAgentPrincipals().getPrincipals(); RepositoryObject updatedPid = repoObjLoader.getRepositoryObject(pid); if (updatedPid.getClass() == WorkObject.class) { pid = ((WorkObject) updatedPid).getPrimaryObject().getPid(); } try { fedoraContentService.streamData(pid, datastream, principals, asAttachment, response); recordDownloadEvent(pid, datastream, principals, request); } catch (IOException e) { log.error("Problem retrieving for {}", pid.toString(), datastream, e); } }

Target:
private void streamData(String pidString, String datastream, boolean asAttachment, HttpServletRequest request, HttpServletResponse response) { PID pid = PIDs.get(pidString); AccessGroupSet principals = getAgentPrincipals().getPrincipals(); RepositoryObject repoObj = repoObjLoader.getRepositoryObject(pid); if (repoObj instanceof WorkObject) { FileObject primaryObj = ((WorkObject) repoObj).getPrimaryObject(); if (primaryObj != null) { pid = primaryObj.getPid(); } } try { fedoraContentService.streamData(pid, datastream, principals, asAttachment, response); recordDownloadEvent(pid, datastream, principals, request); } catch (IOException e) { log.error("Problem retrieving for {}", pid.toString(), datastream, e); } }
Source:
private void setVmToHeadlessMode() { VmStatic vmStatic = vmStaticDao.get(getParameters().getDev().getVmId()); if (vmStatic != null && vmStatic.getDefaultDisplayType() != DisplayType.none) { vmStatic.setDefaultDisplayType(DisplayType.none); vmStatic.setSingleQxlPci(false); vmStaticDao.update(vmStatic); } }

Target:
private boolean setVmToHeadlessMode() { VmStatic vmStatic = vmStaticDao.get(getParameters().getDev().getVmId()); if (vmStatic != null && vmStatic.getDefaultDisplayType() != DisplayType.none) { vmStatic.setDefaultDisplayType(DisplayType.none); vmStatic.setSingleQxlPci(false); resourceManager.getVmManager(getParameters().getDev().getVmId()).update(vmStatic); return true; } return false; }
Source:
protected void incrementFakeParticleTick() { ChunkCoordinates coords = getBurstSourceChunkCoordinates(); TileEntity tile = worldObj.getTileEntity(coords.posX, coords.posY, coords.posZ); if(tile != null && tile instanceof IManaSpreader) { IManaSpreader spreader = (IManaSpreader) tile; spreader.setBurstParticleTick(spreader.getBurstParticleTick()+2); if(spreader.getLastBurstDeathTick() != -1 && spreader.getBurstParticleTick() > spreader.getLastBurstDeathTick()) spreader.setBurstParticleTick(0); } }

Target:
public void incrementFakeParticleTick() { ChunkCoordinates coords = getBurstSourceChunkCoordinates(); TileEntity tile = worldObj.getTileEntity(coords.posX, coords.posY, coords.posZ); if(tile != null && tile instanceof IManaSpreader) { IManaSpreader spreader = (IManaSpreader) tile; spreader.setBurstParticleTick(spreader.getBurstParticleTick()+2); if(spreader.getLastBurstDeathTick() != -1 && spreader.getBurstParticleTick() > spreader.getLastBurstDeathTick()) spreader.setBurstParticleTick(0); } }
Source:
public void postComment() throws Exception { String file = "file"; String contents = "contents"; PushOneCommit push = pushFactory.create(db, admin.getIdent(), "first subject", file, contents); PushOneCommit.Result r = push.to(git, "refs/for/master"); String changeId = r.getChangeId(); String revId = r.getCommit().getName(); ReviewInput input = new ReviewInput(); ReviewInput.CommentInput comment = newCommentInfo( file, Comment.Side.REVISION, 1, "comment 1"); input.comments = new HashMap<>(); input.comments.put(comment.path, Lists.newArrayList(comment)); revision(r).review(input); Map<String, List<CommentInfo>> result = getPublishedComments(changeId, revId); assertThat(result.isEmpty()).isFalse(); CommentInfo actual = Iterables.getOnlyElement(result.get(comment.path)); assertCommentInfo(comment, actual); }

Target:
public void postComment() throws Exception { String file = "file"; String contents = "contents"; PushOneCommit push = pushFactory.create(db, admin.getIdent(), "first subject", file, contents); PushOneCommit.Result r = push.to(git, "refs/for/master"); String changeId = r.getChangeId(); String revId = r.getCommit().getName(); ReviewInput input = new ReviewInput(); ReviewInput.CommentInput comment = newCommentInfo( file, Comment.Side.REVISION, 1, "comment 1"); input.comments = new HashMap<>(); input.comments.put(comment.path, Lists.newArrayList(comment)); revision(r).review(input); Map<String, List<CommentInfo>> result = getPublishedComments(changeId, revId); assertThat(result).isNotEmpty(); CommentInfo actual = Iterables.getOnlyElement(result.get(comment.path)); assertCommentInfo(comment, actual); }
Source:
public void publishInfo(ComponentInfoPublisher componentInfoPublisher) { components.forEach(component -> { log.info("calling publishInfo on ", component); component.publishInfo(componentInfoPublisher); }); }

Target:
public void publishInfo(ComponentInfoPublisher componentInfoPublisher) { components.forEach(component -> { if (log.isDebugEnabled()) { log.debug("calling publishInfo on ", component); } component.publishInfo(componentInfoPublisher); }); }
Source:
public void cleanup() { lock.lock(); try { boolean dirty = false; for (Iterator<Transaction> i = pending.values().iterator(); i.hasNext();) { Transaction tx = i.next(); if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.debug("Found risky transaction in wallet during cleanup.", tx.getHashAsString()); if (!tx.isAnyOutputSpent()) { tx.disconnectInputs(); i.remove(); transactions.remove(tx.getHash()); dirty = true; log.info("Removed transaction from pending pool during cleanup.", tx.getHashAsString()); } else { log.info( "Cannot remove transaction from pending pool during cleanup, as it's already spent partially.", tx.getHashAsString()); } } } if (dirty) saveLater(); } finally { lock.unlock(); } }

Target:
public void cleanup() { lock.lock(); try { boolean dirty = false; for (Iterator<Transaction> i = pending.values().iterator(); i.hasNext();) { Transaction tx = i.next(); if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.debug("Found risky transaction in wallet during cleanup.", tx.getHashAsString()); if (!tx.isAnyOutputSpent()) { tx.disconnectInputs(); i.remove(); transactions.remove(tx.getHash()); dirty = true; log.info("Removed transaction from pending pool during cleanup.", tx.getHashAsString()); } else { log.info( "Cannot remove transaction from pending pool during cleanup, as it's already spent partially.", tx.getHashAsString()); } } } if (dirty) { checkState(isConsistent()); saveLater(); } } finally { lock.unlock(); } }
Source:
private List<ResponseMessage> responseMessages() { return new ArrayList<ResponseMessage>() {{ add(new ResponseMessageBuilder() .code(500) .message("500 message") .responseModel(new ModelRef("Error")) .build()); }}; }

Target:
private List<ResponseMessage> responseMessages() { List<ResponseMessage> responseMessages = new ArrayList<>(); responseMessages .add(new ResponseMessageBuilder() .code(500) .message("500 - Interna server error.\n\n" + "There is a problem with the resource you are looking for, and it can not be dispayed.") .responseModel(new ModelRef("Error")) .build()); return responseMessages; }
Source:
protected LifelineLabelHelper() { masks.put(SHOW_REPRESENT_NAME, "Show represent name"); masks.put(SHOW_REPRESENT_TYPE, "Show represent type"); masks.put(SHOW_UNDEFINED_TYPE, "Always show undefined type"); masks.put(SHOW_LIFELINE_NAME, "Always show lifeline name"); }

Target:
protected LifelineLabelHelper() { masks.put(SHOW_REPRESENT_NAME, "Show represent name"); masks.put(SHOW_REPRESENT_SELECTOR, "Show represent selector"); masks.put(SHOW_REPRESENT_TYPE, "Show represent type"); masks.put(SHOW_UNDEFINED_TYPE, "Always show undefined type"); masks.put(SHOW_LIFELINE_NAME, "Always show lifeline name"); }
Source:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { PatientData<Map<String, String>> data = patient.getData(getName()); if (data == null) { return; } Iterator<Map<String, String>> iterator = data.iterator(); if (iterator == null || !iterator.hasNext()) { return; } JSONArray container = null; while (iterator.hasNext()) { Map<String, String> item = iterator.next(); if (container == null) { json.put(getJsonPropertyName(), new JSONArray()); container = json.getJSONArray(getJsonPropertyName()); } if (item != null && "".equals(item.get(COMMENTS_KEY))) { item.remove(COMMENTS_KEY); } container.add(item); container.add(item); } }

Target:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { PatientData<Map<String, String>> data = patient.getData(getName()); if (data == null) { return; } Iterator<Map<String, String>> iterator = data.iterator(); if (iterator == null || !iterator.hasNext()) { return; } JSONArray container = null; while (iterator.hasNext()) { Map<String, String> item = iterator.next(); if (container == null) { json.put(getJsonPropertyName(), new JSONArray()); container = json.getJSONArray(getJsonPropertyName()); } if (item != null && StringUtils.isBlank(item.get(COMMENTS_KEY))) { item.remove(COMMENTS_KEY); } container.add(item); } }
Source:
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (!(type instanceof Class<?>)) { return null; } Class<?> c = (Class<?>) type; if (!MessageLite.class.isAssignableFrom(c)) { return null; } Parser<MessageLite> parser; try { Method method = c.getDeclaredMethod("parser"); parser = (Parser<MessageLite>) method.invoke(null); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { try { Field field = c.getDeclaredField("PARSER"); parser = (Parser<MessageLite>) field.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalArgumentException("Found a protobuf message but " + c.getName() + " had no parser() method or PARSER field."); } } return new ProtoResponseBodyConverter<>(parser, registry); }

Target:
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (!(type instanceof Class<?>)) { return null; } Class<?> c = (Class<?>) type; if (!MessageLite.class.isAssignableFrom(c)) { return null; } Parser<MessageLite> parser; try { Method method = c.getDeclaredMethod("parser"); parser = (Parser<MessageLite>) method.invoke(null); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } catch (NoSuchMethodException | IllegalAccessException ignored) { try { Field field = c.getDeclaredField("PARSER"); parser = (Parser<MessageLite>) field.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalArgumentException("Found a protobuf message but " + c.getName() + " had no parser() method or PARSER field."); } } return new ProtoResponseBodyConverter<>(parser, registry); }