auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
EmbeddedElasticsearchNode() throws Exception { elasticsearchDirectory = File.createTempFile("elasticsearch-test", Long.toString(System.nanoTime())); elasticsearchDirectory.delete(); elasticsearchDirectory.mkdir(); String clusterName = "test"; Settings setting = Settings.builder() .put("cluster.name", clusterName) .put("path.home", elasticsearchDirectory.getPath()) .put("path.data", new File(elasticsearchDirectory, "data").getAbsolutePath()) .put("path.logs", new File(elasticsearchDirectory, "logs").getAbsolutePath()) .put("transport.type.default", "local") .put("transport.type", "netty4") .put("http.type", "netty4") .put("http.enabled", "true") .put("path.home", "elasticsearch-test-data") .build(); node = new ElasticsearchNode(setting, Arrays.asList(Netty4Plugin.class)); }

Target:
EmbeddedElasticsearchNode() { try { elasticsearchDirectory = File.createTempFile("elasticsearch-test", Long.toString(System.nanoTime())); elasticsearchDirectory.delete(); elasticsearchDirectory.mkdir(); } catch (IOException e) { throw new UncheckedIOException(e); } String clusterName = "test"; Settings setting = Settings.builder() .put("cluster.name", clusterName) .put("path.home", elasticsearchDirectory.getPath()) .put("path.data", new File(elasticsearchDirectory, "data").getAbsolutePath()) .put("path.logs", new File(elasticsearchDirectory, "logs").getAbsolutePath()) .put("transport.type.default", "local") .put("transport.type", "netty4") .put("http.type", "netty4") .put("http.enabled", "true") .put("path.home", "elasticsearch-test-data") .build(); node = new ElasticsearchNode(setting, Arrays.asList(Netty4Plugin.class)); }
Source:
synchronized public String getPreviewOfLastMessage(){ if (mMessages.size() > 0){ return getLastMessage().getPreview(); } else{ return ""; } }

Target:
synchronized public String getPreviewOfLastMessage(){ return mMessages.size() > 0 ? getLastMessage().getPreview() : ""; }
Source:
void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket, boolean s3SelectPushdownEnabled) { this.awsAccessKey = awsAccessKey; this.awsSecretKey = awsSecretKey; this.writableBucket = writableBucket; super.setup(host, port, databaseName, this::createHdfsConfiguration, s3SelectPushdownEnabled); }

Target:
protected void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket, boolean s3SelectPushdownEnabled) { checkArgument(!isNullOrEmpty(host), "Expected non empty host"); checkArgument(!isNullOrEmpty(databaseName), "Expected non empty databaseName"); checkArgument(!isNullOrEmpty(awsAccessKey), "Expected non empty awsAccessKey"); checkArgument(!isNullOrEmpty(awsSecretKey), "Expected non empty awsSecretKey"); checkArgument(!isNullOrEmpty(writableBucket), "Expected non empty writableBucket"); this.awsAccessKey = awsAccessKey; this.awsSecretKey = awsSecretKey; this.writableBucket = writableBucket; super.setup(host, port, databaseName, this::createHdfsConfiguration, s3SelectPushdownEnabled); }
Source:
public static OrbotStatusReceiver getInstance() { if(instance == null) instance = new OrbotStatusReceiver(); return instance; }

Target:
public static OrbotStatusReceiver getInstance() { if(instance == null) { instance = new OrbotStatusReceiver(); } return instance; }
Source:
public String getTechnicalCode() { return "invalid-virtual-host"; }

Target:
public String getTechnicalCode() { return "virtualHost.invalid"; }
Source:
private void initConfig(SystemProperties config) { logger.info("Running {}, core version: {}-{}", config.genesisInfo(), config.projectVersion(), config.projectVersionModifier()); BuildInfo.printInfo(); if (config.databaseReset()){ FileUtil.recursiveDelete(config.databaseDir()); logger.info("Database reset done"); } checkDatabaseVersion.validateDatabaseVersion(config); if (config.getConfig().getBoolean("database.autoResetOldVersion")) { FileUtil.recursiveDelete(config.databaseDir()); logger.info("Auto database reset due to not compatible database version"); } if (logger.isInfoEnabled()) { StringBuilder versions = new StringBuilder(); for (EthVersion v : EthVersion.supported()) { versions.append(v.getCode()).append(", "); } versions.delete(versions.length() - 2, versions.length()); logger.info("capability eth version: [{}]", versions); } logger.info("capability shh version: [{}]", ShhHandler.VERSION); logger.info("capability bzz version: [{}]", BzzHandler.VERSION); }

Target:
private void initConfig(SystemProperties config) { logger.info("Running {}, core version: {}-{}", config.genesisInfo(), config.projectVersion(), config.projectVersionModifier()); BuildInfo.printInfo(); if (config.databaseReset()){ FileUtil.recursiveDelete(config.databaseDir()); logger.info("Database reset done"); } databaseVersionHandler.process(config); if (logger.isInfoEnabled()) { StringBuilder versions = new StringBuilder(); for (EthVersion v : EthVersion.supported()) { versions.append(v.getCode()).append(", "); } versions.delete(versions.length() - 2, versions.length()); logger.info("capability eth version: [{}]", versions); } logger.info("capability shh version: [{}]", ShhHandler.VERSION); logger.info("capability bzz version: [{}]", BzzHandler.VERSION); }
Source:
public void shouldFailFastIfNoDriverFound() { AtomicInteger connectionAttempts = new AtomicInteger(); final JdbcDatabaseContainer container = new JdbcDatabaseContainer("mysql:5.7.22") { @Override public String getDriverClassName() { return "nonexistent.ClassName"; } @Override public String getJdbcUrl() { return ""; } @Override public String getUsername() { return ""; } @Override public String getPassword() { return ""; } @Override protected String getTestQueryString() { return ""; } @Override public Connection createConnection(String queryString) throws SQLException, NoDriverFoundException { connectionAttempts.incrementAndGet(); return super.createConnection(queryString); } }; try { container.start(); fail("The container is expected to fail to start"); } catch (Exception e) { final Throwable rootCause = Throwables.getRootCause(e); assertTrue("ClassNotFoundException is the root cause", rootCause instanceof ClassNotFoundException); } finally { container.stop(); } assertEquals("only one connection attempt should have been made", 1, connectionAttempts.get()); }

