auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static ReftableConfig configureReftable(ReftableConfig cfg, DfsOutputStream out) { cfg = new ReftableConfig(cfg); if (out.blockSize() >= 256) { cfg.setRefBlockSize(out.blockSize()); } else { int sz = DfsBlockCache.getInstance().getBlockSize(); if (cfg.getRefBlockSize() < sz) { cfg.setRefBlockSize(sz); } } return cfg; }

Target:
static ReftableConfig configureReftable(ReftableConfig cfg, DfsOutputStream out) { int bs = out.blockSize(); if (bs > 0) { cfg = new ReftableConfig(cfg); cfg.setRefBlockSize(bs); cfg.setAlignBlocks(true); } return cfg; }
Source:
public void loadFunctionNamespaceManager( String functionNamespaceManagerName, String functionNamespaceManagerId, List<String> catalogSchemaPrefixes, Map<String, String> properties) { FunctionNamespaceManagerFactory factory = functionNamespaceManagerFactories.get(functionNamespaceManagerName); checkState(factory != null, "No factory for function namespace manager %s", functionNamespaceManagerName); FunctionNamespaceManager<?> functionNamespaceManager = factory.create(properties); transactionManager.registerFunctionNamespaceManager(functionNamespaceManagerId, functionNamespaceManager); if (functionNamespaceManagers.putIfAbsent(functionNamespaceManagerId, functionNamespaceManager) != null) { throw new IllegalArgumentException(format("Function namespace manager [%s] is already registered", functionNamespaceManagerId)); } for (String catalogSchemaPrefix : catalogSchemaPrefixes) { if (functionNamespaces.putIfAbsent(CatalogSchemaPrefix.of(catalogSchemaPrefix), functionNamespaceManagerId) != null) { throw new IllegalArgumentException(format("Function namespace [%s] is already registered to function namespace manager [%s]", catalogSchemaPrefix, functionNamespaceManagerId)); } } }

Target:
public void loadFunctionNamespaceManager( String functionNamespaceManagerName, String functionNamespaceManagerId, List<String> catalogSchemaPrefixes, Map<String, String> properties) { requireNonNull(functionNamespaceManagerName, "functionNamespaceManagerName is null"); FunctionNamespaceManagerFactory factory = functionNamespaceManagerFactories.get(functionNamespaceManagerName); checkState(factory != null, "No factory for function namespace manager %s", functionNamespaceManagerName); FunctionNamespaceManager<?> functionNamespaceManager = factory.create(properties); transactionManager.registerFunctionNamespaceManager(functionNamespaceManagerId, functionNamespaceManager); if (functionNamespaceManagers.putIfAbsent(functionNamespaceManagerId, functionNamespaceManager) != null) { throw new IllegalArgumentException(format("Function namespace manager [%s] is already registered", functionNamespaceManagerId)); } for (String catalogSchemaPrefix : catalogSchemaPrefixes) { if (functionNamespaces.putIfAbsent(CatalogSchemaPrefix.of(catalogSchemaPrefix), functionNamespaceManagerId) != null) { throw new IllegalArgumentException(format("Function namespace [%s] is already registered to function namespace manager [%s]", catalogSchemaPrefix, functionNamespaceManagerId)); } } }
Source:
protected BatchItem run() throws Exception { try { final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, KafkaCursor.toKafkaPartition(batchItem.getPartition()), batchItem.getPartition(), batchItem.getEvent().toString()); final Producer<String, String> producer = kafkaFactory.takeProducer(); try { final NakadiCallback callback = new NakadiCallback(); producer.send(kafkaRecord, callback); final Exception exception = callback.result.get(timeout, TimeUnit.MILLISECONDS); if (exception != null) { if (isExceptionShouldLeadToReset(exception)) { LOG.warn("Terminating producer while publishing to topic {}", topicId, exception); kafkaFactory.terminateProducer(producer); } if (hasKafkaConnectionException(exception)) { LOG.error("Kafka timeout: on broker {}", topicId, batchItem.getBrokerId(), exception); batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "timed out"); throw new Exception("Kafka timeout exception"); } } } finally { kafkaFactory.releaseProducer(producer); } } catch (final ExecutionException | RuntimeException ex) { batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); LOG.error("Error publishing message to kafka", ex); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "interrupted"); LOG.error("Error publishing message to kafka", ex); } catch (final java.util.concurrent.TimeoutException ex) { batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "timed out"); LOG.error("Kafka timeout: on broker {}", topicId, batchItem.getBrokerId(), ex); throw new Exception("Kafka timeout exception"); } return batchItem; }

Target:
protected NakadiCallback run() { final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( batchItem.getTopic(), KafkaCursor.toKafkaPartition(batchItem.getPartition()), batchItem.getPartition(), batchItem.getEvent().toString()); final NakadiCallback callback = new NakadiCallback(batchItem); try { producer.send(kafkaRecord, callback); LOG.debug("Sent command to Kafka"); return callback; } catch (final RuntimeException ex) { LOG.error("Error publishing message to kafka", ex); batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); } return null; }
Source:
public void doStop() { if (this.reader != null) { this.stoppedDueToThrottling.set(false); this.reader.stop(); } }

Target:
public void doStop() { this.stoppedDueToThrottling.set(false); if (this.reader != null) { this.reader.stop(); } }
Source:
public void createApplicationContextFrom_validBuilderContext_containingTwoSameExtraComponent_shouldCreateAnApplicationContext() { String name1 = "workers1"; ExecutorService workers1 = Executors.newFixedThreadPool(2); String name2 = "workers2"; ExecutorService workers2 = Executors.newFixedThreadPool(2); Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey(name1, ExecutorService.class), workers1); extraComponents.put(new Platform.ExtraComponentKey(name2, ExecutorService.class), workers2); KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(workers1, applicationContext.getBean(name1)); assertEquals(workers2, applicationContext.getBean(name2)); }

