auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public abstract boolean isDirectory() throws IOException; public abstract boolean isFile() throws IOException; public abstract boolean exists() throws IOException; public abstract @Nonnull VirtualFile[] list() throws IOException; public abstract @Nonnull String[] list(String glob) throws IOException; public abstract @Nonnull VirtualFile child(@Nonnull String name); public abstract long length() throws IOException; public abstract String date() throws IOException; public static final String DateFormat = "MM/dd/yyyy h:mm:ss a"; public abstract long lastModified() throws IOException; public abstract boolean canRead() throws IOException; public abstract InputStream open() throws IOException; @Override public final int compareTo(VirtualFile o) { return getName().compareToIgnoreCase(o.getName()); }

Target:
public abstract boolean isDirectory() throws IOException; public abstract boolean isFile() throws IOException; public abstract boolean exists() throws IOException; public abstract @Nonnull VirtualFile[] list() throws IOException; public abstract @Nonnull String[] list(String glob) throws IOException; public abstract @Nonnull VirtualFile child(@Nonnull String name); public abstract long length() throws IOException; public abstract long lastModified() throws IOException; public abstract boolean canRead() throws IOException; public abstract InputStream open() throws IOException; @Override public final int compareTo(VirtualFile o) { return getName().compareToIgnoreCase(o.getName()); }
Source:
public void testScenarios() throws IOException, DockerCertificateException { String testResourcesPath = getClass().getClassLoader().getResource(".").getPath(); TestScenariosFinder testScenariosFinder = new TestScenariosFinder(testResourcesPath); List<TestScenario> testScenarios = testScenariosFinder.getScenarios(); TestScenarioRunner caseRunner = new TestScenarioRunner(ProjectVersion.currentVersion(), 9080); int successfulScenarios = 0; int failedScenarios = 0; for (TestScenario testScenario: testScenarios) { if (testScenario.enabledTests() == 0) { continue; } int successfulTestCases = caseRunner.run(testScenario); if (successfulTestCases == testScenario.enabledTests()) { System.out.println("\nScenario success: " + testScenario + "\n"); System.out.println("Number of successful test cases: " + successfulTestCases); successfulScenarios++; } else { System.out.println("\nScenario failed: " + testScenario + "\n"); System.out.println("Number of failed test cases: " + (testScenario.enabledTests() - successfulTestCases)); failedScenarios++; } } System.out.println("\n\nScenarios results:\nSuccessful: " + successfulScenarios + ", Failed: " + failedScenarios + "\n\n"); }

Target:
public void testScenarios() throws IOException { String testResourcesPath = getClass().getClassLoader().getResource(".").getPath(); TestScenariosFinder testScenariosFinder = new TestScenariosFinder(testResourcesPath); List<TestScenario> testScenarios = testScenariosFinder.getScenarios(); TestScenarioRunner caseRunner = new TestScenarioRunner(9080); int successfulScenarios = 0; int failedScenarios = 0; for (TestScenario testScenario: testScenarios) { if (testScenario.enabledTests() == 0) { continue; } int successfulTestCases = 0; try { successfulTestCases = caseRunner.run(testScenario); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.print("Exception while running test scenario: " + testScenario); } if (successfulTestCases == testScenario.enabledTests()) { System.out.println("\nScenario success: " + testScenario + "\n"); System.out.println("Number of successful test cases: " + successfulTestCases); successfulScenarios++; } else { System.out.println("\nScenario failed: " + testScenario + "\n"); System.out.println("Number of failed test cases: " + (testScenario.enabledTests() - successfulTestCases)); failedScenarios++; } } System.out.println("\n\nScenarios results:\nSuccessful: " + successfulScenarios + ", Failed: " + failedScenarios + "\n\n"); }
Source:
public Iterator<ModifiableRealmIdentity> getRealmIdentityIterator() throws RealmUnavailableException { if (identityMapping.iteratorFilter == null) { throw log.ldapRealmNotConfiguredToSupportIteratingOverIdentities(); } log.debugf("Trying to iterate over identities."); DirContext context = null; NamingEnumeration<SearchResult> result; try { context = dirContextFactory.obtainDirContext(null); result = context.search(identityMapping.searchDn, identityMapping.iteratorFilter, identityMapping.iteratorFilterArgs, createSearchControls(identityMapping.rdnIdentifier)); } catch (NamingException e) { throw log.ldapRealmIdentitySearchFailed(e); } finally { dirContextFactory.returnContext(context); } return new Iterator<ModifiableRealmIdentity>() { public boolean hasNext() { try { return result.hasMore(); } catch (NamingException e) { throw log.ldapRealmIdentitySearchFailed(e); } } public ModifiableRealmIdentity next() { try { SearchResult entry = result.next(); String name = (String) entry.getAttributes().get(identityMapping.rdnIdentifier).get(); return getRealmIdentityForUpdate(name, null, null); } catch (NamingException e) { throw log.ldapRealmIdentitySearchFailed(e); } } }; }

Target:
public Iterator<ModifiableRealmIdentity> getRealmIdentityIterator() throws RealmUnavailableException { if (identityMapping.iteratorFilter == null) { throw log.ldapRealmNotConfiguredToSupportIteratingOverIdentities(); } log.debugf("Trying to iterate over identities."); DirContext context = null; List<ModifiableRealmIdentity> identifiers = new LinkedList<>(); try { context = dirContextFactory.obtainDirContext(null); } catch (NamingException e) { throw log.ldapRealmIdentitySearchFailed(e); } try { NamingEnumeration<SearchResult> result = context.search(identityMapping.searchDn, identityMapping.iteratorFilter, identityMapping.iteratorFilterArgs, createSearchControls(identityMapping.rdnIdentifier)); try { while (result.hasMore()) { SearchResult entry = result.next(); String name = (String) entry.getAttributes().get(identityMapping.rdnIdentifier).get(); identifiers.add(getRealmIdentityForUpdate(name, null, null)); } } finally { result.close(); } } catch (NamingException e) { throw log.ldapRealmIdentitySearchFailed(e); } finally { dirContextFactory.returnContext(context); } return identifiers.iterator(); }
Source:
public GenericArtifactManager(Registry registry, String key) throws RegistryException { try { GovernanceArtifactConfiguration configuration = GovernanceUtils.findGovernanceArtifactConfiguration(key, registry); if (configuration != null) { this.artifactNameAttribute = configuration.getArtifactNameAttribute(); this.artifactNamespaceAttribute = configuration.getArtifactNamespaceAttribute(); this.artifactElementNamespace = configuration.getArtifactElementNamespace(); manager = new GovernanceArtifactManager(registry, configuration.getMediaType(), this.artifactNameAttribute, this.artifactNamespaceAttribute, configuration.getArtifactElementRoot(), this.artifactElementNamespace, configuration.getPathExpression(), configuration.getLifecycle(), configuration.getValidationAttributes(), configuration.getRelationshipDefinitions()); this.mediaType = configuration.getMediaType(); } else { String message = "Artifact type '" + key + "' is not in registry or unable to find relevant " + "configuration."; log.error(message); throw new RegistryException(message); } } catch (RegistryException e) { String message = "Unable to obtain governance artifact configuration."; log.error(message, e); throw new RegistryException(message, e); } }

