auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.sp_field_officer: fieldOfficerId = mSavingProductsTemplateByProductId .getFieldOfficerOptions().get(position).getId(); break; case R.id.sp_product: productId = mProductSavings.get(position).getId(); if (clientId != 0) { mSavingsAccountPresenter. loadClientSavingAccountTemplateByProduct(clientId, productId); } else { mSavingsAccountPresenter. loadGroupSavingAccountTemplateByProduct(groupId, productId); } break; } }

Target:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.sp_field_officer: fieldOfficerId = mSavingProductsTemplateByProductId .getFieldOfficerOptions().get(position).getId(); break; case R.id.sp_product: productId = mProductSavings.get(position).getId(); if (isGroupAccount) { mSavingsAccountPresenter. loadGroupSavingAccountTemplateByProduct(groupId, productId); } else { mSavingsAccountPresenter. loadClientSavingAccountTemplateByProduct(clientId, productId); } break; } }
Source:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); print(response); checkStation1Exists(response); JSONObject station = getFeaturePropertiesById(response, "st.2"); assertThat(station, notNullValue()); JSONObject contact = station.getJSONObject("contact"); assertThat(contact.size(), is(3)); assertThat(contact.get("@mail"), is("st2@stations.org")); JSONObject phone = contact.getJSONObject("phone"); assertThat(phone.size(), is(1)); assertFalse(phone.has("value")); assertThat(phone.get("@timeZone"), is("")); }

Target:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); checkStation1Exists(response); JSONObject station = getFeaturePropertiesById(response, "st.2"); assertThat(station, notNullValue()); JSONObject contact = station.getJSONObject("contact"); assertThat(contact.size(), is(3)); assertThat(contact.get("@mail"), is("st2@stations.org")); JSONObject phone = contact.getJSONObject("phone"); assertThat(phone.size(), is(1)); assertFalse(phone.has("value")); assertThat(phone.get("@timeZone"), is("")); }
Source:
void highlightView(View view) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams instanceof MarginLayoutParams) { MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layoutParams; mMargins = new Rect(marginLayoutParams.leftMargin, marginLayoutParams.topMargin, marginLayoutParams.rightMargin, marginLayoutParams.bottomMargin); } mPaddings = new Rect(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom()); }

Target:
void highlightView(View view) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams instanceof MarginLayoutParams) { MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layoutParams; mMargins.left = marginLayoutParams.leftMargin; mMargins.top = marginLayoutParams.topMargin; mMargins.right = marginLayoutParams.rightMargin; mMargins.bottom = marginLayoutParams.bottomMargin; } else { mMargins.left = 0; mMargins.top = 0; mMargins.right = 0; mMargins.bottom = 0; } mPaddings.left = view.getPaddingLeft(); mPaddings.top = view.getPaddingTop(); mPaddings.right = view.getPaddingRight(); mPaddings.bottom = view.getPaddingBottom(); }
Source:
public List<CustomAttributes> getAttributes() { return attributes; }

Target:
public List<CustomAttribute> getAttributes() { return Collections.unmodifiableList(attributes); }
Source:
public static MessageBufferInput newBufferInput(InputStream in) { if(in instanceof ByteArrayInputStream) { ByteArrayInputStream b = (ByteArrayInputStream) in; try { byte[] buf = (byte[]) bufField.get(b); int pos = (Integer) bufPosField.get(b); int length = (Integer) bufCountField.get(b); return new ArrayBufferInput(buf, pos, length); } catch(Exception e) { } } else if (in instanceof FileInputStream) { return new ChannelBufferInput(((FileInputStream) in).getChannel()); } return new InputStreamBufferInput(in); }

Target:
public static MessageBufferInput newBufferInput(InputStream in) { checkNotNull(in, "InputStream is null"); if(in.getClass() == ByteArrayInputStream.class) { ByteArrayInputStream b = (ByteArrayInputStream) in; try { byte[] buf = (byte[]) bufField.get(b); int pos = (Integer) bufPosField.get(b); int length = (Integer) bufCountField.get(b); return new ArrayBufferInput(buf, pos, length); } catch(Exception e) { } } else if (in instanceof FileInputStream) { return new ChannelBufferInput(((FileInputStream) in).getChannel()); } return new InputStreamBufferInput(in); }
Source:
public ComponentBuilder append( BaseComponent[] components, FormatRetention retention ) { Preconditions.checkArgument( components.length != 0, "No components to append" ); parts.add( current ); Collections.addAll( parts, components ); current = components[ components.length - 1 ]; retain( retention ); return this; }

Target:
public ComponentBuilder append(BaseComponent[] components, FormatRetention retention) { Preconditions.checkArgument( components.length != 0, "No components to append" ); for ( BaseComponent component : components ) { parts.add( current ); current = component.duplicate(); retain( retention ); } return this; }
Source:
public void updateStats() { physics.setTopSpeed((int) (SPEED + (_score * 1))); weapon.setBulletSpeed((int) (BULLET_SPEED + (_score * 1))); weapon.setFireRate((int) (FIRE_RATE + (_score * 1))); weapon.setDamage((int) (DAMAGE + (_score * 1))); weapon.setMagazineMaxSize((int) (MAGAZINE_MAX_SIZE + (_score * 1))); weapon.setReloadSpeed((int) (RELOAD_SPEED + (_score * 1))); }