Target:
public void createApplicationContextFrom_validBuilderContext_containingTwoSameExtraComponent_shouldCreateAnApplicationContext() { final String name1 = "workers1"; final ExecutorService workers1 = Executors.newFixedThreadPool(2); final String name2 = "workers2"; final ExecutorService workers2 = Executors.newFixedThreadPool(2); final Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey(name1, ExecutorService.class), workers1); extraComponents.put(new Platform.ExtraComponentKey(name2, ExecutorService.class), workers2); final KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(workers1, applicationContext.getBean(name1)); assertEquals(workers2, applicationContext.getBean(name2)); }
Source:
@Override public Connection createConnection(String userName, String password) throws JMSException { Connection connection; if (userName == null || password == null) { connection = super.createConnection(); } else { connection = super.createConnection(userName, password); } if (this.cacheLevel >= JMSConstants.CACHE_CONNECTION) { cachedConnection = connection; } return connection; }

Target:
public Connection createConnection(String userName, String password) throws JMSException { Connection connection; if (userName == null || password == null) { connection = super.createConnection(); } else { connection = super.createConnection(userName, password); } if (this.cacheLevel >= JMSConstants.CACHE_CONNECTION) { cachedConnection = connection; } return connection; }
Source:
public void close() throws IOException { if (closed) { return; } closed = true; rowGroupPosition = 0; rowGroupRowCount = 0; currentChunkRowCount = 0; try (Closer closer = Closer.create()) { closer.register(input); closer.register(decompressor::destroy); } if (writeChecksumBuilder.isPresent()) { WriteChecksum actualChecksum = writeChecksumBuilder.get().build(); validateWrite(validation -> validation.getChecksum().getTotalRowCount() == actualChecksum.getTotalRowCount(), "Invalid row count"); List<Long> columnHashes = actualChecksum.getColumnHashes(); for (int i = 0; i < columnHashes.size(); i++) { int columnIndex = i; validateWrite(validation -> validation.getChecksum().getColumnHashes().get(columnIndex).equals(columnHashes.get(columnIndex)), "Invalid checksum for column %s", columnIndex); } validateWrite(validation -> validation.getChecksum().getRowGroupHash() == actualChecksum.getRowGroupHash(), "Invalid row group checksum"); } }

Target:
public void close() throws IOException { if (closed) { return; } closed = true; rowGroupPosition = 0; rowGroupRowCount = 0; currentChunkRowCount = 0; try { input.close(); } finally { if (decompressor != null) { decompressor.destroy(); } } if (writeChecksumBuilder.isPresent()) { WriteChecksum actualChecksum = writeChecksumBuilder.get().build(); validateWrite(validation -> validation.getChecksum().getTotalRowCount() == actualChecksum.getTotalRowCount(), "Invalid row count"); List<Long> columnHashes = actualChecksum.getColumnHashes(); for (int i = 0; i < columnHashes.size(); i++) { int columnIndex = i; validateWrite(validation -> validation.getChecksum().getColumnHashes().get(columnIndex).equals(columnHashes.get(columnIndex)), "Invalid checksum for column %s", columnIndex); } validateWrite(validation -> validation.getChecksum().getRowGroupHash() == actualChecksum.getRowGroupHash(), "Invalid row group checksum"); } }
Source:
private void recordDailyLast(int env, int day, int field, Object value, String table) { if (env == -1) { Logger.warn(LOG_TAG, "Refusing to record with environment = -1."); return; } final SQLiteDatabase db = this.helper.getWritableDatabase(); final String envString = Integer.toString(env); final String fieldIDString = Integer.toString(field, 10); final String dayString = Integer.toString(day, 10); final ContentValues v = new ContentValues(); putValue(v, value); final int updated = db.update(table, v, WHERE_DATE_AND_ENV_AND_FIELD, new String[] {dayString, envString, fieldIDString}); if (0 == updated) { v.put("env", env); v.put("field", field); v.put("date", day); try { db.insertOrThrow(table, null, v); } catch (SQLiteConstraintException e) { throw new IllegalStateException("Event did not reference existing an environment or field.", e); } catch (Exception e) { Logger.error(LOG_TAG, "Unknown exception thrown while recording daily last value.", e); } } }

Target:
private void recordDailyLast(int env, int day, int field, Object value, String table) { if (env == -1) { Logger.warn(LOG_TAG, "Refusing to record with environment = -1."); return; } final SQLiteDatabase db = this.helper.getWritableDatabase(); final String envString = Integer.toString(env); final String fieldIDString = Integer.toString(field, 10); final String dayString = Integer.toString(day, 10); final ContentValues v = new ContentValues(); putValue(v, value); final int updated = db.update(table, v, WHERE_DATE_AND_ENV_AND_FIELD, new String[] {dayString, envString, fieldIDString}); if (0 == updated) { v.put("env", env); v.put("field", field); v.put("date", day); try { db.insertOrThrow(table, null, v); } catch (SQLiteConstraintException e) { throw new IllegalStateException("Event did not reference existing an environment or field.", e); } } }
Source:
public SanitizedText convert(String value, Class<? extends SanitizedText> type) { return notSanitized(sanitizer.sanitize(value)); }

