auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private DBOptions dataDbOptions() { DBOptions options = new DBOptions() .setCreateIfMissing(true) .setCreateMissingColumnFamilies(true); return options; }

Target:
private DBOptions dataDbOptions() { DBOptions dbOptions; if (databaseProperties != null) { dbOptions = DBOptions.getDBOptionsFromProps(databaseProperties); if (dbOptions == null) { throw log.rocksDBUnknownPropertiesSupplied(databaseProperties.toString()); } } else { dbOptions = new DBOptions(); } return dbOptions .setCreateIfMissing(true) .setCreateMissingColumnFamilies(true); }
Source:
private String getRegistryPrefix(String propertyName) { String[] parts = propertyName.replaceFirst(CONFIG_PREFIX, "").split("\\."); if (parts.length < 2) { throw new IllegalArgumentException(format("You missed '.' in property '%s'. Valid credential registry format is '%s'", propertyName, VALID_DOCKER_PROPERTY_NAME_EXAMPLE)); } if (parts.length > 2) { throw new IllegalArgumentException(format("You set redundant '.' in property '%s'. Valid credential registry format is '%s'", propertyName, VALID_DOCKER_PROPERTY_NAME_EXAMPLE)); } String propertyIdentifier = parts[1]; if (!URL.equals(propertyIdentifier) && !USER_NAME.equals(propertyIdentifier) && !PASSWORD.equals(propertyIdentifier)) { LOG.warn("Set unused property: " + propertyName); } return CONFIG_PREFIX + parts[0] + "."; }