Target:
public void shouldFailFastIfNoDriverFound() { final MissingDriverContainer container = new MissingDriverContainer(); try { container.start(); fail("The container is expected to fail to start"); } catch (Exception e) { final Throwable rootCause = Throwables.getRootCause(e); assertTrue("ClassNotFoundException is the root cause", rootCause instanceof ClassNotFoundException); } finally { container.stop(); } assertEquals("only one connection attempt should have been made", 1, container.getConnectionAttempts()); }
Source:
public void loadBinderTypeRegistry() throws Exception { try { ConfigurableApplicationContext context = createBinderTestContext( new String[]{}); } catch (BeanCreationException e) { assertThat(e.getMessage(),containsString("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath")); } }

Target:
public void loadBinderTypeRegistry() throws Exception { try { ConfigurableApplicationContext context = createBinderTestContext(new String[]{}); fail(); } catch (BeanCreationException e) { assertThat(e.getMessage(),containsString("Cannot create binder factory, no `META-INF/spring.binders` " + "resources found on the classpath")); } }
Source:
private synchronized void checkExpired() { if (timerID >= 0) { long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); } }

Target:
private synchronized void checkExpired() { long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); }
Source:
public static void setup() { FloatMixing.pumpWhen(QuasarHelios.globalControl, FloatMixing.addition.of((FloatInputPoll) spinOverride, motorSpeed), allRollers); Igneous.joystick3.getButtonSource(1).send(new EventOutput() { public void event() { frontRollers.set(1.0f); } }); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Arm", armRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Front", frontRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Internal", internalRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Open", open); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtMost(pneumaticOverride, -0.3f)), Igneous.makeSolenoid(1)); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtLeast(pneumaticOverride, 0.3f)), Igneous.makeSolenoid(2)); }