Target:
public void updateStats() { physics.setTopSpeed( SPEED + (int) (_score * 1)); weapon.setBulletSpeed( BULLET_SPEED + (int) (_score * 1)); weapon.setFireRate( FIRE_RATE + (int) (_score * 1)); weapon.setDamage( DAMAGE + (int) (_score * 1)); weapon.setMagazineMaxSize( MAGAZINE_MAX_SIZE + (int) (_score * 1)); weapon.setReloadSpeed( RELOAD_SPEED + (int) (_score * 1)); }
Source:
public void onServoEvent(Integer eventType, double currentPos) { currentPosInput = mapper.calcInput(currentPos); if (isIKEventEnabled) { ServoEventData data = new ServoEventData(); data.name = getName(); data.pos = currentPosInput; data.state = eventType; data.velocity = velocity; data.targetPos = this.targetPos; invoke("publishIKServoEvent", data); } if (eventType == SERVO_EVENT_STOPPED) { moving = false; } else { moving = true; } if (isEventsEnabled) { invoke("publishServoEvent", currentPosInput); } }

Target:
public void onServoEvent(Integer eventType, double currentPos) { log.info("On servo event called with a current pos {}", currentPos); currentPosInput = mapper.calcInput(currentPos); if (isIKEventEnabled) { ServoEventData data = new ServoEventData(); data.name = getName(); data.pos = currentPosInput; data.state = eventType; data.velocity = velocity; data.targetPos = this.targetPos; invoke("publishIKServoEvent", data); } if (eventType == SERVO_EVENT_STOPPED) { moving = false; } else { moving = true; } if (isEventsEnabled) { invoke("publishServoEvent", currentPosInput); } }
Source:
public void testOperations() { MathOperation multiplication = (int a, int b) -> { return a * b; }; Optional<String> description = getDescriptionForIntCallable(() -> {return this.operate(5, 3, multiplication);});; assertTrue(description.isPresent()); assertNameMatch("operate(_,_,_).Integer.valueOf(_)", "testOperations", CLASSNAME, description.get().toString()); }

Target:
public void testOperations() { MathOperation multiplication = (int a, int b) -> { return a * b; }; Optional<String> description = getDescriptionForIntCallable(() -> {return this.operate(5, 3, multiplication);});; assertTrue(description.isPresent()); assertNameMatch("operate(_,_,_)", "testOperations", CLASSNAME, description.get()); }
Source:
public void restartFrom(RecordsRetrieved recordsRetrieved) { if (!(recordsRetrieved instanceof PrefetchRecordsRetrieved)) { throw new IllegalArgumentException( "Provided RecordsRetrieved was not produced by the PrefetchRecordsPublisher"); } PrefetchRecordsRetrieved prefetchRecordsRetrieved = (PrefetchRecordsRetrieved) recordsRetrieved; resetLock.writeLock().lock(); try { requestedResponses.set(0); getRecordsResultQueue.clear(); giveDrainingControlToPublisherOrDemandNotifier(); prefetchCounters.reset(); highestSequenceNumber = prefetchRecordsRetrieved.lastBatchSequenceNumber(); dataFetcher.resetIterator(prefetchRecordsRetrieved.shardIterator(), highestSequenceNumber, initialPositionInStreamExtended); wasReset = true; } finally { resetLock.writeLock().unlock(); } }

Target:
public void restartFrom(RecordsRetrieved recordsRetrieved) { if (!(recordsRetrieved instanceof PrefetchRecordsRetrieved)) { throw new IllegalArgumentException( "Provided RecordsRetrieved was not produced by the PrefetchRecordsPublisher"); } resetLock.writeLock().lock(); try { publisherSession.reset((PrefetchRecordsRetrieved)recordsRetrieved); wasReset = true; } finally { resetLock.writeLock().unlock(); } }
Source:
static Optional<String> getClientName(Principal principal) { X500Name name = new X500Name(principal.getName()); RDN[] rdns = name.getRDNs(BCStyle.CN); if (rdns.length == 0) { logger.warn("Certificate does not contain CN=xxx,...: {}", principal.getName()); return Optional.empty(); } return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue())); }

Target:
static Optional<String> getClientName(Principal principal) { X500Name name = new X500Name(principal.getName()); RDN[] rdns = name.getRDNs(BCStyle.CN); if (rdns.length == 0) { logger.warn("Certificate's subject does not contain CN=xxx,...: {}", principal.getName()); return Optional.empty(); } return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue())); }
Source:
public List<MetricFamilySamples> collect() { GaugeMetricFamily availablePermissionsFamily = new GaugeMetricFamily( names.getAvailablePermissionsMetricName(), "The number of rate limiter available permissions", LabelNames.NAME ); GaugeMetricFamily waitingThreadsFamily = new GaugeMetricFamily( names.getWaitingThreadsMetricName(), "The number of rate limiter waiting threads", LabelNames.NAME ); for (RateLimiter rateLimiter : supplier.get()) { List<String> nameLabel = singletonList(rateLimiter.getName()); availablePermissionsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getAvailablePermissions()); waitingThreadsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getNumberOfWaitingThreads()); } return Arrays.asList(availablePermissionsFamily, waitingThreadsFamily); }

Target:
public List<MetricFamilySamples> collect() { GaugeMetricFamily availablePermissionsFamily = new GaugeMetricFamily( names.getAvailablePermissionsMetricName(), "The number of available permissions", LabelNames.NAME ); GaugeMetricFamily waitingThreadsFamily = new GaugeMetricFamily( names.getWaitingThreadsMetricName(), "The number of waiting threads", LabelNames.NAME ); for (RateLimiter rateLimiter : supplier.get()) { List<String> nameLabel = singletonList(rateLimiter.getName()); availablePermissionsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getAvailablePermissions()); waitingThreadsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getNumberOfWaitingThreads()); } return Arrays.asList(availablePermissionsFamily, waitingThreadsFamily); }
Source:
public void sampleBoardAutoCreationTest() { assertEquals(panelControl.getNumberOfSavedBoards(), 0); clickMenu("Boards", "Auto-create", SAMPLE_BOARD); waitUntilNodeAppears(SAMPLE_BOARD_DIALOG); click("OK"); assertEquals(panelControl.getPanelCount(), BoardAutoCreator.getSamplePanelDetails().size()); assertEquals(panelControl.getCurrentlySelectedPanel(), Optional.of(0)); assertEquals(panelControl.getNumberOfSavedBoards(), 1); List<PanelInfo> panelInfos = panelControl.getCurrentPanelInfos(); int i = 0; for (String panelName : BoardAutoCreator.getSamplePanelDetails().keySet()) { assertEquals(panelInfos.get(i).getPanelName(), panelName); i++; } int j = 0; for (String panelFilter : BoardAutoCreator.getSamplePanelDetails().values()) { assertEquals(panelInfos.get(j).getPanelFilter(), panelFilter); j++; } }