Target:
private String getRegistryPrefix(String propertyName) { String[] parts = propertyName.replaceFirst(CONFIG_PREFIX, "").split("\\."); if (parts.length < 2) { throw new IllegalArgumentException(format("In the property '%s' is missing '.'. Valid credential registry format is '%s'", propertyName, VALID_DOCKER_PROPERTY_NAME_EXAMPLE)); } if (parts.length > 2) { throw new IllegalArgumentException(format("Property '%s' contains redundant '.'. Valid credential registry format is '%s'", propertyName, VALID_DOCKER_PROPERTY_NAME_EXAMPLE)); } String propertyIdentifier = parts[1]; if (!URL.equals(propertyIdentifier) && !USER_NAME.equals(propertyIdentifier) && !PASSWORD.equals(propertyIdentifier)) { LOG.warn("Set unused property: {}.", propertyName); } return CONFIG_PREFIX + parts[0] + "."; }
Source:
private void login() { cookies = null; try { String url = "http://" + ip + "/cgi/login?username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); URL loginurl = new URL(url); URLConnection connection = loginurl.openConnection(); cookies = connection.getHeaderFields().get("Set-Cookie"); } catch (Exception e) { logger.debug("Cannot log into Waterkotte EcoTouch."); } }

Target:
private void login() { cookies = null; String url = null; try { url = "http://" + ip + "/cgi/login?username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); URL loginurl = new URL(url); URLConnection connection = loginurl.openConnection(); cookies = connection.getHeaderFields().get("Set-Cookie"); } catch (MalformedURLException e) { logger.debug("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.debug("Cannot log into Waterkotte EcoTouch: " + e.toString()); } }
Source:
private void assertQueryUsesIndex(final String baseTableName, final String viewName, Connection conn, boolean isChildView) throws SQLException { String sql = "SELECT A0, A1, A2, A4 FROM " + viewName +" WHERE A4 IN ('1', '2', '3') ORDER BY A4, A2"; ResultSet rs = conn.prepareStatement("EXPLAIN " + sql).executeQuery(); String childViewScanKey = isChildView ? ",'Y'" : ""; assertEquals( "CLIENT PARALLEL 1-WAY SKIP SCAN ON 3 KEYS OVER _IDX_" + baseTableName + " [-32768,'1'" + childViewScanKey + "] - [-32768,'3'" + childViewScanKey + "]\n" + " SERVER FILTER BY FIRST KEY ONLY", QueryUtil.getExplainPlan(rs)); rs = conn.createStatement().executeQuery(sql); assertTrue(rs.next()); assertEquals("1", rs.getString(1)); assertEquals("X", rs.getString(2)); assertEquals("Y", rs.getString(3)); assertEquals("1", rs.getString(4)); assertTrue(rs.next()); assertEquals("2", rs.getString(1)); assertEquals("X", rs.getString(2)); assertEquals("Y", rs.getString(3)); assertEquals("2", rs.getString(4)); assertFalse(rs.next()); }

Target:
private void assertQueryUsesIndex(final String baseTableName, final String viewName, Connection conn, boolean isChildView) throws SQLException { String sql = "SELECT A0, A1, A2, A4 FROM " + viewName +" WHERE A4 IN ('1', '2', '3') ORDER BY A4, A2"; ResultSet rs = conn.prepareStatement("EXPLAIN " + sql).executeQuery(); String childViewScanKey = isChildView ? ",'Y'" : ""; assertEquals( "CLIENT PARALLEL 1-WAY SKIP SCAN ON 3 KEYS OVER _IDX_" + baseTableName + " ["+ Short.MIN_VALUE +",'1'" + childViewScanKey + "] - [" + Short.MIN_VALUE + ",'3'" + childViewScanKey + "]\n" + " SERVER FILTER BY FIRST KEY ONLY", QueryUtil.getExplainPlan(rs)); rs = conn.createStatement().executeQuery(sql); assertTrue(rs.next()); assertEquals("1", rs.getString(1)); assertEquals("X", rs.getString(2)); assertEquals("Y", rs.getString(3)); assertEquals("1", rs.getString(4)); assertTrue(rs.next()); assertEquals("2", rs.getString(1)); assertEquals("X", rs.getString(2)); assertEquals("Y", rs.getString(3)); assertEquals("2", rs.getString(4)); assertFalse(rs.next()); }
Source:
@Test public void testCubeWithGroupBy() { final String query = "select count(*) " + "from \"foodmart\".\"product\" " + "group by cube(\"product_id\",\"product_class_id\")"; final String expected = "SELECT COUNT(*)\n" + "FROM \"foodmart\".\"product\"\n" + "GROUP BY CUBE(\"product_id\", \"product_class_id\")"; final String expectedInSpark = "SELECT COUNT(*)\n" + "FROM foodmart.product\n" + "GROUP BY product_id, product_class_id WITH CUBE"; final String expectedPresto = "SELECT COUNT(*)\n" + "FROM \"foodmart\".\"product\"\n" + "GROUP BY CUBE(\"product_id\", \"product_class_id\")"; sql(query) .ok(expected) .withSpark() .ok(expectedInSpark) .withPresto() .ok(expectedPresto); }

Target:
@Test void testCubeWithGroupBy() { final String query = "select count(*) " + "from \"foodmart\".\"product\" " + "group by cube(\"product_id\",\"product_class_id\")"; final String expected = "SELECT COUNT(*)\n" + "FROM \"foodmart\".\"product\"\n" + "GROUP BY CUBE(\"product_id\", \"product_class_id\")"; final String expectedInSpark = "SELECT COUNT(*)\n" + "FROM foodmart.product\n" + "GROUP BY product_id, product_class_id WITH CUBE"; final String expectedPresto = "SELECT COUNT(*)\n" + "FROM \"foodmart\".\"product\"\n" + "GROUP BY CUBE(\"product_id\", \"product_class_id\")"; sql(query) .ok(expected) .withSpark() .ok(expectedInSpark) .withPresto() .ok(expectedPresto); }
Source:
public static void setUp() { SWTBotUtils.initialize(); SWTBotPreferences.TIMEOUT = 10000; SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; fBot = new SWTWorkbenchBot(); SWTBotUtils.closeView("Welcome", fBot); SWTBotUtils.createProject(TRACE_PROJECT_NAME); SWTBotUtils.switchToTracingPerspective(); WaitUtils.waitForJobs(); final CtfTestTrace cygProfile = CtfTestTrace.CYG_PROFILE; LttngUstTrace trace = LttngUstTestTraceUtils.getTrace(cygProfile); fStart = ((CtfTmfTrace) trace).getStartTime().toNanos(); fFullRange = new TmfTimeRange(TmfTimestamp.fromNanos(fStart), TmfTimestamp.fromNanos(fStart + 100l)); final File file = new File(trace.getPath()); LttngUstTestTraceUtils.dispose(cygProfile); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, file.getAbsolutePath(), UST_ID); SWTBotUtils.openView(CallStackView.ID); fViewBot = fBot.viewByTitle("Call Stack"); WaitUtils.waitForJobs(); MarkerConfigXmlParser.initMarkerSets(); }

Target:
public static void setUp() { SWTBotUtils.initialize(); SWTBotPreferences.TIMEOUT = 10000; SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; fBot = new SWTWorkbenchBot(); SWTBotUtils.closeView("Welcome", fBot); SWTBotUtils.createProject(TRACE_PROJECT_NAME); SWTBotUtils.switchToTracingPerspective(); WaitUtils.waitForJobs(); final CtfTestTrace cygProfile = CtfTestTrace.CYG_PROFILE; LttngUstTrace trace = LttngUstTestTraceUtils.getTrace(cygProfile); fStart = ((CtfTmfTrace) trace).getStartTime().toNanos(); fFullRange = new TmfTimeRange(TmfTimestamp.fromNanos(fStart), TmfTimestamp.fromNanos(fStart + 100l)); final File file = new File(trace.getPath()); LttngUstTestTraceUtils.dispose(cygProfile); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, file.getAbsolutePath(), UST_ID); SWTBotUtils.openView(CallStackView.ID); fViewBot = fBot.viewByTitle("Call Stack"); WaitUtils.waitForJobs(); }
Source:
public static void syncTableAndIndexProperties(PhoenixConnection conn, Admin admin) throws SQLException, IOException { Set<TableDescriptor> tableDescriptorsToSynchronize = new HashSet<>(); for (TableDescriptor origTableDesc : admin.listTableDescriptors()) { if (MetaDataUtil.isViewIndex(origTableDesc.getTableName().getNameWithNamespaceInclAsString())) { continue; } PTable table; String tableName = origTableDesc.getTableName().getNameAsString(); try { table = PhoenixRuntime.getTable(conn, tableName); } catch (TableNotFoundException e) { logger.warn("Error getting PTable for HBase table: " + tableName); continue; } if (table.getType() == PTableType.INDEX) { if (table.getIndexType() == IndexType.GLOBAL && !table.isTransactional() && !table.isImmutableRows() && !origTableDesc.hasCoprocessor(GlobalIndexChecker.class.getName())) { TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(origTableDesc); builder.addCoprocessor(GlobalIndexChecker.class.getName(), null, QueryServicesOptions.DEFAULT_COPROCESSOR_PRIORITY - 1, null); tableDescriptorsToSynchronize.add(builder.build()); } continue; } syncUpdateCacheFreqAllIndexes(conn, table); ColumnFamilyDescriptor defaultColFam = origTableDesc.getColumnFamily(SchemaUtil.getEmptyColumnFamily(table)); Map<String, Object> syncedProps = MetaDataUtil.getSyncedProps(defaultColFam); addTableDescIfPropsChanged(origTableDesc, defaultColFam, syncedProps, tableDescriptorsToSynchronize); syncGlobalIndexesForTable(conn.getQueryServices(), table, defaultColFam, syncedProps, tableDescriptorsToSynchronize); syncViewIndexTable(conn.getQueryServices(), table, defaultColFam, syncedProps, tableDescriptorsToSynchronize); } for (TableDescriptor t: tableDescriptorsToSynchronize) { admin.modifyTable(t); } }