Target:
public SanitizedText convert(String value, Class<? extends SanitizedText> type) { return sanitizer.sanitize(value); }
Source:
public void stopBlobStoreSuccessTest() throws InterruptedException, IOException { List<? extends PartitionId> partitionIds = clusterMap.getAllPartitionIds(); assertTrue("This test needs more than one partition to work", partitionIds.size() > 1); PartitionId id = partitionIds.get(0); List<? extends ReplicaId> replicaIds = id.getReplicaIds(); assertTrue("This test needs more than one replica for the first partition to work", replicaIds.size() > 1); int correlationId = TestUtils.RANDOM.nextInt(); String clientId = UtilsTest.getRandomString(10); long acceptableLagInBytes = 0; short numReplicasCaughtUpPerPartition = 3; replicationManager.reset(); replicationManager.controlReplicationReturnVal = true; generateLagOverrides(0, acceptableLagInBytes); AdminRequest adminRequest = new AdminRequest(AdminRequestOrResponseType.StopBlobStore, id, correlationId, clientId); StopBlobStoreAdminRequest stopBlobStoreAdminRequest = new StopBlobStoreAdminRequest(numReplicasCaughtUpPerPartition, adminRequest); Response response = sendRequestGetResponse(stopBlobStoreAdminRequest, ServerErrorCode.No_Error); assertTrue("Response not of type AdminResponse", response instanceof AdminResponse); }

Target:
public void stopBlobStoreSuccessTest() throws InterruptedException, IOException { List<? extends PartitionId> partitionIds = clusterMap.getAllPartitionIds(); PartitionId id = partitionIds.get(0); List<? extends ReplicaId> replicaIds = id.getReplicaIds(); assertTrue("This test needs more than one replica for the first partition to work", replicaIds.size() > 1); int correlationId = TestUtils.RANDOM.nextInt(); String clientId = UtilsTest.getRandomString(10); long acceptableLagInBytes = 0; short numReplicasCaughtUpPerPartition = 3; replicationManager.reset(); replicationManager.controlReplicationReturnVal = true; generateLagOverrides(0, acceptableLagInBytes); AdminRequest adminRequest = new AdminRequest(AdminRequestOrResponseType.BlobStoreControl, id, correlationId, clientId); BlobStoreControlAdminRequest stopBlobStoreAdminRequest = new BlobStoreControlAdminRequest(numReplicasCaughtUpPerPartition, false, adminRequest); Response response = sendRequestGetResponse(stopBlobStoreAdminRequest, ServerErrorCode.No_Error); assertTrue("Response not of type AdminResponse", response instanceof AdminResponse); assertEquals("Partition disabled for compaction not as expected", id, storageManager.compactionDisabledPartitionId); assertEquals("Origins list should be empty", true, replicationManager.originsVal.isEmpty()); assertEquals("Replication on given BlobStore should be disabled", false, replicationManager.enableVal); assertEquals("Partition shutdown not as expected", id, storageManager.shutdownPartitionId); }
Source:
private SplashDialog(URL welcomeTxtURL, boolean quitOnClose) { super("Welcome to Observing Tool [Version: " + Version.current + "]"); final SplashPanel splashPanel = new SplashPanel(welcomeTxtURL, quitOnClose); getContentPane().add(splashPanel, BorderLayout.CENTER); final Dimension dim = splashPanel.getPreferredSize(); splashPanel.setPreferredSize(dim); final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screen.width / 2 - dim.width / 2, screen.height / 2 - dim.height / 2); int op = quitOnClose ? WindowConstants.EXIT_ON_CLOSE : WindowConstants.DISPOSE_ON_CLOSE; setDefaultCloseOperation(op); if (quitOnClose) { final JFrame dialog = this; ViewerService.instance().get().registerView(dialog); addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { ViewerService.instance().get().unregisterView(dialog); } }); } if (Platform.get() != Platform.osx) { Resources.setOTFrameIcon(this); } pack(); setVisible(true); toFront(); }

Target:
private SplashDialog(URL welcomeTxtURL, boolean quitOnClose) { super("Welcome to Observing Tool [Version: " + Version.current + "]"); final SplashPanel splashPanel = new SplashPanel(welcomeTxtURL, quitOnClose); getContentPane().add(splashPanel, BorderLayout.CENTER); final Dimension dim = splashPanel.getPreferredSize(); splashPanel.setPreferredSize(dim); final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screen.width / 2 - dim.width / 2, screen.height / 2 - dim.height / 2); int op = quitOnClose ? WindowConstants.EXIT_ON_CLOSE : WindowConstants.DISPOSE_ON_CLOSE; setDefaultCloseOperation(op); if (quitOnClose) { final JFrame dialog = this; ViewerService.instance().get().registerView(dialog); addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { ViewerService.instance().get().unregisterView(dialog); } }); } Resources.setOTFrameIcon(this); pack(); setVisible(true); toFront(); }
Source:
public static Map<String, Long> getAllVersions(final ZephyrRestClient restClient, final Long projectID) { final Map<String, Long> versions = new HashMap<>(); final String url = String.format(URL_GET_VERSIONS, restClient.getUrl(), projectID); final HttpResponse response = restClient.get(url); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { final HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException | IOException e) { ZephyrPlugin.log(e); } final JsonArray projArray = new JsonParser().parse(string).getAsJsonArray(); for (int i = 0; i < projArray.size(); i++) { final Long id = projArray.get(i).getAsJsonObject().get("id").getAsLong(); final String projName = projArray.get(i).getAsJsonObject().get("name").getAsString(); versions.put(projName, id); } } else { ZephyrPlugin.log("Unexpected response status: " + statusCode); } return versions; }