Target:
public GenericArtifactManager(Registry registry, String key) throws RegistryException { try { GovernanceArtifactConfiguration configuration = GovernanceUtils.findGovernanceArtifactConfiguration(key, registry); this.artifactNameAttribute = configuration.getArtifactNameAttribute(); this.artifactNamespaceAttribute = configuration.getArtifactNamespaceAttribute(); this.artifactElementNamespace = configuration.getArtifactElementNamespace(); manager = new GovernanceArtifactManager(registry, configuration.getMediaType(), this.artifactNameAttribute, this.artifactNamespaceAttribute, configuration.getArtifactElementRoot(), this.artifactElementNamespace, configuration.getPathExpression(), configuration.getLifecycle(), configuration.getValidationAttributes(), configuration.getRelationshipDefinitions()); this.mediaType = configuration.getMediaType(); } catch (RegistryException e) { throw new GovernanceException("Unable to obtain governance artifact configuration", e); } }
Source:
public void delete(K key) { Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); locker.computeIfAbsent(key, (k) -> { cache.delete(key); rwTable.delete(key); return null; }); }

Target:
public void delete(K key) { Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); atomicDelete(key); }
Source:
protected String updateACHAccountIfNecessary(Person payee, PayeeACHAccountExtractDetail achDetail, PayeeACHAccount achAccount) { StringBuilder processingResults = new StringBuilder(); if (accountHasChanged(achDetail, achAccount)) { PayeeACHData achData = new PayeeACHData(payee, achDetail, achAccount.getPayeeIdentifierTypeCode(), achAccount); String accountUpdateErrors = createAndRoutePayeeACHAccountDocument(achData, this::setupDocumentForACHUpdate); processingResults.append(accountUpdateErrors); } else { LOG.info("Input file's account information for payee of type '" + achAccount.getPayeeIdentifierTypeCode() + "' matches what is already in KFS; no updates will be made for this entry."); } if (processingResults.length() > 0) { processingResults.append(" Update was NOT performed."); LOG.warn("updateACHAccountIfNecessary: " + processingResults.toString()); } return processingResults.toString(); }

Target:
protected String updateACHAccountIfNecessary(Person payee, PayeeACHAccountExtractDetail achDetail, PayeeACHAccount achAccount) { StringBuilder processingResults = new StringBuilder(); if (accountHasChanged(achDetail, achAccount)) { PayeeACHData achData = new PayeeACHData(payee, achDetail, achAccount.getPayeeIdentifierTypeCode(), achAccount); String accountUpdateErrors = createAndRoutePayeeACHAccountDocument(achData, this::setupDocumentForACHUpdate); processingResults.append(accountUpdateErrors); } else { LOG.info("updateACHAccountIfNecessary: Input file's account information for payee of type '" + achAccount.getPayeeIdentifierTypeCode() + "' matches what is already in KFS; no updates will be made for this entry."); } if (processingResults.length() > 0) { processingResults.append(" Update was NOT performed."); LOG.warn("updateACHAccountIfNecessary: " + processingResults.toString()); } return processingResults.toString(); }
Source:
protected StatsDMessage(String aspect, Message.Type type, T value, double sampleRate, String[] tags) { super(aspect, type, value); this.sampleRate = sampleRate; this.tags = tags; }

Target:
protected StatsDMessage(String aspect, Message.Type type, T value, double sampleRate, String[] tags) { super(aspect, type, value, tags); this.sampleRate = sampleRate; }
Source:
public NavigableMap<byte[], List<Cell>> getFamilyCellMap() { if (action instanceof Mutation) { return ((Mutation) action).getFamilyCellMap(); } else { throw new UnsupportedOperationException(); } }

Target:
public NavigableMap<byte[], List<Cell>> getFamilyCellMap() { if (action instanceof Mutation) { return ((Mutation) action).getFamilyCellMap(); } throw new UnsupportedOperationException(); }
Source:
public boolean isSynchronized() { if (getResource().isAccessible()) { return super.isSynchronized(); } return path.toFile().lastModified() == timestamp; }

Target:
public boolean isSynchronized() { return path.toFile().lastModified() == timestamp; }
Source:
public void shouldGetDiagnoses() { Encounter encounter = new Encounter(3); List<Diagnosis> firstDiagnoses= diagnosisDAO.getDiagnoses(encounter); assertEquals(2, firstDiagnoses.size()); Encounter otherEncounter = new Encounter(9); List<Diagnosis> secondDiagnoses= diagnosisDAO.getDiagnoses(otherEncounter); assertEquals(0, secondDiagnoses.size()); }

Target:
public void shouldGetDiagnoses() { assertEquals(2, diagnosisDAO.getDiagnoses(new Encounter(3)).size()); assertEquals(0, diagnosisDAO.getDiagnoses(new Encounter(9)).size()); }
Source:
private boolean validateHostsConnectionResults(List<Pair<Guid, Boolean>> hostsConnectionResults) { for (Pair<Guid, Boolean> hostsConnectionResult : hostsConnectionResults) { if (hostsConnectionResult.getSecond() == true) { return true; } } return false; }