Target:
public static void syncTableAndIndexProperties(PhoenixConnection conn, Admin admin) throws SQLException, IOException { Set<TableDescriptor> tableDescriptorsToSynchronize = new HashSet<>(); for (TableDescriptor origTableDesc : admin.listTableDescriptors()) { if (MetaDataUtil.isViewIndex(origTableDesc.getTableName().getNameWithNamespaceInclAsString())) { continue; } PTable table; String tableName = origTableDesc.getTableName().getNameAsString(); try { table = PhoenixRuntime.getTable(conn, tableName); } catch (TableNotFoundException e) { logger.warn("Error getting PTable for HBase table: " + tableName); continue; } if (table.getType() == PTableType.INDEX) { continue; } syncUpdateCacheFreqAllIndexes(conn, table); ColumnFamilyDescriptor defaultColFam = origTableDesc.getColumnFamily(SchemaUtil.getEmptyColumnFamily(table)); Map<String, Object> syncedProps = MetaDataUtil.getSyncedProps(defaultColFam); addTableDescIfPropsChanged(origTableDesc, defaultColFam, syncedProps, tableDescriptorsToSynchronize); syncGlobalIndexesForTable(conn.getQueryServices(), table, defaultColFam, syncedProps, tableDescriptorsToSynchronize); syncViewIndexTable(conn.getQueryServices(), table, defaultColFam, syncedProps, tableDescriptorsToSynchronize); } for (TableDescriptor t: tableDescriptorsToSynchronize) { admin.modifyTable(t); } }
Source:
public void returnsCorrectPartLength() throws IOException { final int length = 5000; final String body = Joiner.on(RqMultipartTest.CRLF).join( "--zzz", "Content-Disposition: form-data; name=\"x-1\"", "", StringUtils.repeat("X", length), "--zzz--" ); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: www.example.com", contentLengthHeader(body.getBytes().length), "Content-Type: multipart/form-data; boundary=zzz" ), body ); final RqMultipart.Smart regsmart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( regsmart.single("x-1").body().available(), Matchers.equalTo(length) ); } finally { req.body().close(); regsmart.part("x-1").iterator().next().body().close(); } }

Target:
public void returnsCorrectPartLength() throws IOException { final int length = 5000; final String part = "x-1"; final String body = Joiner.on(RqMultipartTest.CRLF).join( "--zzz", String.format(RqMultipartTest.CONTENT, part), "", StringUtils.repeat("X", length), "--zzz--" ); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: www.example.com", contentLengthHeader(body.getBytes().length), "Content-Type: multipart/form-data; boundary=zzz" ), body ); final RqMultipart.Smart regsmart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( regsmart.single(part).body().available(), Matchers.equalTo(length) ); } finally { req.body().close(); regsmart.part(part).iterator().next().body().close(); } }
Source:
public void setUp() { this.T_integer = new ConstT("Integer"); this.T_float = new ConstT("Floating"); this.T_string = new ConstT("String"); this.T_numeric = new TypeClass("Num", T_integer, T_float); this.T_a = new VarT("a", T_numeric); this.T_b = new VarT("b", T_numeric); this.T_c = new VarT("c", T_numeric, T_string); }

Target:
public void setUp() { this.T_integer = new ConstT("Integer"); this.T_float = new ConstT("Float"); this.T_string = new ConstT("String"); this.T_numeric = new TypeClass("Num", T_integer, T_float); this.T_a = new VarT("a", T_numeric); this.T_b = new VarT("b", T_numeric); this.T_c = new VarT("c", T_numeric, T_string); }
Source:
public void foo4() { int prog, user; prog = (int)(Math.random() * 10) + 1; Scanner input = new Scanner(System.in, "utf-8"); if( input.hasNextInt() ) { do { user = input.nextInt(); if(user == prog) { String.CASE_INSENSITIVE_ORDER.equals("Good!"); } else { if (user > 0 && user <= 10) { String.CASE_INSENSITIVE_ORDER.equals("Bad! "); if( prog < user ) { String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); } else { String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); } } else { String.CASE_INSENSITIVE_ORDER.equals("Brrr!"); } } } while( user != prog ); } else { String.CASE_INSENSITIVE_ORDER.equals("Brrr!"); } String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); }

Target:
public void foo4() { int prog, user; prog = (int)(Math.random() * 10) + 1; Scanner input = new Scanner(System.in, "utf-8"); if( input.hasNextInt() ) { do { user = input.nextInt(); if(user == prog) { String.CASE_INSENSITIVE_ORDER.equals("Good!"); } else { if (user > 0 && user <= 10) { String.CASE_INSENSITIVE_ORDER.equals("Bad! "); if( prog < user ) { String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); } else { String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); } } else { String.CASE_INSENSITIVE_ORDER.equals("Violation!"); } } } while( user != prog ); } else { String.CASE_INSENSITIVE_ORDER.equals("Violation!"); } String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); }
Source:
public static double krcc(List<Double> uItems, List<Double> vItems) { int common = 0, all = 0; double sum = 0; List<Integer> temp = new ArrayList<>(); Set<Double> items = new HashSet<>(); items.addAll(uItems); items.addAll(vItems); all = items.size(); common = uItems.size() + vItems.size() - all; for (int i = 0; i < uItems.size(); i++) { if (uItems.get(i) > 0 && vItems.get(i) > 0) { temp.add(i); } } for (int m = 0; m < temp.size(); m++) { for (int n = m + 1; n < temp.size(); n++) { if ((uItems.get(temp.get(m)) - uItems.get(temp.get(n))) * (vItems.get(temp.get(m)) - vItems.get(temp.get(n))) < 0) { sum += 1; } } } return 1 - 4 * sum / (common * (common - 1)); }

Target:
public static double krcc(List<Double> uItems, List<Double> vItems) { int common = 0, all = 0; double sum = 0; List<Integer> temp = new ArrayList<>(); Set<Double> items = new HashSet<>(); items.addAll(uItems); items.addAll(vItems); all = items.size(); common = uItems.size() + vItems.size() - all; for (int i = 0; i < uItems.size(); i++) { if (uItems.get(i) > 0 && vItems.get(i) > 0) { temp.add(i); } } for (int m = 0; m < temp.size(); m++) { for (int n = m + 1; n < temp.size(); n++) { if ((uItems.get(temp.get(m)) - uItems.get(temp.get(n))) * (vItems.get(temp.get(m)) - vItems.get(temp.get(n))) < 0) { sum += 1; } } } return 1 - 4 * sum / common / (common - 1); }
Source:
public Identity(MerchantConfig merchantConfig,X509Certificate x509Certificate) throws SignException { this.merchantConfig = merchantConfig; this.x509Cert=x509Certificate; if(merchantConfig.getEnablejdkcert()){ setUpJdkServer(); } else{ setUpServer(); } }

Target:
public Identity(MerchantConfig merchantConfig,X509Certificate x509Certificate) throws SignException { this.merchantConfig = merchantConfig; this.x509Cert=x509Certificate; if(merchantConfig.isJdkCertEnabled()){ setupJdkServerCerts(); } else{ setUpServer(); } }
Source:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { initializeConfigs(getConfiguration(updater)); return new KerberosHadoopAuthentication(kerberosAuthentication); }