Target:
public static void setup() { FloatMixing.pumpWhen(QuasarHelios.globalControl, FloatMixing.addition.of((FloatInputPoll) spinOverride, motorSpeed), allRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Arm", armRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Front", frontRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Speed Internal", internalRollers); Cluck.publish(QuasarHelios.testPrefix + "Roller Open", open); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtMost(pneumaticOverride, -0.3f)), Igneous.makeSolenoid(1)); BooleanMixing.pumpWhen(QuasarHelios.globalControl, BooleanMixing.xorBooleans(open, FloatMixing.floatIsAtLeast(pneumaticOverride, 0.3f)), Igneous.makeSolenoid(2)); }
Source:
public void highestCardWins() { String highest8 = "4D 5S 6S 8D 3C"; String highest10 = "2S 4C 7S 9H 10H"; String highestJ = "3S 4S 5D 6H JH"; assertEquals(Arrays.asList(highestJ), new Poker(Arrays.asList(highest8, highest10, highestJ)).getBestHands()); }

Target:
public void highestCardWins() { String highest8 = "4D 5S 6S 8D 3C"; String highest10 = "2S 4C 7S 9H 10H"; String highestJ = "3S 4S 5D 6H JH"; assertEquals(Collections.singletonList(highestJ), new Poker(Arrays.asList(highest8, highest10, highestJ)).getBestHands()); }
Source:
public final String lastString() { return lastValue().toString(); }

Target:
public final String lastString() { V ret = lastValue(); return ret == null ? null : ret.toString(); }
Source:
public int cancelObservations(Client client) { String registrationId = client.getRegistrationId(); if (registrationId == null) return 0; Set<Observation> observations = getObservations(registrationId); int removed = 0; for (Observation observation : observations) { removed = doCancelObservation(observation) ? ++removed : removed; } return removed; }

Target:
public int cancelObservations(Client client) { String registrationId = client.getRegistrationId(); if (registrationId == null) return 0; Set<Observation> observations = getObservations(registrationId); int removed = 0; for (Observation observation : observations) { if (doCancelObservation(observation)) { removed++; } } return removed; }
Source:
public SchedulerImpl( @Nonnull SlotSelectionStrategy slotSelectionStrategy, @Nonnull SlotPool slotPool, @Nonnull Map<SlotSharingGroupId, SlotSharingManager> slotSharingManagers) { this.slotSelectionStrategy = slotSelectionStrategy; this.slotSharingManagers = slotSharingManagers; this.slotPool = slotPool; this.componentMainThreadExecutor = new ComponentMainThreadExecutor.DummyComponentMainThreadExecutor( "Scheduler is not initialized with proper main thread executor. " + "Call to Scheduler.start(...) required."); this.slotRequestBulkChecker = PhysicalSlotRequestBulkCheckerImpl.fromSlotPool(slotPool, SystemClock.getInstance()); this.bulkSlotProvider = new BulkSlotProviderImpl(slotSelectionStrategy, slotPool, slotRequestBulkChecker); this.physicalSlotProvider = new PhysicalSlotProviderImpl(slotSelectionStrategy, slotPool); }

Target:
public SchedulerImpl( @Nonnull SlotSelectionStrategy slotSelectionStrategy, @Nonnull SlotPool slotPool, @Nonnull Map<SlotSharingGroupId, SlotSharingManager> slotSharingManagers) { this.slotSelectionStrategy = slotSelectionStrategy; this.slotSharingManagers = slotSharingManagers; this.slotPool = slotPool; this.componentMainThreadExecutor = new ComponentMainThreadExecutor.DummyComponentMainThreadExecutor( "Scheduler is not initialized with proper main thread executor. " + "Call to Scheduler.start(...) required."); }
Source:
public void purgeConcept_shouldPurgeTheConceptIfNotBeingUsedByAnObs() throws Exception { conceptService.purgeConcept(conceptService.getConcept(88)); assertNull(conceptService.getConcept(88)); }

Target:
public void purgeConcept_shouldPurgeTheConceptIfNotBeingUsedByAnObs() throws Exception { int conceptId = 88; conceptService.purgeConcept(conceptService.getConcept(conceptId)); assertNull(conceptService.getConcept(conceptId)); }
Source:
public String getResourcesUrl() { return getHostPortScheme(baseURI)+ getResourcesPath(); }

Target:
public String getResourcesUrl() { return Urls.themeRoot(baseURI).toString() + "/" + theme.getType().toString().toLowerCase() +"/" + theme.getName(); }
Source:
Object listMoves() { Map<String, Boolean> moves = new HashMap<>(this.activeMoveRequests.size()); Iterator<Entry<String, MoveRequest>> moveIt = activeMoveRequests.entrySet().iterator(); while (moveIt.hasNext()) { Entry<String, MoveRequest> move = moveIt.next(); long finishedAt = move.getValue().finishedAt; if (finishedAt == -1 || finishedAt + TIME_TO_LIVE_AFTER_FINISH > System.currentTimeMillis()) { moves.put(move.getKey(), finishedAt == -1); } else { moveIt.remove(); } } return moves; }

Target:
Object listMoves() { Map<String, Object> results = new HashMap<>(2); List<String> active = new ArrayList<>(); List<String> complete = new ArrayList<>(); Iterator<Entry<String, MoveRequest>> moveIt = moveRequests.entrySet().iterator(); while (moveIt.hasNext()) { Entry<String, MoveRequest> move = moveIt.next(); long finishedAt = move.getValue().finishedAt; if (finishedAt == -1 || finishedAt + TIME_TO_LIVE_AFTER_FINISH > System.currentTimeMillis()) { if (finishedAt == -1) { active.add(move.getKey()); } else { complete.add(move.getKey()); } } else { moveIt.remove(); } } results.put("active", active); results.put("complete", complete); return results; }
Source:
private SiriusServerDashboardDto getDashboard() { int projectsCount = this.getModelingProjects().mapToInt(e -> 1).sum(); int viewpointsCount = ViewpointRegistry.getInstance().getViewpoints().size(); List<SiriusServerDashboardProjectDto> projects = this.getModelingProjects() .limit(8) .map(this::convertToProject) .collect(Collectors.toList()); return new SiriusServerDashboardDto(projectsCount, viewpointsCount, projects); }

Target:
private SiriusServerDashboardDto getDashboard() { int projectsCount = this.getModelingProjects().mapToInt(e -> 1).sum(); int viewpointsCount = ViewpointRegistry.getInstance().getViewpoints().size(); int metamodelsCount = EPackage.Registry.INSTANCE.size(); List<SiriusServerDashboardProjectDto> projects = this.getModelingProjects() .limit(7) .map(this::convertToProject) .collect(Collectors.toList()); return new SiriusServerDashboardDto(projectsCount, viewpointsCount, metamodelsCount, projects); }
Source:
protected IInteractionContext getContext() { IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IEditorPart activeEditor = activePage.getActiveEditor(); IInteractionContext context = null; if (activeEditor != null && activePage.getActivePart().equals(activeEditor)) { context = (IInteractionContext) activeEditor.getEditorInput().getAdapter(IInteractionContext.class); } if (context == null && ContextCorePlugin.getContextManager().isContextActive()) { context = ContextCorePlugin.getContextManager().getActiveContext(); } if (context == null) { throw new IllegalStateException("error determining action context"); } return context; }

Target:
protected IInteractionContext getContext() { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IInteractionContext context = null; if (!(activeWorkbenchWindow == null || activeWorkbenchWindow.getActivePage() == null)) { IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor != null && activePage.getActivePart().equals(activeEditor)) { context = (IInteractionContext) activeEditor.getEditorInput().getAdapter(IInteractionContext.class); } } if (context == null && ContextCorePlugin.getContextManager().isContextActive()) { context = ContextCorePlugin.getContextManager().getActiveContext(); } if (context == null) { throw new IllegalStateException("error determining action context"); } return context; }
Source:
private static Optional<FileStoreAttributes> readFromConfig( FileStore s) { FileBasedConfig userConfig = SystemReader.getInstance() .openUserConfig(null, FS.DETECTED); try { userConfig.load(); } catch (IOException e) { LOG.error(MessageFormat.format(JGitText.get().readConfigFailed, userConfig.getFile().getAbsolutePath()), e); } catch (ConfigInvalidException e) { LOG.error(MessageFormat.format( JGitText.get().repositoryConfigFileInvalid, userConfig.getFile().getAbsolutePath(), e.getMessage())); } String key = getConfigKey(s); Duration resolution = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); if (UNDEFINED_DURATION.equals(resolution)) { return Optional.empty(); } Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); FileStoreAttributes c = new FileStoreAttributes(resolution); if (!UNDEFINED_DURATION.equals(minRacyThreshold)) { c.minimalRacyInterval = minRacyThreshold; } return Optional.of(c); }

Target:
private static Optional<FileStoreAttributes> readFromConfig( FileStore s) { FileBasedConfig userConfig = SystemReader.getInstance() .openUserConfig(null, FS.DETECTED); try { userConfig.load(false); } catch (IOException e) { LOG.error(MessageFormat.format(JGitText.get().readConfigFailed, userConfig.getFile().getAbsolutePath()), e); } catch (ConfigInvalidException e) { LOG.error(MessageFormat.format( JGitText.get().repositoryConfigFileInvalid, userConfig.getFile().getAbsolutePath(), e.getMessage())); } String key = getConfigKey(s); Duration resolution = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); if (UNDEFINED_DURATION.equals(resolution)) { return Optional.empty(); } Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit( ConfigConstants.CONFIG_FILESYSTEM_SECTION, key, ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD, UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS)); FileStoreAttributes c = new FileStoreAttributes(resolution); if (!UNDEFINED_DURATION.equals(minRacyThreshold)) { c.minimalRacyInterval = minRacyThreshold; } return Optional.of(c); }
Source:
public ParquetTupleScheme(FilterPredicate filterPredicate) { this.filterPredicate = Objects.requireNonNull(filterPredicate, "filterPredicate"); }