Target:
public void sampleBoardAutoCreationTest() { assertEquals(panelControl.getNumberOfSavedBoards(), 0); clickMenu("Boards", "Auto-create", SAMPLE_BOARD); waitUntilNodeAppears(SAMPLE_BOARD_DIALOG); click("OK"); verifyBoard(panelControl, BoardAutoCreator.getSamplePanelDetails()); }
Source:
public Collection<Event> search(final Optional<RyaURI> subject, final Optional<Collection<IndexingExpr>> geoFilters, final Optional<Collection<IndexingExpr>> temporalFilters) throws EventStorageException { requireNonNull(subject); try { final Collection<IndexingExpr> geos = (geoFilters.isPresent() ? geoFilters.get() : new ArrayList<>()); final Collection<IndexingExpr> tempos = (temporalFilters.isPresent() ? temporalFilters.get() : new ArrayList<>()); final DBObject filterObj = queryAdapter.getFilterQuery(geos, tempos); final BasicDBObjectBuilder builder = BasicDBObjectBuilder .start(filterObj.toMap()); if(subject.isPresent()) { builder.append(EventDocumentConverter.SUBJECT, subject.get().getData()); } final MongoCursor<Document> results = mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .find( BsonDocument.parse(builder.get().toString()) ) .iterator(); final List<Event> events = new ArrayList<>(); final EventDocumentConverter adapter = new EventDocumentConverter(); while(results.hasNext()) { events.add(adapter.fromDocument(results.next())); } return events; } catch(final MongoException | DocumentConverterException | GeoTemporalIndexException e) { throw new EventStorageException("Could not get the Event.", e); } }

Target:
public Collection<Event> search(final Optional<RyaURI> subject, final Optional<Collection<IndexingExpr>> geoFilters, final Optional<Collection<IndexingExpr>> temporalFilters) throws EventStorageException { requireNonNull(subject); try { final Collection<IndexingExpr> geos = (geoFilters.isPresent() ? geoFilters.get() : new ArrayList<>()); final Collection<IndexingExpr> tempos = (temporalFilters.isPresent() ? temporalFilters.get() : new ArrayList<>()); final DBObject filterObj = queryAdapter.getFilterQuery(geos, tempos); final BasicDBObjectBuilder builder = BasicDBObjectBuilder .start(filterObj.toMap()); if(subject.isPresent()) { builder.append(EventDocumentConverter.SUBJECT, subject.get().getData()); } final MongoCursor<Document> results = mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .find( BsonDocument.parse(builder.get().toString()) ) .iterator(); final List<Event> events = new ArrayList<>(); while(results.hasNext()) { events.add(EVENT_CONVERTER.fromDocument(results.next())); } return events; } catch(final MongoException | DocumentConverterException | GeoTemporalIndexException e) { throw new EventStorageException("Could not get the Event.", e); } }
Source:
private String getDefaultVersion(Set<String> keys, String appName) { String aut = null; SortedSet<String> listOfApps = new TreeSet<String>(); if (keys.size() > 0) { for (String key : keys) { if (key.split(":")[0].contentEquals(appName)) { listOfApps.add(key); } } } if (listOfApps.size() > 0) { aut = listOfApps.last(); } return aut; }

Target:
private String getDefaultVersion(Set<String> keys, String appName) { SortedSet<String> listOfApps = new TreeSet<String>(); for (String key : keys) { if (key.split(":")[0].contentEquals(appName)) { listOfApps.add(key); } } return listOfApps.size() > 0 ? listOfApps.last() : null; }
Source:
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) { String githubClientId = propertyManager.getProperty(SocialProperties.GITHUB_CLIENT_ID); String githubSecret = propertyManager.getProperty(SocialProperties.GITHUB_SECRET); AdjustableGithubConnectionFactory githubFactory = new AdjustableGithubConnectionFactory(githubClientId, githubSecret); cfConfig.addConnectionFactory(githubFactory); reloadService.addFactory(IReloadService.GITHUB, githubFactory); identityProviderRegistry.addProvider(githubFactory.getProviderId()); identityProviderRegistry.addProviderTokenChecker(githubFactory.getProviderId(), GitHubChecker.ID); }

Target:
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) { String githubClientId = propertyManager.getProperty(SocialProperties.GITHUB_CLIENT_ID); String githubSecret = propertyManager.getProperty(SocialProperties.GITHUB_SECRET); AdjustableGithubConnectionFactory githubFactory = new AdjustableGithubConnectionFactory(githubClientId, githubSecret); cfConfig.addConnectionFactory(githubFactory); reloadService.addFactory(IReloadService.GITHUB, githubFactory); }
Source:
protected NotificationChannel getNotificationChannel(Context context, Intent intent) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel notificationChannel = new NotificationChannel("parse_push", "Push notifications", NotificationManager.IMPORTANCE_DEFAULT); nm.createNotificationChannel(notificationChannel); return notificationChannel; }