Target:
public static Map<String, Long> getAllVersions(final ZephyrRestClient restClient, final Long projectID) { final Map<String, Long> versions = new HashMap<>(); final String url = String.format(URL_GET_VERSIONS, restClient.getUrl(), projectID); try (final CloseableHttpResponse response = restClient.get(url)) { final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { final HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException | IOException e) { throw new IllegalArgumentException( String.format("Bad response entity upon receipt of versions <%s>", url), e); } final JsonArray projArray = new JsonParser().parse(string).getAsJsonArray(); for (int i = 0; i < projArray.size(); i++) { final Long id = projArray.get(i).getAsJsonObject().get("id").getAsLong(); final String projName = projArray.get(i).getAsJsonObject().get("name").getAsString(); versions.put(projName, id); } } else { throw new IllegalArgumentException(String .format("Unexpected response status <%s> upon receipt of versions <%s>", statusCode, url)); } } catch (IOException e) { throw new IllegalArgumentException(e); } return versions; }
Source:
protected void doStart() { Configuration auth = config.getJAASConfiguration(); try { super.doStart(); if (getEndpoint().getConfig().isConnectOnStartup()) { ostream = setupHdfs(true); } SplitStrategy idleStrategy = null; for (SplitStrategy strategy : config.getSplitStrategies()) { if (strategy.type == SplitStrategyType.IDLE) { idleStrategy = strategy; break; } } if (idleStrategy != null) { scheduler = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "HdfsIdleCheck"); log.debug("Creating IdleCheck task scheduled to run every millis", config.getCheckIdleInterval()); scheduler.scheduleAtFixedRate(new IdleCheck(idleStrategy), config.getCheckIdleInterval(), config.getCheckIdleInterval(), TimeUnit.MILLISECONDS); } } catch (Exception e) { LOG.warn("Failed to start the HDFS producer. Caused by: [{}]", e.getMessage()); LOG.trace("", e); throw new RuntimeException(e); } finally { config.setJAASConfiguration(auth); } }

Target:
protected void doStart() { Configuration auth = HdfsComponent.getJAASConfiguration(); try { super.doStart(); if (getEndpoint().getConfig().isConnectOnStartup()) { ostream = setupHdfs(true); } SplitStrategy idleStrategy = null; for (SplitStrategy strategy : config.getSplitStrategies()) { if (strategy.type == SplitStrategyType.IDLE) { idleStrategy = strategy; break; } } if (idleStrategy != null) { scheduler = getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "HdfsIdleCheck"); log.debug("Creating IdleCheck task scheduled to run every millis", config.getCheckIdleInterval()); scheduler.scheduleAtFixedRate(new IdleCheck(idleStrategy), config.getCheckIdleInterval(), config.getCheckIdleInterval(), TimeUnit.MILLISECONDS); } } catch (Exception e) { LOG.warn("Failed to start the HDFS producer. Caused by: [{}]", e.getMessage()); LOG.debug("", e); throw new RuntimeException(e); } finally { HdfsComponent.setJAASConfiguration(auth); } }
Source:
private void checkParameters() { boolean explain = isQuery && sql.startsWith("EXPLAIN"); for (ParameterInterface p : parameters) { if (explain) p.setValue(ValueNull.INSTANCE, false); p.checkSet(); } }

Target:
private void checkParameters() { if (cmdType != EXPLAIN) { for (ParameterInterface p : parameters) { p.checkSet(); } } }
Source:
public void logoutFunctionTest() { selectAll(); type("dummy").push(KeyCode.TAB); type("dummy").push(KeyCode.TAB); type("test").push(KeyCode.TAB); type("test"); clickOn("Sign in"); sleep(2000); clickOn("File"); clickOn("Logout"); File testConfig = new File(configFileDirectory, testConfigFileName); if (!(testConfig.exists() && testConfig.isFile())) { fail("File not found: " + testConfig.getAbsolutePath()); } Preferences testPref = TestController.loadTestPreferences(); assertEquals("", testPref.getLastLoginUsername()); assertEquals("", testPref.getLastLoginPassword()); }

Target:
public void logoutFunctionTest() { selectAll(); type("dummy").push(KeyCode.TAB); type("dummy").push(KeyCode.TAB); type("test").push(KeyCode.TAB); type("test"); clickOn("Sign in"); sleep(EVENT_DELAY); clickOn("File"); clickOn("Logout"); File testConfig = new File(configFileDirectory, testConfigFileName); if (!(testConfig.exists() && testConfig.isFile())) { fail("File not found: " + testConfig.getAbsolutePath()); } Preferences testPref = TestController.loadTestPreferences(); assertEquals("", testPref.getLastLoginUsername()); assertEquals("", testPref.getLastLoginPassword()); }
Source:
public void processConcurEventNotifications() { Collection<ConcurEventNotification> concurEventNotifications = concurEventNotificationService.retrieveConcurEventNotificationsForProcessing(); if (concurEventNotifications != null && CollectionUtils.isNotEmpty(concurEventNotifications)) { for (ConcurEventNotification concurEventNotification : concurEventNotifications) { ExpenseDetailedReportDTO expenseDetailedReport = retrieveExpenseDetailedReportFromConcur(concurEventNotification); ConcurAccountInfo concurAccountInfo = extractAccountInfo(expenseDetailedReport); concurAccountValidationService.validateConcurAccountInfo(concurAccountInfo); updateExpenseReportStatusInConcur(); } } }

Target:
public void processConcurEventNotifications() { Collection<ConcurEventNotification> concurEventNotifications = concurEventNotificationService.retrieveConcurEventNotificationsForProcessing(); if (ObjectUtils.isNotNull(concurEventNotifications)) { for (ConcurEventNotification concurEventNotification : concurEventNotifications) { ExpenseDetailedReportDTO expenseDetailedReport = retrieveExpenseDetailedReportFromConcur(concurEventNotification); ConcurAccountInfo concurAccountInfo = extractAccountInfo(expenseDetailedReport); concurAccountValidationService.validateConcurAccountInfo(concurAccountInfo); updateExpenseReportStatusInConcur(); } } }
Source:
private HttpRedirect(String url, int code, String keepUri, String fqdn, String zone) { this.url = checkNotNull(url, "url"); checkArgument(code == 301 || code == 302, "code of %s must be 301 or 302", code); checkArgument("Y".equals(keepUri) || "N".equals(keepUri), "code of %s must be 'Y' or 'N'", keepUri); this.code = code; this.keepUri = keepUri; this.fqdn = checkNotNull(fqdn, "fqdn");; this.zone = checkNotNull(zone, "zone"); this.delegate = ImmutableMap.<String, Object> builder() .put("url", url) .put("code", code) .put("keep_uri", keepUri) .put("fqdn", fqdn) .put("zone", zone).build(); }