Target:
public ParquetTupleScheme(FilterPredicate filterPredicate) { this.filterPredicate = Objects.requireNonNull(filterPredicate, "filterPredicate cannot be null"); }
Source:
protected void writeToFile(String data) { Connection conn = null; try { conn = DriverManager.getConnection(dbUrl); } catch (SQLException e) { e.printStackTrace(); } try { Statement sta = conn.createStatement(); String payload = "CREATE TABLE PROPERTIES (Name VARCHAR(100), Type VARCHAR(20), Value VARCHAR(50))"; int count = sta.executeUpdate(payload); sta.close(); } catch (SQLException e) { } String[] splitData = data.split(lineSeperator); for (String line : splitData) { String[] values = line.split(propertyDelimiter); String payload = "UPDATE PROPERTIES SET TYPE='" + values[0] + "', VALUE='" + values[2] + "' WHERE NAME = '" + values[1] + "'"; Statement sta; try { sta = conn.createStatement(); int count = sta.executeUpdate(payload); if (count == 0) { payload = "INSERT INTO PROPERTIES VALUES ('" + values[1] + "', '" + values[0] + "', '" + values[2] + "')"; Statement insert = conn.createStatement(); count = insert.executeUpdate(payload); } } catch (SQLException e) { e.printStackTrace(); } } }

Target:
protected void writeToFile(String data) { Connection conn = null; try { conn = DriverManager.getConnection(dbUrl); } catch (SQLException e) { e.printStackTrace(); } try { Statement sta = conn.createStatement(); String payload = "CREATE TABLE PROPERTIES (Name VARCHAR(100), Type VARCHAR(20), Value VARCHAR(50))"; sta.executeUpdate(payload); sta.close(); } catch (SQLException e) { } String[] splitData = data.split(lineSeperator); for (String line : splitData) { String[] values = line.split(propertyDelimiter); String payload = "UPDATE PROPERTIES SET TYPE='" + values[0] + "', VALUE='" + values[2] + "' WHERE NAME = '" + values[1] + "'"; Statement sta; try { sta = conn.createStatement(); int count = sta.executeUpdate(payload); if (count == 0) { payload = "INSERT INTO PROPERTIES VALUES ('" + values[1] + "', '" + values[0] + "', '" + values[2] + "')"; Statement insert = conn.createStatement(); count = insert.executeUpdate(payload); } } catch (SQLException e) { e.printStackTrace(); } } }
Source:
private void runUserRestrictionsChange( boolean currentDisallow, boolean nextDisallow, String[] activeTetheringIfacesList, int expectedInteractionsWithShowNotification) throws Exception { final Bundle newRestrictions = new Bundle(); newRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, nextDisallow); final Tethering mockTethering = mock(Tethering.class); when(mockTethering.getTetheredIfaces()).thenReturn(activeTetheringIfacesList); when(mUserManager.getUserRestrictions()).thenReturn(newRestrictions); final Tethering.UserRestrictionActionListener ural = new Tethering.UserRestrictionActionListener( mUserManager, mockTethering, mNotificationUpdater); ural.mDisallowTethering = currentDisallow; ural.onUserRestrictionsChanged(); verify(mNotificationUpdater, times(expectedInteractionsWithShowNotification)) .notifyTetheringDisabledByRestriction(); final boolean hasActiveTetheringIfaces = activeTetheringIfacesList.length > 0; verify(mockTethering, times(hasActiveTetheringIfaces ? expectedInteractionsWithShowNotification : 0)) .untetherAll(); }

Target:
private void runUserRestrictionsChange( boolean currentDisallow, boolean nextDisallow, String[] activeTetheringIfacesList, int expectedInteractionsWithShowNotification) throws Exception { final Bundle newRestrictions = new Bundle(); newRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, nextDisallow); final Tethering mockTethering = mock(Tethering.class); when(mockTethering.getTetheredIfaces()).thenReturn(activeTetheringIfacesList); when(mUserManager.getUserRestrictions()).thenReturn(newRestrictions); final Tethering.UserRestrictionActionListener ural = new Tethering.UserRestrictionActionListener( mUserManager, mockTethering, mNotificationUpdater); ural.mDisallowTethering = currentDisallow; ural.onUserRestrictionsChanged(); verify(mNotificationUpdater, times(expectedInteractionsWithShowNotification)) .notifyTetheringDisabledByRestriction(); verify(mockTethering, times(expectedInteractionsWithShowNotification)).untetherAll(); }
Source:
public Number getLineOpacity() { if (paint.get("line-opacity") != null) { return (Number) paint.get("line-opacity"); } else { return 1; } }

Target:
public Number getLineOpacity() { if( paint.containsKey("line-opacity")){ Object lineOpacity = paint.get("line-opacity"); if( lineOpacity == null ){ return 1; } else if (lineOpacity instanceof JSONObject){ throw new UnsupportedOperationException("Functions not supported yet"); } else if (lineOpacity instanceof Number){ return (Number) lineOpacity; } else if(lineOpacity instanceof String){ return Double.parseDouble((String)lineOpacity); } else { throw new IllegalArgumentException( "json contents invalid, line-opacity value limited to Number, String, or JSONObject (function)" + lineOpacity.getClass().getSimpleName()); } } else { return 1; } }
Source:
public void handleRequestType(SAML2HandlerRequest request, SAML2HandlerResponse response) throws ProcessingException { super.handleRequestType(request, response); log.info("EngineAttributeHandler . handleRequestType"); if (request.getSAML2Object() instanceof LogoutRequestType) return; if (getType() == HANDLER_TYPE.SP) return; HTTPContext httpContext = (HTTPContext) request.getContext(); HttpSession session = httpContext.getRequest().getSession(false); Principal userPrincipal = (Principal) session.getAttribute(GeneralConstants.PRINCIPAL_ID); if (userPrincipal == null) userPrincipal = httpContext.getRequest().getUserPrincipal(); Map<String, Object> attribs = (Map<String, Object>) session.getAttribute(GeneralConstants.ATTRIBUTES); if (attribs != null) { log.info("EngineAttributeHandler . handleRequestType attr is not null "+ attribs.keySet()); if (userPrincipal instanceof EnginePrincipal) { log.info("EngineAttributeHandler . handleRequestType setting ENGINE_SESSION_ID in attribs to " + ((EnginePrincipal) userPrincipal).getEngineSessionId()); String engineSessionId = ((EnginePrincipal) userPrincipal).getEngineSessionId(); attribs.put(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, engineSessionId); session.setAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, engineSessionId); } request.addOption(GeneralConstants.ATTRIBUTES, attribs); session.setAttribute(GeneralConstants.ATTRIBUTES, attribs); } else { log.info("EngineAttributeHandler . handleRequestType attr is null"); } }