Target:
private boolean validateHostsConnectionResults(List<Pair<Guid, Boolean>> hostsConnectionResults) { for (Pair<Guid, Boolean> hostsConnectionResult : hostsConnectionResults) { if (hostsConnectionResult.getSecond()) { return true; } } return false; }
Source:
public void testEditWhenHeaderCellSelected() { final GridColumn.HeaderMetaData headerMetaData = mock(GridColumn.HeaderMetaData.class); final GridColumn<?> gridColumn = mockGridColumn(100.0, Arrays.asList(headerMetaData)); doReturn(ci).when(gridRendererHelper).getColumnInformation(50.0); doReturn(gridColumn).when(ci).getColumn(); doReturn(0.0).when(ci).getOffsetX(); doReturn(0).when(ci).getUiColumnIndex(); gridWidget.getModel().appendColumn(gridColumn); gridWidget.getModel().selectHeaderCell(0, 0); CellContextUtilities.editSelectedCell(gridWidget); verify(headerMetaData).edit(any(GridBodyCellEditContext.class)); verify(gridWidget, never()).startEditingCell(anyInt(), anyInt()); verify(gridWidget, never()).startEditingCell(any(Point2D.class)); }

Target:
public void testEditWhenHeaderCellSelected() { final GridColumn.HeaderMetaData headerMetaDataC1 = mock(GridColumn.HeaderMetaData.class); final GridColumn.HeaderMetaData headerMetaDataC2 = mock(GridColumn.HeaderMetaData.class); final GridColumn<?> gridColumnOne = mockGridColumn(100.0, Arrays.asList(headerMetaDataC1)); final GridColumn<?> gridColumnTwo = mockGridColumn(100.0, Arrays.asList(headerMetaDataC2)); doReturn(0).when(gridColumnOne).getIndex(); doReturn(1).when(gridColumnTwo).getIndex(); final double secondColumnXCoordinate = gridColumnOne.getWidth() + gridColumnTwo.getWidth() / 2; doReturn(ci).when(gridRendererHelper).getColumnInformation(secondColumnXCoordinate); doReturn(gridColumnOne.getWidth()).when(gridRendererHelper).getColumnOffset(gridColumnTwo); doReturn(gridColumnTwo).when(ci).getColumn(); doReturn(0.0).when(ci).getOffsetX(); doReturn(1).when(ci).getUiColumnIndex(); doReturn(Arrays.asList(gridColumnOne, gridColumnTwo)).when(ri).getAllColumns(); gridWidget.getModel().appendColumn(gridColumnOne); gridWidget.getModel().appendColumn(gridColumnTwo); gridWidget.getModel().selectHeaderCell(0, 1); CellContextUtilities.editSelectedCell(gridWidget); verify(headerMetaDataC1, never()).edit(any(GridBodyCellEditContext.class)); verify(headerMetaDataC2).edit(gridBodyCellEditContextCaptor.capture()); final GridBodyCellEditContext gridBodyCellEditContext = gridBodyCellEditContextCaptor.getValue(); assertThat(gridBodyCellEditContext) .hasFieldOrPropertyWithValue("columnIndex", 1) .hasFieldOrPropertyWithValue("rowIndex", 0); verify(gridWidget, never()).startEditingCell(anyInt(), anyInt()); verify(gridWidget, never()).startEditingCell(any(Point2D.class)); }
Source:
public <T> Object create(Class<T> cls) { final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(cls); final InjectionTargetFactory<T> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType); final BeanAttributes<T> attributes = beanManager.createBeanAttributes(annotatedType); final Bean<T> bean = beanManager.createBean(attributes, cls, injectionTargetFactory); final CreationalContext<?> context = beanManager.createCreationalContext(bean); return beanManager.getReference(bean, cls, context); }

Target:
public <T> Object create(Class<T> cls) { final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(cls); final InjectionTargetFactory<T> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType); final BeanAttributes<T> attributes = beanManager.createBeanAttributes(annotatedType); final Bean<T> bean = beanManager.createBean(attributes, cls, injectionTargetFactory); final CreationalContext<?> context = beanManager.createCreationalContext(bean); if (!beanManager.isNormalScope(bean.getScope())) { beanManager.fireEvent(new DisposableCreationalContext(context)); } return beanManager.getReference(bean, cls, context); }
Source:
private void removeUserRemovedNetworkAttachments(List<NetworkAttachment> existingNetworkAttachments) { for (Guid attachmentId : userRemovedNetworkAttachments) { networkAttachmentDao.remove(attachmentId); } for (Iterator<NetworkAttachment> iterator = existingNetworkAttachments.iterator(); iterator.hasNext();) { Guid networkAttachmentId = iterator.next().getId(); if (networkAttachmentId != null && userRemovedNetworkAttachments.contains(networkAttachmentId)) { iterator.remove(); break; } } }

Target:
private void removeUserRemovedNetworkAttachments(List<NetworkAttachment> existingNetworkAttachments) { for (Guid attachmentId : userRemovedNetworkAttachments) { networkAttachmentDao.remove(attachmentId); } for (Iterator<NetworkAttachment> iterator = existingNetworkAttachments.iterator(); iterator.hasNext();) { Guid networkAttachmentId = iterator.next().getId(); if (userRemovedNetworkAttachments.contains(networkAttachmentId)) { iterator.remove(); } } }
Source:
public void onBackStackChanged() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(getSupportFragmentManager().getBackStackEntryCount() > 0); } }

Target:
public void onBackStackChanged() { this.updateUpButtonVisibility(); }
Source:
public long rangeSelectivity(DataValueDescriptor start,DataValueDescriptor stop, boolean includeStart,boolean includeStop,boolean useExtrapolation) { if ((start == null || start.isNull()) && (stop == null || stop.isNull())) return nullCount; if (start.equals(stop)) return rpv; return (long)(0.1 * totalCount); }

Target:
public long rangeSelectivity(DataValueDescriptor start,DataValueDescriptor stop, boolean includeStart,boolean includeStop,boolean useExtrapolation) { if ((start == null || start.isNull()) && (stop == null || stop.isNull())) return nullCount; if (start.equals(stop)) return rpv; return (long)(DEFAULT_RANGE_SELECTIVITY * totalCount); }
Source:
protected void executeCommand() { updateQuotaCache(); if (_oldStoragePool.getStatus() == StoragePoolStatus.Up && getMasterDomain() != null) { if (!StringUtils.equals(_oldStoragePool.getName(), getStoragePool().getName())) { runVdsCommand(VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters( getStoragePool().getId(), getStoragePool().getName()) ); } } copyUnchangedStoragePoolProperties(getStoragePool(), _oldStoragePool); getStoragePoolDAO().updatePartial(getStoragePool()); updateStoragePoolFormatType(); setSucceeded(true); }