Target:
private HttpRedirect(String url, int code, String keepUri, String fqdn, String zone) { this.url = checkNotNull(url, "url"); checkArgument(code == 301 || code == 302, "code must be 301 or 302 but was %s", code); this.code = code; checkNotNull(keepUri, "keepUri"); checkArgument("Y".equalsIgnoreCase(keepUri) || "N".equalsIgnoreCase(keepUri), "keepUri must be 'Y' or 'N' but was %s", keepUri); this.keepUri = keepUri.toUpperCase(); this.fqdn = checkNotNull(fqdn, "fqdn");; this.zone = checkNotNull(zone, "zone"); this.delegate = ImmutableMap.<String, Object> builder() .put("url", url) .put("code", code) .put("keep_uri", keepUri) .put("fqdn", fqdn) .put("zone", zone).build(); }
Source:
private void doGrowVine(EntityRef root, VineNodeComponent nodeComponent, VineDefinitionComponent vineComponent) { if (nodeComponent.length != -1) { if (nodeComponent.length < 20) { recurseGrow(root, vineComponent); } resetDelay(root, vineComponent.minGrowTime, vineComponent.maxGrowTime); } }

Target:
private void doGrowVine(EntityRef root, VineNodeComponent nodeComponent, VineDefinitionComponent vineComponent) { if (nodeComponent.length != -1) { if (nodeComponent.length < vineComponent.maxLength) { recurseGrow(root, vineComponent); } resetDelay(root, vineComponent.minGrowTime, vineComponent.maxGrowTime); } }
Source:
public String getThemeStyleSheet(ApplicationType type) { if (type == null) { type = DEFAULT_APPLICATION_TYPE; } return brandingProperties.getProperty(type.getCssKey()); }

Target:
public String getThemeStyleSheet(ApplicationType type) { return brandingProperties.getProperty(type.getCssKey()); }
Source:
public boolean shouldContinue() { long spent = currentTimeSeconds() - startTime; boolean shouldContinue; if (spent >= totalRuntime) { for (Thread t : workers) { if (t.isAlive()) { try { t.interrupt(); t.join(); } catch (InterruptedException ignored) { } } } shouldContinue = false; } else { int total = workers.size(); int done = 0; for (Thread t : workers) { if (!t.isAlive()) done++; } shouldContinue = !(done == total); } if(!shouldContinue) { out.close(); } return shouldContinue; }

Target:
public boolean shouldContinue() { long spent = currentTimeSeconds() - _startTime; boolean shouldContinue; if (spent >= _totalRuntime) { for (Thread t : _workers) { if (t.isAlive()) { try { t.interrupt(); t.join(); } catch (InterruptedException ignored) { } } } shouldContinue = false; } else { int total = _workers.size(); int done = 0; for (Thread t : _workers) { if (!t.isAlive()) { done++; } } shouldContinue = (done != total); } if (!shouldContinue) { _out.close(); } return shouldContinue; }
Source:
public void finalizeTerminationForInstancesWithoutInstanceIds(Long stackId) { try { transactionService.required(() -> { Stack stack = stackService.getByIdWithListsInTransaction(stackId); terminateInstancesWithoutInstanceIds(stack); return null; }); } catch (TransactionExecutionException ex) { LOGGER.info("Failed to terminate cluster infrastructure."); throw new TerminationFailedException(ex); } }

Target:
public void finalizeTerminationForInstancesWithoutInstanceIds(Long stackId) { Stack stack = stackService.getByIdWithListsInTransaction(stackId); terminateInstancesWithoutInstanceIds(stack); }
Source:
public void selectByQuery_on_empty_list_of_component_uuids() { ComponentQuery dbQuery = ComponentQuery.builder().setQualifiers(Qualifiers.PROJECT).setComponentUuids(emptySet()).build(); List<ComponentDto> result = underTest.selectByQuery(dbSession, dbQuery, 0, 10); int count = underTest.countByQuery(dbSession, dbQuery); assertThat(result).isEmpty(); assertThat(count).isEqualTo(0); }

Target:
public void selectByQuery_on_empty_list_of_component_uuids() { db.components().insertPrivateProject(); ComponentQuery dbQuery = ComponentQuery.builder().setQualifiers(Qualifiers.PROJECT).setComponentUuids(emptySet()).build(); List<ComponentDto> result = underTest.selectByQuery(dbSession, dbQuery, 0, 10); int count = underTest.countByQuery(dbSession, dbQuery); assertThat(result).isEmpty(); assertThat(count).isEqualTo(0); }
Source:
public static File findTemplateDirectory(Class<?> type) { try { String classFolder = type.getName().replace(".", "/"); URL resource = type.getClassLoader().getResource(classFolder); if (resource != null) { return new File(resource.toURI()); } } catch (URISyntaxException ignored) return null; }