Target:
public void handleRequestType(SAML2HandlerRequest request, SAML2HandlerResponse response) throws ProcessingException { super.handleRequestType(request, response); log.info("EngineAttributeHandler . handleRequestType"); if (request.getSAML2Object() instanceof LogoutRequestType) return; if (getType() == HANDLER_TYPE.SP) return; HTTPContext httpContext = (HTTPContext) request.getContext(); HttpSession session = httpContext.getRequest().getSession(false); if (session != null) { Principal userPrincipal = (Principal) session.getAttribute(GeneralConstants.PRINCIPAL_ID); if (userPrincipal == null) userPrincipal = httpContext.getRequest().getUserPrincipal(); Map<String, Object> attribs = (Map<String, Object>) session.getAttribute(GeneralConstants.ATTRIBUTES); if (attribs != null) { log.info("EngineAttributeHandler . handleRequestType attr is not null "+ attribs.keySet()); if (userPrincipal instanceof EnginePrincipal) { log.info("EngineAttributeHandler . handleRequestType setting ENGINE_SESSION_ID in attribs to " + ((EnginePrincipal) userPrincipal).getEngineSessionId()); String engineSessionId = ((EnginePrincipal) userPrincipal).getEngineSessionId(); attribs.put(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, engineSessionId); session.setAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, engineSessionId); } request.addOption(GeneralConstants.ATTRIBUTES, attribs); session.setAttribute(GeneralConstants.ATTRIBUTES, attribs); } else { log.info("EngineAttributeHandler . handleRequestType attr is null"); } } }
Source:
protected void verify(Host model, Host transform) { assertNotNull(transform); assertEquals(model.getName(), transform.getName()); assertEquals(model.getId(), transform.getId()); assertNotNull(transform.getCluster()); assertEquals(model.getCluster().getId(), transform.getCluster().getId()); assertEquals(model.getAddress(), transform.getAddress()); assertEquals(model.getPort(), transform.getPort()); assertEquals(model.getSsh(), transform.getSsh()); assertEquals(model.getStorageManager().getPriority(), transform.getStorageManager().getPriority()); assertEquals(model.getDisplay().getAddress(), transform.getDisplay().getAddress()); }

Target:
protected void verify(Host model, Host transform) { assertNotNull(transform); assertEquals(model.getName(), transform.getName()); assertEquals(model.getId(), transform.getId()); assertNotNull(transform.getCluster()); assertEquals(model.getCluster().getId(), transform.getCluster().getId()); assertEquals(model.getAddress(), transform.getAddress()); assertEquals(model.getPort(), transform.getPort()); assertEquals(model.getSsh().getUser().getUserName(), transform.getSsh().getUser().getUserName()); assertEquals(model.getSsh().getUser().getPassword(), transform.getSsh().getUser().getPassword()); assertEquals(model.getSsh().getFingerprint(), transform.getSsh().getFingerprint()); assertEquals(model.getSsh().getPort(), transform.getSsh().getPort()); assertEquals(model.getStorageManager().getPriority(), transform.getStorageManager().getPriority()); assertEquals(model.getDisplay().getAddress(), transform.getDisplay().getAddress()); }
Source:
default void inputDetail() { optional(cluster()); optional(clone()); optional(exclusive()); optional(template().name()); or(optional(storageDomain().id()), optional(storageDomain().name())); optional(vm().diskAttachments()[COLLECTION].id()); }

Target:
default void inputDetail() { or(optional(cluster().id()), optional(cluster().name())); optional(clone()); optional(exclusive()); optional(template().name()); or(optional(storageDomain().id()), optional(storageDomain().name())); optional(vm().diskAttachments()[COLLECTION].id()); }
Source:
private void setTextAppearance(Context context, int data) { titleText.setTextAppearance(context, data); }

Target:
private void setTextAppearance(Context context, int data) { titleText.setTextAppearance(context, data); separatorText.setTextAppearance(context, data); titleText.setTextAppearance(context, data); editText.setTextAppearance(context, data); }
Source:
public static <K> InternalTimeServiceManager<K> create( CheckpointableKeyedStateBackend<K> keyedStatedBackend, ClassLoader userClassloader, KeyContext keyContext, ProcessingTimeService processingTimeService, Iterable<KeyGroupStatePartitionStreamProvider> rawKeyedStates) { if (!(keyedStatedBackend instanceof BatchExecutionKeyedStateBackend)) { throw new IllegalStateException( "Batch execution specific time service can work only with BatchExecutionKeyedStateBackend"); } BatchExecutionInternalTimeServiceManager<K> timeServiceManager = new BatchExecutionInternalTimeServiceManager<>( processingTimeService ); keyedStatedBackend.registerKeySelectionListener(timeServiceManager); return timeServiceManager; }

Target:
public static <K> InternalTimeServiceManager<K> create( CheckpointableKeyedStateBackend<K> keyedStatedBackend, ClassLoader userClassloader, KeyContext keyContext, ProcessingTimeService processingTimeService, Iterable<KeyGroupStatePartitionStreamProvider> rawKeyedStates) { checkState( keyedStatedBackend instanceof BatchExecutionKeyedStateBackend, "Batch execution specific time service can work only with BatchExecutionKeyedStateBackend"); BatchExecutionInternalTimeServiceManager<K> timeServiceManager = new BatchExecutionInternalTimeServiceManager<>( processingTimeService ); keyedStatedBackend.registerKeySelectionListener(timeServiceManager); return timeServiceManager; }
Source:
private static void verifyOutput(String expected, AuditEvent... events) { final TestByteArrayOutputStream out = new TestByteArrayOutputStream(); final XpathFileGeneratorAuditListener listener = new XpathFileGeneratorAuditListener(out, AutomaticBean.OutputStreamOptions.CLOSE); for (AuditEvent event : events) { listener.addError(event); } listener.auditFinished(null); assertWithMessage("Output steam flush count") .that(out.flushCount) .isEqualTo(TestUtil.adjustFlushCountForOutputStreamClose(1)); assertWithMessage("Output steam close count") .that(out.closeCount) .isEqualTo(1); final String actual = out.toString(); assertEquals("Invalid suppressions file content", expected, actual); }