Target:
protected NotificationChannel getNotificationChannel(Context context, Intent intent) { return new NotificationChannel("parse_push", "Push notifications", NotificationManager.IMPORTANCE_DEFAULT); }
Source:
public int compareTo( PointValue other ) { return unsafeCompareTo(other); }

Target:
public int compareTo( PointValue other ) { int cmpCRS = this.crs.getCode() - other.crs.getCode(); if ( cmpCRS != 0 ) { return cmpCRS; } if ( this.coordinate.length > other.coordinate.length ) { return 1; } else if ( this.coordinate.length < other.coordinate.length ) { return -1; } for ( int i = 0; i < coordinate.length; i++ ) { int cmpVal = Double.compare( this.coordinate[i], other.coordinate[i] ); if ( cmpVal != 0 ) { return cmpVal; } } return 0; }
Source:
public void run() { while (!shutdown) { synchronized (this) { try { if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { logger.info( "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } }

Target:
public void run() { while (!shutdown) { synchronized (this) { try { if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { logger.error( "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } }
Source:
static HeadRules creaeHeadRules(TrainerToolParams params) throws IOException { ArtifactSerializer headRulesSerializer; if (params.getHeadRulesSerializerImpl() != null) { headRulesSerializer = ExtensionLoader.instantiateExtension(ArtifactSerializer.class, params.getHeadRulesSerializerImpl()); } else { if ("en".equals(params.getLang()) || "eng".equals(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } else if ("es".equals(params.getLang()) || "spa".equals(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.es.AncoraSpanishHeadRules.HeadRulesSerializer(); } else { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } } Object headRulesObject = headRulesSerializer.create(new FileInputStream(params.getHeadRules())); if (headRulesObject instanceof HeadRules) { return (HeadRules) headRulesObject; } else { throw new TerminateToolException(-1, "HeadRules Artifact Serializer must create an object of type HeadRules!"); } }

Target:
static HeadRules creaeHeadRules(TrainerToolParams params) throws IOException { ArtifactSerializer headRulesSerializer; if (params.getHeadRulesSerializerImpl() != null) { headRulesSerializer = ExtensionLoader.instantiateExtension(ArtifactSerializer.class, params.getHeadRulesSerializerImpl()); } else { if ("en".equalsIgnoreCase(params.getLang()) || "eng".equalsIgnoreCase(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } else if ("es".equalsIgnoreCase(params.getLang()) || "spa".equalsIgnoreCase(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.es.AncoraSpanishHeadRules.HeadRulesSerializer(); } else { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } } Object headRulesObject = headRulesSerializer.create(new FileInputStream(params.getHeadRules())); if (headRulesObject instanceof HeadRules) { return (HeadRules) headRulesObject; } else { throw new TerminateToolException(-1, "HeadRules Artifact Serializer must create an object of type HeadRules!"); } }
Source:
public void listWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listWithMultipleKeysRunner(key, key2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().keys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return new IterableResponse<>(Flux.fromStream(selected.stream())); }); }

Target:
public void listWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listWithMultipleKeysRunner(key, key2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().keys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); }
Source:
public Spliterator<T> spliterator() { class SpliteratorProxy implements Spliterator<T> { private final Spliterator<Tuple2<Integer, T>> spliterator; private SpliteratorProxy(Spliterator<Tuple2<Integer, T>> spliterator) { this.spliterator = spliterator; } @Override public boolean tryAdvance(Consumer<? super T> action) { return spliterator.tryAdvance(a -> action.accept(a._2)); } @Override public Spliterator<T> trySplit() { return new SpliteratorProxy(spliterator.trySplit()); } @Override public long estimateSize() { return spliterator.estimateSize(); } @Override public int characteristics() { return spliterator.characteristics(); } @Override public Comparator<? super T> getComparator() { return null; } } return new SpliteratorProxy(original.spliterator()); }

Target:
public Spliterator<T> spliterator() { class SpliteratorProxy implements Spliterator<T> { private final Spliterator<Tuple2<Integer, T>> spliterator; private SpliteratorProxy(Spliterator<Tuple2<Integer, T>> spliterator) { this.spliterator = spliterator; } @Override public boolean tryAdvance(Consumer<? super T> action) { return spliterator.tryAdvance(a -> action.accept(a._2)); } @Override public Spliterator<T> trySplit() { return new SpliteratorProxy(spliterator.trySplit()); } @Override public long estimateSize() { return spliterator.estimateSize(); } @Override public int characteristics() { return spliterator.characteristics(); } @Override public Comparator<? super T> getComparator() { if (hasCharacteristics(Spliterator.SORTED)) { return null; } throw new IllegalStateException(); } } return new SpliteratorProxy(original.spliterator()); }
Source:
private boolean hasRegistrationFormSelected() { SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions(); boolean registrationFormSelected = false; for (int i = 0; i < checkedItemPositions.size(); i++) { if (checkedItemPositions.valueAt(i)) { AvailableForm selectedForm = (AvailableForm) listView.getItemAtPosition(checkedItemPositions.keyAt(i)); if (selectedForm.hasDescriminator(Constants.FORM_DISCRIMINATOR_REGISTRATION)) { registrationFormSelected = true; } } } return registrationFormSelected; }

Target:
private boolean hasRegistrationFormSelected() { SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions(); boolean registrationFormSelected = false; for (int i = 0; i < checkedItemPositions.size(); i++) { if (checkedItemPositions.valueAt(i)) { AvailableForm selectedForm = (AvailableForm) listView.getItemAtPosition(checkedItemPositions.keyAt(i)); if (selectedForm.isRegistrationForm()) { registrationFormSelected = true; } } } return registrationFormSelected; }
Source:
protected PreparedStatement generateBulkInsertStatement(String table, int rows, String... cols) throws DatabaseException, SQLException { if (rows > 0) { StringBuilder builder, rowbuilder; if (!this.database.getDatabaseProductName().matches(".*(?i:oracle).*")) { rowbuilder = new StringBuilder(2 + cols.length << 1); rowbuilder.append('('); for (int i = 0; i < cols.length; ++i) { rowbuilder.append("?,"); } rowbuilder.deleteCharAt(rowbuilder.length() - 1).append(')'); builder = new StringBuilder(15 + 20 * cols.length + table.length() + (2 + cols.length * 3) * rows); builder.append("INSERT INTO ").append(table).append('('); for (String column : cols) { builder.append(column).append(','); } builder.deleteCharAt(builder.length() - 1).append(") VALUES"); for (int i = 0; i < rows; ++i) { builder.append(rowbuilder).append(','); } builder.deleteCharAt(builder.length() - 1); } else { rowbuilder = new StringBuilder(20 * cols.length + table.length()); rowbuilder.append("INTO ").append(table).append('('); for (String column : cols) { rowbuilder.append(column).append(','); } rowbuilder.deleteCharAt(rowbuilder.length() - 1).append(") VALUES("); for (int i = 0; i < cols.length; ++i) { rowbuilder.append("?,"); } rowbuilder.deleteCharAt(rowbuilder.length() - 1).append(") "); builder = new StringBuilder(30 + (20 * cols.length + table.length()) * rows); builder.append("INSERT ALL "); for (int i = 0; i < rows; ++i) { builder.append(rowbuilder); } builder.append("SELECT 1 FROM DUAL"); } return this.connection.prepareStatement(builder.toString()); } return null; }

Target:
protected PreparedStatement generateBulkInsertStatement(String table, int rows, String... cols) throws DatabaseException, SQLException { if (rows > 0) { StringBuilder builder, rowbuilder; if (!this.database.getDatabaseProductName().matches(".*(?i:oracle).*")) { rowbuilder = new StringBuilder(2 + cols.length * 2); rowbuilder.append('('); for (int i = 0; i < cols.length; ++i) { rowbuilder.append("?,"); } rowbuilder.deleteCharAt(rowbuilder.length() - 1).append(')'); builder = new StringBuilder(15 + 20 * cols.length + table.length() + (2 + cols.length * 3) * rows); builder.append("INSERT INTO ").append(table).append('('); for (String column : cols) { builder.append(column).append(','); } builder.deleteCharAt(builder.length() - 1).append(") VALUES"); for (int i = 0; i < rows; ++i) { builder.append(rowbuilder).append(','); } builder.deleteCharAt(builder.length() - 1); } else { rowbuilder = new StringBuilder(20 * cols.length + table.length()); rowbuilder.append("INTO ").append(table).append('('); for (String column : cols) { rowbuilder.append(column).append(','); } rowbuilder.deleteCharAt(rowbuilder.length() - 1).append(") VALUES("); for (int i = 0; i < cols.length; ++i) { rowbuilder.append("?,"); } rowbuilder.deleteCharAt(rowbuilder.length() - 1).append(") "); builder = new StringBuilder(30 + (20 * cols.length + table.length()) * rows); builder.append("INSERT ALL "); for (int i = 0; i < rows; ++i) { builder.append(rowbuilder); } builder.append("SELECT 1 FROM DUAL"); } return this.connection.prepareStatement(builder.toString()); } return null; }
Source:
public ExecutionPlan plan(ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc) { validateConfig(); JobGraph jobGraph = createJobGraph(config, appDesc, new JobGraphJsonGenerator(), new JobNodeConfigureGenerator()); fetchInputAndOutputStreamPartitions(jobGraph, streamManager); new IntermediateStreamPartitionPlanner(config, appDesc).calculatePartitions(jobGraph); return jobGraph; }

Target:
public ExecutionPlan plan(ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc) { validateConfig(); JobGraph jobGraph = createJobGraph(config, appDesc); setInputAndOutputStreamPartitionCount(jobGraph, streamManager); new IntermediateStreamManager(config, appDesc).calculatePartitions(jobGraph); return jobGraph; }
Source:
public static SortOrder toSortOrder(SortItem sortItem) { if (sortItem.getOrdering() == SortItem.Ordering.ASCENDING) { if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.ASC_NULLS_FIRST; } else { return SortOrder.ASC_NULLS_LAST; } } else { if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.DESC_NULLS_FIRST; } else { return SortOrder.DESC_NULLS_LAST; } } }

Target:
public static SortOrder toSortOrder(SortItem sortItem) { if (sortItem.getOrdering() == SortItem.Ordering.ASCENDING) { if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.ASC_NULLS_FIRST; } return SortOrder.ASC_NULLS_LAST; } if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.DESC_NULLS_FIRST; } return SortOrder.DESC_NULLS_LAST; }
Source:
public void prepare() throws NotDeliciousException { this.addCondiments("sour cream", "chives", "butter", "crumbled bacon", "grated cheese", "ketchup", "salt", "tabasco", "pepporoni", "sausage"); this.listCondiments(); if(!this.isDelicious()) throw new NotDeliciousException(); }

Target:
public void prepare() throws NotDeliciousException { this.addCondiments("sour cream", "chives", "butter", "crumbled bacon", "grated cheese", "ketchup", "salt", "tabasco", "pepperoni", "sausage"); this.listCondiments(); if(!this.isDelicious()) throw new NotDeliciousException(); }
Source:
public ConsumptionMap getByTicketIdIfValid(Long ticketId) { if(!ticketService.getTicketById(ticketId).isValid()){ throw new InvalidTicketException("Ticket is invalid; can't reset consumptions"); } Collection<ConsumptionMap> consumptionMaps = consumptionMapsRepository.findAll(); Optional<ConsumptionMap> mapOptional = consumptionMapsRepository.findByTicketId(ticketId); if(mapOptional.isPresent()){ return mapOptional.get(); }else{ return InitializeConsumptionMap(ticketId); } }

Target:
public ConsumptionMap getByTicketIdIfValid(Long ticketId) { if(!ticketService.getTicketById(ticketId).isValid()){ throw new InvalidTicketException("Ticket is invalid; It can not be used for consumptions."); } Optional<ConsumptionMap> mapOptional = consumptionMapsRepository.findByTicketId(ticketId); if(mapOptional.isPresent()){ return mapOptional.get(); }else{ return initializeConsumptionMap(ticketId); } }
Source:
private void clickOnElement(WebElement element) { Actions action = new Actions(seleniumWebDriver); action.moveToElement(element).click().perform(); }

Target:
private void clickOnElement(WebElement element) { actionsFactory.createAction(seleniumWebDriver).moveToElement(element).click().perform(); }
Source:
public void testLoadAndSaveAggregate() { String identifier = UUID.randomUUID().toString(); DomainEventMessage event1 = new GenericDomainEventMessage<>("type", identifier, (long) 1, "Mock contents", emptyInstance()); DomainEventMessage event2 = new GenericDomainEventMessage<>("type", identifier, (long) 2, "Mock contents", emptyInstance()); DomainEventMessage event3 = new GenericDomainEventMessage<>("otherType", identifier, (long) 1, "Other contents", emptyInstance()); when(mockEventStore.readEvents(identifier)).thenReturn(DomainEventStream.of(event1, event2, event3)); Aggregate<TestAggregate> aggregate = testSubject.load(identifier, null); assertEquals(2, aggregate.invoke(TestAggregate::getHandledEvents).size()); assertSame(event1, aggregate.invoke(TestAggregate::getHandledEvents).get(0)); assertSame(event2, aggregate.invoke(TestAggregate::getHandledEvents).get(1)); assertEquals(0, aggregate.invoke(TestAggregate::getLiveEvents).size()); StubDomainEvent event4 = new StubDomainEvent(); aggregate.execute(r -> r.apply(event4)); CurrentUnitOfWork.commit(); verify(mockEventStore, times(1)).publish((EventMessage) anyVararg()); assertEquals(1, aggregate.invoke(TestAggregate::getLiveEvents).size()); assertSame(event4, aggregate.invoke(TestAggregate::getLiveEvents).get(0).getPayload()); }

Target:
public void testLoadAndSaveAggregate() { String identifier = UUID.randomUUID().toString(); DomainEventMessage event1 = new GenericDomainEventMessage<>("type", identifier, (long) 1, "Mock contents", emptyInstance()); DomainEventMessage event2 = new GenericDomainEventMessage<>("type", identifier, (long) 2, "Mock contents", emptyInstance()); when(mockEventStore.readEvents(identifier)).thenReturn(DomainEventStream.of(event1, event2)); Aggregate<TestAggregate> aggregate = testSubject.load(identifier, null); assertEquals(2, aggregate.invoke(TestAggregate::getHandledEvents).size()); assertSame(event1, aggregate.invoke(TestAggregate::getHandledEvents).get(0)); assertSame(event2, aggregate.invoke(TestAggregate::getHandledEvents).get(1)); assertEquals(0, aggregate.invoke(TestAggregate::getLiveEvents).size()); StubDomainEvent event3 = new StubDomainEvent(); aggregate.execute(r -> r.apply(event3)); CurrentUnitOfWork.commit(); verify(mockEventStore, times(1)).publish((EventMessage) anyVararg()); assertEquals(1, aggregate.invoke(TestAggregate::getLiveEvents).size()); assertSame(event3, aggregate.invoke(TestAggregate::getLiveEvents).get(0).getPayload()); }
Source:
private static Configuration readTestConfiguration() { String testConfigurationUris = System.getProperty(TEST_CONFIGURATION_URI_KEY, DEFAULT_TEST_CONFIGURATION_LOCATION); Configuration configuration = emptyConfiguration(); for (String testConfigurationUri : Splitter.on(",").split(testConfigurationUris)) { Optional<InputStream> testConfigurationStream = getConfigurationInputStream(testConfigurationUri); if (!testConfigurationStream.isPresent()) { throw new IllegalArgumentException("Unable find to configuration: " + testConfigurationUri); } Configuration parsedConfiguration = parseConfiguration(testConfigurationStream.get()); configuration = new HierarchicalConfiguration(parsedConfiguration, configuration); } return configuration; }

Target:
private static Configuration readTestConfiguration() { String testConfigurationUris = System.getProperty(TEST_CONFIGURATION_URIS_KEY, DEFAULT_TEST_CONFIGURATION_LOCATION); Configuration configuration = emptyConfiguration(); for (String testConfigurationUri : Splitter.on(",").split(testConfigurationUris)) { Optional<InputStream> testConfigurationStream = getConfigurationInputStream(testConfigurationUri); if (!testConfigurationStream.isPresent()) { throw new IllegalArgumentException("Unable find to configuration: " + testConfigurationUri); } Configuration parsedConfiguration = parseConfiguration(testConfigurationStream.get()); configuration = new HierarchicalConfiguration(configuration, parsedConfiguration); } return configuration; }
Source:
public void setValue(final String value) { final Moment moment = moment(value, "HH:mm:ss"); if (moment.isValid()) { view.setDate(moment); } }

Target:
public void setValue(final String value) { final Moment moment = moment(value, TIME_FORMAT); if (moment.isValid()) { view.setDate(moment); } }
Source:
void testInitializeFromAggregateSnapshot() { StubAggregate aggregate = new StubAggregate("stubId"); DomainEventMessage<StubAggregate> snapshotMessage = new GenericDomainEventMessage<>("StubAggregate", aggregate.getIdentifier(), 2, aggregate); GenericAggregateFactory<StubAggregate> factory = new GenericAggregateFactory<>(StubAggregate.class); assertSame(aggregate, factory.createAggregateRoot(aggregate.getIdentifier(), snapshotMessage)); }

Target:
void testInitializeFromAggregateSnapshot() { StubAggregate aggregate = new StubAggregate("stubId"); DomainEventMessage<StubAggregate> snapshotMessage = new GenericDomainEventMessage<>("type", aggregate.getIdentifier(), 2, aggregate); GenericAggregateFactory<StubAggregate> factory = new GenericAggregateFactory<>(StubAggregate.class); assertSame(aggregate, factory.createAggregateRoot(aggregate.getIdentifier(), snapshotMessage)); }
Source:
public void testProlongDueDate() { String responsible = "john"; long caseId = wcs.createWork("Integrate module X into project Y", "Module X working in the project Y by ...", responsible); wcs.prolongTimeoutTo(caseId, 15); try { Thread.sleep(11000); } catch (InterruptedException e) { e.printStackTrace(); } ProcessInstanceLog pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_ACTIVE); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED); }

Target:
public void testProlongDueDate() { String responsible = "john"; long caseId = wcs.createWork("Integrate module X into project Y", "Module X working in the project Y by ...", responsible, 1); wcs.prolongTimeoutTo(caseId, 3); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } ProcessInstanceLog pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_ACTIVE); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED); }
Source:
protected void createAndDispatchGDBFocusChangedEvent() { fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }

Target:
private void createAndDispatchGDBFocusChangedEvent() { assert fCurrentThreadCtx != null; fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }
Source:
public boolean isActive(IJavaProject project) { boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED, false, new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE, DefaultScope.INSTANCE }); if (!enabled) return false; IProject iproject = project.getProject(); if (iproject.isOpen() && !PDE.hasPluginNature(iproject)) return false; if (WorkspaceModelManager.isBinaryProject(project.getProject())) return false; try { IType annotationType = project.findType(COMPONENT_ANNOTATION); return annotationType != null && annotationType.isAnnotation(); } catch (JavaModelException e) { Activator.log(e); } return false; }

Target:
public boolean isActive(IJavaProject project) { boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED, false, new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE, DefaultScope.INSTANCE }); if (!enabled) return false; IProject iproject = project.getProject(); if (!iproject.isOpen() || !PDE.hasPluginNature(iproject)) return false; if (WorkspaceModelManager.isBinaryProject(project.getProject())) return false; try { IType annotationType = project.findType(COMPONENT_ANNOTATION); return annotationType != null && annotationType.isAnnotation(); } catch (JavaModelException e) { Activator.log(e); } return false; }
Source:
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { final int sqlType; if (type == LocalDate.class) { sqlType = Types.DATE; } else if (type == LocalTime.class) { sqlType = Types.TIME; } else if (type == LocalDateTime.class) { sqlType = Types.TIMESTAMP; } else if (type == OffsetDateTime.class) { sqlType = Types.TIMESTAMP_WITH_TIMEZONE; } else { return Optional.empty(); } return Optional.of(ObjectArgument.of(value, sqlType)); }