Target:
private static File findTemplateDirectory(Class<?> type) { try { String classFolder = getPath(type); URL resource = type.getClassLoader().getResource(classFolder); if (resource != null) { return new File(resource.toURI()); } } catch (URISyntaxException ignored) { } return null; }
Source:
public void testWriter() throws SQLException { DbState writer = DbState.writer(DbState.driverManager("jdbc:h2:mem:")); DB<Unit> setup = new DB<Unit>() { @Override public Unit run(Connection c) throws SQLException { Statement s = c.createStatement(); assertThat(s.executeUpdate("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"), is(0)); assertThat(s.executeUpdate("INSERT INTO TEST (ID, NAME) VALUES (10, 'FOO')"), is (1)); return Unit.unit(); } }; DB<Option<Integer>> query = new DB<Option<Integer>>() { @Override public Option<Integer> run(Connection c) throws SQLException { PreparedStatement ps = c.prepareStatement("SELECT ID FROM TEST WHERE NAME = ?"); ps.setString(1, "FOO"); ResultSet rs = ps.executeQuery(); if (rs.next()) { return Option.some(rs.getInt("ID")); } else { return Option.none(); } } }; assertThat(writer.run(setup.bind(v -> query)).some(), is(10)); }

Target:
public void testWriter() throws SQLException { final int TEN = 10; DbState writer = DbState.writer(DbState.driverManager("jdbc:h2:mem:")); DB<Unit> setup = new DB<Unit>() { @Override public Unit run(Connection c) throws SQLException { Statement s = null; try { s = c.createStatement(); assertThat(s.executeUpdate("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"), is(0)); assertThat(s.executeUpdate("INSERT INTO TEST (ID, NAME) VALUES (" + TEN + ", 'FOO')"), is(1)); } finally { DbUtils.closeQuietly(s); } return Unit.unit(); } }; DB<Option<Integer>> query = new DB<Option<Integer>>() { @Override public Option<Integer> run(Connection c) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; try { ps = c.prepareStatement("SELECT ID FROM TEST WHERE NAME = ?"); ps.setString(1, "FOO"); rs = ps.executeQuery(); if (rs.next()) { return Option.some(rs.getInt("ID")); } else { return Option.none(); } } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(ps); } } }; assertThat(writer.run(setup.bind(v -> query)).some(), is(TEN)); }
Source:
private PutChunk getChunkToFill() { if (latestFillerChunk != null && latestFillerChunk.isBuilding()) { return latestFillerChunk; } else { for (PutChunk chunk : putChunks) { if (chunk.isFree()) { chunkCounter++; chunk.prepareForBuilding(chunkCounter, getSizeOfChunkAt(chunkCounter)); latestFillerChunk = chunk; return chunk; } } } return null; }

Target:
private PutChunk getChunkToFill() { if (chunkToFill != null && chunkToFill.isBuilding()) { return chunkToFill; } chunkToFill = null; for (PutChunk chunk : putChunks) { if (chunk.isFree()) { chunkCounter++; chunk.prepareForBuilding(chunkCounter, getSizeOfChunkAt(chunkCounter)); chunkToFill = chunk; break; } } return chunkToFill; }
Source:
public void start() { List<Encounter> mVisitNoteEncounters = new EncounterDAO().getAllEncountersByType(mPatient.getId(), new EncounterType(EncounterType.VISIT_NOTE)); mPatientDiagnosisView.setDiagnosesToDisplay(getAllDiagnosis(mVisitNoteEncounters)); }

Target:
public void start() { loadDiagnosis(); }
Source:
public List<OAIRecord> findOaiRecordsBySetName(String setName, Date from, Date until, boolean excludeSet) { String queryString ="SELECT object(h) from OAIRecord as h where h.id is not null"; if (setName != null) { if (excludeSet) { queryString += " and h.setName is not null and h.setName != '' and h.setName != :setName"; } else { queryString += " and h.setName = :setName"; } } else { queryString += " and h.setName is null"; } queryString += from != null ? " and h.lastUpdateTime >= :from" : ""; queryString += until != null ? " and h.lastUpdateTime<=:until" : ""; queryString += " order by h.globalId"; logger.fine("Query: "+queryString); Query query = em.createQuery(queryString); if (setName != null) { query.setParameter("setName",setName); } if (from != null) { query.setParameter("from",from,TemporalType.TIMESTAMP); } if (until != null) { if (until.getTime() % (24 * 3600 * 1000) == 0) { logger.fine("plain date. incrementing by one day"); until.setTime(until.getTime()+(24 * 3600 * 1000)); } else { logger.fine("date and time. incrementing by one second"); until.setTime(until.getTime()+1000); } query.setParameter("until",until,TemporalType.TIMESTAMP); } try { return query.getResultList(); } catch (Exception ex) { logger.fine("Caught exception; returning null."); return null; } }

Target:
public List<OAIRecord> findOaiRecordsBySetName(String setName, Date from, Date until, boolean excludeSet) { String queryString ="SELECT object(h) from OAIRecord h where h.id is not null"; if (setName != null) { if (excludeSet) { queryString += " and h.setName is not null and h.setName != '' and h.setName != :setName"; } else { queryString += " and h.setName = :setName"; } } else { queryString += " and h.setName is null"; } queryString += from != null ? " and h.lastUpdateTime >= :from" : ""; queryString += until != null ? " and h.lastUpdateTime<=:until" : ""; queryString += " order by h.globalId"; logger.fine("Query: "+queryString); Query query = em.createQuery(queryString); if (setName != null) { query.setParameter("setName",setName); } if (from != null) { query.setParameter("from",from,TemporalType.TIMESTAMP); } if (until != null) { if (until.getTime() % (24 * 3600 * 1000) == 0) { logger.fine("plain date. incrementing by one day"); until.setTime(until.getTime()+(24 * 3600 * 1000)); } else { logger.fine("date and time. incrementing by one second"); until.setTime(until.getTime()+1000); } query.setParameter("until",until,TemporalType.TIMESTAMP); } try { return query.getResultList(); } catch (Exception ex) { logger.fine("Caught exception; returning null."); return null; } }
Source:
protected boolean checkIfLunDiskCanBeAdded(DiskValidator diskValidator) { LunDisk lunDisk = ((LunDisk) getParameters().getDiskInfo()); LUNs lun = lunDisk.getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } for (StorageServerConnections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } break; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } if (getVm() != null && !(isVmNotLocked() && isVmNotInPreviewSnapshot())) { return false; } if (!validate(diskValidator.isVirtIoScsiValid(getVm()))) { return false; } if (!validate(diskValidator.isDiskInterfaceSupported(getVm()))) { return false; } if (getVds() != null && !validate(diskValidator.isLunDiskVisible(lun, getVds()))) { return false; } ValidationResult validationResult = diskValidator.isUsingScsiReservationValid(getVm(), lunDisk); if (!validate(validationResult)) { return false; } return true; }