Target:
private static void verifyOutput(String expected, AuditEvent... events) { final TestByteArrayOutputStream out = new TestByteArrayOutputStream(); final XpathFileGeneratorAuditListener listener = new XpathFileGeneratorAuditListener(out, AutomaticBean.OutputStreamOptions.CLOSE); for (AuditEvent event : events) { listener.addError(event); } listener.auditFinished(null); assertWithMessage("Output stream flush count") .that(out.flushCount) .isEqualTo(TestUtil.adjustFlushCountForOutputStreamClose(1)); assertWithMessage("Output stream close count") .that(out.closeCount) .isEqualTo(1); final String actual = out.toString(); assertEquals("Invalid suppressions file content", expected, actual); }
Source:
private Set<String> getDefaultOrigins() { log.debug("getDefaultOrigins() called"); List<VDS> allVds = vdsDao.getAll(getUserID(), getParameters().isFiltered()); Set<String> result = new HashSet<>(); for (VDS vds : allVds) { if (getParameters().getSuffixes().size() > 0) { for (String suffix : getParameters().getSuffixes()) { result.add(HTTPS + vds.getHostName() + suffix); } } else { result.add(HTTPS + vds.getHostName()); } } log.debug("Default list of origins refreshed to: {}" , StringUtils.join(result, ',')); return result; }

Target:
private Set<String> getDefaultOrigins() { List<VDS> allVds = vdsDao.getAll(getUserID(), getParameters().isFiltered()); Set<String> result = new HashSet<>(); for (VDS vds : allVds) { if (!getParameters().getSuffixes().isEmpty()) { for (String suffix : getParameters().getSuffixes()) { result.add(HTTPS + vds.getHostName() + suffix); } } else { result.add(HTTPS + vds.getHostName()); } } if (log.isDebugEnabled()) { log.debug("Default list of origins refreshed to: {}", StringUtils.join(result, ',')); } return result; }
Source:
public void testRemoveJobGraph() throws Exception { final CompletableFuture<JobID> removeFuture = new CompletableFuture<>(); final TestingStateHandleStore<JobGraph> stateHandleStore = builder .setAddFunction((ignore, state) -> jobGraphStorageHelper.store(state)) .setRemoveFunction(name -> removeFuture.complete(JobID.fromHexString(name))) .build(); final JobGraphStore jobGraphStore = createAndStartJobGraphStore(stateHandleStore); jobGraphStore.removeJobGraph(testingJobGraph.getJobID()); jobGraphStore.putJobGraph(testingJobGraph); jobGraphStore.removeJobGraph(testingJobGraph.getJobID()); final JobID actual = removeFuture.get(timeout, TimeUnit.MILLISECONDS); assertThat(actual, is(testingJobGraph.getJobID())); }

Target:
public void testRemoveJobGraph() throws Exception { final CompletableFuture<JobID> removeFuture = new CompletableFuture<>(); final TestingStateHandleStore<JobGraph> stateHandleStore = builder .setAddFunction((ignore, state) -> jobGraphStorageHelper.store(state)) .setRemoveFunction(name -> removeFuture.complete(JobID.fromHexString(name))) .build(); final JobGraphStore jobGraphStore = createAndStartJobGraphStore(stateHandleStore); jobGraphStore.putJobGraph(testingJobGraph); jobGraphStore.removeJobGraph(testingJobGraph.getJobID()); final JobID actual = removeFuture.get(timeout, TimeUnit.MILLISECONDS); assertThat(actual, is(testingJobGraph.getJobID())); }
Source:
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { final Lock readLock = rwLock.readLock(); readLock.lock(); if (tt != null) { request.addHeader(TT_HEADER, tt); } final HttpResponse resp; try { resp = this.httpClient.execute(target, request, context); } finally { readLock.unlock(); } return handleResponse(target, request, resp, context); }

Target:
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { final Lock readLock = rwLock.readLock(); readLock.lock(); final HttpResponse resp; try { if (tt != null) { notNull(request, "Request can't be null"); request.addHeader(TT_HEADER, tt); } resp = this.httpClient.execute(target, request, context); } finally { readLock.unlock(); } return handleResponse(target, request, resp, context); }
Source:
protected boolean isPeerValid(AdminRow peerRow) { boolean hasPeersRpcAddress = peerRow.getInetAddress("rpc_address") != null; boolean hasPeersV2RpcAddress = peerRow.getInetAddress("native_address") != null && peerRow.getInteger("native_port") != null; boolean hasRpcAddress = hasPeersV2RpcAddress || hasPeersRpcAddress; boolean hasHostId = peerRow.getUuid("host_id") != null; boolean hasSchemaVersion = peerRow.getUuid("schema_version") != null; boolean valid = hasRpcAddress && hasHostId && hasSchemaVersion; if (!valid) { LOG.warn( "[{}] Found invalid row in for peer: {}. " + "This is likely a gossip or snitch issue, this node will be ignored.", logPrefix, getPeerTableName(), peerRow.getInetAddress("peer")); } return valid; }