Target:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); configuration.set("hadoop.security.authentication", "kerberos"); String authToLocalRules = configuration.get("hadoop.security.auth_to_local"); if (authToLocalRules == null) { KerberosName.setRules("DEFAULT"); } UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }
Source:
public void load(Map<?, ?> options) throws IOException { if (!isLoaded) { useURIFragmentAsId = Boolean.TRUE.equals(options.get(DescriptionResourceImpl.OPTION_USE_URI_FRAGMENT_AS_ID)) && getURI().isPlatformPlugin(); Diagnostic migrationMismatchDiagnostic = migrationHandler.handleMigrationOptions(getURI(), this.getDefaultLoadOptions(), this.getDefaultSaveOptions()); super.load(options); if (migrationMismatchDiagnostic != null) { getErrors().add(migrationMismatchDiagnostic); } } }

Target:
public void load(Map<?, ?> options) throws IOException { if (!isLoaded) { useURIFragmentAsId = Boolean.TRUE.equals(options.get(DescriptionResourceImpl.OPTION_USE_URI_FRAGMENT_AS_ID)) && getURI().isPlatformPlugin(); Diagnostic migrationMismatchDiagnostic = null; if (migrationHandler.isPresent()) { migrationMismatchDiagnostic = migrationHandler.get().handleMigrationOptions(getURI(), this.getDefaultLoadOptions(), this.getDefaultSaveOptions()); } super.load(options); if (migrationMismatchDiagnostic != null) { getErrors().add(migrationMismatchDiagnostic); } } }
Source:
private void preloadEventTypes(final EventTypeRepository eventTypeRepository) { final long start = System.currentTimeMillis(); eventTypeRepository.list().stream().map(EventType::getName).forEach((name) -> { try { this.getEventType(name); } catch (NoSuchEventTypeException | InternalNakadiException e) { LOG.warn("Failed to preload event type {}", name, e); } }); LOG.info("Cache preload complete, load event types within ms", this.eventTypeCache.size(), System.currentTimeMillis() - start); }

Target:
private void preloadEventTypes(final EventTypeRepository eventTypeRepository) { final long start = System.currentTimeMillis(); rwLock.writeLock().lock(); try { final Map<String, CachedValue> preloaded = eventTypeRepository.list().stream().collect(Collectors.toMap( EventType::getName, et -> new CachedValue(et, EventValidation.forType(et)) )); new ArrayList<>(preloaded.keySet()).forEach(eventType -> { try { created(eventType); } catch (final Exception e) { LOG.error("Failed to create node for {}", eventType, e); preloaded.remove(eventType); } }); this.eventTypeCache.putAll(preloaded); LOG.info("Cache preload complete, load event types within ms", preloaded.size(), System.currentTimeMillis() - start); } finally { rwLock.writeLock().unlock(); } }
Source:
protected void testAccessControl() throws Exception { String[] submissionParams = new String[] { Const.ParamsNames.USER_ID, account.googleId, Const.ParamsNames.BLOB_KEY, account.studentProfile.pictureKey }; verifyAnyRegisteredUserCanAccess(submissionParams); }

Target:
protected void testAccessControl() throws Exception { testActionWithEmailAndCourseUnauthorisedInstructorOrStudent(); testActionWithEmailAndCourseUnauthorisedInstructorOrStudentMasquerade(); }
Source:
public String toString() { return "Task["+(Strings.isNonEmpty(displayName) ? displayName : job + (tags!=null && !tags.isEmpty() ? ";"+tags : "")) + ":"+getId()+"]"; }

Target:
public String toString() { return "Task["+ (Strings.isNonEmpty(displayName) ? displayName : (job + (tags!=null && !tags.isEmpty() ? ";"+tags : "")) ) + ":"+getId()+"]"; }
Source:
public void getBucketSerials_shouldReturnAnArrayOfIllegalSerials_whenBucketsAreNull() { RegionAttributes regionAttributes = mock(RegionAttributes.class); PartitionAttributes partitionAttributes = mock(PartitionAttributes.class); when(partitionedRegion.getAttributes()).thenReturn(regionAttributes); when(regionAttributes.getPartitionAttributes()).thenReturn(partitionAttributes); when(partitionAttributes.getTotalNumBuckets()).thenReturn(3); assertThat(regionAdvisor.getBucketSerials()).containsExactly(serials); }

Target:
public void getBucketSerials_shouldReturnAnArrayOfIllegalSerials_whenBucketsAreNull() { RegionAttributes regionAttributes = mock(RegionAttributes.class); PartitionAttributes partitionAttributes = mock(PartitionAttributes.class); when(partitionedRegion.getAttributes()).thenReturn(regionAttributes); when(regionAttributes.getPartitionAttributes()).thenReturn(partitionAttributes); when(partitionAttributes.getTotalNumBuckets()).thenReturn(serials.length); assertThat(regionAdvisor.getBucketSerials()).containsExactly(serials); }
Source:
public CoreCollection(Path path){ this.path = path; this.allowedFileSuffix = new HashSet<>(Arrays.asList(".json.xz", "json")); }

Target:
public CoreCollection(Path path){ this.path = path; this.allowedFileSuffix = Set.of(".json.xz", "json"); }
Source:
protected CacheEntryEvent<K, V> shouldInvoke(CacheEntryEvent<K, V> event, boolean isLocalNodePrimaryOwner) { if (onlyPrimary && !isLocalNodePrimaryOwner) return null; if (event instanceof EventImpl) { EventImpl<K, V> eventImpl = (EventImpl<K, V>)event; if (eventImpl.isPre() && clustered) return null; EventType eventType; if (filter != null && (eventType = getEvent(eventImpl)) != null) { if (filter == converter && filter instanceof CacheEventFilterConverter) { Object newValue = ((CacheEventFilterConverter)filter).filterAndConvert(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType); if (newValue != null) { eventImpl.setValue((V) newValue); } else { return null; } } else if (!filter.accept(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType)) { return null; } } } return event; }