Target:
protected void executeCommand() { updateQuotaCache(); if (_oldStoragePool.getStatus() == StoragePoolStatus.Up) { if (!StringUtils.equals(_oldStoragePool.getName(), getStoragePool().getName())) { runVdsCommand(VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters( getStoragePool().getId(), getStoragePool().getName()) ); } } copyUnchangedStoragePoolProperties(getStoragePool(), _oldStoragePool); getStoragePoolDAO().updatePartial(getStoragePool()); updateStoragePoolFormatType(); setSucceeded(true); }
Source:
public void onRequestStarted(Map<Object, Object> ephemeralProperties) { if (ephemeralProperties.get(REQUEST_RECEIVED_MILLIS_KEY) != null) { long started = (long) ephemeralProperties.get(REQUEST_RECEIVED_MILLIS_KEY); long duration = System.currentTimeMillis() - started; if (duration > highWatermark) { LOGGER.warn(String.format( "request spent %d ms in the transport buffer, your consumer might be backed up", duration)); } } }

Target:
public void onRequestStarted(Map<Object, Object> ephemeralProperties) { if (ephemeralProperties.get(REQUEST_RECEIVED_MILLIS_KEY) != null) { long started = (long) ephemeralProperties.get(REQUEST_RECEIVED_MILLIS_KEY); long duration = clock.millis() - started; if (duration > highWatermark) { LOGGER.warn(String.format( "request spent %d ms in the transport buffer, your consumer might be backed up", duration)); } } }
Source:
public Histogram aggregateHistogram() { Histogram aggregate = AGGREGATE_HISTOGRAM.get(); aggregate.reset(); aggregate.add(histogramAtomicReference.get()); synchronized (this) { histogramQueue .forEach(aggregate::add); } return aggregate; }

Target:
public Histogram aggregateHistogram() { Histogram aggregate = createHistogram(); synchronized (LOCK) { aggregate.add(liveHistogram); histogramQueue .forEach(aggregate::add); } return aggregate; }
Source:
public ModelAndView getGroupUsers(@PathVariable("groupId") Long groupId) throws org.jtalks.common.service.exceptions.NotFoundException { checkForAdminPermissions(); GroupDto groupDto = new GroupDto(groupId, groupService.get(groupId).getName(), groupService.getGroupUsers(groupId, 4)); return new ModelAndView("groupUserList").addObject("group", groupDto); }

Target:
public ModelAndView getGroupUsers(@PathVariable("groupId") Long groupId) throws org.jtalks.common.service.exceptions.NotFoundException { checkForAdminPermissions(); GroupDto groupDto = new GroupDto(groupId, groupService.get(groupId).getName(), groupService.getGroupUsers(groupId, 20)); return new ModelAndView("groupUserList").addObject("group", groupDto); }
Source:
public void testPutIfAbsent() throws Exception{ String fileID = store.get(file1); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull(fileID); fileID = store.putIfAbsent(file1, file1Id); assertNotNull(fileID); assertEquals(file1Id, fileID); }

Target:
public void testPutIfAbsent() throws Exception { String fileID = store.get(file1); assertNull("Get First time, Key doesnt exists", fileID); fileID = store.putIfAbsent(file1, file1Id); assertNull("Insert First time, Key insertion successful", fileID); fileID = store.putIfAbsent(file1, "56789"); assertNotNull("Key Already Exists - Insertion Failed, for different value", fileID); assertEquals("Retrieving the Old Value", file1Id, fileID); assertEquals("Retrieving the Old Value", file1Id, store.get(file1)); }
Source:
public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) { if (checkOpen(true)) { if (!config().isAutoRead()) { tempInboundMessages().add(msg); } else { pipeline().fireChannelRead(msg); } } return checkException(promise); }

Target:
public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) { if (checkOpen(true)) { if (!config().isAutoRead()) { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages = tempInboundMessages(); tempInboundMessages.add(new AbstractMap.SimpleEntry<Object, ChannelPromise>(msg, promise)); return promise; } else { pipeline().fireChannelRead(msg); } } return checkException(promise); }
Source:
public void testUpdate() throws Exception { int count = handle.createStatement("INSERT INTO user(id, name) VALUES(:id, :name)") .bind("id", 3) .bind("name", "Charlie") .execute(); assertThat(count, is(1)); }

Target:
public void testUpdate() throws Exception { int count = handle.createUpdate("INSERT INTO user(id, name) VALUES(:id, :name)") .bind("id", 3) .bind("name", "Charlie") .execute(); assertThat(count).isEqualTo(1); }
Source:
private List<Facet> updateStringFacets(JsonObject aggregations, DiscreteFacetRequest facetRequest) { JsonElement aggregation = aggregations.get( facetRequest.getFacetingName() ); if ( aggregation == null ) { return Collections.emptyList(); } if ( facetRequest.getFieldName().contains( "." ) ) { aggregation = aggregation.getAsJsonObject().get( facetRequest.getFacetingName() ); } if ( aggregation == null ) { return Collections.emptyList(); } ArrayList<Facet> facets = new ArrayList<>(); for ( JsonElement bucket : aggregation.getAsJsonObject().get( "buckets" ).getAsJsonArray() ) { facets.add( facetRequest.createFacet( bucket.getAsJsonObject().get( "key" ).getAsString(), bucket.getAsJsonObject().get( "doc_count" ).getAsInt() ) ); } return facets; }

Target:
private List<Facet> updateStringFacets(JsonObject aggregations, DiscreteFacetRequest facetRequest) { JsonElement aggregation = aggregations.get( facetRequest.getFacetingName() ); if ( aggregation == null ) { return Collections.emptyList(); } if ( FieldHelper.isEmbeddedField( facetRequest.getFieldName() ) ) { aggregation = aggregation.getAsJsonObject().get( facetRequest.getFacetingName() ); } if ( aggregation == null ) { return Collections.emptyList(); } ArrayList<Facet> facets = new ArrayList<>(); for ( JsonElement bucket : aggregation.getAsJsonObject().get( "buckets" ).getAsJsonArray() ) { facets.add( facetRequest.createFacet( bucket.getAsJsonObject().get( "key" ).getAsString(), bucket.getAsJsonObject().get( "doc_count" ).getAsInt() ) ); } return facets; }
Source:
private boolean hasStoragePermissions() { int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); Log.i("Glucosio", "Storage permissions granted."); if (permission != PackageManager.PERMISSION_GRANTED) { requestStoragePermission(); return false; } else { return true; } }