Target:
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { return Optional.ofNullable(TYPES.get(type)) .map(sqlType -> ObjectArgument.of(value, sqlType)); }
Source:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { String txnMgr = context.hiveConf.getVar(HiveConf.ConfVars.HIVE_TXN_MANAGER); boolean concurrency = context.hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY); String dbTxnMgr = "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager"; if (!txnMgr.equals(dbTxnMgr) || !concurrency) { context.log.error("Cannot load transaction events as acid is not enabled"); throw new SemanticException("Cannot load transaction events as acid is not enabled"); } AbortTxnMessage msg = deserializer.getAbortTxnMessage(context.dmd.getPayload()); Task<ReplTxnWork> abortTxnTask = TaskFactory.get( new ReplTxnWork(context.dbName, context.tableName, msg.getTxnId(), ReplTxnWork.OperationType.REPL_ABORT_TXN), context.hiveConf ); updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); context.log.debug("Added Abort txn task : {}", abortTxnTask.getId()); return Collections.singletonList(abortTxnTask); }

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { if (!AcidUtils.isAcidEnabled(context.hiveConf)) { context.log.error("Cannot load transaction events as acid is not enabled"); throw new SemanticException("Cannot load transaction events as acid is not enabled"); } AbortTxnMessage msg = deserializer.getAbortTxnMessage(context.dmd.getPayload()); Task<ReplTxnWork> abortTxnTask = TaskFactory.get( new ReplTxnWork(context.dbName, context.tableName, msg.getTxnId(), ReplTxnWork.OperationType.REPL_ABORT_TXN), context.hiveConf ); updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); context.log.debug("Added Abort txn task : {}", abortTxnTask.getId()); return Collections.singletonList(abortTxnTask); }
Source:
private void validateGateway(VdsNetworkInterface iface) { if (!FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && StringUtils.isNotEmpty(iface.getGateway())) { addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } }

Target:
private void validateGateway(VdsNetworkInterface iface) { if (StringUtils.isNotEmpty(iface.getGateway()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && !FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion())) { addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } }
Source:
public Optional<BackupMetadata> getLatestBackupMetaData(List<BackupMetadata> metadata) { metadata = metadata.stream() .filter(backupMetadata -> backupMetadata.getStatus() == Status.FINISHED) .collect(Collectors.toList()); metadata.sort((o1, o2) -> o2.getStart().compareTo(o1.getStart())); return metadata.stream().findFirst(); }

Target:
public Optional<BackupMetadata> getLatestBackupMetaData(List<BackupMetadata> metadata) { return metadata.stream() .filter(backupMetadata -> backupMetadata.getStatus() == Status.FINISHED) .sorted(Comparator.comparing(BackupMetadata::getStart).reversed()) .findFirst(); }
Source:
synchronized void handleFailedBatch(ProducerBatch batch, RuntimeException exception, boolean adjustSequenceNumbers) { maybeTransitionToErrorState(exception); removeInFlightBatch(batch); if (!matchesProducerIdAndEpoch(batch) || hasFatalError()) { log.debug("Ignoring failed batch with producer id {}, epoch {}, and sequence number " + "since the batch has been reset internally", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (exception instanceof OutOfOrderSequenceException && !isTransactional()) { log.error("The broker returned for topic-partition with producerId {}, epoch {}, and sequence number {}", exception, batch.topicPartition, batch.producerId(), batch.producerEpoch(), batch.baseSequence()); requestEpochBumpForPartition(batch.topicPartition); } else if (exception instanceof UnknownProducerIdException) { resetSequenceForPartition(batch.topicPartition); } else { if (adjustSequenceNumbers) { if (!isTransactional()) { requestEpochBumpForPartition(batch.topicPartition); } else { adjustSequencesDueToFailedBatch(batch); } } } }

Target:
synchronized void handleFailedBatch(ProducerBatch batch, RuntimeException exception, boolean adjustSequenceNumbers) { maybeTransitionToErrorState(exception); removeInFlightBatch(batch); if (hasFatalError()) { log.debug("Ignoring batch with producer id {}, epoch {}, and sequence number " + "since the producer is already in fatal error state", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (!matchesProducerIdAndEpoch(batch)) { log.debug("Ignoring failed batch with producer id {}, epoch {}, and sequence number " + "since the producerId has been reset internally", batch, batch.producerId(), batch.producerEpoch(), batch.baseSequence(), exception); return; } if (exception instanceof OutOfOrderSequenceException && !isTransactional()) { log.error("The broker returned for topic-partition with producerId {}, epoch {}, and sequence number {}", exception, batch.topicPartition, batch.producerId(), batch.producerEpoch(), batch.baseSequence()); requestEpochBumpForPartition(batch.topicPartition); } else if (exception instanceof UnknownProducerIdException) { resetSequenceForPartition(batch.topicPartition); } else { if (adjustSequenceNumbers) { if (!isTransactional()) { requestEpochBumpForPartition(batch.topicPartition); } else { adjustSequencesDueToFailedBatch(batch); } } } }
Source:
public void onSaveInstanceState(Bundle outState) { outState.putBundle(KEY_DIALOG_BUNDLE, mBundle); }

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle(KEY_DIALOG_BUNDLE, mBundle); }
Source:
public void actionPerformed(ActionEvent e) { DbxState dbxState = etc.getEditorState().getDbxState(); if(Cloud.getInstance().getStatus() != Cloud.Status.DBX_CONNECTED || dbxState == null) { JOptionPane.showMessageDialog(null, "No Dropbox file has been loaded.\n" + "You must open Dropbox file, before you save it.", "Cannot save progress", JOptionPane.WARNING_MESSAGE); return; } String[] periodOptions = {"Disable", "1 minute", "3 minutes", "5 minutes", "10 minutes"}; syncPeriod = (String) JOptionPane.showInputDialog( null, "Select the auto sync period (in min)", "Period of Dropbox Remote Sync", JOptionPane.QUESTION_MESSAGE, null, periodOptions, periodOptions[0] ); LOGGER.log("You set your interval of Dropbox auto sync as: " + syncPeriod); if(syncPeriod == null) { return; } if(!syncPeriod.startsWith("Disable")) { syncPeriod = syncPeriod.substring(0, syncPeriod.indexOf(" ")); if(autoSyncThread == null) { dbxAutoSyncObj = new DbxAutoSync(Integer.valueOf(syncPeriod)); autoSyncThread = new Thread(dbxAutoSyncObj); autoSyncThread.start(); } else { dbxAutoSyncObj.setInterval(Integer.valueOf(syncPeriod)); } } else { if(autoSyncThread != null){ dbxAutoSyncObj.setInterval(0); autoSyncThread.interrupt(); autoSyncThread = null; } } }

Target:
public void actionPerformed(ActionEvent e) { DbxState dbxState = etc.getEditorState().getDbxState(); if(Cloud.getInstance().getStatus() != Cloud.Status.DBX_CONNECTED || dbxState == null) { JOptionPane.showMessageDialog(null, "No Dropbox file has been loaded.\n" + "You must open Dropbox file, before you save it.", "Cannot save progress", JOptionPane.WARNING_MESSAGE); return; } SyncPeriod[] periodOptions = { SyncPeriod.Disable, SyncPeriod.OneMinute, SyncPeriod.ThreeMinutes, SyncPeriod.FiveMinutes, SyncPeriod.TenMinutes }; syncPeriodEnum = (SyncPeriod) JOptionPane.showInputDialog( null, "Select the auto sync period (in minute)", "Period of Dropbox Remote Sync", JOptionPane.QUESTION_MESSAGE, null, periodOptions, periodOptions[0] ); if(syncPeriodEnum == null) { return; } LOGGER.log("You set your interval of Dropbox auto sync as: " + syncPeriodEnum.toString()); if(syncPeriodEnum != SyncPeriod.Disable) { if(autoSyncThread == null) { dbxAutoSyncObj = new DbxAutoSync(syncPeriodEnum.getPeriod()); autoSyncThread = new Thread(dbxAutoSyncObj); autoSyncThread.start(); } else { dbxAutoSyncObj.setInterval(syncPeriodEnum.getPeriod()); } } else { if(autoSyncThread != null){ dbxAutoSyncObj.setInterval(SyncPeriod.Disable.getPeriod()); autoSyncThread.interrupt(); autoSyncThread = null; } } }