Target:
protected CacheEntryEvent<K, V> shouldInvoke(CacheEntryEvent<K, V> event, boolean isLocalNodePrimaryOwner) { if (onlyPrimary && !isLocalNodePrimaryOwner) return null; if (event instanceof EventImpl) { EventImpl<K, V> eventImpl = (EventImpl<K, V>)event; if (eventImpl.isPre() && clustered) return null; EventType eventType; if (filter != null && (eventType = getEvent(eventImpl)) != null) { if (filter == converter && filter instanceof CacheEventFilterConverter) { Object newValue = ((CacheEventFilterConverter)filter).filterAndConvert(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType); if (newValue != null) { EventImpl<K, V> clone = eventImpl.clone(); clone.setValue((V) newValue); return clone; } else { return null; } } else if (!filter.accept(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType)) { return null; } } } return event; }
Source:
public TestRunner addOverrideConfig(String key, String value) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(value); configs.put(String.format("jobs.%s.%s", JOB_NAME, key), value); return this; }

Target:
public TestRunner addOverrideConfig(String key, String value) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(value); String configKeyPrefix = String.format(JobConfig.CONFIG_JOB_PREFIX(), JOB_NAME); configs.put(String.format("%s%s", configKeyPrefix, key), value); return this; }
Source:
public void deleteSurveyThrowsGoodExceptionIfSurveyDoesntExist() throws Exception { setupContext(API_STUDY_ID, DEVELOPER, UNCONSENTED, null); when(service.getSurvey(TestConstants.TEST_STUDY, KEYS, false, false)).thenReturn(null); Result result = controller.deleteSurvey(SURVEY_GUID, CREATED_ON.toString(), "false"); TestUtils.assertResult(result, 200, "Survey deleted."); }

Target:
public void deleteSurveyThrowsGoodExceptionIfSurveyDoesntExist() throws Exception { setupContext(API_STUDY_ID, DEVELOPER, UNCONSENTED, null); when(service.getSurvey(ImmutableSet.of(DEVELOPER), TestConstants.TEST_STUDY, KEYS, false, false)).thenReturn(null); controller.deleteSurvey(SURVEY_GUID, CREATED_ON.toString(), "false"); }
Source:
private boolean hasServerPropertyChanged(MavenProject project, MavenProject backupProject) { Properties p = getPropertiesWithKeyPrefix(project.getProperties(), "liberty.bootstrap."); Properties q = getPropertiesWithKeyPrefix(backupProject.getProperties(), "liberty.bootstrap."); if (!Objects.equals(p, q)) { return true; } else { p = getPropertiesWithKeyPrefix(project.getProperties(), "liberty.jvm."); q = getPropertiesWithKeyPrefix(backupProject.getProperties(), "liberty.jvm."); if (!Objects.equals(p, q)) { return true; } else { p = getPropertiesWithKeyPrefix(project.getProperties(), "liberty.env."); q = getPropertiesWithKeyPrefix(backupProject.getProperties(), "liberty.env."); if (!Objects.equals(p, q)) { return true; } } } return false; }

Target:
private boolean hasServerPropertyChanged(MavenProject project, MavenProject backupProject) { Properties projProp = project.getProperties(); Properties backupProjProp = backupProject.getProperties(); if (!Objects.equals(getPropertiesWithKeyPrefix(projProp, LIBERTY_BOOTSTRAP_PROP), getPropertiesWithKeyPrefix(backupProjProp, LIBERTY_BOOTSTRAP_PROP))) { return true; } if (!Objects.equals(getPropertiesWithKeyPrefix(projProp, LIBERTY_JVM_PROP), getPropertiesWithKeyPrefix(backupProjProp, LIBERTY_JVM_PROP))) { return true; } if (!Objects.equals(getPropertiesWithKeyPrefix(projProp, LIBERTY_ENV_PROP), getPropertiesWithKeyPrefix(backupProjProp, LIBERTY_ENV_PROP))) { return true; } return false; }
Source:
public Observable<Void> change(final Interest<InstanceInfo> newInterest) { if (state.get() == STATE.Closed) { return Observable.error(CHANNEL_CLOSED_EXCEPTION); } Observable<Void> serverRequest = connect() .switchMap(new Func1<MessageConnection, Observable<Void>>() { @Override public Observable<Void> call(MessageConnection serverConnection) { return sendExpectAckOnConnection(serverConnection, new InterestRegistration(newInterest)); } }); return Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { if (STATE.Closed == state.get()) { subscriber.onError(CHANNEL_CLOSED_EXCEPTION); } else if (moveToState(STATE.Idle, STATE.Open)) { logger.debug("First time registration: {}", newInterest); channelInterestStream.subscribe(channelInterestSubscriber); remoteBatchingRegistry.subscribe(channelInterestStream); } else { logger.debug("Channel changes: {}", newInterest); } remoteBatchingRegistry.retainAll(newInterest); subscriber.onCompleted(); } }).concatWith(serverRequest); }

Target:
public Observable<Void> change(final Interest<InstanceInfo> newInterest) { if (state.get() == STATE.Closed) { return Observable.error(CHANNEL_CLOSED_EXCEPTION); } Observable<Void> serverRequest = connect() .switchMap(new Func1<MessageConnection, Observable<Void>>() { @Override public Observable<Void> call(MessageConnection serverConnection) { return sendExpectAckOnConnection(serverConnection, new InterestRegistration(newInterest)); } }); return Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { if (STATE.Closed == state.get()) { subscriber.onError(CHANNEL_CLOSED_EXCEPTION); } else if (moveToState(STATE.Idle, STATE.Open)) { logger.debug("First time registration: {}", newInterest); channelInterestStream.subscribe(channelInterestSubscriber); remoteBatchingRegistry.connectTo(channelInterestStream); } else { logger.debug("Channel changes: {}", newInterest); } remoteBatchingRegistry.retainAll(newInterest); subscriber.onCompleted(); } }).concatWith(serverRequest); }
Source:
public List<ResponseInfo> sendAndPoll(List<RequestInfo> requestInfos, int pollTimeoutMs) { if (closed) { throw new IllegalStateException("The NetworkClient is closed."); } long startTime = time.milliseconds(); List<ResponseInfo> responseInfoList = new ArrayList<>(); try { for (RequestInfo requestInfo : requestInfos) { ClientNetworkRequestMetrics clientNetworkRequestMetrics = new ClientNetworkRequestMetrics(networkMetrics.requestQueueTime, networkMetrics.requestSendTime, networkMetrics.requestSendTotalTime, 0); pendingRequests.add(new RequestMetadata(time.milliseconds(), requestInfo, clientNetworkRequestMetrics)); } List<NetworkSend> sends = prepareSends(responseInfoList); selector.poll(pollTimeoutMs, sends); handleSelectorEvents(responseInfoList); } catch (Exception e) { networkMetrics.networkClientException.inc(); } finally { numPendingRequests.set(pendingRequests.size()); networkMetrics.networkClientSendAndPollTime.update(time.milliseconds() - startTime); } return responseInfoList; }