Target:
protected boolean isPeerValid(AdminRow peerRow) { boolean hasPeersRpcAddress = !peerRow.isNull("rpc_address"); boolean hasPeersV2RpcAddress = !peerRow.isNull("native_address") && !peerRow.isNull("native_port"); boolean hasRpcAddress = hasPeersV2RpcAddress || hasPeersRpcAddress; boolean valid = hasRpcAddress && !peerRow.isNull("host_id") && !peerRow.isNull("data_center") && !peerRow.isNull("rack") && !peerRow.isNull("tokens"); if (!valid) { LOG.warn( "[{}] Found invalid row in for peer: {}. " + "This is likely a gossip or snitch issue, this node will be ignored.", logPrefix, getPeerTableName(), peerRow.getInetAddress("peer")); } return valid; }
Source:
public ElasticsearchRecordCursor(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { this.columnHandles = columnHandles; maxHits = config.getMaxHits(); tupleDomain = split.getTupleDomain(); jsonPathToIndex = new HashMap(); totalBytes = 0; for (int i = 0; i < columnHandles.size(); i++) { jsonPathToIndex.put(columnHandles.get(i).getColumnJsonPath(), i); } ElasticsearchQueryBuilder builder = new ElasticsearchQueryBuilder(columnHandles, config, split); lines = sendElasticQuery(builder).iterator(); }

Target:
public ElasticsearchRecordCursor(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { this.columnHandles = requireNonNull(columnHandles, "columnHandle is null"); this.maxHits = requireNonNull(config, "config is null").getMaxHits(); this.timeout = config.getRequestTimeout(); for (int i = 0; i < columnHandles.size(); i++) { jsonPathToIndex.put(columnHandles.get(i).getColumnJsonPath(), i); } this.builder = new ElasticsearchQueryBuilder(columnHandles, config, split); this.searchHits = sendElasticQuery(builder).iterator(); }
Source:
private void testCreateInsertion(String insertion) throws Exception { String url = "/ats/program/" + getSawProgram().getArtId() + "/insertion"; JsonArray array = postAndCheck(url, Entity.entity(insertion, MediaType.APPLICATION_JSON_TYPE)); Assert.assertEquals(1, array.size()); JsonObject obj = getObjectNamed("JAX Insertion", array); Assert.assertNotNull("Did not find value Jax Insertion", obj); }

Target:
private void testCreateInsertion(String insertion) throws Exception { String url = "/ats/program/" + getSawProgram().getUuid() + "/insertion"; JsonArray array = postAndCheck(url, Entity.entity(insertion, MediaType.APPLICATION_JSON_TYPE)); Assert.assertEquals(1, array.size()); JsonObject obj = getObjectNamed("JAX Insertion", array); Assert.assertNotNull("Did not find value Jax Insertion", obj); }
Source:
public void testUnsupportedProtoExceptionMsg() throws IOException { exceptionRule.expect(IllegalStateException.class); exceptionRule.expectMessage(UnsupportedProto.class.getName()); ConnectionPool.newConnection(conf, TEST_NN_ADDRESS, TEST_USER1, UnsupportedProto.class); }

Target:
public void testUnsupportedProtoExceptionMsg() throws Exception { LambdaTestUtils.intercept(IllegalStateException.class, "Unsupported protocol for connection to NameNode: " + TestConnectionManager.class.getName(), () -> ConnectionPool.newConnection(conf, TEST_NN_ADDRESS, TEST_USER1, TestConnectionManager.class)); }
Source:
public Response getToolZip(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "toolId", required = true) @PathParam("toolId") Long toolId, @ApiParam(value = "tagId", required = true) @PathParam("tagId") Long tagId) { Tool tool; if (user.isPresent()) { tool = toolDAO.findById(toolId); checkEntry(tool); checkUser(user.get(), tool); } else { tool = toolDAO.findPublishedById(toolId); checkEntry(tool); } Tag tag = tool.getTags().stream().filter(innertag -> innertag.getId() == tagId).findFirst().orElseThrow(() -> new CustomWebApplicationException("Could not find tag", HttpStatus.SC_NOT_FOUND)); Set<SourceFile> sourceFiles = tag.getSourceFiles(); if (sourceFiles == null || sourceFiles.size() == 0) { return null; } String fileName = tool.getToolPath().replaceAll("/", "-") + ".zip"; File returnZipFile = downloadAsZip(sourceFiles, fileName); return Response .ok(returnZipFile) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"") .build(); }

Target:
public Response getToolZip(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "toolId", required = true) @PathParam("toolId") Long toolId, @ApiParam(value = "tagId", required = true) @PathParam("tagId") Long tagId) { Tool tool; if (user.isPresent()) { tool = toolDAO.findById(toolId); checkEntry(tool); checkUser(user.get(), tool); } else { tool = toolDAO.findPublishedById(toolId); checkEntry(tool); } Tag tag = tool.getTags().stream().filter(innertag -> innertag.getId() == tagId).findFirst() .orElseThrow(() -> new CustomWebApplicationException("Could not find tag", HttpStatus.SC_NOT_FOUND)); Set<SourceFile> sourceFiles = tag.getSourceFiles(); if (sourceFiles == null || sourceFiles.size() == 0) { throw new CustomWebApplicationException("no files found to zip", HttpStatus.SC_NO_CONTENT); } String fileName = tool.getToolPath().replaceAll("/", "-") + ".zip"; return Response.ok().entity((StreamingOutput)output -> writeStreamAsZip(sourceFiles, output)) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build(); }
Source:
public Response createNewPayment(@Auth String accountId, JsonNode requestPayload, @Context UriInfo uriInfo) throws IOException { logger.info("received create payment request: [ ]", requestPayload); Optional<List<String>> missingFields = checkMissingFields(requestPayload); if (missingFields.isPresent()) { return fieldsMissingResponse(logger, missingFields.get()); } Response connectorResponse = client.target(connectorUrl + "/v1/api/charges") .request() .post(buildChargeRequestPayload(accountId, requestPayload)); return responseFrom(uriInfo, connectorResponse, HttpStatus.SC_CREATED, (locationUrl, data) -> Response.created(locationUrl).entity(data), data -> badRequestResponse(logger, data)); }

Target:
public Response createNewPayment(@Auth String accountId, JsonNode requestPayload, @Context UriInfo uriInfo) throws IOException { logger.info("received create payment request: [ ]", requestPayload); Optional<List<String>> missingFields = checkMissingFields(requestPayload); if (missingFields.isPresent()) { return fieldsMissingResponse(logger, missingFields.get()); } Response connectorResponse = client.target(connectorUrl + CONNECTOR_CHARGES_RESOURCE) .request() .post(buildChargeRequestPayload(accountId, requestPayload)); return responseFrom(uriInfo, connectorResponse, HttpStatus.SC_CREATED, (locationUrl, data) -> Response.created(locationUrl).entity(data), data -> badRequestResponse(logger, data)); }
Source:
public RecordWriter<K, V> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { if (wrapped.realOutputFormat instanceof WorkFileOverride) { ((WorkFileOverride) wrapped.realOutputFormat).setName(name); } return wrapped.getRecordWriter(ignored, job, name, progress); }