Target:
protected boolean checkIfLunDiskCanBeAdded(DiskValidator diskValidator) { LunDisk lunDisk = ((LunDisk) getParameters().getDiskInfo()); LUNs lun = lunDisk.getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } for (StorageServerConnections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } break; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } if (getVm() != null && !(isVmNotLocked() && isVmNotInPreviewSnapshot())) { return false; } if (!validate(diskValidator.isVirtIoScsiValid(getVm()))) { return false; } if (!validate(diskValidator.isDiskInterfaceSupported(getVm()))) { return false; } if (getVds() != null && !validate(diskValidator.isLunDiskVisible(lun, getVds()))) { return false; } if (!validate(diskValidator.isUsingScsiReservationValid(getVm(), lunDisk))) { return false; } return true; }
Source:
protected boolean canMigrateVm(VM vm) { if (vm == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND); } else { if (vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_PINNED_TO_HOST); } if (vm.getMigrationSupport() == MigrationSupport.IMPLICITLY_NON_MIGRATABLE && !forcedMigrationForNonMigratableVM) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NON_MIGRTABLE_AND_IS_NOT_FORCED_BY_USER_TO_MIGRATE); } if (vm.getStatus() == VMStatus.MigratingFrom) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_MIGRATION_IN_PROGRESS); } if (vm.getStatus() == VMStatus.NotResponding) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL); } if (vm.getStatus() == VMStatus.Paused) { return failCanDoAction(VdcBllMessages.MIGRATE_PAUSED_VM_IS_UNSUPPORTED); } if (!vm.isQualifyToMigrate()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_RUNNING); } if (getDestinationVds() != null && getDestinationVds().getStatus() != VDSStatus.Up) { addCanDoActionMessage(VdcBllMessages.VAR__HOST_STATUS__UP); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL); } return validate(new DiskImagesValidator(ImagesHandler.getPluggedImagesForVm(vm.getId())).diskImagesNotLocked()) && validate(new SnapshotsValidator().vmNotDuringSnapshot(vm.getId())) && getVdsSelector().canFindVdsToRunOn(getReturnValue().getCanDoActionMessages(), true); } }

Target:
protected boolean canMigrateVm(VM vm) { if (vm == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (vm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_PINNED_TO_HOST); } if (vm.getMigrationSupport() == MigrationSupport.IMPLICITLY_NON_MIGRATABLE && !forcedMigrationForNonMigratableVM) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NON_MIGRTABLE_AND_IS_NOT_FORCED_BY_USER_TO_MIGRATE); } if (vm.getStatus() == VMStatus.MigratingFrom) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_MIGRATION_IN_PROGRESS); } if (vm.getStatus() == VMStatus.NotResponding) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL); } if (vm.getStatus() == VMStatus.Paused) { return failCanDoAction(VdcBllMessages.MIGRATE_PAUSED_VM_IS_UNSUPPORTED); } if (!vm.isQualifyToMigrate()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_RUNNING); } if (getDestinationVds() != null && getDestinationVds().getStatus() != VDSStatus.Up) { addCanDoActionMessage(VdcBllMessages.VAR__HOST_STATUS__UP); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL); } return validate(new DiskImagesValidator(ImagesHandler.getPluggedImagesForVm(vm.getId())).diskImagesNotLocked()) && validate(new SnapshotsValidator().vmNotDuringSnapshot(vm.getId())) && getVdsSelector().canFindVdsToRunOn(getReturnValue().getCanDoActionMessages(), true); }
Source:
protected ScheduledExecutorService startKerberosLoginThread() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.schedule(new Callable() { public Object call() throws Exception { if (runKerberosLogin()) { scheduledExecutorService .schedule(this, getTimeAsMs(getKerberosRefreshInterval()), TimeUnit.MILLISECONDS); } else { kinitFailCount++; logger.info("runKerberosLogin failed for " + kinitFailCount + "time"); if (kinitFailCount >= kinitFailThreshold()) { logger.error("runKerberosLogin failed for max attempts, calling close interpreter."); close(); } else { scheduledExecutorService.submit(this); } } return null; } }, getTimeAsMs(getKerberosRefreshInterval()), TimeUnit.MILLISECONDS); return scheduledExecutorService; }