Target:
public List<ResponseInfo> sendAndPoll(List<RequestInfo> requestInfos, int pollTimeoutMs) { if (closed || !selector.isOpen()) { throw new IllegalStateException("The NetworkClient is closed."); } long startTime = time.milliseconds(); List<ResponseInfo> responseInfoList = new ArrayList<>(); try { for (RequestInfo requestInfo : requestInfos) { ClientNetworkRequestMetrics clientNetworkRequestMetrics = new ClientNetworkRequestMetrics(networkMetrics.requestQueueTime, networkMetrics.requestSendTime, networkMetrics.requestSendTotalTime, 0); pendingRequests.add(new RequestMetadata(time.milliseconds(), requestInfo, clientNetworkRequestMetrics)); } List<NetworkSend> sends = prepareSends(responseInfoList); selector.poll(pollTimeoutMs, sends); handleSelectorEvents(responseInfoList); } catch (Exception e) { logger.error("Received an unexpected error during sendAndPoll(): ", e); networkMetrics.networkClientException.inc(); } finally { numPendingRequests.set(pendingRequests.size()); networkMetrics.networkClientSendAndPollTime.update(time.milliseconds() - startTime); } return responseInfoList; }
Source:
public void onRunFinish(boolean succeeded, BatchSourceContext context) { super.onRunFinish(succeeded, context); if (StringUtils.isNotEmpty(this.config.tableName)) { try { File file = new File(this.config.tableName); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null) { long processingTime = new Date().getTime(); processedFileTrackingTable.write(line.getBytes(Charsets.UTF_8), String.valueOf(processingTime).getBytes(Charsets.UTF_8)); } reader.close(); file.delete(); } catch (IOException exception) { exception.printStackTrace(); } } }

Target:
public void onRunFinish(boolean succeeded, BatchSourceContext context) { super.onRunFinish(succeeded, context); try { FileStatus[] status = fileSystem.listStatus(tempDirectoryPath); long processingTime = new Date().getTime(); Path[] paths = FileUtil.stat2Paths(status); if (paths != null && paths.length > 0) { for (Path path : paths) { try (FSDataInputStream input = fileSystem.open(path)) { String key = input.readUTF(); processedFileTrackingTable.write(Bytes.toBytes(key), Bytes.toBytes(processingTime)); } } } } catch (IOException exception) { LOG.error("IOException occurred while reading temp directory path : " + exception.getMessage()); } }
Source:
AuthenticationSessionModel createAuthenticationSessionForClient(String clientID) throws UriBuilderException, IllegalArgumentException { AuthenticationSessionModel authSession; ClientModel client = session.realms().getClientByClientId(clientID, realm); String redirectUri = null; if (client == null) { client = SystemClientUtil.getSystemClient(realm); } else { redirectUri = client.getRedirectUris() .stream() .findFirst() .orElse(null); } if (redirectUri == null) { redirectUri = Urls.accountBase(session.getContext().getUri().getBaseUri()).path("/").build(realm.getName()).toString(); } RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true); authSession = rootAuthSession.createAuthenticationSession(client); authSession.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name()); END_AFTER_REQUIRED_ACTIONS, "true"); authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); authSession.setRedirectUri(redirectUri); authSession.setClientNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE); authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri); authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())); return authSession; }

Target:
AuthenticationSessionModel createAuthenticationSessionForClient(String clientID) throws UriBuilderException, IllegalArgumentException { AuthenticationSessionModel authSession; ClientModel client = session.realms().getClientByClientId(clientID, realm); String redirectUri; if (client == null) { client = SystemClientUtil.getSystemClient(realm); redirectUri = Urls.accountBase(session.getContext().getUri().getBaseUri()).path("/").build(realm.getName()).toString(); } else { redirectUri = RedirectUtils.getFirstValidRedirectUri(session, client.getRootUrl(), client.getRedirectUris()); } RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true); authSession = rootAuthSession.createAuthenticationSession(client); authSession.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name()); END_AFTER_REQUIRED_ACTIONS, "true"); authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); authSession.setRedirectUri(redirectUri); authSession.setClientNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE); authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri); authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())); return authSession; }
Source:
public void invokeLocalBuildPipeLine( LocalBuildRequest buildRequest, Consumer< LocalBinaryConfig > consumer ) { Pipeline pipe = pipelineRegistry.getPipelineByName( BuildPipelineInitializer.LOCAL_BUILD_PIPELINE ); Input input = new Input( ) { { put( LocalSourceConfig.ROOT_PATH, buildRequest.getProject( ).getRootPath( ).toURI( ) ); put( LocalBuildConfig.BUILD_TYPE, buildRequest.getBuildType( ).name( ) ); if ( buildRequest.isSingleResource( ) ) { put( LocalBuildConfig.RESOURCE, encodePath( buildRequest.getResource( ) ) ); } else { addResourceChanges( this, buildRequest.getResourceChanges( ) ); } if ( buildRequest.getDeploymentType( ) != null ) { put( LocalBuildConfig.DEPLOYMENT_TYPE, buildRequest.getDeploymentType( ).name( ) ); put( LocalBuildConfig.SUPPRESS_HANDLERS, Boolean.toString( buildRequest.isSuppressHandlers( ) ) ); } } }; buildPipelineInitializer.getExecutor( ).execute( input, pipe, ( Consumer< LocalBinaryConfig > ) binary -> { consumer.accept( binary ); } ); }