Target:
public RecordWriter<K, V> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { return wrapped.getRecordWriter(ignored, job, name, progress); }
Source:
public void standard() throws Exception { JsxStandardElementTree tree = parse("<foo> Hello my <bar>world</bar> ! </foo>", Kind.JSX_STANDARD_ELEMENT); assertThat(tree.is(Kind.JSX_STANDARD_ELEMENT)).isTrue(); assertThat(tree.openingElement().ltToken().text()).isEqualTo("<"); assertThat(tree.openingElement().gtToken().text()).isEqualTo(">"); assertThat(tree.openingElement().attributes()).isEmpty(); assertThat(expressionToString(tree.openingElement().elementName())).isEqualTo("foo"); assertThat(tree.closingElement().ltToken().text()).isEqualTo("<"); assertThat(tree.closingElement().gtToken().text()).isEqualTo(">"); assertThat(tree.closingElement().divToken().text()).isEqualTo("/"); assertThat(expressionToString(tree.closingElement().elementName())).isEqualTo("foo"); assertThat(tree.children()).hasSize(3); assertThat(tree.children().get(0).is(Kind.JSX_TEXT)).isTrue(); assertThat(expressionToString(tree.children().get(0))).isEqualTo("Hello my"); assertThat(tree.children().get(1).is(Kind.JSX_STANDARD_ELEMENT)).isTrue(); assertThat(tree.children().get(2).is(Kind.JSX_TEXT)).isTrue(); assertThat(expressionToString(tree.children().get(2))).isEqualTo("!"); }

Target:
public void standard() throws Exception { JsxStandardElementTree tree = parse("<foo> Hello my <bar>world</bar> ! </foo>", Kind.JSX_STANDARD_ELEMENT); assertThat(tree.is(Kind.JSX_STANDARD_ELEMENT)).isTrue(); assertThat(tree.openingElement().openAngleBracketToken().text()).isEqualTo("<"); assertThat(tree.openingElement().closeAngleBracketToken().text()).isEqualTo(">"); assertThat(tree.openingElement().attributes()).isEmpty(); assertThat(expressionToString(tree.openingElement().elementName())).isEqualTo("foo"); assertThat(tree.closingElement().openAngleBracketToken().text()).isEqualTo("<"); assertThat(tree.closingElement().closeAngleBracketToken().text()).isEqualTo(">"); assertThat(tree.closingElement().slashToken().text()).isEqualTo("/"); assertThat(expressionToString(tree.closingElement().elementName())).isEqualTo("foo"); assertThat(tree.children()).hasSize(3); assertThat(tree.children().get(0).is(Kind.JSX_TEXT)).isTrue(); assertThat(((JsxTextTree) tree.children().get(0)).token().text()).isEqualTo(" Hello my "); assertThat(tree.children().get(1).is(Kind.JSX_STANDARD_ELEMENT)).isTrue(); assertThat(tree.children().get(2).is(Kind.JSX_TEXT)).isTrue(); assertThat(expressionToString(tree.children().get(2))).isEqualTo("!"); }
Source:
public static boolean shouldReplicate(ReplicationSpec replicationSpec, Table tableHandle, boolean isEventDump, HiveConf hiveConf) { if (replicationSpec == null) { replicationSpec = new ReplicationSpec(); } if (replicationSpec.isNoop() || tableHandle == null) { return false; } if (tableHandle.isNonNative() && !replicationSpec.isMetadataOnly()) { return false; } if (replicationSpec.isInReplicationScope()) { if (tableHandle.isTemporary()) { return false; } if (MetaStoreUtils.isExternalTable(tableHandle.getTTable())) { boolean shouldReplicateExternalTables = hiveConf.getBoolVar(HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES) || replicationSpec.isMetadataOnly(); if (isEventDump) { shouldReplicateExternalTables = shouldReplicateExternalTables && !hiveConf.getBoolVar(HiveConf.ConfVars.REPL_BOOTSTRAP_EXTERNAL_TABLES); } return shouldReplicateExternalTables; } if (AcidUtils.isTransactionalTable(tableHandle.getTTable())) { boolean shouldReplicateAcidTables = true; if (hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_IN_TEST_REPL)) { shouldReplicateAcidTables = hiveConf.getBoolVar((HiveConf.ConfVars.REPL_DUMP_INCLUDE_ACID_TABLES)); } if (!shouldReplicateAcidTables) { return false; } if (isEventDump) { return !hiveConf.getBoolVar(HiveConf.ConfVars.REPL_BOOTSTRAP_ACID_TABLES); } } } return true; }

Target:
public static boolean shouldReplicate(ReplicationSpec replicationSpec, Table tableHandle, boolean isEventDump, HiveConf hiveConf) { if (replicationSpec == null) { replicationSpec = new ReplicationSpec(); } if (replicationSpec.isNoop() || tableHandle == null) { return false; } if (tableHandle.isNonNative() && !replicationSpec.isMetadataOnly()) { return false; } if (replicationSpec.isInReplicationScope()) { if (tableHandle.isTemporary()) { return false; } if (MetaStoreUtils.isExternalTable(tableHandle.getTTable())) { boolean shouldReplicateExternalTables = hiveConf.getBoolVar(HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES) || replicationSpec.isMetadataOnly(); if (isEventDump) { shouldReplicateExternalTables = shouldReplicateExternalTables && !hiveConf.getBoolVar(HiveConf.ConfVars.REPL_BOOTSTRAP_EXTERNAL_TABLES); } return shouldReplicateExternalTables; } if (AcidUtils.isTransactionalTable(tableHandle.getTTable())) { if (!ReplUtils.includeAcidTableInDump(hiveConf)) { return false; } if (isEventDump) { return !hiveConf.getBoolVar(HiveConf.ConfVars.REPL_BOOTSTRAP_ACID_TABLES); } } } return true; }