Target:
protected ScheduledExecutorService startKerberosLoginThread() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.schedule(new Callable() { public Object call() throws Exception { if (runKerberosLogin()) { logger.info("Ran runKerberosLogin command successfully."); kinitFailCount = 0; scheduledExecutorService .schedule(this, getTimeAsMs(getKerberosRefreshInterval()), TimeUnit.MILLISECONDS); } else { kinitFailCount++; logger.info("runKerberosLogin failed for " + kinitFailCount + " time(s)."); if (kinitFailCount >= kinitFailThreshold()) { logger.error("runKerberosLogin failed for max attempts, calling close interpreter."); close(); } else { scheduledExecutorService.submit(this); } } return null; } }, getTimeAsMs(getKerberosRefreshInterval()), TimeUnit.MILLISECONDS); return scheduledExecutorService; }
Source:
protected void onBind() { super.onBind(); logger.info("onBind"); getModel().retrieveEngineErrata(); getModel().addErrorMessageChangeListener(new IEventListener<PropertyChangedEventArgs>(){ @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { logger.info(this.getClass().toString() + " eventRaised"); if (getModel().getMessage() != null && !getModel().getMessage().isEmpty()) { logger.info("bus published message that there was a query error. update view."); getView().showErrorMessage(SafeHtmlUtils.fromString(getModel().getMessage())); } else if (getModel().getMessage() == null || getModel().getMessage().isEmpty()) { logger.info("bus published message that there was not a query error. clearMessage() / show table."); getView().clearErrorMessage(); } } }); }

Target:
protected void onBind() { super.onBind(); getModel().retrieveEngineErrata(); getModel().addErrorMessageChangeListener(new IEventListener<PropertyChangedEventArgs>(){ @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if (getModel().getMessage() != null && !getModel().getMessage().isEmpty()) { getView().showErrorMessage(SafeHtmlUtils.fromString(getModel().getMessage())); } else if (getModel().getMessage() == null || getModel().getMessage().isEmpty()) { getView().clearErrorMessage(); } } }); }
Source:
private void setSpiceImplementation() { consoleMode = ClientConsoleMode.valueOf((String) AsyncDataProvider.GetConfigValuePreConverted(ConfigurationValues.ClientConsoleModeDefault)); switch (consoleMode) { case Native: setspice((ISpice) TypeResolver.getInstance().Resolve(ISpiceNative.class)); break; case Plugin: setspice((ISpice) TypeResolver.getInstance().Resolve(ISpicePlugin.class)); break; default: ISpicePlugin pluginSpice = (ISpicePlugin) TypeResolver.getInstance().Resolve(ISpicePlugin.class); if (pluginSpice.detectBrowserPlugin()) { setspice(pluginSpice); } else { setspice((ISpice) TypeResolver.getInstance().Resolve(ISpiceNative.class)); } break; } }

Target:
private void setSpiceImplementation() { consoleMode = ClientConsoleMode.valueOf((String) AsyncDataProvider.GetConfigValuePreConverted(ConfigurationValues.ClientConsoleModeDefault)); switch (consoleMode) { case Native: setspice((ISpice) TypeResolver.getInstance().Resolve(ISpiceNative.class)); break; case Plugin: setspice((ISpice) TypeResolver.getInstance().Resolve(ISpicePlugin.class)); break; default: ISpicePlugin pluginSpice = (ISpicePlugin) TypeResolver.getInstance().Resolve(ISpicePlugin.class); setspice(pluginSpice.detectBrowserPlugin() ? pluginSpice : (ISpice) TypeResolver.getInstance().Resolve(ISpiceNative.class)); break; } }
Source:
private void restoreSavedInstanceState(Bundle savedInstanceState) { boolean isInSearchMode = false; String lastSearch = ""; if (savedInstanceState != null) { mCurrentLocalId = savedInstanceState.getInt(KEY_LOCAL_ID); isInSearchMode = savedInstanceState.getBoolean(KEY_IS_IN_SEARCH_MODE); lastSearch = savedInstanceState.getString(KEY_LAST_SEARCH); mSitePickerMode = (SitePickerMode) savedInstanceState.getSerializable(KEY_SITE_PICKER_MODE); mHashSelectedPositions = (HashSet<Integer>) savedInstanceState.getSerializable(KEY_SELECTED_POSITIONS); mIsInEditMode = savedInstanceState.getBoolean(KEY_IS_IN_EDIT_MODE); mShowMenuEnabled = savedInstanceState.getBoolean(KEY_IS_SHOW_MENU_ENABLED); mHideMenuEnabled = savedInstanceState.getBoolean(KEY_IS_HIDE_MENU_ENABLED); } else if (getIntent() != null) { mCurrentLocalId = getIntent().getIntExtra(KEY_LOCAL_ID, 0); mSitePickerMode = (SitePickerMode) getIntent().getSerializableExtra(KEY_SITE_PICKER_MODE); } setNewAdapter(lastSearch, isInSearchMode); }

Target:
private void restoreSavedInstanceState(Bundle savedInstanceState) { boolean isInSearchMode = false; String lastSearch = ""; if (savedInstanceState != null) { mCurrentLocalId = savedInstanceState.getInt(KEY_LOCAL_ID); isInSearchMode = savedInstanceState.getBoolean(KEY_IS_IN_SEARCH_MODE); lastSearch = savedInstanceState.getString(KEY_LAST_SEARCH); mSitePickerMode = (SitePickerMode) savedInstanceState.getSerializable(KEY_SITE_PICKER_MODE); mSelectedPositions = (HashSet<Integer>) savedInstanceState.getSerializable(KEY_SELECTED_POSITIONS); mIsInEditMode = savedInstanceState.getBoolean(KEY_IS_IN_EDIT_MODE); mShowMenuEnabled = savedInstanceState.getBoolean(KEY_IS_SHOW_MENU_ENABLED); mHideMenuEnabled = savedInstanceState.getBoolean(KEY_IS_HIDE_MENU_ENABLED); } else if (getIntent() != null) { mCurrentLocalId = getIntent().getIntExtra(KEY_LOCAL_ID, 0); mSitePickerMode = (SitePickerMode) getIntent().getSerializableExtra(KEY_SITE_PICKER_MODE); } setNewAdapter(lastSearch, isInSearchMode); }