Target:
public void invokeLocalBuildPipeLine( LocalBuildRequest buildRequest, Consumer< LocalBinaryConfig > consumer ) { Pipeline pipe = pipelineRegistry.getPipelineByName( BuildPipelineInitializer.LOCAL_BUILD_PIPELINE ); Input input = new Input( ) { { put( LocalSourceConfig.ROOT_PATH, buildRequest.getProject( ).getRootPath( ).toURI( ) ); put( LocalBuildConfig.BUILD_TYPE, buildRequest.getBuildType( ).name( ) ); if ( buildRequest.isSingleResource( ) ) { put( LocalBuildConfig.RESOURCE, encodePath( buildRequest.getResource( ) ) ); } else { addResourceChanges( this, buildRequest.getResourceChanges( ) ); } if ( buildRequest.getDeploymentType( ) != null ) { put( LocalBuildConfig.DEPLOYMENT_TYPE, buildRequest.getDeploymentType( ).name( ) ); put( LocalBuildConfig.SUPPRESS_HANDLERS, Boolean.toString( buildRequest.isSuppressHandlers( ) ) ); } } }; executor.execute( input, pipe, consumer ); }
Source:
public void run() { Iterable<HTInterval> currentIntervals; try { boolean done = false; currentIntervals = intervalQueue.take(); while (!done) { for (HTInterval currentInterval : currentIntervals) { if (currentInterval.getAttribute() == -1) { done = true; break; } getSHT().insertInterval(currentInterval); } if (!done) { currentIntervals = intervalQueue.take(); } } for (HTInterval currentInterval : currentIntervals) { getSHT().closeTree(currentInterval.getEndTime()); return; } } catch (InterruptedException e) { Activator.getDefault().logError("State History Tree interrupted!", e); } catch (TimeRangeException e) { Activator.getDefault().logError("Error starting the state system", e); } }

Target:
public void run() { Iterable<HTInterval> currentIntervals; try { currentIntervals = intervalQueue.take(); while (true) { for (HTInterval currentInterval : currentIntervals) { if (currentInterval.getAttribute() == -1) { getSHT().closeTree(currentInterval.getEndTime()); return; } getSHT().insertInterval(currentInterval); } currentIntervals = intervalQueue.take(); } } catch (InterruptedException e) { Activator.getDefault().logError("State History Tree interrupted!", e); } catch (TimeRangeException e) { Activator.getDefault().logError("Error starting the state system", e); } }
Source:
public void testNotSoundsLikeAndNotMatches() { final String ruleName = "test not soundslike constraint"; final RuleModel model = new RuleModel(); model.name = ruleName; final FactPattern pattern = new FactPattern("Person"); final CompositeFieldConstraint notMatchesAndNotSounsLike = new CompositeFieldConstraint(); notMatchesAndNotSounsLike.setCompositeJunctionType(CompositeFieldConstraint.COMPOSITE_TYPE_AND); pattern.addConstraint(notMatchesAndNotSounsLike); final SingleFieldConstraint fieldNotSoundsLikeGoo = new SingleFieldConstraint(); fieldNotSoundsLikeGoo.setFieldType(DataType.TYPE_STRING); fieldNotSoundsLikeGoo.setFieldName("field"); fieldNotSoundsLikeGoo.setOperator("not soundslike"); fieldNotSoundsLikeGoo.setValue("goo"); fieldNotSoundsLikeGoo.setConstraintValueType(SingleFieldConstraint.TYPE_LITERAL); notMatchesAndNotSounsLike.addConstraint(fieldNotSoundsLikeGoo); final SingleFieldConstraint fieldNotMatchesGoo = new SingleFieldConstraint(); fieldNotMatchesGoo.setFieldType(DataType.TYPE_STRING); fieldNotMatchesGoo.setFieldName("field"); fieldNotMatchesGoo.setOperator("not matches"); fieldNotMatchesGoo.setValue("goo"); fieldNotMatchesGoo.setConstraintValueType(SingleFieldConstraint.TYPE_LITERAL); notMatchesAndNotSounsLike.addConstraint(fieldNotMatchesGoo); model.addLhsItem(pattern); String expected = "rule \"" + ruleName + "\"" + "\tdialect \"mvel\"\n when " + "Person( field not soundslike \"goo\" && field not matches \"goo\" )" + "then" + "end"; checkMarshalling(expected, model); }

Target:
public void testNotSoundsLikeAndNotMatches() { final String ruleName = "test not soundslike constraint"; final RuleModel model = new RuleModel(); model.name = ruleName; final FactPattern pattern = new FactPattern("Person"); final CompositeFieldConstraint notMatchesAndNotSoundsLike = new CompositeFieldConstraint(); notMatchesAndNotSoundsLike.setCompositeJunctionType(CompositeFieldConstraint.COMPOSITE_TYPE_AND); pattern.addConstraint(notMatchesAndNotSoundsLike); final SingleFieldConstraint fieldNotSoundsLikeGoo = new SingleFieldConstraint(); fieldNotSoundsLikeGoo.setFieldType(DataType.TYPE_STRING); fieldNotSoundsLikeGoo.setFieldName("field"); fieldNotSoundsLikeGoo.setOperator("not soundslike"); fieldNotSoundsLikeGoo.setValue("goo"); fieldNotSoundsLikeGoo.setConstraintValueType(SingleFieldConstraint.TYPE_LITERAL); notMatchesAndNotSoundsLike.addConstraint(fieldNotSoundsLikeGoo); final SingleFieldConstraint fieldNotMatchesGoo = new SingleFieldConstraint(); fieldNotMatchesGoo.setFieldType(DataType.TYPE_STRING); fieldNotMatchesGoo.setFieldName("field"); fieldNotMatchesGoo.setOperator("not matches"); fieldNotMatchesGoo.setValue("goo"); fieldNotMatchesGoo.setConstraintValueType(SingleFieldConstraint.TYPE_LITERAL); notMatchesAndNotSoundsLike.addConstraint(fieldNotMatchesGoo); model.addLhsItem(pattern); String expected = "rule \"" + ruleName + "\"" + "\tdialect \"mvel\"\n when " + "Person( field not soundslike \"goo\" && field not matches \"goo\" )" + "then" + "end"; checkMarshalling(expected, model); }
Source:
public void testUntrackedNotIgnoredFolders() throws Exception { Git git = new Git(db); IndexDiff diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders()); writeTrashFile("readme", ""); writeTrashFile("src/com/A.java", ""); writeTrashFile("src/com/B.java", ""); writeTrashFile("src/org/A.java", ""); writeTrashFile("src/org/B.java", ""); writeTrashFile("target/com/A.java", ""); writeTrashFile("target/com/B.java", ""); writeTrashFile("target/org/A.java", ""); writeTrashFile("target/org/B.java", ""); writeTrashFile(".gitignore", "/target"); git.add().addFilepattern("readme").call(); git.commit().setMessage("initial").call(); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(new HashSet<String>(Arrays.asList("src")), diff.getUntrackedFolders()); git.add().addFilepattern("src").call(); writeTrashFile("src/tst/A.java", ""); writeTrashFile("src/tst/B.java", ""); deleteTrashFile(".gitignore"); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(new HashSet<String>(Arrays.asList("target", "src/tst")), diff.getUntrackedFolders()); }