Target:
private boolean hasStoragePermissions() { int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); Log.i("Glucosio", "Storage permissions granted."); if (permission == PackageManager.PERMISSION_DENIED) { requestStoragePermission(); return false; } else { return true; } }
Source:
public static String getUniqueUserID() { String defaultUuidValue = "UUID missing, defaulting to this value"; String uniqueUserID = Preference.APPLICATION_SCOPED.get(BriefcasePreferences.BRIEFCASE_UNIQUE_USER_ID_PROPERTY, defaultUuidValue); if ( uniqueUserID.equals(defaultUuidValue)) { Preference.APPLICATION_SCOPED.put(BriefcasePreferences.BRIEFCASE_UNIQUE_USER_ID_PROPERTY, UUID.randomUUID().toString()); } return Preference.APPLICATION_SCOPED.get(BriefcasePreferences.BRIEFCASE_UNIQUE_USER_ID_PROPERTY, defaultUuidValue); }

Target:
public static String getUniqueUserID() { String defaultUuidValue = "UUID missing, defaulting to this message"; String uniqueUserID = Preference.APPLICATION_SCOPED.get(BriefcasePreferences.BRIEFCASE_UNIQUE_USER_ID_PROPERTY, defaultUuidValue); if ( uniqueUserID.equals(defaultUuidValue)) { Preference.APPLICATION_SCOPED.put(BriefcasePreferences.BRIEFCASE_UNIQUE_USER_ID_PROPERTY, UUID.randomUUID().toString()); } return Preference.APPLICATION_SCOPED.get(BriefcasePreferences.BRIEFCASE_UNIQUE_USER_ID_PROPERTY, defaultUuidValue); }
Source:
public void close() { try (Closer closer = Closer.create()) { closer.register(() -> directReader.close()); closer.register(() -> dictionaryReader.close()); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
public void close() { try (Closer closer = Closer.create()) { closer.register(directReader::close); closer.register(dictionaryReader::close); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public void remove(@NotNull(message = "name cannot be NULL") final String name ) throws IOException { if (this.labelSet().contains(name)) { this.storage.apply( new Directives().xpath( String.format("%s/label[.='%s']", this.xpath(), name) ).remove() ); final MkIssueEvents events = new MkIssueEvents( this.storage, this.self, this.repo ); events.create( Event.UNLABELED, this.ticket, this.self, Optional.of(name) ); } }

Target:
public void remove(@NotNull(message = "name cannot be NULL") final String name ) throws IOException { if (this.labels().contains(name)) { this.storage.apply( new Directives().xpath( String.format("%s/label[.='%s']", this.xpath(), name) ).remove() ); new MkIssueEvents( this.storage, this.self, this.repo ).create( Event.UNLABELED, this.ticket, this.self, Optional.of(name) ); } }
Source:
private boolean isValid() { return !StringUtils.isBlank(topic) && payload.length > 0; }

Target:
private boolean isValid() { return !StringUtils.isBlank(topic); }
Source:
public void testVariantIdsFoundAndNotFound() { List<String> ids = new ArrayList<>(); ids.add("rs148957270"); ids.add("rs575961545"); ids.add("a1b1c1d1e1"); List<VariantRepositoryFilter> filters = new ArrayList<>(); List<String> exclude = new ArrayList<>(); List<VariantMongo> variantEntityList = variantRepository .findByIdsAndComplexFilters(ids, filters, exclude, null); assertNotNull(variantEntityList); assertTrue(variantEntityList.size() > 0); assertEquals(2, variantEntityList.size()); }

Target:
public void testVariantIdsFoundAndNotFound() { List<String> ids = new ArrayList<>(); ids.add("rs148957270"); ids.add("rs575961545"); ids.add("a1b1c1d1e1"); List<VariantRepositoryFilter> filters = new ArrayList<>(); List<String> exclude = new ArrayList<>(); List<VariantMongo> variantEntityList = variantRepository .findByIdsAndComplexFilters(ids, filters, exclude, null); assertNotNull(variantEntityList); assertTrue(variantEntityList.size() > 0); assertEquals(2, variantEntityList.size()); assertTrue(variantEntityList.get(0).getIds().contains(ids.get(0)) || variantEntityList.get(0).getIds().contains(ids.get(1))); assertTrue(variantEntityList.get(1).getIds().contains(ids.get(0)) || variantEntityList.get(1).getIds().contains(ids.get(1))); }
Source:
public void refreshGeneratedScript() throws InvalidParamsException, UnsupportedTypeException, NoScriptDefinitionSelectedException { ScriptDefinitionWrapper config = getScriptDefinition() .orElseThrow(() -> new NoScriptDefinitionSelectedException("Tried to generate a script with no config selected to generate it with")); try { if(areParamsValid()) { generator.doRunstrategy(AlgorithmType.GENERATE_PYTHON, currentlyLoadedDataFile, scriptGeneratorTable, config, GeneratedProgrammingLanguage.PYTHON); } else { throw new InvalidParamsException("Parameters are invalid, cannot generate script"); } } catch (InterruptedException | ExecutionException e) { firePropertyChange(THREAD_ERROR_PROPERTY, threadError, true); LOG.error(e); threadError = true; } }

Target:
public void refreshGeneratedScript() throws InvalidParamsException, UnsupportedLanguageException, NoScriptDefinitionSelectedException { ScriptDefinitionWrapper scriptDefinition = getScriptDefinition() .orElseThrow(() -> new NoScriptDefinitionSelectedException( "Tried to generate a script with no script definition selected to generate it with")); try { if (areParamsValid()) { String filePath = preferenceSupplier.scriptGeneratorScriptDefinitionFolders() + scriptDefinition.getName() + PYTHON_EXT; String jsonContent = scriptGenFileHandler.createJsonString(scriptGeneratorTable.getActions(), scriptGenFileHandler.readFileContent(filePath), filePath); generator.refreshGeneratedScript(scriptGeneratorTable, scriptDefinition, jsonContent); } else { throw new InvalidParamsException("Parameters are invalid, cannot generate script"); } } catch (InterruptedException | ExecutionException e) { firePropertyChange(THREAD_ERROR_PROPERTY, threadError, true); LOG.error(e); threadError = true; } catch (IOException e) { LOG.error(e); } }
Source:
public void shouldNotHaveTheRemoteCause() { try { Document wrongDoc = (Document) session.newRequest(FetchDocument.ID).set("value", "/test").execute(); fail("Unexpected " + wrongDoc); } catch (RemoteException e) { assertNotNull(e); assertNull(e.getRemoteCause()); } catch (Exception e) { fail(); } }

Target:
public void shouldNotHaveTheRemoteCause() throws IOException { try { Document wrongDoc = (Document) session.newRequest(FetchDocument.ID).set("value", "/test").execute(); fail("Unexpected " + wrongDoc); } catch (RemoteException e) { assertNotNull(e); assertNull(e.getRemoteCause()); } }
Source:
public Weld beanClasses(Class<?>... classes) { this.beanClasses.clear(); for (Class<?> beanClass : classes) { this.beanClasses.add(beanClass.getName()); } return this; }

Target:
public Weld beanClasses(Class<?>... classes) { beanClasses.clear(); for (Class<?> beanClass : classes) { addBeanClass(beanClass); } return this; }
Source:
public void testValidImports() throws IOException { setUpOpennmsHomeInTmpDir(); final String validXml = "<model-import xmlns=\"<LINK_0>\" date-stamp=\"2019-04-04T07:49:24.053+02:00\" foreign-source=\"ABC\" last-import=\"2019-04-04T07:49:30.777+02:00\"/>"; final Path etcDir = java.nio.file.Files.createDirectories(Paths.get(this.opennmsHomeDir.getPath(), "etc/imports")); final File file = new File(etcDir.toFile(), "ABC.xml"); Files.write(validXml, file, StandardCharsets.UTF_8); testConfigFile("imports"); }

Target:
public void testValidImports() throws IOException { final String validXml = "<model-import xmlns=\"<LINK_0>\" date-stamp=\"2019-04-04T07:49:24.053+02:00\" foreign-source=\"ABC\" last-import=\"2019-04-04T07:49:30.777+02:00\"/>"; testXmlFile("imports", validXml); }
Source:
public void run() { try { while ( !isCompleted() && !end ) { Unit candidate = current.next; if ( candidate != null ) { if ( id < candidate.processors ) { long time = nanoTime(); forkedProcess( id, candidate.processors, candidate.batch ); candidate.processorDone( nanoTime() - time ); } current = candidate; } else { PARK.park( this ); } } } catch ( Throwable e ) { issuePanic( e, false ); } }

Target:
public void run() { try { while ( !isCompleted() ) { Unit candidate = current.next; if ( candidate != null ) { if ( id < candidate.processors ) { long time = nanoTime(); forkedProcess( id, candidate.processors, candidate.batch ); candidate.processorDone( nanoTime() - time ); } current = candidate; } else { PARK.park( this ); } } } catch ( Throwable e ) { issuePanic( e, false ); } }
Source:
void printUsageInfo() { StringBuilder usage = new StringBuilder(); usage.append(" System Properties: \n"); usage.append(" -DselionHome=<folderPath>: \n"); usage.append(" Path of SeLion home directory. Defaults to <user.home>/.selion/ \n"); usage.append(" -D[property]=[value]: \n"); usage.append(" Any other System Property you wish to pass to the JVM \n"); System.out.print(usage.toString()); }

Target:
void printUsageInfo() { StringBuilder usage = new StringBuilder(); usage.append(" System Properties: \n"); usage.append(" -DselionHome=<folderPath>: \n"); usage.append(" Path of SeLion home directory. Defaults to <user.home>/.selion2/ \n"); usage.append(" -D[property]=[value]: \n"); usage.append(" Any other System Property you wish to pass to the JVM \n"); System.out.print(usage.toString()); }
Source:
public Rectangle getBounds() { bounds = new Rectangle(0,0,bv.hex_size.width, bv.hex_size.height); Point hexOrigin = bounds.getLocation(); Point ePos; if (secondaryPos == -1) { ePos = bv.getHexLocation(entity.getPosition()); } else { ePos = bv.getHexLocation(entity.getSecondaryPositions().get(secondaryPos)); } bounds.setLocation(hexOrigin.x + ePos.x, hexOrigin.y + ePos.y); return bounds; }

Target:
public Rectangle getBounds() { bounds = new Rectangle(0, 0, bv.hex_size.width, bv.hex_size.height); Point hexOrigin = bounds.getLocation(); Point ePos; if (secondaryPos < 0 || secondaryPos >= entity.getSecondaryPositions().size()) { ePos = bv.getHexLocation(entity.getPosition()); } else { ePos = bv.getHexLocation(entity.getSecondaryPositions().get(secondaryPos)); } bounds.setLocation(hexOrigin.x + ePos.x, hexOrigin.y + ePos.y); return bounds; }
Source:
public static Object[][] adsVUAPTopMercury() { return new Object[][]{ { new Page("project43", "SyntheticTests/VUAP"), ImmutableMap.of("src", "mobile", "slotName", AdsContent.MOBILE_TOP_LB) } }; }

Target:
public static Object[][] adsVUAPTopMercury() { return new Object[][]{ { new Page("project43", "SyntheticTests/VUAP"), AdsContent.MOBILE_TOP_LB, String.format( "google_ads_iframe_/5441/wka.life/_project43 AdsContent.MOBILE_TOP_LB ) } }; }
Source:
public void batch_update_using_sso_credential() { final WhoisResources whoisResources = mapRpslObjects( RpslObject.parse( "inetnum: 19.0.0.0 - 19.1.255.255\n" + "netname: TEST-NET-NAME\n" + "descr: TEST network\n" + "country: BE\n" + "admin-c: TP1-TEST\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER4-MNT\n" + "source: TEST") ); try { RestTest.target(getPort(), "whois/batch/TEST") .request() .cookie("crowd.token_key", "valid-token") .post(Entity.entity(whoisResources, MediaType.APPLICATION_JSON_TYPE), WhoisResources.class); } catch (BadRequestException bre) { final WhoisResources response = bre.getResponse().readEntity(WhoisResources.class); System.out.println(response); } assertNotNull(databaseHelper.lookupObject(ObjectType.INETNUM, "19.0.0.0 - 19.1.255.255")); }

Target:
public void batch_update_using_sso_credential() { final WhoisResources whoisResources = mapRpslObjects( RpslObject.parse( "inetnum: 19.0.0.0 - 19.1.255.255\n" + "netname: TEST-NET-NAME\n" + "descr: TEST network\n" + "country: BE\n" + "admin-c: TP1-TEST\n" + "tech-c: TP1-TEST\n" + "status: ASSIGNED PA\n" + "mnt-by: OWNER4-MNT\n" + "source: TEST") ); RestTest.target(getPort(), "whois/batch/TEST") .request() .cookie("crowd.token_key", "valid-token") .post(Entity.entity(whoisResources, MediaType.APPLICATION_JSON_TYPE), WhoisResources.class); assertNotNull(databaseHelper.lookupObject(ObjectType.INETNUM, "19.0.0.0 - 19.1.255.255")); }
Source:
public void emit(Event event) { if (!started.get()) { throw new ISE("WTF emit was called while service is not started yet"); } if (event instanceof ServiceMetricEvent) { final ServiceMetricEvent serviceMetricEvent = (ServiceMetricEvent) event; final GraphiteEvent graphiteEvent = graphiteEventConverter.druidMetricToGraphite(serviceMetricEvent); if (graphiteEvent == null) { return; } try { final boolean isSuccessful = eventsQueue.offer(graphiteEvent, DEFAULT_PUT_GET_TIMEOUT, TimeUnit.MILLISECONDS); if (!isSuccessful) { log.error( "Throwing metrics on the floor Graphite queue is full please increase the capacity or/and the consumer frequency" ); } } catch (InterruptedException e) { log.error(e, e.getMessage()); } } else if (graphiteEmitterConfig.getLogAlerts() && event instanceof AlertEvent) { try { log.warn(mapper.writeValueAsString(event)); } catch (JsonProcessingException e) { log.error(e, "error while serializing alert event[%s]", ((AlertEvent) event).getDescription()); } } }

Target:
public void emit(Event event) { if (!started.get()) { throw new ISE("WTF emit was called while service is not started yet"); } if (event instanceof ServiceMetricEvent) { final GraphiteEvent graphiteEvent = graphiteEventConverter.druidEventToGraphite((ServiceMetricEvent) event); if (graphiteEvent == null) { return; } try { final boolean isSuccessful = eventsQueue.offer(graphiteEvent, DEFAULT_PUT_GET_TIMEOUT, TimeUnit.MILLISECONDS); if (!isSuccessful) { log.error( "Throwing event [%s] on the floor Graphite queue is full please increase the capacity or/and the consumer frequency", mapper.writeValueAsString(event) ); } } catch (InterruptedException e) { log.error(e, "got interrupted with message [%s]", e.getMessage()); Thread.currentThread().interrupt(); } catch (JsonProcessingException e) { log.error(e, e.getMessage()); } } else if (!emitterList.isEmpty() && event instanceof AlertEvent) { for (Emitter emitter : emitterList) { emitter.emit(event); } } else { throw new ISE("unknown event type [%s]", event.getClass()); } }
Source:
public void getOrderGroupsByPatient_shouldGetOrderGroupsGivenPatient() { Patient existingPatient1 = Context.getPatientService().getPatient(8); List<OrderGroup> ordergroups1 = Context.getOrderService().getOrderGroupsByPatient(existingPatient1); assertEquals(1, ordergroups1.size()); }

Target:
public void getOrderGroupsByPatient_shouldGetOrderGroupsGivenPatient() { Patient existingPatient = Context.getPatientService().getPatient(8); List<OrderGroup> ordergroups = Context.getOrderService().getOrderGroupsByPatient(existingPatient); assertEquals(1, ordergroups.size()); }
Source:
private List<Map<String, AttributeValue>> getItemsBetweenLocalTime( final Long accountId, final DeviceId deviceId, final DateTime startUTCTime, final DateTime endUTCTime, final DateTime startLocalTime, final DateTime endLocalTime, final Collection<DeviceDataAttribute> attributes) { final String externalDeviceId = deviceId.externalDeviceId.get(); final Expression keyConditionExpression = Expressions.and( Expressions.compare(DeviceDataAttribute.ACCOUNT_ID, "=", toAttributeValue(accountId)), Expressions.between(DeviceDataAttribute.RANGE_KEY, getRangeKey(startUTCTime, externalDeviceId), getRangeKey(endUTCTime, externalDeviceId))); final Expression filterExpression = Expressions.between(DeviceDataAttribute.LOCAL_UTC_TIMESTAMP, dateTimeToAttributeValue(startLocalTime), dateTimeToAttributeValue(endLocalTime)); final List<Map<String, AttributeValue>> results = Lists.newArrayList(); for (final Map<String, AttributeValue> result : queryTables(getTableNames(startUTCTime, endUTCTime), keyConditionExpression, filterExpression, attributes)) { if (externalDeviceIdFromDDBItem(result).equals(externalDeviceId)) { results.add(result); } } return results; }

Target:
private List<Map<String, AttributeValue>> getItemsBetweenLocalTime( final Long accountId, final DeviceId deviceId, final DateTime startUTCTime, final DateTime endUTCTime, final DateTime startLocalTime, final DateTime endLocalTime, final Collection<DeviceDataAttribute> attributes) { final String externalDeviceId = deviceId.externalDeviceId.get(); final Expression keyConditionExpression = Expressions.and( Expressions.equals(DeviceDataAttribute.ACCOUNT_ID, toAttributeValue(accountId)), Expressions.between(DeviceDataAttribute.RANGE_KEY, getRangeKey(startUTCTime, externalDeviceId), getRangeKey(endUTCTime, externalDeviceId))); final Expression filterExpression = Expressions.between(DeviceDataAttribute.LOCAL_UTC_TIMESTAMP, dateTimeToAttributeValue(startLocalTime), dateTimeToAttributeValue(endLocalTime)); final List<Map<String, AttributeValue>> results = Lists.newArrayList(); for (final Map<String, AttributeValue> result : queryTables(getTableNames(startUTCTime, endUTCTime), keyConditionExpression, filterExpression, attributes)) { if (externalDeviceIdFromDDBItem(result).equals(externalDeviceId)) { results.add(result); } } return results; }
Source:
public int hashCode() { int result = interval != null ? interval.hashCode() : 0; result = 31 * result + (condition != null ? condition.hashCode() : 0); return result; }

Target:
public int hashCode() { return interval != null ? interval.hashCode() : condition.hashCode(); }
Source:
void saveReceipt(Date date, TimeZone timeZone, String price, String tax, String exchangeRate, String comment, PaymentMethod paymentMethod, boolean isReimbursable, boolean isFullPage, String name, Category category, String currency, String extraText1, String extraText2, String extraText3) { final Receipt receipt = fragment.getEditableItem(); final Trip parentTrip = fragment.getParentTrip(); final ReceiptBuilderFactory builderFactory = (receipt == null) ? new ReceiptBuilderFactory(-1) : new ReceiptBuilderFactory(receipt); builderFactory.setName(name) .setTrip(parentTrip) .setDate((Date) date.clone()) .setTimeZone(timeZone) .setPrice(price) .setTax(tax) .setExchangeRate(new ExchangeRateBuilderFactory().setBaseCurrency(currency) .setRate(parentTrip.getTripCurrency(), exchangeRate) .build()) .setCategory(category) .setCurrency(currency) .setComment(comment) .setPaymentMethod(paymentMethod) .setIsReimbursable(isReimbursable) .setIsFullPage(isFullPage) .setExtraEditText1(extraText1) .setExtraEditText2(extraText2) .setExtraEditText3(extraText3); if (fragment.shouldGenerateHash()) { builderFactory.setImgHash(hashImgFile(fragment.getFile())); } if (receipt == null) { receiptTableController.insert(builderFactory.setFile(fragment.getFile()).build(), new DatabaseOperationMetadata()); } else { receiptTableController.update(receipt, builderFactory.build(), new DatabaseOperationMetadata()); } }

Target:
void saveReceipt(Date date, TimeZone timeZone, String price, String tax, String exchangeRate, String comment, PaymentMethod paymentMethod, boolean isReimbursable, boolean isFullPage, String name, Category category, String currency, String extraText1, String extraText2, String extraText3) { final Receipt receipt = fragment.getEditableItem(); final Trip parentTrip = fragment.getParentTrip(); final ReceiptBuilderFactory builderFactory = (receipt == null) ? new ReceiptBuilderFactory(-1) : new ReceiptBuilderFactory(receipt); builderFactory.setName(name) .setTrip(parentTrip) .setDate((Date) date.clone()) .setTimeZone(timeZone) .setPrice(price) .setTax(tax) .setExchangeRate(new ExchangeRateBuilderFactory().setBaseCurrency(currency) .setRate(parentTrip.getTripCurrency(), exchangeRate) .build()) .setCategory(category) .setCurrency(currency) .setComment(comment) .setPaymentMethod(paymentMethod) .setIsReimbursable(isReimbursable) .setIsFullPage(isFullPage) .setExtraEditText1(extraText1) .setExtraEditText2(extraText2) .setExtraEditText3(extraText3); if (receipt == null) { receiptTableController.insert(builderFactory.setFile(fragment.getFile()).build(), new DatabaseOperationMetadata()); } else { receiptTableController.update(receipt, builderFactory.build(), new DatabaseOperationMetadata()); } }
Source:
public static String getAPIKey(String userid, String password) throws UnsupportedEncodingException{ String api_creds = userid + ":" + password; String apiKey = "Basic " + DatatypeConverter.printBase64Binary(api_creds .getBytes("UTF-8")); return apiKey; }

Target:
public static String getAPIKey(String userid, String password) throws UnsupportedEncodingException{ String api_creds = userid + ":" + password; String apiKey = "Basic " + DatatypeConverter.printBase64Binary(api_creds .getBytes(StandardCharsets.UTF_8)); return apiKey; }
Source:
public synchronized void rollback() throws DatabaseEngineRuntimeException { try { for (final MappedEntity mappedEntity : entities.values()) { mappedEntity.getInsert().clearBatch(); } conn.rollback(); conn.setAutoCommit(true); } catch (SQLException ex) { throw new DatabaseEngineRuntimeException("Something went wrong while rolling back the transaction", ex); } }

Target:
public synchronized void rollback() throws DatabaseEngineRuntimeException { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException ex) { throw new DatabaseEngineRuntimeException("Something went wrong while rolling back the transaction", ex); } }
Source:
protected synchronized Object getValueFromTable(String table, String key) { Object value = null; Cursor cursor = null; try { SQLiteDatabase db = getReadableDatabase(); cursor = queryDb( db, table, new String[]{KEY_FIELD, VALUE_FIELD}, KEY_FIELD + " = ?", new String[]{key}, null, null, null, null ); if (cursor.moveToFirst()) { value = table.equals(STORE_TABLE_NAME) ? cursor.getString(1) : cursor.getLong(1); } } catch (SQLiteException e) { logger.e(TAG, String.format("getValue from %s failed", table), e); Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("getValue from %s failed", table), e); Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); delete(); } catch (IllegalStateException e) { Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); delete(); } catch (RuntimeException e) { Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); convertIfCursorWindowException(e); } finally { if (cursor != null) { cursor.close(); } close(); } return value; }

Target:
protected synchronized Object getValueFromTable(String table, String key) { Object value = null; Cursor cursor = null; try { SQLiteDatabase db = getReadableDatabase(); cursor = queryDb( db, table, new String[]{KEY_FIELD, VALUE_FIELD}, KEY_FIELD + " = ?", new String[]{key}, null, null, null, null ); if (cursor.moveToFirst()) { value = table.equals(STORE_TABLE_NAME) ? cursor.getString(1) : cursor.getLong(1); } } catch (SQLiteException e) { logger.e(TAG, String.format("getValue from %s failed", table), e); Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); delete(); } catch (StackOverflowError e) { logger.e(TAG, String.format("getValue from %s failed", table), e); Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); delete(); } catch (IllegalStateException e) { Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); handleIfCursorRowTooLargeException(e); } catch (RuntimeException e) { Diagnostics.getLogger().logError( String.format("DB: Failed to getValue: %s", key), e ); convertIfCursorWindowException(e); } finally { if (cursor != null) { cursor.close(); } close(); } return value; }