Target:
public void testUntrackedNotIgnoredFolders() throws Exception { Git git = new Git(db); IndexDiff diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders()); writeTrashFile("readme", ""); writeTrashFile("sr/com/X.java", ""); writeTrashFile("src/com/A.java", ""); writeTrashFile("src/org/B.java", ""); writeTrashFile("srcs/org/Y.java", ""); writeTrashFile("target/com/A.java", ""); writeTrashFile("target/org/B.java", ""); writeTrashFile(".gitignore", "/target\n/sr"); git.add().addFilepattern("readme").addFilepattern(".gitignore") .addFilepattern("srcs/").call(); git.commit().setMessage("initial").call(); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(new HashSet<String>(Arrays.asList("src")), diff.getUntrackedFolders()); git.add().addFilepattern("src").call(); writeTrashFile("sr/com/X1.java", ""); writeTrashFile("src/tst/A.java", ""); writeTrashFile("src/tst/B.java", ""); writeTrashFile("srcs/com/Y1.java", ""); deleteTrashFile(".gitignore"); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals( new HashSet<String>(Arrays.asList("srcs/com", "sr", "src/tst", "target")), diff.getUntrackedFolders()); }
Source:
public void testParseGrantQuery() throws Exception { String sql0 = "GRANT 'RX' ON SYSTEM.\"SEQUENCE\" TO 'user'"; parseQuery(sql0); String sql1 = "GRANT 'RWXCA' ON TABLE some_table0 TO 'user0'"; parseQuery(sql1); String sql2 = "GRANT 'RWX' ON some_table1 TO 'user1'"; parseQuery(sql2); String sql3 = "GRANT 'CA' ON SCHEMA some_schema2 TO 'user2'"; parseQuery(sql3); String sql4 = "GRANT 'RXW' ON some_table3 TO GROUP 'group3'"; parseQuery(sql4); String sql5 = "GRANT 'RXW' ON \"some_schema5\".\"some_table5\" TO GROUP 'group5'"; parseQuery(sql5); String sql6 = "GRANT 'RWA' TO 'user6'"; parseQuery(sql6); String sql7 = "GRANT 'A' TO GROUP 'group7'"; parseQuery(sql7); }

Target:
public void testParseGrantQuery() throws Exception { String sql0 = "GRANT 'RX' ON SYSTEM.\"SEQUENCE\" TO 'user'"; parseQuery(sql0); String sql1 = "GRANT 'RWXCA' ON TABLE some_table0 TO 'user0'"; parseQuery(sql1); String sql2 = "GRANT 'RWX' ON some_table1 TO 'user1'"; parseQuery(sql2); String sql3 = "GRANT 'CA' ON SCHEMA some_schema2 TO 'user2'"; parseQuery(sql3); String sql4 = "GRANT 'RXW' ON some_table3 TO GROUP 'group3'"; parseQuery(sql4); String sql5 = "GRANT 'RXW' ON \"some_schema5\".\"some_table5\" TO GROUP 'group5'"; parseQuery(sql5); String sql6 = "GRANT 'RWA' TO 'user6'"; parseQuery(sql6); String sql7 = "GRANT 'A' TO GROUP 'group7'"; parseQuery(sql7); String sql8 = "GRANT 'ARXRRRRR' TO GROUP 'group8'"; parseQueryThatShouldFail(sql8); }
Source:
public int compare(Type type1, Type type2) { String errorMessage = "No label for the %s type, using its id instead."; String translatedLabel1 = null; String label1 = type1.getLabel(); if (label1 == null) { String type1Id = type1.getId(); log.error(String.format(errorMessage, type1Id)); translatedLabel1 = type1Id; } else { translatedLabel1 = messages.get(label1); if (translatedLabel1 == null) { translatedLabel1 = label1; } } String translatedLabel2 = null; String label2 = type2.getLabel(); if (label2 == null) { String type2Id = type2.getId(); log.error(String.format(errorMessage, type2Id)); translatedLabel2 = type2Id; } else { translatedLabel2 = messages.get(label2); if (translatedLabel2 == null) { translatedLabel2 = label2; } } return translatedLabel1.compareTo(translatedLabel2); }

Target:
public int compare(Type type1, Type type2) { return getTranslatedLabel(type1).compareTo(getTranslatedLabel(type2)); }
Source:
protected void addProjectedField(String s) { try { Field f = inClazz.getDeclaredField(s); TypeInfo t = new TypeInfo(f.getName(), ClassUtils.primitiveToWrapper(f.getType())); t.getter = PojoUtils.createGetter(inClazz, t.name, t.type); logger.debug("Creating setter {}", projectedClazz, t.name, t.type); t.setter = PojoUtils.createSetter(projectedClazz, t.name, t.type); projectedFields.add(t); } catch (NoSuchFieldException e) { throw new RuntimeException("Field " + s + " not found in class " + inClazz, e); } }

Target:
protected void addProjectedField(String s) { try { Field f = inClazz.getDeclaredField(s); TypeInfo t = new TypeInfo(f.getName(), ClassUtils.primitiveToWrapper(f.getType())); t.getter = PojoUtils.createGetter(inClazz, t.name, t.type); t.setter = PojoUtils.createSetter(projectedClazz, t.name, t.type); projectedFields.add(t); } catch (NoSuchFieldException e) { throw new RuntimeException("Field " + s + " not found in class " + inClazz, e); } }