repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
CiscoCTA/taxii-log-adapter | src/main/java/com/cisco/cta/taxii/adapter/ScheduleConfiguration.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// public class TaxiiStatusDao {
//
// private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class);
//
// private final TaxiiStatusFileHandler fileHandler;
// private TaxiiStatus dirtyStatus;
//
// public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) {
// this.fileHandler = fileHandler;
// dirtyStatus = fileHandler.load();
// if (dirtyStatus == null) {
// LOG.warn("TAXII status file not found, all feeds will be fully downloaded");
// dirtyStatus = new TaxiiStatus();
// } else {
// LOG.debug("TAXII status file loaded: {}", dirtyStatus);
// }
// }
//
// public Feed find(String feedName) {
// for (Feed feed : dirtyStatus.getFeed()) {
// if (feed.getName().equals(feedName)) {
// return feed;
// }
// }
// return null;
// }
//
// public synchronized void updateOrAdd(Feed feed) {
// Feed savedFeed = find(feed.getName());
// if (savedFeed != null) {
// savedFeed.setMore(feed.getMore());
// savedFeed.setResultId(feed.getResultId());
// savedFeed.setResultPartNumber(feed.getResultPartNumber());
// savedFeed.setLastUpdate(feed.getLastUpdate());
// } else {
// dirtyStatus.getFeed().add(feed);
// }
// fileHandler.save(dirtyStatus);
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ScheduleSettings.java
// @ConfigurationProperties(prefix="schedule")
// @Data
// @Validated
// public class ScheduleSettings {
//
// @NotNull
// private String cron;
//
// }
| import java.util.concurrent.ScheduledFuture;
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import com.cisco.cta.taxii.adapter.settings.ScheduleSettings; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter;
/**
* Spring configuration providing factory methods for scheduling beans.
*/
@Configuration
@Profile("schedule")
@Import(AdapterConfiguration.class)
public class ScheduleConfiguration {
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public ScheduledFuture<?> scheduleAdapterTask( | // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// public class TaxiiStatusDao {
//
// private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class);
//
// private final TaxiiStatusFileHandler fileHandler;
// private TaxiiStatus dirtyStatus;
//
// public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) {
// this.fileHandler = fileHandler;
// dirtyStatus = fileHandler.load();
// if (dirtyStatus == null) {
// LOG.warn("TAXII status file not found, all feeds will be fully downloaded");
// dirtyStatus = new TaxiiStatus();
// } else {
// LOG.debug("TAXII status file loaded: {}", dirtyStatus);
// }
// }
//
// public Feed find(String feedName) {
// for (Feed feed : dirtyStatus.getFeed()) {
// if (feed.getName().equals(feedName)) {
// return feed;
// }
// }
// return null;
// }
//
// public synchronized void updateOrAdd(Feed feed) {
// Feed savedFeed = find(feed.getName());
// if (savedFeed != null) {
// savedFeed.setMore(feed.getMore());
// savedFeed.setResultId(feed.getResultId());
// savedFeed.setResultPartNumber(feed.getResultPartNumber());
// savedFeed.setLastUpdate(feed.getLastUpdate());
// } else {
// dirtyStatus.getFeed().add(feed);
// }
// fileHandler.save(dirtyStatus);
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ScheduleSettings.java
// @ConfigurationProperties(prefix="schedule")
// @Data
// @Validated
// public class ScheduleSettings {
//
// @NotNull
// private String cron;
//
// }
// Path: src/main/java/com/cisco/cta/taxii/adapter/ScheduleConfiguration.java
import java.util.concurrent.ScheduledFuture;
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import com.cisco.cta.taxii.adapter.settings.ScheduleSettings;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter;
/**
* Spring configuration providing factory methods for scheduling beans.
*/
@Configuration
@Profile("schedule")
@Import(AdapterConfiguration.class)
public class ScheduleConfiguration {
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public ScheduledFuture<?> scheduleAdapterTask( | ScheduleSettings scheduleSettings, |
CiscoCTA/taxii-log-adapter | src/main/java/com/cisco/cta/taxii/adapter/ScheduleConfiguration.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// public class TaxiiStatusDao {
//
// private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class);
//
// private final TaxiiStatusFileHandler fileHandler;
// private TaxiiStatus dirtyStatus;
//
// public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) {
// this.fileHandler = fileHandler;
// dirtyStatus = fileHandler.load();
// if (dirtyStatus == null) {
// LOG.warn("TAXII status file not found, all feeds will be fully downloaded");
// dirtyStatus = new TaxiiStatus();
// } else {
// LOG.debug("TAXII status file loaded: {}", dirtyStatus);
// }
// }
//
// public Feed find(String feedName) {
// for (Feed feed : dirtyStatus.getFeed()) {
// if (feed.getName().equals(feedName)) {
// return feed;
// }
// }
// return null;
// }
//
// public synchronized void updateOrAdd(Feed feed) {
// Feed savedFeed = find(feed.getName());
// if (savedFeed != null) {
// savedFeed.setMore(feed.getMore());
// savedFeed.setResultId(feed.getResultId());
// savedFeed.setResultPartNumber(feed.getResultPartNumber());
// savedFeed.setLastUpdate(feed.getLastUpdate());
// } else {
// dirtyStatus.getFeed().add(feed);
// }
// fileHandler.save(dirtyStatus);
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ScheduleSettings.java
// @ConfigurationProperties(prefix="schedule")
// @Data
// @Validated
// public class ScheduleSettings {
//
// @NotNull
// private String cron;
//
// }
| import java.util.concurrent.ScheduledFuture;
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import com.cisco.cta.taxii.adapter.settings.ScheduleSettings; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter;
/**
* Spring configuration providing factory methods for scheduling beans.
*/
@Configuration
@Profile("schedule")
@Import(AdapterConfiguration.class)
public class ScheduleConfiguration {
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public ScheduledFuture<?> scheduleAdapterTask(
ScheduleSettings scheduleSettings,
AdapterConfiguration adapterConfiguration,
RequestFactory requestFactory, | // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// public class TaxiiStatusDao {
//
// private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class);
//
// private final TaxiiStatusFileHandler fileHandler;
// private TaxiiStatus dirtyStatus;
//
// public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) {
// this.fileHandler = fileHandler;
// dirtyStatus = fileHandler.load();
// if (dirtyStatus == null) {
// LOG.warn("TAXII status file not found, all feeds will be fully downloaded");
// dirtyStatus = new TaxiiStatus();
// } else {
// LOG.debug("TAXII status file loaded: {}", dirtyStatus);
// }
// }
//
// public Feed find(String feedName) {
// for (Feed feed : dirtyStatus.getFeed()) {
// if (feed.getName().equals(feedName)) {
// return feed;
// }
// }
// return null;
// }
//
// public synchronized void updateOrAdd(Feed feed) {
// Feed savedFeed = find(feed.getName());
// if (savedFeed != null) {
// savedFeed.setMore(feed.getMore());
// savedFeed.setResultId(feed.getResultId());
// savedFeed.setResultPartNumber(feed.getResultPartNumber());
// savedFeed.setLastUpdate(feed.getLastUpdate());
// } else {
// dirtyStatus.getFeed().add(feed);
// }
// fileHandler.save(dirtyStatus);
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ScheduleSettings.java
// @ConfigurationProperties(prefix="schedule")
// @Data
// @Validated
// public class ScheduleSettings {
//
// @NotNull
// private String cron;
//
// }
// Path: src/main/java/com/cisco/cta/taxii/adapter/ScheduleConfiguration.java
import java.util.concurrent.ScheduledFuture;
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import com.cisco.cta.taxii.adapter.settings.ScheduleSettings;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter;
/**
* Spring configuration providing factory methods for scheduling beans.
*/
@Configuration
@Profile("schedule")
@Import(AdapterConfiguration.class)
public class ScheduleConfiguration {
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public ScheduledFuture<?> scheduleAdapterTask(
ScheduleSettings scheduleSettings,
AdapterConfiguration adapterConfiguration,
RequestFactory requestFactory, | TaxiiServiceSettings taxiiServiceSettings, |
CiscoCTA/taxii-log-adapter | src/main/java/com/cisco/cta/taxii/adapter/ScheduleConfiguration.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// public class TaxiiStatusDao {
//
// private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class);
//
// private final TaxiiStatusFileHandler fileHandler;
// private TaxiiStatus dirtyStatus;
//
// public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) {
// this.fileHandler = fileHandler;
// dirtyStatus = fileHandler.load();
// if (dirtyStatus == null) {
// LOG.warn("TAXII status file not found, all feeds will be fully downloaded");
// dirtyStatus = new TaxiiStatus();
// } else {
// LOG.debug("TAXII status file loaded: {}", dirtyStatus);
// }
// }
//
// public Feed find(String feedName) {
// for (Feed feed : dirtyStatus.getFeed()) {
// if (feed.getName().equals(feedName)) {
// return feed;
// }
// }
// return null;
// }
//
// public synchronized void updateOrAdd(Feed feed) {
// Feed savedFeed = find(feed.getName());
// if (savedFeed != null) {
// savedFeed.setMore(feed.getMore());
// savedFeed.setResultId(feed.getResultId());
// savedFeed.setResultPartNumber(feed.getResultPartNumber());
// savedFeed.setLastUpdate(feed.getLastUpdate());
// } else {
// dirtyStatus.getFeed().add(feed);
// }
// fileHandler.save(dirtyStatus);
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ScheduleSettings.java
// @ConfigurationProperties(prefix="schedule")
// @Data
// @Validated
// public class ScheduleSettings {
//
// @NotNull
// private String cron;
//
// }
| import java.util.concurrent.ScheduledFuture;
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import com.cisco.cta.taxii.adapter.settings.ScheduleSettings; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter;
/**
* Spring configuration providing factory methods for scheduling beans.
*/
@Configuration
@Profile("schedule")
@Import(AdapterConfiguration.class)
public class ScheduleConfiguration {
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public ScheduledFuture<?> scheduleAdapterTask(
ScheduleSettings scheduleSettings,
AdapterConfiguration adapterConfiguration,
RequestFactory requestFactory,
TaxiiServiceSettings taxiiServiceSettings, | // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// public class TaxiiStatusDao {
//
// private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class);
//
// private final TaxiiStatusFileHandler fileHandler;
// private TaxiiStatus dirtyStatus;
//
// public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) {
// this.fileHandler = fileHandler;
// dirtyStatus = fileHandler.load();
// if (dirtyStatus == null) {
// LOG.warn("TAXII status file not found, all feeds will be fully downloaded");
// dirtyStatus = new TaxiiStatus();
// } else {
// LOG.debug("TAXII status file loaded: {}", dirtyStatus);
// }
// }
//
// public Feed find(String feedName) {
// for (Feed feed : dirtyStatus.getFeed()) {
// if (feed.getName().equals(feedName)) {
// return feed;
// }
// }
// return null;
// }
//
// public synchronized void updateOrAdd(Feed feed) {
// Feed savedFeed = find(feed.getName());
// if (savedFeed != null) {
// savedFeed.setMore(feed.getMore());
// savedFeed.setResultId(feed.getResultId());
// savedFeed.setResultPartNumber(feed.getResultPartNumber());
// savedFeed.setLastUpdate(feed.getLastUpdate());
// } else {
// dirtyStatus.getFeed().add(feed);
// }
// fileHandler.save(dirtyStatus);
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ScheduleSettings.java
// @ConfigurationProperties(prefix="schedule")
// @Data
// @Validated
// public class ScheduleSettings {
//
// @NotNull
// private String cron;
//
// }
// Path: src/main/java/com/cisco/cta/taxii/adapter/ScheduleConfiguration.java
import java.util.concurrent.ScheduledFuture;
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import com.cisco.cta.taxii.adapter.settings.ScheduleSettings;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter;
/**
* Spring configuration providing factory methods for scheduling beans.
*/
@Configuration
@Profile("schedule")
@Import(AdapterConfiguration.class)
public class ScheduleConfiguration {
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Bean
public ScheduledFuture<?> scheduleAdapterTask(
ScheduleSettings scheduleSettings,
AdapterConfiguration adapterConfiguration,
RequestFactory requestFactory,
TaxiiServiceSettings taxiiServiceSettings, | TaxiiStatusDao taxiiStatusDao) throws Exception { |
CiscoCTA/taxii-log-adapter | src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactoryTest.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactory.java
// public class HttpClientFactory {
//
// private ProxySettings proxySettings;
//
// public HttpClientFactory(ProxySettings proxySettings) {
// this.proxySettings = proxySettings;
// }
//
// public HttpClient create() {
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// if (proxySettings.getUrl() != null) {
// URL proxyUrl = proxySettings.getUrl();
// HttpHost proxyHost = new HttpHost(
// proxyUrl.getHost(),
// proxyUrl.getPort(),
// proxyUrl.getProtocol());
// clientBuilder.setProxy(proxyHost);
// }
// return clientBuilder.build();
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
| import com.cisco.cta.taxii.adapter.httpclient.HttpClientFactory;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import org.apache.http.client.HttpClient;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.net.MalformedURLException;
import java.net.URL;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Mockito.*; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
public class HttpClientFactoryTest {
@Mock | // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactory.java
// public class HttpClientFactory {
//
// private ProxySettings proxySettings;
//
// public HttpClientFactory(ProxySettings proxySettings) {
// this.proxySettings = proxySettings;
// }
//
// public HttpClient create() {
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// if (proxySettings.getUrl() != null) {
// URL proxyUrl = proxySettings.getUrl();
// HttpHost proxyHost = new HttpHost(
// proxyUrl.getHost(),
// proxyUrl.getPort(),
// proxyUrl.getProtocol());
// clientBuilder.setProxy(proxyHost);
// }
// return clientBuilder.build();
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactoryTest.java
import com.cisco.cta.taxii.adapter.httpclient.HttpClientFactory;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import org.apache.http.client.HttpClient;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.net.MalformedURLException;
import java.net.URL;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Mockito.*;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
public class HttpClientFactoryTest {
@Mock | private ProxySettings proxySettings; |
CiscoCTA/taxii-log-adapter | src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactoryTest.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactory.java
// public class HttpClientFactory {
//
// private ProxySettings proxySettings;
//
// public HttpClientFactory(ProxySettings proxySettings) {
// this.proxySettings = proxySettings;
// }
//
// public HttpClient create() {
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// if (proxySettings.getUrl() != null) {
// URL proxyUrl = proxySettings.getUrl();
// HttpHost proxyHost = new HttpHost(
// proxyUrl.getHost(),
// proxyUrl.getPort(),
// proxyUrl.getProtocol());
// clientBuilder.setProxy(proxyHost);
// }
// return clientBuilder.build();
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
| import com.cisco.cta.taxii.adapter.httpclient.HttpClientFactory;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import org.apache.http.client.HttpClient;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.net.MalformedURLException;
import java.net.URL;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Mockito.*; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
public class HttpClientFactoryTest {
@Mock
private ProxySettings proxySettings;
| // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactory.java
// public class HttpClientFactory {
//
// private ProxySettings proxySettings;
//
// public HttpClientFactory(ProxySettings proxySettings) {
// this.proxySettings = proxySettings;
// }
//
// public HttpClient create() {
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// if (proxySettings.getUrl() != null) {
// URL proxyUrl = proxySettings.getUrl();
// HttpHost proxyHost = new HttpHost(
// proxyUrl.getHost(),
// proxyUrl.getPort(),
// proxyUrl.getProtocol());
// clientBuilder.setProxy(proxyHost);
// }
// return clientBuilder.build();
// }
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientFactoryTest.java
import com.cisco.cta.taxii.adapter.httpclient.HttpClientFactory;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import org.apache.http.client.HttpClient;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.net.MalformedURLException;
import java.net.URL;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Mockito.*;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
public class HttpClientFactoryTest {
@Mock
private ProxySettings proxySettings;
| private HttpClientFactory httpClientFactory; |
CiscoCTA/taxii-log-adapter | src/test/java/com/cisco/cta/taxii/adapter/Slf4JWriterTest.java | // Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.core.Appender;
import org.slf4j.MDC;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.io.Writer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy; | char[] chars = "PAYLOAD".toCharArray();
writer.write(chars);
verifyZeroInteractions(logger);
verifyZeroInteractions(statistics);
writer.close();
}
@Test
public void writeFinishedLine() throws Exception {
char[] chars = "PAYLOAD\n".toCharArray();
writer.write(chars);
verify(logger, only()).info("PAYLOAD");
assertThat(statistics.getLogs(), is(1L));
writer.close();
}
@Test
public void ignoreCharactersOutsideBoundaries() throws Exception {
char[] chars = "beforePAYLOAD\nafter\nend".toCharArray();
writer.write(chars, 6, 8);
verify(logger, only()).info("PAYLOAD");
assertThat(statistics.getLogs(), is(1L));
writer.close();
}
@Test
public void logErrorOnClosingBeforeFinishedLine() throws Exception {
char[] chars = "PAYLOAD\nend".toCharArray();
writer.write(chars);
writer.close(); | // Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
// Path: src/test/java/com/cisco/cta/taxii/adapter/Slf4JWriterTest.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.core.Appender;
import org.slf4j.MDC;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.io.Writer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
char[] chars = "PAYLOAD".toCharArray();
writer.write(chars);
verifyZeroInteractions(logger);
verifyZeroInteractions(statistics);
writer.close();
}
@Test
public void writeFinishedLine() throws Exception {
char[] chars = "PAYLOAD\n".toCharArray();
writer.write(chars);
verify(logger, only()).info("PAYLOAD");
assertThat(statistics.getLogs(), is(1L));
writer.close();
}
@Test
public void ignoreCharactersOutsideBoundaries() throws Exception {
char[] chars = "beforePAYLOAD\nafter\nend".toCharArray();
writer.write(chars, 6, 8);
verify(logger, only()).info("PAYLOAD");
assertThat(statistics.getLogs(), is(1L));
writer.close();
}
@Test
public void logErrorOnClosingBeforeFinishedLine() throws Exception {
char[] chars = "PAYLOAD\nend".toCharArray();
writer.write(chars);
writer.close(); | verifyLog(mockAppender, "unfinished"); |
CiscoCTA/taxii-log-adapter | src/test/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactoryTest.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java
// public class TaxiiServiceSettingsFactory {
//
// public static TaxiiServiceSettings createDefaults() {
// try {
// TaxiiServiceSettings connSettings = new TaxiiServiceSettings();
// connSettings.setPollEndpoint(new URL("http://localhost:8080/service"));
// connSettings.setUsername("user");
// connSettings.setPassword("pass");
// return connSettings;
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
| import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.Appender;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import javax.net.ServerSocketFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
@SuppressWarnings("all")
public class BasicAuthHttpRequestFactoryTest {
private ClientHttpRequestFactory factory;
private HttpClient httpClient; | // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java
// public class TaxiiServiceSettingsFactory {
//
// public static TaxiiServiceSettings createDefaults() {
// try {
// TaxiiServiceSettings connSettings = new TaxiiServiceSettings();
// connSettings.setPollEndpoint(new URL("http://localhost:8080/service"));
// connSettings.setUsername("user");
// connSettings.setPassword("pass");
// return connSettings;
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactoryTest.java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.Appender;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import javax.net.ServerSocketFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
@SuppressWarnings("all")
public class BasicAuthHttpRequestFactoryTest {
private ClientHttpRequestFactory factory;
private HttpClient httpClient; | private TaxiiServiceSettings connSettings; |
CiscoCTA/taxii-log-adapter | src/test/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactoryTest.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java
// public class TaxiiServiceSettingsFactory {
//
// public static TaxiiServiceSettings createDefaults() {
// try {
// TaxiiServiceSettings connSettings = new TaxiiServiceSettings();
// connSettings.setPollEndpoint(new URL("http://localhost:8080/service"));
// connSettings.setUsername("user");
// connSettings.setPassword("pass");
// return connSettings;
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
| import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.Appender;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import javax.net.ServerSocketFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when; | /*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
@SuppressWarnings("all")
public class BasicAuthHttpRequestFactoryTest {
private ClientHttpRequestFactory factory;
private HttpClient httpClient;
private TaxiiServiceSettings connSettings;
private CredentialsProvider credentialsProvider;
@Mock
private Appender mockAppender;
@Before
public void setUp() throws Exception {
httpClient = HttpClients.createDefault();
credentialsProvider = Mockito.mock(CredentialsProvider.class); | // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java
// public class TaxiiServiceSettingsFactory {
//
// public static TaxiiServiceSettings createDefaults() {
// try {
// TaxiiServiceSettings connSettings = new TaxiiServiceSettings();
// connSettings.setPollEndpoint(new URL("http://localhost:8080/service"));
// connSettings.setUsername("user");
// connSettings.setPassword("pass");
// return connSettings;
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactoryTest.java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.Appender;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import javax.net.ServerSocketFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
/*
Copyright 2015 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cisco.cta.taxii.adapter.httpclient;
@SuppressWarnings("all")
public class BasicAuthHttpRequestFactoryTest {
private ClientHttpRequestFactory factory;
private HttpClient httpClient;
private TaxiiServiceSettings connSettings;
private CredentialsProvider credentialsProvider;
@Mock
private Appender mockAppender;
@Before
public void setUp() throws Exception {
httpClient = HttpClients.createDefault();
credentialsProvider = Mockito.mock(CredentialsProvider.class); | connSettings = TaxiiServiceSettingsFactory.createDefaults(); |
CiscoCTA/taxii-log-adapter | src/test/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactoryTest.java | // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java
// public class TaxiiServiceSettingsFactory {
//
// public static TaxiiServiceSettings createDefaults() {
// try {
// TaxiiServiceSettings connSettings = new TaxiiServiceSettings();
// connSettings.setPollEndpoint(new URL("http://localhost:8080/service"));
// connSettings.setUsername("user");
// connSettings.setPassword("pass");
// return connSettings;
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
| import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.Appender;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import javax.net.ServerSocketFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when; | private HttpClient httpClient;
private TaxiiServiceSettings connSettings;
private CredentialsProvider credentialsProvider;
@Mock
private Appender mockAppender;
@Before
public void setUp() throws Exception {
httpClient = HttpClients.createDefault();
credentialsProvider = Mockito.mock(CredentialsProvider.class);
connSettings = TaxiiServiceSettingsFactory.createDefaults();
credentialsProvider = Mockito.mock(CredentialsProvider.class);
factory = new BasicAuthHttpRequestFactory(httpClient, connSettings, credentialsProvider);
MockitoAnnotations.initMocks(this);
when(mockAppender.getName()).thenReturn("MOCK");
Logger authCacheLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(RequestAuthCache.class.getCanonicalName());
authCacheLogger.setLevel(Level.DEBUG);
authCacheLogger.addAppender(mockAppender);
}
@Test
public void tryConnectWithBasicAuthentication() throws Exception {
try {
ClientHttpRequest req = factory.createRequest(connSettings.getPollEndpoint().toURI(), HttpMethod.POST);
req.execute();
fail("connection must fail");
} catch (Throwable e) {
assertThat(e, instanceOf(HttpHostConnectException.class));
} | // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// @ConfigurationProperties(prefix="proxy")
// @Data
// public class ProxySettings {
//
// private URL url;
//
// private ProxyAuthenticationType authenticationType;
//
// private String domain;
//
// private String username;
//
// private String password;
//
// private String workstation;
//
// }
//
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java
// @ConfigurationProperties(prefix="taxii-service")
// @Data
// @Validated
// public class TaxiiServiceSettings {
//
// private static final Charset UTF8 = Charset.forName("UTF-8");
//
// @NotNull
// private URL pollEndpoint;
//
// @NotNull
// private String username;
//
// @NotNull
// private String password;
//
// private List<String> feeds;
//
// private File feedNamesFile;
//
// private File statusFile = new File("taxii-status.xml");
//
// @PostConstruct
// public void loadFeedNames() throws IOException {
// Preconditions.checkState(
// feeds != null ^ feedNamesFile != null,
// "taxii-service.feeds or taxii-service.feedNamesFile must be set");
// if (feedNamesFile != null) {
// feeds = Files.readLines(feedNamesFile, UTF8);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java
// public class TaxiiServiceSettingsFactory {
//
// public static TaxiiServiceSettings createDefaults() {
// try {
// TaxiiServiceSettings connSettings = new TaxiiServiceSettings();
// connSettings.setPollEndpoint(new URL("http://localhost:8080/service"));
// connSettings.setUsername("user");
// connSettings.setPassword("pass");
// return connSettings;
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: src/test/java/com/cisco/cta/taxii/adapter/IsEventContaining.java
// public static void verifyLog(Appender<ILoggingEvent> mockAppender, final String substring) {
// verify(mockAppender, atLeastOnce())
// .doAppend(argThat(isEventContaining(substring)));
// }
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactoryTest.java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.Appender;
import com.cisco.cta.taxii.adapter.settings.ProxySettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.HttpClients;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import javax.net.ServerSocketFactory;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import static com.cisco.cta.taxii.adapter.IsEventContaining.verifyLog;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
private HttpClient httpClient;
private TaxiiServiceSettings connSettings;
private CredentialsProvider credentialsProvider;
@Mock
private Appender mockAppender;
@Before
public void setUp() throws Exception {
httpClient = HttpClients.createDefault();
credentialsProvider = Mockito.mock(CredentialsProvider.class);
connSettings = TaxiiServiceSettingsFactory.createDefaults();
credentialsProvider = Mockito.mock(CredentialsProvider.class);
factory = new BasicAuthHttpRequestFactory(httpClient, connSettings, credentialsProvider);
MockitoAnnotations.initMocks(this);
when(mockAppender.getName()).thenReturn("MOCK");
Logger authCacheLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(RequestAuthCache.class.getCanonicalName());
authCacheLogger.setLevel(Level.DEBUG);
authCacheLogger.addAppender(mockAppender);
}
@Test
public void tryConnectWithBasicAuthentication() throws Exception {
try {
ClientHttpRequest req = factory.createRequest(connSettings.getPollEndpoint().toURI(), HttpMethod.POST);
req.execute();
fail("connection must fail");
} catch (Throwable e) {
assertThat(e, instanceOf(HttpHostConnectException.class));
} | verifyLog(mockAppender, "Re-using cached 'basic' auth scheme for http://localhost:80"); |
napstr/SqlSauce | discord-entities/src/main/java/space/npstr/sqlsauce/entities/discord/DiscordUser.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/converters/PostgresHStoreConverter.java
// @Converter(autoApply = true)
// public class PostgresHStoreConverter implements AttributeConverter<Map<String, String>, String>, Serializable {
//
// private static final long serialVersionUID = 6734295028227191361L;
//
// @Override
// public String convertToDatabaseColumn(@Nullable final Map<String, String> attribute) {
// return HStoreConverter.toString(attribute != null ? attribute : new HashMap<>());
// }
//
// @Override
// public Map<String, String> convertToEntityAttribute(@Nullable final String dbData) {
// if (dbData == null) {
// return new HashMap<>();
// }
// return HStoreConverter.fromString(dbData);
// }
// }
//
// Path: discord-entities/src/main/java/space/npstr/sqlsauce/jda/listeners/CacheableUser.java
// public interface CacheableUser<S> extends Cacheable<S> {
//
// /**
// * Set whatever values are necessary from a JDA user.
// */
// S set(User user);
//
// /**
// * Set whatever values are necessary from a JDA member.
// */
// S set(Member member);
// }
| import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
import org.hibernate.annotations.ColumnDefault;
import space.npstr.sqlsauce.converters.PostgresHStoreConverter;
import space.npstr.sqlsauce.jda.listeners.CacheableUser; | /*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.entities.discord;
/**
* Created by napster on 17.10.17.
* <p>
* Base class for discord user entities. Best used in conjunction with a UserCachingListener.
* Intended to provide a simple way to save user specific settings etc.
* <p>
* Attention: Unless you manually sync these entities between bot downtimes, there is no guarantee that the data is
* consistent with reality. Consider this: A user changes their avatar while your bot is down (reconnecting, updating
* whatever). Due to it being down, the change of the avatar is missed, so the avatarId field will contain an outdated
* value.
*/
@MappedSuperclass
public abstract class DiscordUser<S extends BaseDiscordUser<S>> extends BaseDiscordUser<S> implements CacheableUser<S> {
@Transient
public static final String UNKNOWN_NAME = "Unknown User";
@Column(name = "name", nullable = false, columnDefinition = "text")
@ColumnDefault(value = UNKNOWN_NAME)
protected String name = UNKNOWN_NAME;
@Column(name = "discriminator", nullable = false)
@ColumnDefault(value = "-1")
protected short discriminator;
@Nullable
@Column(name = "avatar_id", nullable = true, columnDefinition = "text")
protected String avatarId;
@Column(name = "bot", nullable = false)
@ColumnDefault(value = "false")
protected boolean bot;
@Column(name = "nicks", columnDefinition = "hstore") | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/converters/PostgresHStoreConverter.java
// @Converter(autoApply = true)
// public class PostgresHStoreConverter implements AttributeConverter<Map<String, String>, String>, Serializable {
//
// private static final long serialVersionUID = 6734295028227191361L;
//
// @Override
// public String convertToDatabaseColumn(@Nullable final Map<String, String> attribute) {
// return HStoreConverter.toString(attribute != null ? attribute : new HashMap<>());
// }
//
// @Override
// public Map<String, String> convertToEntityAttribute(@Nullable final String dbData) {
// if (dbData == null) {
// return new HashMap<>();
// }
// return HStoreConverter.fromString(dbData);
// }
// }
//
// Path: discord-entities/src/main/java/space/npstr/sqlsauce/jda/listeners/CacheableUser.java
// public interface CacheableUser<S> extends Cacheable<S> {
//
// /**
// * Set whatever values are necessary from a JDA user.
// */
// S set(User user);
//
// /**
// * Set whatever values are necessary from a JDA member.
// */
// S set(Member member);
// }
// Path: discord-entities/src/main/java/space/npstr/sqlsauce/entities/discord/DiscordUser.java
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
import org.hibernate.annotations.ColumnDefault;
import space.npstr.sqlsauce.converters.PostgresHStoreConverter;
import space.npstr.sqlsauce.jda.listeners.CacheableUser;
/*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.entities.discord;
/**
* Created by napster on 17.10.17.
* <p>
* Base class for discord user entities. Best used in conjunction with a UserCachingListener.
* Intended to provide a simple way to save user specific settings etc.
* <p>
* Attention: Unless you manually sync these entities between bot downtimes, there is no guarantee that the data is
* consistent with reality. Consider this: A user changes their avatar while your bot is down (reconnecting, updating
* whatever). Due to it being down, the change of the avatar is missed, so the avatarId field will contain an outdated
* value.
*/
@MappedSuperclass
public abstract class DiscordUser<S extends BaseDiscordUser<S>> extends BaseDiscordUser<S> implements CacheableUser<S> {
@Transient
public static final String UNKNOWN_NAME = "Unknown User";
@Column(name = "name", nullable = false, columnDefinition = "text")
@ColumnDefault(value = UNKNOWN_NAME)
protected String name = UNKNOWN_NAME;
@Column(name = "discriminator", nullable = false)
@ColumnDefault(value = "-1")
protected short discriminator;
@Nullable
@Column(name = "avatar_id", nullable = true, columnDefinition = "text")
protected String avatarId;
@Column(name = "bot", nullable = false)
@ColumnDefault(value = "false")
protected boolean bot;
@Column(name = "nicks", columnDefinition = "hstore") | @Convert(converter = PostgresHStoreConverter.class) |
napstr/SqlSauce | sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/EmptyFetching.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; | /*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "empty_test") | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/EmptyFetching.java
import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "empty_test") | public final class EmptyFetching extends SaucedEntity<Long, EmptyFetching> { |
napstr/SqlSauce | notifications/src/main/java/space/npstr/sqlsauce/notifications/NotificationService.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseException.java
// public class DatabaseException extends RuntimeException {
//
//
// private static final long serialVersionUID = 4421127305934584766L;
//
// //force creation with a message
// private DatabaseException() {
//
// }
//
// public DatabaseException(final String message) {
// super(message);
// }
//
// public DatabaseException(final String message, final Throwable t) {
// super(message, t);
// }
// }
//
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/LoggingNsExceptionHandler.java
// public class LoggingNsExceptionHandler implements NsExceptionHandler {
//
// private final Logger logger;
//
// public LoggingNsExceptionHandler(Logger log) {
// this.logger = log;
// }
//
// @Override
// public void handleNotificationServiceException(Exception e) {
// logger.error("Notification Service internal exception", e);
// }
//
// @Override
// public void handleListenerException(Exception e) {
// logger.error("Uncaught notification listener exception", e);
// }
// }
//
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/NsExceptionHandler.java
// public interface NsExceptionHandler {
// /**
// * Any exceptions, most notably all kinds of SQL exceptions will be passed in here.
// */
// void handleNotificationServiceException(Exception e);
//
// /**
// * Any uncaught exceptions from calling {@link NotificationListener#notif} will be passed in here.
// */
// void handleListenerException(Exception e);
// }
| import org.postgresql.PGNotification;
import org.postgresql.jdbc.PgConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import space.npstr.sqlsauce.DatabaseException;
import space.npstr.sqlsauce.notifications.exceptions.LoggingNsExceptionHandler;
import space.npstr.sqlsauce.notifications.exceptions.NsExceptionHandler;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | /*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.notifications;
/**
* Created by napster on 06.01.18.
* <p>
* This class supports Postgres' LISTEN / NOTIFY feature, mostly the LISTENs (NOTIFYs are easy, just shoot a query at the DB).
* NOTIFY can be called on any database connection, but you can also use the built in method of this class.
* <p>
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* ATTENTION: We can't use prepared statements for the queries issueing the LISTENs and UNLISTENs, so the channel names
* need to be checked by the code calling the methods of these class for their legitimacy. Do not allow these to be set
* by any user values ever or else sql injections might happen.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* <p>
* This class creates a single connection to the database. We cannot use a pooled connection, or integrate this feature
* with a whole pool without a lot of hassle, as LISTENs and UNLISTENs would need to be executed on each connection all
* the time. Given this and connections being a costly resource, you are encouraged, but not required, to use a single
* object of this class in your application to register all your listeners with.
* <p>
* todo try async registering of listeners while listening to notifications
*/
public class NotificationService {
private static final Logger log = LoggerFactory.getLogger(NotificationService.class);
//todo is there a better way to synchronize / thread safety?
//current thread safety design synchronizes on the listeners object whenever the Map or any of the Sets of its
//values are accessed
private final Map<String, Set<NotificationListener>> listeners = new HashMap<>();
private final Connection connection; //connection that we are listening on
private final ExecutorService exec; //runs the main loop | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseException.java
// public class DatabaseException extends RuntimeException {
//
//
// private static final long serialVersionUID = 4421127305934584766L;
//
// //force creation with a message
// private DatabaseException() {
//
// }
//
// public DatabaseException(final String message) {
// super(message);
// }
//
// public DatabaseException(final String message, final Throwable t) {
// super(message, t);
// }
// }
//
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/LoggingNsExceptionHandler.java
// public class LoggingNsExceptionHandler implements NsExceptionHandler {
//
// private final Logger logger;
//
// public LoggingNsExceptionHandler(Logger log) {
// this.logger = log;
// }
//
// @Override
// public void handleNotificationServiceException(Exception e) {
// logger.error("Notification Service internal exception", e);
// }
//
// @Override
// public void handleListenerException(Exception e) {
// logger.error("Uncaught notification listener exception", e);
// }
// }
//
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/NsExceptionHandler.java
// public interface NsExceptionHandler {
// /**
// * Any exceptions, most notably all kinds of SQL exceptions will be passed in here.
// */
// void handleNotificationServiceException(Exception e);
//
// /**
// * Any uncaught exceptions from calling {@link NotificationListener#notif} will be passed in here.
// */
// void handleListenerException(Exception e);
// }
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/NotificationService.java
import org.postgresql.PGNotification;
import org.postgresql.jdbc.PgConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import space.npstr.sqlsauce.DatabaseException;
import space.npstr.sqlsauce.notifications.exceptions.LoggingNsExceptionHandler;
import space.npstr.sqlsauce.notifications.exceptions.NsExceptionHandler;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.notifications;
/**
* Created by napster on 06.01.18.
* <p>
* This class supports Postgres' LISTEN / NOTIFY feature, mostly the LISTENs (NOTIFYs are easy, just shoot a query at the DB).
* NOTIFY can be called on any database connection, but you can also use the built in method of this class.
* <p>
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* ATTENTION: We can't use prepared statements for the queries issueing the LISTENs and UNLISTENs, so the channel names
* need to be checked by the code calling the methods of these class for their legitimacy. Do not allow these to be set
* by any user values ever or else sql injections might happen.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* <p>
* This class creates a single connection to the database. We cannot use a pooled connection, or integrate this feature
* with a whole pool without a lot of hassle, as LISTENs and UNLISTENs would need to be executed on each connection all
* the time. Given this and connections being a costly resource, you are encouraged, but not required, to use a single
* object of this class in your application to register all your listeners with.
* <p>
* todo try async registering of listeners while listening to notifications
*/
public class NotificationService {
private static final Logger log = LoggerFactory.getLogger(NotificationService.class);
//todo is there a better way to synchronize / thread safety?
//current thread safety design synchronizes on the listeners object whenever the Map or any of the Sets of its
//values are accessed
private final Map<String, Set<NotificationListener>> listeners = new HashMap<>();
private final Connection connection; //connection that we are listening on
private final ExecutorService exec; //runs the main loop | private final NsExceptionHandler exceptionHandler; //handles all exceptions after successful init |
napstr/SqlSauce | sqlsauce-core/src/main/java/space/npstr/sqlsauce/hibernate/types/HashSetBasicType.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DbUtils.java
// public class DbUtils {
//
// private static final Logger log = LoggerFactory.getLogger(DbUtils.class);
//
// private DbUtils() {
// }
//
// /**
// * Build parameters for queries like the true lazy bastard you are.
// * <p>
// * Pass pairs of strings and objects, and you'll be fine, various exceptions or logs otherwise.
// */
// @CheckReturnValue
// public static Map<String, Object> paramsOf(Object... stringObjectPairs) {
// if (stringObjectPairs.length % 2 == 1) {
// log.warn("Passed an uneven number of args to the parameter factory, this is a likely bug.");
// }
//
// Map<String, Object> result = new HashMap<>();
// for (int ii = 0; ii < stringObjectPairs.length - 1; ii += 2) {
// result.put((String) stringObjectPairs[ii], stringObjectPairs[ii + 1]);
// }
// return result;
// }
//
// @Nullable
// public static <T extends Annotation> T getAnnotation(Annotation[] annotations, Class<T> anClass) {
// for (Annotation annotation : annotations) {
// if (anClass.isInstance(annotation)) {
// @SuppressWarnings("unchecked") T result = (T) annotation;
// return result;
// }
// }
// return null;
// }
// }
| import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import space.npstr.sqlsauce.DbUtils;
import javax.annotation.Nullable;
import java.sql.Array; | public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
st.setNull(index, sqlTypes()[0]);
} else {
if (this.basicType == null) {
throw new IllegalStateException("Not properly initialized, missing the basic type");
}
Connection connection = st.getConnection();
Array array;
if (basicType.equals(Integer.class)) {
@SuppressWarnings("unchecked") Integer[] ints = ((HashSet<Integer>) value).toArray(new Integer[0]);
array = connection.createArrayOf("integer", ints);
} else if (basicType.equals(Long.class)) {
@SuppressWarnings("unchecked") Long[] longs = ((HashSet<Long>) value).toArray(new Long[0]);
array = connection.createArrayOf("bigint", longs);
} else if (basicType.equals(String.class)) {
@SuppressWarnings("unchecked") String[] strings = ((HashSet<String>) value).toArray(new String[0]);
array = connection.createArrayOf("text", strings);
} else {
throw new IllegalArgumentException("Unsupported type: " + basicType.getSimpleName());
}
st.setArray(index, array);
}
}
private Class<?> getBasicType(ParameterType reader) { | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DbUtils.java
// public class DbUtils {
//
// private static final Logger log = LoggerFactory.getLogger(DbUtils.class);
//
// private DbUtils() {
// }
//
// /**
// * Build parameters for queries like the true lazy bastard you are.
// * <p>
// * Pass pairs of strings and objects, and you'll be fine, various exceptions or logs otherwise.
// */
// @CheckReturnValue
// public static Map<String, Object> paramsOf(Object... stringObjectPairs) {
// if (stringObjectPairs.length % 2 == 1) {
// log.warn("Passed an uneven number of args to the parameter factory, this is a likely bug.");
// }
//
// Map<String, Object> result = new HashMap<>();
// for (int ii = 0; ii < stringObjectPairs.length - 1; ii += 2) {
// result.put((String) stringObjectPairs[ii], stringObjectPairs[ii + 1]);
// }
// return result;
// }
//
// @Nullable
// public static <T extends Annotation> T getAnnotation(Annotation[] annotations, Class<T> anClass) {
// for (Annotation annotation : annotations) {
// if (anClass.isInstance(annotation)) {
// @SuppressWarnings("unchecked") T result = (T) annotation;
// return result;
// }
// }
// return null;
// }
// }
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/hibernate/types/HashSetBasicType.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import space.npstr.sqlsauce.DbUtils;
import javax.annotation.Nullable;
import java.sql.Array;
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
st.setNull(index, sqlTypes()[0]);
} else {
if (this.basicType == null) {
throw new IllegalStateException("Not properly initialized, missing the basic type");
}
Connection connection = st.getConnection();
Array array;
if (basicType.equals(Integer.class)) {
@SuppressWarnings("unchecked") Integer[] ints = ((HashSet<Integer>) value).toArray(new Integer[0]);
array = connection.createArrayOf("integer", ints);
} else if (basicType.equals(Long.class)) {
@SuppressWarnings("unchecked") Long[] longs = ((HashSet<Long>) value).toArray(new Long[0]);
array = connection.createArrayOf("bigint", longs);
} else if (basicType.equals(String.class)) {
@SuppressWarnings("unchecked") String[] strings = ((HashSet<String>) value).toArray(new String[0]);
array = connection.createArrayOf("text", strings);
} else {
throw new IllegalArgumentException("Unsupported type: " + basicType.getSimpleName());
}
st.setArray(index, array);
}
}
private Class<?> getBasicType(ParameterType reader) { | BasicType annotation = DbUtils.getAnnotation(reader.getAnnotationsMethod(), BasicType.class); |
napstr/SqlSauce | sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/Fetching.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; | /*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "fetching_test") | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/Fetching.java
import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "fetching_test") | public final class Fetching extends SaucedEntity<Long, Fetching> { |
napstr/SqlSauce | sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/Delete.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; | /*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "delete_test") | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/Delete.java
import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "delete_test") | public final class Delete extends SaucedEntity<Long, Delete> { |
napstr/SqlSauce | sqlsauce-core/src/main/java/space/npstr/sqlsauce/hibernate/types/HashSetPostgreSQLEnumUserType.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DbUtils.java
// public class DbUtils {
//
// private static final Logger log = LoggerFactory.getLogger(DbUtils.class);
//
// private DbUtils() {
// }
//
// /**
// * Build parameters for queries like the true lazy bastard you are.
// * <p>
// * Pass pairs of strings and objects, and you'll be fine, various exceptions or logs otherwise.
// */
// @CheckReturnValue
// public static Map<String, Object> paramsOf(Object... stringObjectPairs) {
// if (stringObjectPairs.length % 2 == 1) {
// log.warn("Passed an uneven number of args to the parameter factory, this is a likely bug.");
// }
//
// Map<String, Object> result = new HashMap<>();
// for (int ii = 0; ii < stringObjectPairs.length - 1; ii += 2) {
// result.put((String) stringObjectPairs[ii], stringObjectPairs[ii + 1]);
// }
// return result;
// }
//
// @Nullable
// public static <T extends Annotation> T getAnnotation(Annotation[] annotations, Class<T> anClass) {
// for (Annotation annotation : annotations) {
// if (anClass.isInstance(annotation)) {
// @SuppressWarnings("unchecked") T result = (T) annotation;
// return result;
// }
// }
// return null;
// }
// }
| import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import space.npstr.sqlsauce.DbUtils;
import javax.annotation.Nullable; | private static Enum stringToEnum(Class<? extends Enum> enumClass, String value) {
@SuppressWarnings("unchecked") Enum anEnum = Enum.valueOf(enumClass, value.trim());
return anEnum;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
st.setNull(index, sqlTypes()[0]);
} else {
Connection connection = st.getConnection();
@SuppressWarnings("unchecked") HashSet<? extends Enum> castObject = (HashSet) value;
if (this.enumClass == null) {
throw new IllegalStateException("Not properly initialized, missing the enum class");
}
if (this.typeName == null) {
throw new IllegalStateException("Not properly initialized, missing the type name");
}
Enum[] enums = castObject.toArray(new Enum[0]);
String type = this.typeName.isEmpty() ? this.enumClass.getSimpleName() : this.typeName;
Array array = connection.createArrayOf(type, enums);
st.setArray(index, array);
}
}
private Class<? extends Enum> getEnumClass(ParameterType reader) { | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DbUtils.java
// public class DbUtils {
//
// private static final Logger log = LoggerFactory.getLogger(DbUtils.class);
//
// private DbUtils() {
// }
//
// /**
// * Build parameters for queries like the true lazy bastard you are.
// * <p>
// * Pass pairs of strings and objects, and you'll be fine, various exceptions or logs otherwise.
// */
// @CheckReturnValue
// public static Map<String, Object> paramsOf(Object... stringObjectPairs) {
// if (stringObjectPairs.length % 2 == 1) {
// log.warn("Passed an uneven number of args to the parameter factory, this is a likely bug.");
// }
//
// Map<String, Object> result = new HashMap<>();
// for (int ii = 0; ii < stringObjectPairs.length - 1; ii += 2) {
// result.put((String) stringObjectPairs[ii], stringObjectPairs[ii + 1]);
// }
// return result;
// }
//
// @Nullable
// public static <T extends Annotation> T getAnnotation(Annotation[] annotations, Class<T> anClass) {
// for (Annotation annotation : annotations) {
// if (anClass.isInstance(annotation)) {
// @SuppressWarnings("unchecked") T result = (T) annotation;
// return result;
// }
// }
// return null;
// }
// }
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/hibernate/types/HashSetPostgreSQLEnumUserType.java
import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import space.npstr.sqlsauce.DbUtils;
import javax.annotation.Nullable;
private static Enum stringToEnum(Class<? extends Enum> enumClass, String value) {
@SuppressWarnings("unchecked") Enum anEnum = Enum.valueOf(enumClass, value.trim());
return anEnum;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
st.setNull(index, sqlTypes()[0]);
} else {
Connection connection = st.getConnection();
@SuppressWarnings("unchecked") HashSet<? extends Enum> castObject = (HashSet) value;
if (this.enumClass == null) {
throw new IllegalStateException("Not properly initialized, missing the enum class");
}
if (this.typeName == null) {
throw new IllegalStateException("Not properly initialized, missing the type name");
}
Enum[] enums = castObject.toArray(new Enum[0]);
String type = this.typeName.isEmpty() ? this.enumClass.getSimpleName() : this.typeName;
Array array = connection.createArrayOf(type, enums);
st.setArray(index, array);
}
}
private Class<? extends Enum> getEnumClass(ParameterType reader) { | PostgreSQLEnum enumAnn = DbUtils.getAnnotation(reader.getAnnotationsMethod(), PostgreSQLEnum.class); |
napstr/SqlSauce | sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/Merge.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; | /*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "merge_test") | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/test/java/space/npstr/sqlsauce/test/entities/Merge.java
import space.npstr.sqlsauce.entities.SaucedEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* MIT License
*
* Copyright (c) 2017-2018, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.test.entities;
/**
* Created by napster on 27.04.18.
*/
@Entity
@Table(name = "merge_test") | public final class Merge extends SaucedEntity<Long, Merge> { |
napstr/SqlSauce | sqlsauce-core/src/main/java/space/npstr/sqlsauce/fp/types/Transfiguration.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.SaucedEntity;
import java.io.Serializable;
import java.util.function.Function; | /*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.fp.types;
/**
* Created by napster on 03.12.17.
* <p>
* Describes a transformation that can be applied to an entity.
* <p>
* Somewhat of a Type class.
* <p>
* The relation between I and E is controlled by the publicly available constructors / factory methods.
* <p>
* As for the name....I needed a name ¯\_(ツ)_/¯. Didnt want another "EntitySomething" class.
*/
public class Transfiguration<I, E> {
public final EntityKey<I, E> key;
public final Function<E, E> tf;
| // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/fp/types/Transfiguration.java
import space.npstr.sqlsauce.entities.SaucedEntity;
import java.io.Serializable;
import java.util.function.Function;
/*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.fp.types;
/**
* Created by napster on 03.12.17.
* <p>
* Describes a transformation that can be applied to an entity.
* <p>
* Somewhat of a Type class.
* <p>
* The relation between I and E is controlled by the publicly available constructors / factory methods.
* <p>
* As for the name....I needed a name ¯\_(ツ)_/¯. Didnt want another "EntitySomething" class.
*/
public class Transfiguration<I, E> {
public final EntityKey<I, E> key;
public final Function<E, E> tf;
| public static <E extends SaucedEntity<I, E>, I extends Serializable> |
napstr/SqlSauce | sqlsauce-core/src/main/java/space/npstr/sqlsauce/fp/types/EntityKey.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/IEntity.java
// @TypeDef(name = "string-array", typeClass = StringArrayType.class)
// @TypeDef(name = "int-array", typeClass = IntArrayType.class)
// @TypeDef(name = "json-node", typeClass = JsonNodeStringType.class)
// @TypeDef(name = "jsonb-node", typeClass = JsonNodeBinaryType.class)
// @TypeDef(name = "json", typeClass = JsonStringType.class)
// @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
// @TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
// @TypeDef(name = "nullable-char", typeClass = NullableCharacterType.class)
// @TypeDef(name = "long-array", typeClass = LongArrayType.class)
// @TypeDef(name = "array-list-long", typeClass = ArrayListLongUserType.class)
// @TypeDef(name = "hash_set-pgsql_enum", typeClass = HashSetPostgreSQLEnumUserType.class)
// @TypeDef(name = "hash-set-basic", typeClass = HashSetBasicType.class)
// //@formatter:on
// @MappedSuperclass
// public interface IEntity<I extends Serializable, S extends IEntity<I, S>> {
//
// @CheckReturnValue
// S setId(I id);
//
// I getId();
//
// @CheckReturnValue
// Class<S> getClazz();
// }
//
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.IEntity;
import space.npstr.sqlsauce.entities.SaucedEntity;
import java.io.Serializable;
import java.util.Objects; | /*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.fp.types;
/**
* Created by napster on 29.11.17.
* <p>
* Unique key for entities, describing both their id and class.
* <p>
* Somewhat of a Type class.
* <p>
* The relation between I and E is controlled by the publicly available constructors / factory methods.
*/
public class EntityKey<I, E> {
public final I id;
public final Class<E> clazz;
| // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/IEntity.java
// @TypeDef(name = "string-array", typeClass = StringArrayType.class)
// @TypeDef(name = "int-array", typeClass = IntArrayType.class)
// @TypeDef(name = "json-node", typeClass = JsonNodeStringType.class)
// @TypeDef(name = "jsonb-node", typeClass = JsonNodeBinaryType.class)
// @TypeDef(name = "json", typeClass = JsonStringType.class)
// @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
// @TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
// @TypeDef(name = "nullable-char", typeClass = NullableCharacterType.class)
// @TypeDef(name = "long-array", typeClass = LongArrayType.class)
// @TypeDef(name = "array-list-long", typeClass = ArrayListLongUserType.class)
// @TypeDef(name = "hash_set-pgsql_enum", typeClass = HashSetPostgreSQLEnumUserType.class)
// @TypeDef(name = "hash-set-basic", typeClass = HashSetBasicType.class)
// //@formatter:on
// @MappedSuperclass
// public interface IEntity<I extends Serializable, S extends IEntity<I, S>> {
//
// @CheckReturnValue
// S setId(I id);
//
// I getId();
//
// @CheckReturnValue
// Class<S> getClazz();
// }
//
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/fp/types/EntityKey.java
import space.npstr.sqlsauce.entities.IEntity;
import space.npstr.sqlsauce.entities.SaucedEntity;
import java.io.Serializable;
import java.util.Objects;
/*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.fp.types;
/**
* Created by napster on 29.11.17.
* <p>
* Unique key for entities, describing both their id and class.
* <p>
* Somewhat of a Type class.
* <p>
* The relation between I and E is controlled by the publicly available constructors / factory methods.
*/
public class EntityKey<I, E> {
public final I id;
public final Class<E> clazz;
| public static <I extends Serializable, E extends IEntity<I, E>> EntityKey<I, E> of(final I id, |
napstr/SqlSauce | sqlsauce-core/src/main/java/space/npstr/sqlsauce/fp/types/EntityKey.java | // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/IEntity.java
// @TypeDef(name = "string-array", typeClass = StringArrayType.class)
// @TypeDef(name = "int-array", typeClass = IntArrayType.class)
// @TypeDef(name = "json-node", typeClass = JsonNodeStringType.class)
// @TypeDef(name = "jsonb-node", typeClass = JsonNodeBinaryType.class)
// @TypeDef(name = "json", typeClass = JsonStringType.class)
// @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
// @TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
// @TypeDef(name = "nullable-char", typeClass = NullableCharacterType.class)
// @TypeDef(name = "long-array", typeClass = LongArrayType.class)
// @TypeDef(name = "array-list-long", typeClass = ArrayListLongUserType.class)
// @TypeDef(name = "hash_set-pgsql_enum", typeClass = HashSetPostgreSQLEnumUserType.class)
// @TypeDef(name = "hash-set-basic", typeClass = HashSetBasicType.class)
// //@formatter:on
// @MappedSuperclass
// public interface IEntity<I extends Serializable, S extends IEntity<I, S>> {
//
// @CheckReturnValue
// S setId(I id);
//
// I getId();
//
// @CheckReturnValue
// Class<S> getClazz();
// }
//
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
| import space.npstr.sqlsauce.entities.IEntity;
import space.npstr.sqlsauce.entities.SaucedEntity;
import java.io.Serializable;
import java.util.Objects; | /*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.fp.types;
/**
* Created by napster on 29.11.17.
* <p>
* Unique key for entities, describing both their id and class.
* <p>
* Somewhat of a Type class.
* <p>
* The relation between I and E is controlled by the publicly available constructors / factory methods.
*/
public class EntityKey<I, E> {
public final I id;
public final Class<E> clazz;
public static <I extends Serializable, E extends IEntity<I, E>> EntityKey<I, E> of(final I id,
final Class<E> clazz) {
return new EntityKey<>(id, clazz);
}
public static <I extends Serializable, E extends IEntity<I, E>> EntityKey<I, E> of(final IEntity<I, E> entity) {
return new EntityKey<>(entity.getId(), entity.getClazz());
}
| // Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/IEntity.java
// @TypeDef(name = "string-array", typeClass = StringArrayType.class)
// @TypeDef(name = "int-array", typeClass = IntArrayType.class)
// @TypeDef(name = "json-node", typeClass = JsonNodeStringType.class)
// @TypeDef(name = "jsonb-node", typeClass = JsonNodeBinaryType.class)
// @TypeDef(name = "json", typeClass = JsonStringType.class)
// @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
// @TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType.class)
// @TypeDef(name = "nullable-char", typeClass = NullableCharacterType.class)
// @TypeDef(name = "long-array", typeClass = LongArrayType.class)
// @TypeDef(name = "array-list-long", typeClass = ArrayListLongUserType.class)
// @TypeDef(name = "hash_set-pgsql_enum", typeClass = HashSetPostgreSQLEnumUserType.class)
// @TypeDef(name = "hash-set-basic", typeClass = HashSetBasicType.class)
// //@formatter:on
// @MappedSuperclass
// public interface IEntity<I extends Serializable, S extends IEntity<I, S>> {
//
// @CheckReturnValue
// S setId(I id);
//
// I getId();
//
// @CheckReturnValue
// Class<S> getClazz();
// }
//
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/entities/SaucedEntity.java
// @MappedSuperclass
// public abstract class SaucedEntity<I extends Serializable, S extends SaucedEntity<I, S>> implements IEntity<I, S> {
//
// @SuppressWarnings("unchecked")
// protected S getThis() {
// return (S) this;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public Class<S> getClazz() {
// return (Class<S>) this.getClass();
// }
//
//
// //################################################################################
// // Locking
// //################################################################################
//
// @Transient
// private static final transient Map<Class, Object[]> ENTITY_LOCKS = new ConcurrentHashMap<>();
// // How many partitions the hashed entity locks shall have
// // The chosen, uncustomizable, value is considered good enough:tm: for the current implementation where locks are
// // bound to classes (amount of hanging around lock objects is equal to implemented SaucedEntities * concurrencyLevel).
// // Prime number to reduce possible collisions due to bad hashes.
// // TODO implement customizable amount
// @Transient
// private static final transient int CONCURRENCY_LEVEL = 17;
//
//
// /**
// * Abusing Hibernate with a lot of load/create entity -> detach -> save entity can lead to concurrent inserts
// * if an entity is created two times and then merged simultaneously. Use one of the lock below for any writing
// * operations, including lookup operations that will lead to writes (for example SaucedEntity#save()).
// */
// @CheckReturnValue
// public Object getEntityLock() {
// return getEntityLock(EntityKey.of(this));
// }
//
//
// @CheckReturnValue
// public static <E extends SaucedEntity<I, E>, I extends Serializable> Object getEntityLock(final SaucedEntity<I, E> entity) {
// return getEntityLock(EntityKey.of(entity));
// }
//
// /**
// * @return A hashed lock. Uses the Object#hashCode method of the provided id to determine the hash.
// */
// @CheckReturnValue
// public static Object getEntityLock(final EntityKey id) {
// Object[] hashedClasslocks = ENTITY_LOCKS.computeIfAbsent(id.clazz, k -> createObjectArray(CONCURRENCY_LEVEL));
// return hashedClasslocks[Math.floorMod(Objects.hash(id), hashedClasslocks.length)];
// }
//
// //################################################################################
// // Internals
// //################################################################################
//
// @CheckReturnValue
// private static Object[] createObjectArray(final int size) {
// final Object[] result = new Object[size];
// for (int i = 0; i < size; i++) {
// result[i] = new Object();
// }
// return result;
// }
//
// }
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/fp/types/EntityKey.java
import space.npstr.sqlsauce.entities.IEntity;
import space.npstr.sqlsauce.entities.SaucedEntity;
import java.io.Serializable;
import java.util.Objects;
/*
* MIT License
*
* Copyright (c) 2017, Dennis Neufeld
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package space.npstr.sqlsauce.fp.types;
/**
* Created by napster on 29.11.17.
* <p>
* Unique key for entities, describing both their id and class.
* <p>
* Somewhat of a Type class.
* <p>
* The relation between I and E is controlled by the publicly available constructors / factory methods.
*/
public class EntityKey<I, E> {
public final I id;
public final Class<E> clazz;
public static <I extends Serializable, E extends IEntity<I, E>> EntityKey<I, E> of(final I id,
final Class<E> clazz) {
return new EntityKey<>(id, clazz);
}
public static <I extends Serializable, E extends IEntity<I, E>> EntityKey<I, E> of(final IEntity<I, E> entity) {
return new EntityKey<>(entity.getId(), entity.getClazz());
}
| public static <I extends Serializable, E extends SaucedEntity<I, E>> EntityKey<I, E> of(final SaucedEntity<I, E> entity) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/TokenMatcher.java | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public interface ITokenMatcher {
// boolean match_EOF(Token token);
// boolean match_Empty(Token token);
// boolean match_Comment(Token token);
// boolean match_TagLine(Token token);
// boolean match_FeatureLine(Token token);
// boolean match_BackgroundLine(Token token);
// boolean match_ScenarioLine(Token token);
// boolean match_ScenarioOutlineLine(Token token);
// boolean match_ExamplesLine(Token token);
// boolean match_StepLine(Token token);
// boolean match_DocStringSeparator(Token token);
// boolean match_TableRow(Token token);
// boolean match_Language(Token token);
// boolean match_Other(Token token);
// void reset();
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum TokenType {
// None,
// EOF,
// Empty,
// Comment,
// TagLine,
// FeatureLine,
// BackgroundLine,
// ScenarioLine,
// ScenarioOutlineLine,
// ExamplesLine,
// StepLine,
// DocStringSeparator,
// TableRow,
// Language,
// Other,
// ;
// }
| import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import gherkin.ast.Location;
import static gherkin.Parser.ITokenMatcher;
import static gherkin.Parser.TokenType; | package gherkin;
public class TokenMatcher implements ITokenMatcher {
private static final Pattern LANGUAGE_PATTERN = Pattern.compile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$");
private final IGherkinDialectProvider dialectProvider;
private GherkinDialect currentDialect;
private String activeDocStringSeparator = null;
private int indentToRemove = 0;
public TokenMatcher(IGherkinDialectProvider dialectProvider) {
this.dialectProvider = dialectProvider;
reset();
}
@Override
public void reset() {
activeDocStringSeparator = null;
indentToRemove = 0;
currentDialect = dialectProvider.getDefaultDialect();
}
public GherkinDialect getCurrentDialect() {
return currentDialect;
}
| // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public interface ITokenMatcher {
// boolean match_EOF(Token token);
// boolean match_Empty(Token token);
// boolean match_Comment(Token token);
// boolean match_TagLine(Token token);
// boolean match_FeatureLine(Token token);
// boolean match_BackgroundLine(Token token);
// boolean match_ScenarioLine(Token token);
// boolean match_ScenarioOutlineLine(Token token);
// boolean match_ExamplesLine(Token token);
// boolean match_StepLine(Token token);
// boolean match_DocStringSeparator(Token token);
// boolean match_TableRow(Token token);
// boolean match_Language(Token token);
// boolean match_Other(Token token);
// void reset();
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum TokenType {
// None,
// EOF,
// Empty,
// Comment,
// TagLine,
// FeatureLine,
// BackgroundLine,
// ScenarioLine,
// ScenarioOutlineLine,
// ExamplesLine,
// StepLine,
// DocStringSeparator,
// TableRow,
// Language,
// Other,
// ;
// }
// Path: kheera-testrunner/src/main/java/gherkin/TokenMatcher.java
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import gherkin.ast.Location;
import static gherkin.Parser.ITokenMatcher;
import static gherkin.Parser.TokenType;
package gherkin;
public class TokenMatcher implements ITokenMatcher {
private static final Pattern LANGUAGE_PATTERN = Pattern.compile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$");
private final IGherkinDialectProvider dialectProvider;
private GherkinDialect currentDialect;
private String activeDocStringSeparator = null;
private int indentToRemove = 0;
public TokenMatcher(IGherkinDialectProvider dialectProvider) {
this.dialectProvider = dialectProvider;
reset();
}
@Override
public void reset() {
activeDocStringSeparator = null;
indentToRemove = 0;
currentDialect = dialectProvider.getDefaultDialect();
}
public GherkinDialect getCurrentDialect() {
return currentDialect;
}
| protected void setTokenMatched(Token token, TokenType matchedType, String text, String keyword, Integer indent, List<GherkinLineSpan> items) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/TokenMatcher.java | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public interface ITokenMatcher {
// boolean match_EOF(Token token);
// boolean match_Empty(Token token);
// boolean match_Comment(Token token);
// boolean match_TagLine(Token token);
// boolean match_FeatureLine(Token token);
// boolean match_BackgroundLine(Token token);
// boolean match_ScenarioLine(Token token);
// boolean match_ScenarioOutlineLine(Token token);
// boolean match_ExamplesLine(Token token);
// boolean match_StepLine(Token token);
// boolean match_DocStringSeparator(Token token);
// boolean match_TableRow(Token token);
// boolean match_Language(Token token);
// boolean match_Other(Token token);
// void reset();
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum TokenType {
// None,
// EOF,
// Empty,
// Comment,
// TagLine,
// FeatureLine,
// BackgroundLine,
// ScenarioLine,
// ScenarioOutlineLine,
// ExamplesLine,
// StepLine,
// DocStringSeparator,
// TableRow,
// Language,
// Other,
// ;
// }
| import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import gherkin.ast.Location;
import static gherkin.Parser.ITokenMatcher;
import static gherkin.Parser.TokenType; | package gherkin;
public class TokenMatcher implements ITokenMatcher {
private static final Pattern LANGUAGE_PATTERN = Pattern.compile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$");
private final IGherkinDialectProvider dialectProvider;
private GherkinDialect currentDialect;
private String activeDocStringSeparator = null;
private int indentToRemove = 0;
public TokenMatcher(IGherkinDialectProvider dialectProvider) {
this.dialectProvider = dialectProvider;
reset();
}
@Override
public void reset() {
activeDocStringSeparator = null;
indentToRemove = 0;
currentDialect = dialectProvider.getDefaultDialect();
}
public GherkinDialect getCurrentDialect() {
return currentDialect;
}
protected void setTokenMatched(Token token, TokenType matchedType, String text, String keyword, Integer indent, List<GherkinLineSpan> items) {
token.matchedType = matchedType;
token.matchedKeyword = keyword;
token.matchedText = text;
token.mathcedItems = items;
token.matchedGherkinDialect = getCurrentDialect();
token.matchedIndent = indent != null ? indent : (token.line == null ? 0 : token.line.indent()); | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public interface ITokenMatcher {
// boolean match_EOF(Token token);
// boolean match_Empty(Token token);
// boolean match_Comment(Token token);
// boolean match_TagLine(Token token);
// boolean match_FeatureLine(Token token);
// boolean match_BackgroundLine(Token token);
// boolean match_ScenarioLine(Token token);
// boolean match_ScenarioOutlineLine(Token token);
// boolean match_ExamplesLine(Token token);
// boolean match_StepLine(Token token);
// boolean match_DocStringSeparator(Token token);
// boolean match_TableRow(Token token);
// boolean match_Language(Token token);
// boolean match_Other(Token token);
// void reset();
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum TokenType {
// None,
// EOF,
// Empty,
// Comment,
// TagLine,
// FeatureLine,
// BackgroundLine,
// ScenarioLine,
// ScenarioOutlineLine,
// ExamplesLine,
// StepLine,
// DocStringSeparator,
// TableRow,
// Language,
// Other,
// ;
// }
// Path: kheera-testrunner/src/main/java/gherkin/TokenMatcher.java
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import gherkin.ast.Location;
import static gherkin.Parser.ITokenMatcher;
import static gherkin.Parser.TokenType;
package gherkin;
public class TokenMatcher implements ITokenMatcher {
private static final Pattern LANGUAGE_PATTERN = Pattern.compile("^\\s*#\\s*language\\s*:\\s*([a-zA-Z\\-_]+)\\s*$");
private final IGherkinDialectProvider dialectProvider;
private GherkinDialect currentDialect;
private String activeDocStringSeparator = null;
private int indentToRemove = 0;
public TokenMatcher(IGherkinDialectProvider dialectProvider) {
this.dialectProvider = dialectProvider;
reset();
}
@Override
public void reset() {
activeDocStringSeparator = null;
indentToRemove = 0;
currentDialect = dialectProvider.getDefaultDialect();
}
public GherkinDialect getCurrentDialect() {
return currentDialect;
}
protected void setTokenMatched(Token token, TokenType matchedType, String text, String keyword, Integer indent, List<GherkinLineSpan> items) {
token.matchedType = matchedType;
token.matchedKeyword = keyword;
token.matchedText = text;
token.mathcedItems = items;
token.matchedGherkinDialect = getCurrentDialect();
token.matchedIndent = indent != null ? indent : (token.line == null ? 0 : token.line.indent()); | token.location = new Location(token.location.getLine(), token.matchedIndent + 1); |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/Token.java | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
| import java.util.List;
import gherkin.ast.Location; | package gherkin;
public class Token {
public final IGherkinLine line;
public Parser.TokenType matchedType;
public String matchedKeyword;
public String matchedText;
public List<GherkinLineSpan> mathcedItems;
public int matchedIndent;
public GherkinDialect matchedGherkinDialect; | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
// Path: kheera-testrunner/src/main/java/gherkin/Token.java
import java.util.List;
import gherkin.ast.Location;
package gherkin;
public class Token {
public final IGherkinLine line;
public Parser.TokenType matchedType;
public String matchedKeyword;
public String matchedText;
public List<GherkinLineSpan> mathcedItems;
public int matchedIndent;
public GherkinDialect matchedGherkinDialect; | public Location location; |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/IGherkinDialectProvider.java | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
| import gherkin.ast.Location; | package gherkin;
public interface IGherkinDialectProvider {
GherkinDialect getDefaultDialect();
| // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
// Path: kheera-testrunner/src/main/java/gherkin/IGherkinDialectProvider.java
import gherkin.ast.Location;
package gherkin;
public interface IGherkinDialectProvider {
GherkinDialect getDefaultDialect();
| GherkinDialect getDialect(String language, Location location); |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/GherkinLine.java | // Path: kheera-testrunner/src/main/java/gherkin/StringUtils.java
// public static String ltrim(String s) {
// int i = 0;
// while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
// i++;
// }
// return s.substring(i);
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/SymbolCounter.java
// public static int countSymbols(String string) {
// return string.codePointCount(0, string.length());
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static gherkin.StringUtils.ltrim;
import static gherkin.SymbolCounter.countSymbols; | package gherkin;
public class GherkinLine implements IGherkinLine {
private final String lineText;
private final String trimmedLineText;
public GherkinLine(String lineText) {
this.lineText = lineText; | // Path: kheera-testrunner/src/main/java/gherkin/StringUtils.java
// public static String ltrim(String s) {
// int i = 0;
// while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
// i++;
// }
// return s.substring(i);
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/SymbolCounter.java
// public static int countSymbols(String string) {
// return string.codePointCount(0, string.length());
// }
// Path: kheera-testrunner/src/main/java/gherkin/GherkinLine.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static gherkin.StringUtils.ltrim;
import static gherkin.SymbolCounter.countSymbols;
package gherkin;
public class GherkinLine implements IGherkinLine {
private final String lineText;
private final String trimmedLineText;
public GherkinLine(String lineText) {
this.lineText = lineText; | this.trimmedLineText = ltrim(lineText); |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/GherkinLine.java | // Path: kheera-testrunner/src/main/java/gherkin/StringUtils.java
// public static String ltrim(String s) {
// int i = 0;
// while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
// i++;
// }
// return s.substring(i);
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/SymbolCounter.java
// public static int countSymbols(String string) {
// return string.codePointCount(0, string.length());
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static gherkin.StringUtils.ltrim;
import static gherkin.SymbolCounter.countSymbols; | package gherkin;
public class GherkinLine implements IGherkinLine {
private final String lineText;
private final String trimmedLineText;
public GherkinLine(String lineText) {
this.lineText = lineText;
this.trimmedLineText = ltrim(lineText);
}
@Override
public Integer indent() { | // Path: kheera-testrunner/src/main/java/gherkin/StringUtils.java
// public static String ltrim(String s) {
// int i = 0;
// while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
// i++;
// }
// return s.substring(i);
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/SymbolCounter.java
// public static int countSymbols(String string) {
// return string.codePointCount(0, string.length());
// }
// Path: kheera-testrunner/src/main/java/gherkin/GherkinLine.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static gherkin.StringUtils.ltrim;
import static gherkin.SymbolCounter.countSymbols;
package gherkin;
public class GherkinLine implements IGherkinLine {
private final String lineText;
private final String trimmedLineText;
public GherkinLine(String lineText) {
this.lineText = lineText;
this.trimmedLineText = ltrim(lineText);
}
@Override
public Integer indent() { | return countSymbols(lineText) - countSymbols(trimmedLineText); |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/TableConverter.java | // Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleCell.java
// public class PickleCell {
// private final PickleLocation location;
// private final String value;
//
// public PickleCell(PickleLocation location, String value) {
// this.location = location;
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// public PickleLocation getLocation() {
// return location;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleRow.java
// public class PickleRow {
// private final List<PickleCell> cells;
//
// public PickleRow(List<PickleCell> cells) {
// this.cells = unmodifiableList(cells);
// }
//
// public List<PickleCell> getCells() {
// return cells;
// }
//
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleTable.java
// public class PickleTable implements Argument {
//
// private final List<PickleRow> rows;
//
// public PickleTable(List<PickleRow> rows) {
// this.rows = unmodifiableList(rows);
// }
//
// public List<PickleRow> getRows() {
// return rows;
// }
//
// @Override
// public PickleLocation getLocation() {
// return rows.get(0).getCells().get(0).getLocation();
// }
// }
| import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jodamob.reflect.SuperReflect;
import gherkin.pickles.PickleCell;
import gherkin.pickles.PickleRow;
import gherkin.pickles.PickleTable; | return result;
} else {
return null;
}
} else {
return null;
}
}
static <T> List<T> toList(PickleTable dataTable, Type itemType, JsonElement testData) {
List<T> result = new ArrayList<T>();
List<String> keys = convertTopCellsToFieldNames(raw(dataTable.getRows().get(0)));
int count = dataTable.getRows().size();
for (int i = 1; i < count; i++) {
List<String> valueRow = raw(dataTable.getRows().get(i));
T item = (T) SuperReflect.on((Class) itemType).create().get();
int j = 0;
for (String cell : valueRow) {
SuperReflect.on(item).set(keys.get(j), cell);
j++;
}
result.add(item);
}
return Collections.unmodifiableList(result);
}
static List<String> toStringList(PickleTable dataTable, JsonElement testData) {
List<String> result = new ArrayList<String>();
int count = dataTable.getRows().size();
if (count == 1) { | // Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleCell.java
// public class PickleCell {
// private final PickleLocation location;
// private final String value;
//
// public PickleCell(PickleLocation location, String value) {
// this.location = location;
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// public PickleLocation getLocation() {
// return location;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleRow.java
// public class PickleRow {
// private final List<PickleCell> cells;
//
// public PickleRow(List<PickleCell> cells) {
// this.cells = unmodifiableList(cells);
// }
//
// public List<PickleCell> getCells() {
// return cells;
// }
//
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleTable.java
// public class PickleTable implements Argument {
//
// private final List<PickleRow> rows;
//
// public PickleTable(List<PickleRow> rows) {
// this.rows = unmodifiableList(rows);
// }
//
// public List<PickleRow> getRows() {
// return rows;
// }
//
// @Override
// public PickleLocation getLocation() {
// return rows.get(0).getCells().get(0).getLocation();
// }
// }
// Path: kheera-testrunner/src/main/java/gherkin/TableConverter.java
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jodamob.reflect.SuperReflect;
import gherkin.pickles.PickleCell;
import gherkin.pickles.PickleRow;
import gherkin.pickles.PickleTable;
return result;
} else {
return null;
}
} else {
return null;
}
}
static <T> List<T> toList(PickleTable dataTable, Type itemType, JsonElement testData) {
List<T> result = new ArrayList<T>();
List<String> keys = convertTopCellsToFieldNames(raw(dataTable.getRows().get(0)));
int count = dataTable.getRows().size();
for (int i = 1; i < count; i++) {
List<String> valueRow = raw(dataTable.getRows().get(i));
T item = (T) SuperReflect.on((Class) itemType).create().get();
int j = 0;
for (String cell : valueRow) {
SuperReflect.on(item).set(keys.get(j), cell);
j++;
}
result.add(item);
}
return Collections.unmodifiableList(result);
}
static List<String> toStringList(PickleTable dataTable, JsonElement testData) {
List<String> result = new ArrayList<String>();
int count = dataTable.getRows().size();
if (count == 1) { | for (PickleCell cell : dataTable.getRows().get(0).getCells()) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/TableConverter.java | // Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleCell.java
// public class PickleCell {
// private final PickleLocation location;
// private final String value;
//
// public PickleCell(PickleLocation location, String value) {
// this.location = location;
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// public PickleLocation getLocation() {
// return location;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleRow.java
// public class PickleRow {
// private final List<PickleCell> cells;
//
// public PickleRow(List<PickleCell> cells) {
// this.cells = unmodifiableList(cells);
// }
//
// public List<PickleCell> getCells() {
// return cells;
// }
//
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleTable.java
// public class PickleTable implements Argument {
//
// private final List<PickleRow> rows;
//
// public PickleTable(List<PickleRow> rows) {
// this.rows = unmodifiableList(rows);
// }
//
// public List<PickleRow> getRows() {
// return rows;
// }
//
// @Override
// public PickleLocation getLocation() {
// return rows.get(0).getCells().get(0).getLocation();
// }
// }
| import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jodamob.reflect.SuperReflect;
import gherkin.pickles.PickleCell;
import gherkin.pickles.PickleRow;
import gherkin.pickles.PickleTable; | } else {
return null;
}
}
static <T> List<T> toList(PickleTable dataTable, Type itemType, JsonElement testData) {
List<T> result = new ArrayList<T>();
List<String> keys = convertTopCellsToFieldNames(raw(dataTable.getRows().get(0)));
int count = dataTable.getRows().size();
for (int i = 1; i < count; i++) {
List<String> valueRow = raw(dataTable.getRows().get(i));
T item = (T) SuperReflect.on((Class) itemType).create().get();
int j = 0;
for (String cell : valueRow) {
SuperReflect.on(item).set(keys.get(j), cell);
j++;
}
result.add(item);
}
return Collections.unmodifiableList(result);
}
static List<String> toStringList(PickleTable dataTable, JsonElement testData) {
List<String> result = new ArrayList<String>();
int count = dataTable.getRows().size();
if (count == 1) {
for (PickleCell cell : dataTable.getRows().get(0).getCells()) {
result.add(replaceWithTestData(testData, cell.getValue()));
}
} else { | // Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleCell.java
// public class PickleCell {
// private final PickleLocation location;
// private final String value;
//
// public PickleCell(PickleLocation location, String value) {
// this.location = location;
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// public PickleLocation getLocation() {
// return location;
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleRow.java
// public class PickleRow {
// private final List<PickleCell> cells;
//
// public PickleRow(List<PickleCell> cells) {
// this.cells = unmodifiableList(cells);
// }
//
// public List<PickleCell> getCells() {
// return cells;
// }
//
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/pickles/PickleTable.java
// public class PickleTable implements Argument {
//
// private final List<PickleRow> rows;
//
// public PickleTable(List<PickleRow> rows) {
// this.rows = unmodifiableList(rows);
// }
//
// public List<PickleRow> getRows() {
// return rows;
// }
//
// @Override
// public PickleLocation getLocation() {
// return rows.get(0).getCells().get(0).getLocation();
// }
// }
// Path: kheera-testrunner/src/main/java/gherkin/TableConverter.java
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import de.jodamob.reflect.SuperReflect;
import gherkin.pickles.PickleCell;
import gherkin.pickles.PickleRow;
import gherkin.pickles.PickleTable;
} else {
return null;
}
}
static <T> List<T> toList(PickleTable dataTable, Type itemType, JsonElement testData) {
List<T> result = new ArrayList<T>();
List<String> keys = convertTopCellsToFieldNames(raw(dataTable.getRows().get(0)));
int count = dataTable.getRows().size();
for (int i = 1; i < count; i++) {
List<String> valueRow = raw(dataTable.getRows().get(i));
T item = (T) SuperReflect.on((Class) itemType).create().get();
int j = 0;
for (String cell : valueRow) {
SuperReflect.on(item).set(keys.get(j), cell);
j++;
}
result.add(item);
}
return Collections.unmodifiableList(result);
}
static List<String> toStringList(PickleTable dataTable, JsonElement testData) {
List<String> result = new ArrayList<String>();
int count = dataTable.getRows().size();
if (count == 1) {
for (PickleCell cell : dataTable.getRows().get(0).getCells()) {
result.add(replaceWithTestData(testData, cell.getValue()));
}
} else { | for (PickleRow row : dataTable.getRows()) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/AstNode.java | // Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum RuleType {
// None,
// _EOF, // #EOF
// _Empty, // #Empty
// _Comment, // #Comment
// _TagLine, // #TagLine
// _FeatureLine, // #FeatureLine
// _BackgroundLine, // #BackgroundLine
// _ScenarioLine, // #ScenarioLine
// _ScenarioOutlineLine, // #ScenarioOutlineLine
// _ExamplesLine, // #ExamplesLine
// _StepLine, // #StepLine
// _DocStringSeparator, // #DocStringSeparator
// _TableRow, // #TableRow
// _Language, // #Language
// _Other, // #Other
// GherkinDocument, // GherkinDocument! := Feature?
// Feature, // Feature! := Feature_Header Background? Scenario_Definition*
// Feature_Header, // Feature_Header! := #Language? Tags? #FeatureLine Feature_Description
// Background, // Background! := #BackgroundLine Background_Description Scenario_Step*
// Scenario_Definition, // Scenario_Definition! := Tags? (Scenario | ScenarioOutline)
// Scenario, // Scenario! := #ScenarioLine Scenario_Description Scenario_Step*
// ScenarioOutline, // ScenarioOutline! := #ScenarioOutlineLine ScenarioOutline_Description ScenarioOutline_Step* Examples_Definition*
// Examples_Definition, // Examples_Definition! [#Empty|#Comment|#TagLine->#ExamplesLine] := Tags? Examples
// Examples, // Examples! := #ExamplesLine Examples_Description Examples_Table?
// Examples_Table, // Examples_Table! := #TableRow #TableRow*
// Scenario_Step, // Scenario_Step := Step
// ScenarioOutline_Step, // ScenarioOutline_Step := Step
// Step, // Step! := #StepLine Step_Arg?
// Step_Arg, // Step_Arg := (DataTable | DocString)
// DataTable, // DataTable! := #TableRow+
// DocString, // DocString! := #DocStringSeparator #Other* #DocStringSeparator
// Tags, // Tags! := #TagLine+
// Feature_Description, // Feature_Description := Description_Helper
// Background_Description, // Background_Description := Description_Helper
// Scenario_Description, // Scenario_Description := Description_Helper
// ScenarioOutline_Description, // ScenarioOutline_Description := Description_Helper
// Examples_Description, // Examples_Description := Description_Helper
// Description_Helper, // Description_Helper := #Empty* Description? #Comment*
// Description, // Description! := #Other+
// ;
//
// public static RuleType cast(TokenType tokenType) {
// return RuleType.values()[tokenType.ordinal()];
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum TokenType {
// None,
// EOF,
// Empty,
// Comment,
// TagLine,
// FeatureLine,
// BackgroundLine,
// ScenarioLine,
// ScenarioOutlineLine,
// ExamplesLine,
// StepLine,
// DocStringSeparator,
// TableRow,
// Language,
// Other,
// ;
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static gherkin.Parser.RuleType;
import static gherkin.Parser.TokenType; | package gherkin;
public class AstNode {
private final Map<RuleType, List<Object>> subItems = new HashMap<RuleType, List<Object>>();
public final RuleType ruleType;
public AstNode(RuleType ruleType) {
this.ruleType = ruleType;
}
public void add(RuleType ruleType, Object obj) {
List<Object> items = subItems.get(ruleType);
if (items == null) {
items = new ArrayList<Object>();
subItems.put(ruleType, items);
}
items.add(obj);
}
public <T> T getSingle(RuleType ruleType, T defaultResult) {
List<Object> items = getItems(ruleType);
return (T) (items.isEmpty() ? defaultResult : items.get(0));
}
public <T> List<T> getItems(RuleType ruleType) {
List<T> items = (List<T>) subItems.get(ruleType);
if (items == null) {
return Collections.emptyList();
}
return items;
}
| // Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum RuleType {
// None,
// _EOF, // #EOF
// _Empty, // #Empty
// _Comment, // #Comment
// _TagLine, // #TagLine
// _FeatureLine, // #FeatureLine
// _BackgroundLine, // #BackgroundLine
// _ScenarioLine, // #ScenarioLine
// _ScenarioOutlineLine, // #ScenarioOutlineLine
// _ExamplesLine, // #ExamplesLine
// _StepLine, // #StepLine
// _DocStringSeparator, // #DocStringSeparator
// _TableRow, // #TableRow
// _Language, // #Language
// _Other, // #Other
// GherkinDocument, // GherkinDocument! := Feature?
// Feature, // Feature! := Feature_Header Background? Scenario_Definition*
// Feature_Header, // Feature_Header! := #Language? Tags? #FeatureLine Feature_Description
// Background, // Background! := #BackgroundLine Background_Description Scenario_Step*
// Scenario_Definition, // Scenario_Definition! := Tags? (Scenario | ScenarioOutline)
// Scenario, // Scenario! := #ScenarioLine Scenario_Description Scenario_Step*
// ScenarioOutline, // ScenarioOutline! := #ScenarioOutlineLine ScenarioOutline_Description ScenarioOutline_Step* Examples_Definition*
// Examples_Definition, // Examples_Definition! [#Empty|#Comment|#TagLine->#ExamplesLine] := Tags? Examples
// Examples, // Examples! := #ExamplesLine Examples_Description Examples_Table?
// Examples_Table, // Examples_Table! := #TableRow #TableRow*
// Scenario_Step, // Scenario_Step := Step
// ScenarioOutline_Step, // ScenarioOutline_Step := Step
// Step, // Step! := #StepLine Step_Arg?
// Step_Arg, // Step_Arg := (DataTable | DocString)
// DataTable, // DataTable! := #TableRow+
// DocString, // DocString! := #DocStringSeparator #Other* #DocStringSeparator
// Tags, // Tags! := #TagLine+
// Feature_Description, // Feature_Description := Description_Helper
// Background_Description, // Background_Description := Description_Helper
// Scenario_Description, // Scenario_Description := Description_Helper
// ScenarioOutline_Description, // ScenarioOutline_Description := Description_Helper
// Examples_Description, // Examples_Description := Description_Helper
// Description_Helper, // Description_Helper := #Empty* Description? #Comment*
// Description, // Description! := #Other+
// ;
//
// public static RuleType cast(TokenType tokenType) {
// return RuleType.values()[tokenType.ordinal()];
// }
// }
//
// Path: kheera-testrunner/src/main/java/gherkin/Parser.java
// public enum TokenType {
// None,
// EOF,
// Empty,
// Comment,
// TagLine,
// FeatureLine,
// BackgroundLine,
// ScenarioLine,
// ScenarioOutlineLine,
// ExamplesLine,
// StepLine,
// DocStringSeparator,
// TableRow,
// Language,
// Other,
// ;
// }
// Path: kheera-testrunner/src/main/java/gherkin/AstNode.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static gherkin.Parser.RuleType;
import static gherkin.Parser.TokenType;
package gherkin;
public class AstNode {
private final Map<RuleType, List<Object>> subItems = new HashMap<RuleType, List<Object>>();
public final RuleType ruleType;
public AstNode(RuleType ruleType) {
this.ruleType = ruleType;
}
public void add(RuleType ruleType, Object obj) {
List<Object> items = subItems.get(ruleType);
if (items == null) {
items = new ArrayList<Object>();
subItems.put(ruleType, items);
}
items.add(obj);
}
public <T> T getSingle(RuleType ruleType, T defaultResult) {
List<Object> items = getItems(ruleType);
return (T) (items.isEmpty() ? defaultResult : items.get(0));
}
public <T> List<T> getItems(RuleType ruleType) {
List<T> items = (List<T>) subItems.get(ruleType);
if (items == null) {
return Collections.emptyList();
}
return items;
}
| public Token getToken(TokenType tokenType) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/com/kheera/KheeraRunner.java | // Path: kheera-testrunner/src/main/java/com/kheera/factory/FeatureFileExecutorFactory.java
// public class FeatureFileExecutorFactory extends RunnerBuilder {
// @Override
// public Runner runnerForClass(Class<?> testClass) throws Throwable {
// if(testClass.isAnnotationPresent(TestModule.class))
// {
// // Generate test config
// TestRunnerConfig testConfig = getTestConfig();
//
// return new FeatureFileExecutor(testConfig, testClass);
// }
// else return null;
// }
//
// private TestRunnerConfig getTestConfig() throws AutomationRunnerException {
// TestRunnerConfig testConfig = new TestRunnerConfig();
// Bundle arguments = InstrumentationRegistry.getArguments();
//
// String testConfigName = "default";
// if (arguments != null && arguments.containsKey("config")) {
// testConfigName = arguments.getString("config");
// }
// if (arguments != null && arguments.containsKey("coverage") && Boolean.parseBoolean(arguments.getString("coverage"))) {
// testConfigName = "coverage";
// }
//
// testConfig = (TestRunnerConfig) new Gson().fromJson(AssetUtils.ReadAsset(getContext(), "config" + File.separator + testConfigName + File.separator + "testsetup.json"), TestRunnerConfig.class);
//
// if (arguments != null && arguments.containsKey("screenshots")) {
// testConfig.Screenshots = Boolean.parseBoolean(arguments.getString("screenshots"));
// }
//
// if (arguments != null && arguments.containsKey("includeskipped")) {
// testConfig.IncludeSkipped = Boolean.parseBoolean(arguments.getString("includeskipped"));
// }
//
// if (arguments != null && arguments.containsKey("writetestreport")) {
// testConfig.WriteTestReport = Boolean.parseBoolean(arguments.getString("writetestreport"));
// }
//
// if(arguments != null && arguments.containsKey("detailederrors")) {
// testConfig.DetailedErrors = Boolean.parseBoolean(arguments.getString("detailederrors"));
// }
//
// if(testConfig.CoverageReport) {
// if (arguments != null && arguments.containsKey("coverageFile")) {
// testConfig.CoverageFile = arguments.getString("coverageFile");
// }
// }
//
// if (arguments != null && arguments.containsKey("tags") && arguments.getString("tags") != null) {
// testConfig.FilterType = "tag";
// testConfig.FilterBy = arguments.getString("tags").toLowerCase(Locale.getDefault());
// }
// if (arguments != null && arguments.containsKey("tag") && arguments.getString("tag") != null) {
// testConfig.FilterType = "tag";
// testConfig.FilterBy = arguments.getString("tag").toLowerCase(Locale.getDefault());
// } else if (arguments != null && arguments.containsKey("file") && arguments.getString("file") != null) {
// testConfig.FilterType = "file";
// testConfig.FilterBy = arguments.getString("file").toLowerCase(Locale.getDefault());
// } else if (arguments != null && arguments.containsKey("scenario") && arguments.getString("scenario") != null) {
// testConfig.FilterType = "scenario";
// testConfig.FilterBy = arguments.getString("scenario").toLowerCase(Locale.getDefault());
// }
// else if(arguments != null && arguments.containsKey("runmode") && arguments.getString("runmode") != null) {
// testConfig.FilterType = arguments.getString("runmode").toLowerCase(Locale.getDefault());
// if(testConfig.FilterType.equals("previously-failed") && !testConfig.WriteTestReport) {
// throw new AutomationRunnerException("Previously failed tests only was requested, but report logging was disabled in the given testsetup.json.", null);
// }
// }
//
// return testConfig;
// }
// }
| import android.os.Bundle;
import android.os.Debug;
import com.kheera.factory.FeatureFileExecutorFactory;
import androidx.test.runner.AndroidJUnitRunner; | package com.kheera;
public class KheeraRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
boolean waitForDebugger = arguments != null && arguments.containsKey("debug") && Boolean.parseBoolean(arguments.getString("debug"));
if (waitForDebugger) {
Debug.waitForDebugger();
}
| // Path: kheera-testrunner/src/main/java/com/kheera/factory/FeatureFileExecutorFactory.java
// public class FeatureFileExecutorFactory extends RunnerBuilder {
// @Override
// public Runner runnerForClass(Class<?> testClass) throws Throwable {
// if(testClass.isAnnotationPresent(TestModule.class))
// {
// // Generate test config
// TestRunnerConfig testConfig = getTestConfig();
//
// return new FeatureFileExecutor(testConfig, testClass);
// }
// else return null;
// }
//
// private TestRunnerConfig getTestConfig() throws AutomationRunnerException {
// TestRunnerConfig testConfig = new TestRunnerConfig();
// Bundle arguments = InstrumentationRegistry.getArguments();
//
// String testConfigName = "default";
// if (arguments != null && arguments.containsKey("config")) {
// testConfigName = arguments.getString("config");
// }
// if (arguments != null && arguments.containsKey("coverage") && Boolean.parseBoolean(arguments.getString("coverage"))) {
// testConfigName = "coverage";
// }
//
// testConfig = (TestRunnerConfig) new Gson().fromJson(AssetUtils.ReadAsset(getContext(), "config" + File.separator + testConfigName + File.separator + "testsetup.json"), TestRunnerConfig.class);
//
// if (arguments != null && arguments.containsKey("screenshots")) {
// testConfig.Screenshots = Boolean.parseBoolean(arguments.getString("screenshots"));
// }
//
// if (arguments != null && arguments.containsKey("includeskipped")) {
// testConfig.IncludeSkipped = Boolean.parseBoolean(arguments.getString("includeskipped"));
// }
//
// if (arguments != null && arguments.containsKey("writetestreport")) {
// testConfig.WriteTestReport = Boolean.parseBoolean(arguments.getString("writetestreport"));
// }
//
// if(arguments != null && arguments.containsKey("detailederrors")) {
// testConfig.DetailedErrors = Boolean.parseBoolean(arguments.getString("detailederrors"));
// }
//
// if(testConfig.CoverageReport) {
// if (arguments != null && arguments.containsKey("coverageFile")) {
// testConfig.CoverageFile = arguments.getString("coverageFile");
// }
// }
//
// if (arguments != null && arguments.containsKey("tags") && arguments.getString("tags") != null) {
// testConfig.FilterType = "tag";
// testConfig.FilterBy = arguments.getString("tags").toLowerCase(Locale.getDefault());
// }
// if (arguments != null && arguments.containsKey("tag") && arguments.getString("tag") != null) {
// testConfig.FilterType = "tag";
// testConfig.FilterBy = arguments.getString("tag").toLowerCase(Locale.getDefault());
// } else if (arguments != null && arguments.containsKey("file") && arguments.getString("file") != null) {
// testConfig.FilterType = "file";
// testConfig.FilterBy = arguments.getString("file").toLowerCase(Locale.getDefault());
// } else if (arguments != null && arguments.containsKey("scenario") && arguments.getString("scenario") != null) {
// testConfig.FilterType = "scenario";
// testConfig.FilterBy = arguments.getString("scenario").toLowerCase(Locale.getDefault());
// }
// else if(arguments != null && arguments.containsKey("runmode") && arguments.getString("runmode") != null) {
// testConfig.FilterType = arguments.getString("runmode").toLowerCase(Locale.getDefault());
// if(testConfig.FilterType.equals("previously-failed") && !testConfig.WriteTestReport) {
// throw new AutomationRunnerException("Previously failed tests only was requested, but report logging was disabled in the given testsetup.json.", null);
// }
// }
//
// return testConfig;
// }
// }
// Path: kheera-testrunner/src/main/java/com/kheera/KheeraRunner.java
import android.os.Bundle;
import android.os.Debug;
import com.kheera.factory.FeatureFileExecutorFactory;
import androidx.test.runner.AndroidJUnitRunner;
package com.kheera;
public class KheeraRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
boolean waitForDebugger = arguments != null && arguments.containsKey("debug") && Boolean.parseBoolean(arguments.getString("debug"));
if (waitForDebugger) {
Debug.waitForDebugger();
}
| arguments.putString("runnerBuilder", FeatureFileExecutorFactory.class.getCanonicalName()); |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/GherkinDialectProvider.java | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
| import com.google.gson.Gson;
import java.util.Map;
import gherkin.ast.Location; | package gherkin;
public class GherkinDialectProvider implements IGherkinDialectProvider {
private final String default_dialect_name;
private Map dialects;
public void loadDialects(String source) {
Gson gson = new Gson();
this.dialects = gson.fromJson(source, Map.class);
}
public GherkinDialectProvider(String default_dialect_name, String dialectFile) {
this.default_dialect_name = default_dialect_name;
if(dialectFile != null)
this.loadDialects(dialectFile);
}
public GherkinDialectProvider() {
this("en", null);
}
public GherkinDialect getDefaultDialect() {
return getDialect(default_dialect_name, null);
}
@Override | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
// Path: kheera-testrunner/src/main/java/gherkin/GherkinDialectProvider.java
import com.google.gson.Gson;
import java.util.Map;
import gherkin.ast.Location;
package gherkin;
public class GherkinDialectProvider implements IGherkinDialectProvider {
private final String default_dialect_name;
private Map dialects;
public void loadDialects(String source) {
Gson gson = new Gson();
this.dialects = gson.fromJson(source, Map.class);
}
public GherkinDialectProvider(String default_dialect_name, String dialectFile) {
this.default_dialect_name = default_dialect_name;
if(dialectFile != null)
this.loadDialects(dialectFile);
}
public GherkinDialectProvider() {
this("en", null);
}
public GherkinDialect getDefaultDialect() {
return getDialect(default_dialect_name, null);
}
@Override | public GherkinDialect getDialect(String language, Location location) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/com/kheera/internal/StepDefFunctionTable.java | // Path: kheera-testrunner/src/main/java/gherkin/pickles/Pickle.java
// public class Pickle {
// private final String name;
// private final List<PickleStep> steps;
// private final List<PickleTag> tags;
// private final List<PickleLocation> locations;
//
// public Pickle(String name, List<PickleStep> steps, List<PickleTag> tags, List<PickleLocation> locations) {
// this.name = name;
// this.steps = unmodifiableList(steps);
// this.tags = tags;
// this.locations = unmodifiableList(locations);
// }
//
// public String getName() {
// return name;
// }
//
// public List<PickleStep> getSteps() {
// return steps;
// }
//
// public List<PickleLocation> getLocations() {
// return locations;
// }
//
// public List<PickleTag> getTags() { return tags; }
//
// public String getIdentification() {
// StringBuilder builder = new StringBuilder();
// for (PickleLocation loc : locations) {
// builder.append(loc.getPath());
// builder.append(loc.getLine());
// builder.append(loc.getColumn());
// }
// builder.append(name);
// return builder.toString();
// }
// }
| import android.content.Context;
import com.kheera.annotations.TestModule;
import com.kheera.annotations.RootTestModule;
import com.kheera.annotations.OnFinishTest;
import com.kheera.annotations.OnStartTest;
import com.kheera.annotations.TestStep;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import androidx.test.core.app.ApplicationProvider;
import dalvik.system.DexFile;
import gherkin.pickles.Pickle; | package com.kheera.internal;
/**
* Created by andrewc on 4/07/2016.
*/
public class StepDefFunctionTable {
private final HashSet<OnStartMethodMappingEntry> declaredBeforeMethods;
private final HashMap<String, TestStepMappingEntry> declaredTestStepMethods;
private final HashSet<OnFinishMethodMappingEntry> declaredFinishMethods;
private final HashMap<String, TestStepMappingEntry> expressionCache;
private final Context context;
private final Class<? extends StepDefinition> stepDefClass;
private final StepDefinition stepDefObject;
//private Class gerkinRootClass;
//private Object gerkinRootObject;
private boolean enableExpressionCache = true;
public StepDefFunctionTable(Context context, StepDefinition stepDef) throws AutomationRunnerException{
this.context = context;
this.stepDefClass = stepDef.getClass();
this.stepDefObject = stepDef;
this.declaredBeforeMethods = new HashSet<OnStartMethodMappingEntry>();
this.declaredTestStepMethods = new HashMap<String, TestStepMappingEntry>();
this.declaredFinishMethods = new HashSet<OnFinishMethodMappingEntry>();
this.expressionCache = new HashMap<String, TestStepMappingEntry>();
if(stepDefClass != null) {
indexStepDefClass();
}
}
private void indexStepDefClass() throws AutomationRunnerException {
indexStepsOnModule(stepDefObject);
}
| // Path: kheera-testrunner/src/main/java/gherkin/pickles/Pickle.java
// public class Pickle {
// private final String name;
// private final List<PickleStep> steps;
// private final List<PickleTag> tags;
// private final List<PickleLocation> locations;
//
// public Pickle(String name, List<PickleStep> steps, List<PickleTag> tags, List<PickleLocation> locations) {
// this.name = name;
// this.steps = unmodifiableList(steps);
// this.tags = tags;
// this.locations = unmodifiableList(locations);
// }
//
// public String getName() {
// return name;
// }
//
// public List<PickleStep> getSteps() {
// return steps;
// }
//
// public List<PickleLocation> getLocations() {
// return locations;
// }
//
// public List<PickleTag> getTags() { return tags; }
//
// public String getIdentification() {
// StringBuilder builder = new StringBuilder();
// for (PickleLocation loc : locations) {
// builder.append(loc.getPath());
// builder.append(loc.getLine());
// builder.append(loc.getColumn());
// }
// builder.append(name);
// return builder.toString();
// }
// }
// Path: kheera-testrunner/src/main/java/com/kheera/internal/StepDefFunctionTable.java
import android.content.Context;
import com.kheera.annotations.TestModule;
import com.kheera.annotations.RootTestModule;
import com.kheera.annotations.OnFinishTest;
import com.kheera.annotations.OnStartTest;
import com.kheera.annotations.TestStep;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import androidx.test.core.app.ApplicationProvider;
import dalvik.system.DexFile;
import gherkin.pickles.Pickle;
package com.kheera.internal;
/**
* Created by andrewc on 4/07/2016.
*/
public class StepDefFunctionTable {
private final HashSet<OnStartMethodMappingEntry> declaredBeforeMethods;
private final HashMap<String, TestStepMappingEntry> declaredTestStepMethods;
private final HashSet<OnFinishMethodMappingEntry> declaredFinishMethods;
private final HashMap<String, TestStepMappingEntry> expressionCache;
private final Context context;
private final Class<? extends StepDefinition> stepDefClass;
private final StepDefinition stepDefObject;
//private Class gerkinRootClass;
//private Object gerkinRootObject;
private boolean enableExpressionCache = true;
public StepDefFunctionTable(Context context, StepDefinition stepDef) throws AutomationRunnerException{
this.context = context;
this.stepDefClass = stepDef.getClass();
this.stepDefObject = stepDef;
this.declaredBeforeMethods = new HashSet<OnStartMethodMappingEntry>();
this.declaredTestStepMethods = new HashMap<String, TestStepMappingEntry>();
this.declaredFinishMethods = new HashSet<OnFinishMethodMappingEntry>();
this.expressionCache = new HashMap<String, TestStepMappingEntry>();
if(stepDefClass != null) {
indexStepDefClass();
}
}
private void indexStepDefClass() throws AutomationRunnerException {
indexStepsOnModule(stepDefObject);
}
| public Set<OnFinishMethodMappingEntry> findOnFinishMethod(Pickle pickle) { |
andrewjc/kheera-testrunner-android | kheera-testrunner/src/main/java/gherkin/TokenScanner.java | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import gherkin.ast.Location; | package gherkin;
/**
* <p>
* The scanner reads a gherkin doc (typically read from a .feature file) and creates a token
* for each line. The tokens are passed to the parser, which outputs an AST (Abstract Syntax Tree).</p>
*
* <p>
* If the scanner sees a # language header, it will reconfigure itself dynamically to look for
* Gherkin keywords for the associated language. The keywords are defined in gherkin-languages.json.</p>
*/
public class TokenScanner implements Parser.ITokenScanner {
private final BufferedReader reader;
private int lineNumber;
public TokenScanner(String source) {
this(new StringReader(source));
}
public TokenScanner(Reader source) {
this.reader = new BufferedReader(source);
}
@Override
public Token read() {
try {
String line = reader.readLine(); | // Path: kheera-testrunner/src/main/java/gherkin/ast/Location.java
// public class Location {
// private final int line;
// private final int column;
//
// public Location(int line, int column) {
// this.line = line;
// this.column = column;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getColumn() {
// return column;
// }
// }
// Path: kheera-testrunner/src/main/java/gherkin/TokenScanner.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import gherkin.ast.Location;
package gherkin;
/**
* <p>
* The scanner reads a gherkin doc (typically read from a .feature file) and creates a token
* for each line. The tokens are passed to the parser, which outputs an AST (Abstract Syntax Tree).</p>
*
* <p>
* If the scanner sees a # language header, it will reconfigure itself dynamically to look for
* Gherkin keywords for the associated language. The keywords are defined in gherkin-languages.json.</p>
*/
public class TokenScanner implements Parser.ITokenScanner {
private final BufferedReader reader;
private int lineNumber;
public TokenScanner(String source) {
this(new StringReader(source));
}
public TokenScanner(Reader source) {
this.reader = new BufferedReader(source);
}
@Override
public Token read() {
try {
String line = reader.readLine(); | Location location = new Location(++lineNumber, 0); |
andrewjc/kheera-testrunner-android | samples/src/androidTest/java/com/kheera/kheerasample/stepdefs/LoginPageFeatureFile.java | // Path: kheera-testrunner/src/main/java/com/kheera/internal/StepDefinition.java
// public interface StepDefinition {
// void onCreate(Context context, TestRunnerConfig runnerConfig);
// }
//
// Path: kheera-testrunner/src/main/java/com/kheera/internal/TestRunnerConfig.java
// public class TestRunnerConfig {
// @SerializedName("Name")
// public String Name;
//
// @SerializedName("Description")
// public String Description;
//
// @SerializedName("TestData")
// public String TestDataFile;
//
// @SerializedName("AppConfig")
// public String AppConfigFile;
//
// @SerializedName("Screenshots")
// public boolean Screenshots;
//
// @SerializedName("IncludeSkipped")
// public boolean IncludeSkipped;
//
// @SerializedName("WriteTestReport")
// public boolean WriteTestReport;
//
// @SerializedName("ReportLogPath")
// public String ReportLogPath;
//
// @SerializedName("FilterBy")
// public String FilterBy;
//
// @SerializedName("FilterType")
// public String FilterType;
//
// @SerializedName("DetailedErrors")
// public boolean DetailedErrors;
//
// @SerializedName("CoverageReport")
// public boolean CoverageReport;
//
// @SerializedName("CoverageFile")
// public String CoverageFile;
//
// @SerializedName("LogTag")
// public String LogTag;
// }
//
// Path: samples/src/androidTest/java/com/kheera/kheerasample/screens/LoginScreen.java
// public class LoginScreen {
// public static Activity ActivityInstance;
//
// public static void open() {
//
// boolean mInitialTouchMode = false;
//
// getInstrumentation().setInTouchMode(mInitialTouchMode);
//
// Intent newIntent = new Intent(getInstrumentation().getTargetContext(), LoginActivity.class);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// ActivityInstance = getInstrumentation().startActivitySync(newIntent);
//
// getInstrumentation().waitForIdleSync();
//
// ((KeyguardManager) getInstrumentation().getContext().getSystemService(KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE).disableKeyguard();
//
// //turn the screen on
// ActivityInstance.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// ActivityInstance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
// | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
// }
// });
// }
//
// public static void enterEmail(String email) {
// onView(withId(R.id.email)).perform(typeText(email));
// }
//
// public static void enterPassword(String password) {
// onView(withId(R.id.password)).perform(typeText(password));
// }
//
// public static void performLogin() {
// onView(withId(R.id.email_sign_in_button)).perform(click());
// }
// }
| import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.kheera.annotations.OnFinishTest;
import com.kheera.annotations.OnStartTest;
import com.kheera.annotations.RetainAcrossTests;
import com.kheera.annotations.TestModule;
import com.kheera.annotations.TestStep;
import com.kheera.internal.StepDefinition;
import com.kheera.internal.TestRunnerConfig;
import com.kheera.kheerasample.R;
import com.kheera.kheerasample.screens.LoginScreen;
import java.util.concurrent.TimeUnit;
import androidx.test.espresso.IdlingPolicies;
import androidx.test.espresso.intent.Intents;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; | package com.kheera.kheerasample.stepdefs;
/**
* Created by andrewc on 28/9/17.
*/
@TestModule(featureFile = "loginpage.feature")
public class LoginPageFeatureFile implements StepDefinition {
private static final String DEFAULT_EMAIL = "admin@kheera.com";
private static final String DEFAULT_PASSWORD = "admin123";
| // Path: kheera-testrunner/src/main/java/com/kheera/internal/StepDefinition.java
// public interface StepDefinition {
// void onCreate(Context context, TestRunnerConfig runnerConfig);
// }
//
// Path: kheera-testrunner/src/main/java/com/kheera/internal/TestRunnerConfig.java
// public class TestRunnerConfig {
// @SerializedName("Name")
// public String Name;
//
// @SerializedName("Description")
// public String Description;
//
// @SerializedName("TestData")
// public String TestDataFile;
//
// @SerializedName("AppConfig")
// public String AppConfigFile;
//
// @SerializedName("Screenshots")
// public boolean Screenshots;
//
// @SerializedName("IncludeSkipped")
// public boolean IncludeSkipped;
//
// @SerializedName("WriteTestReport")
// public boolean WriteTestReport;
//
// @SerializedName("ReportLogPath")
// public String ReportLogPath;
//
// @SerializedName("FilterBy")
// public String FilterBy;
//
// @SerializedName("FilterType")
// public String FilterType;
//
// @SerializedName("DetailedErrors")
// public boolean DetailedErrors;
//
// @SerializedName("CoverageReport")
// public boolean CoverageReport;
//
// @SerializedName("CoverageFile")
// public String CoverageFile;
//
// @SerializedName("LogTag")
// public String LogTag;
// }
//
// Path: samples/src/androidTest/java/com/kheera/kheerasample/screens/LoginScreen.java
// public class LoginScreen {
// public static Activity ActivityInstance;
//
// public static void open() {
//
// boolean mInitialTouchMode = false;
//
// getInstrumentation().setInTouchMode(mInitialTouchMode);
//
// Intent newIntent = new Intent(getInstrumentation().getTargetContext(), LoginActivity.class);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// ActivityInstance = getInstrumentation().startActivitySync(newIntent);
//
// getInstrumentation().waitForIdleSync();
//
// ((KeyguardManager) getInstrumentation().getContext().getSystemService(KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE).disableKeyguard();
//
// //turn the screen on
// ActivityInstance.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// ActivityInstance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
// | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
// }
// });
// }
//
// public static void enterEmail(String email) {
// onView(withId(R.id.email)).perform(typeText(email));
// }
//
// public static void enterPassword(String password) {
// onView(withId(R.id.password)).perform(typeText(password));
// }
//
// public static void performLogin() {
// onView(withId(R.id.email_sign_in_button)).perform(click());
// }
// }
// Path: samples/src/androidTest/java/com/kheera/kheerasample/stepdefs/LoginPageFeatureFile.java
import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.kheera.annotations.OnFinishTest;
import com.kheera.annotations.OnStartTest;
import com.kheera.annotations.RetainAcrossTests;
import com.kheera.annotations.TestModule;
import com.kheera.annotations.TestStep;
import com.kheera.internal.StepDefinition;
import com.kheera.internal.TestRunnerConfig;
import com.kheera.kheerasample.R;
import com.kheera.kheerasample.screens.LoginScreen;
import java.util.concurrent.TimeUnit;
import androidx.test.espresso.IdlingPolicies;
import androidx.test.espresso.intent.Intents;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
package com.kheera.kheerasample.stepdefs;
/**
* Created by andrewc on 28/9/17.
*/
@TestModule(featureFile = "loginpage.feature")
public class LoginPageFeatureFile implements StepDefinition {
private static final String DEFAULT_EMAIL = "admin@kheera.com";
private static final String DEFAULT_PASSWORD = "admin123";
| private TestRunnerConfig runnerConfig; |
andrewjc/kheera-testrunner-android | samples/src/androidTest/java/com/kheera/kheerasample/stepdefs/LoginPageFeatureFile.java | // Path: kheera-testrunner/src/main/java/com/kheera/internal/StepDefinition.java
// public interface StepDefinition {
// void onCreate(Context context, TestRunnerConfig runnerConfig);
// }
//
// Path: kheera-testrunner/src/main/java/com/kheera/internal/TestRunnerConfig.java
// public class TestRunnerConfig {
// @SerializedName("Name")
// public String Name;
//
// @SerializedName("Description")
// public String Description;
//
// @SerializedName("TestData")
// public String TestDataFile;
//
// @SerializedName("AppConfig")
// public String AppConfigFile;
//
// @SerializedName("Screenshots")
// public boolean Screenshots;
//
// @SerializedName("IncludeSkipped")
// public boolean IncludeSkipped;
//
// @SerializedName("WriteTestReport")
// public boolean WriteTestReport;
//
// @SerializedName("ReportLogPath")
// public String ReportLogPath;
//
// @SerializedName("FilterBy")
// public String FilterBy;
//
// @SerializedName("FilterType")
// public String FilterType;
//
// @SerializedName("DetailedErrors")
// public boolean DetailedErrors;
//
// @SerializedName("CoverageReport")
// public boolean CoverageReport;
//
// @SerializedName("CoverageFile")
// public String CoverageFile;
//
// @SerializedName("LogTag")
// public String LogTag;
// }
//
// Path: samples/src/androidTest/java/com/kheera/kheerasample/screens/LoginScreen.java
// public class LoginScreen {
// public static Activity ActivityInstance;
//
// public static void open() {
//
// boolean mInitialTouchMode = false;
//
// getInstrumentation().setInTouchMode(mInitialTouchMode);
//
// Intent newIntent = new Intent(getInstrumentation().getTargetContext(), LoginActivity.class);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// ActivityInstance = getInstrumentation().startActivitySync(newIntent);
//
// getInstrumentation().waitForIdleSync();
//
// ((KeyguardManager) getInstrumentation().getContext().getSystemService(KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE).disableKeyguard();
//
// //turn the screen on
// ActivityInstance.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// ActivityInstance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
// | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
// }
// });
// }
//
// public static void enterEmail(String email) {
// onView(withId(R.id.email)).perform(typeText(email));
// }
//
// public static void enterPassword(String password) {
// onView(withId(R.id.password)).perform(typeText(password));
// }
//
// public static void performLogin() {
// onView(withId(R.id.email_sign_in_button)).perform(click());
// }
// }
| import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.kheera.annotations.OnFinishTest;
import com.kheera.annotations.OnStartTest;
import com.kheera.annotations.RetainAcrossTests;
import com.kheera.annotations.TestModule;
import com.kheera.annotations.TestStep;
import com.kheera.internal.StepDefinition;
import com.kheera.internal.TestRunnerConfig;
import com.kheera.kheerasample.R;
import com.kheera.kheerasample.screens.LoginScreen;
import java.util.concurrent.TimeUnit;
import androidx.test.espresso.IdlingPolicies;
import androidx.test.espresso.intent.Intents;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; | package com.kheera.kheerasample.stepdefs;
/**
* Created by andrewc on 28/9/17.
*/
@TestModule(featureFile = "loginpage.feature")
public class LoginPageFeatureFile implements StepDefinition {
private static final String DEFAULT_EMAIL = "admin@kheera.com";
private static final String DEFAULT_PASSWORD = "admin123";
private TestRunnerConfig runnerConfig;
private Context context;
@RetainAcrossTests
private Object someObjectToRetain;
@Override
public void onCreate(Context context, TestRunnerConfig runnerConfig) {
this.context = context;
this.runnerConfig = runnerConfig;
}
@OnStartTest()
public void onStartTest(String featureName, String scenarioName) {
IdlingPolicies.setMasterPolicyTimeout(30, TimeUnit.SECONDS);
Log.v(runnerConfig.LogTag, "Starting Test: " + featureName + " - " + scenarioName);
Intents.init();
}
@OnFinishTest()
public void onFinishTest(String featureName, String scenarioName) {
getInstrumentation().waitForIdleSync();
| // Path: kheera-testrunner/src/main/java/com/kheera/internal/StepDefinition.java
// public interface StepDefinition {
// void onCreate(Context context, TestRunnerConfig runnerConfig);
// }
//
// Path: kheera-testrunner/src/main/java/com/kheera/internal/TestRunnerConfig.java
// public class TestRunnerConfig {
// @SerializedName("Name")
// public String Name;
//
// @SerializedName("Description")
// public String Description;
//
// @SerializedName("TestData")
// public String TestDataFile;
//
// @SerializedName("AppConfig")
// public String AppConfigFile;
//
// @SerializedName("Screenshots")
// public boolean Screenshots;
//
// @SerializedName("IncludeSkipped")
// public boolean IncludeSkipped;
//
// @SerializedName("WriteTestReport")
// public boolean WriteTestReport;
//
// @SerializedName("ReportLogPath")
// public String ReportLogPath;
//
// @SerializedName("FilterBy")
// public String FilterBy;
//
// @SerializedName("FilterType")
// public String FilterType;
//
// @SerializedName("DetailedErrors")
// public boolean DetailedErrors;
//
// @SerializedName("CoverageReport")
// public boolean CoverageReport;
//
// @SerializedName("CoverageFile")
// public String CoverageFile;
//
// @SerializedName("LogTag")
// public String LogTag;
// }
//
// Path: samples/src/androidTest/java/com/kheera/kheerasample/screens/LoginScreen.java
// public class LoginScreen {
// public static Activity ActivityInstance;
//
// public static void open() {
//
// boolean mInitialTouchMode = false;
//
// getInstrumentation().setInTouchMode(mInitialTouchMode);
//
// Intent newIntent = new Intent(getInstrumentation().getTargetContext(), LoginActivity.class);
// newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// ActivityInstance = getInstrumentation().startActivitySync(newIntent);
//
// getInstrumentation().waitForIdleSync();
//
// ((KeyguardManager) getInstrumentation().getContext().getSystemService(KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE).disableKeyguard();
//
// //turn the screen on
// ActivityInstance.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// ActivityInstance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
// | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
// | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
// }
// });
// }
//
// public static void enterEmail(String email) {
// onView(withId(R.id.email)).perform(typeText(email));
// }
//
// public static void enterPassword(String password) {
// onView(withId(R.id.password)).perform(typeText(password));
// }
//
// public static void performLogin() {
// onView(withId(R.id.email_sign_in_button)).perform(click());
// }
// }
// Path: samples/src/androidTest/java/com/kheera/kheerasample/stepdefs/LoginPageFeatureFile.java
import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.kheera.annotations.OnFinishTest;
import com.kheera.annotations.OnStartTest;
import com.kheera.annotations.RetainAcrossTests;
import com.kheera.annotations.TestModule;
import com.kheera.annotations.TestStep;
import com.kheera.internal.StepDefinition;
import com.kheera.internal.TestRunnerConfig;
import com.kheera.kheerasample.R;
import com.kheera.kheerasample.screens.LoginScreen;
import java.util.concurrent.TimeUnit;
import androidx.test.espresso.IdlingPolicies;
import androidx.test.espresso.intent.Intents;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
package com.kheera.kheerasample.stepdefs;
/**
* Created by andrewc on 28/9/17.
*/
@TestModule(featureFile = "loginpage.feature")
public class LoginPageFeatureFile implements StepDefinition {
private static final String DEFAULT_EMAIL = "admin@kheera.com";
private static final String DEFAULT_PASSWORD = "admin123";
private TestRunnerConfig runnerConfig;
private Context context;
@RetainAcrossTests
private Object someObjectToRetain;
@Override
public void onCreate(Context context, TestRunnerConfig runnerConfig) {
this.context = context;
this.runnerConfig = runnerConfig;
}
@OnStartTest()
public void onStartTest(String featureName, String scenarioName) {
IdlingPolicies.setMasterPolicyTimeout(30, TimeUnit.SECONDS);
Log.v(runnerConfig.LogTag, "Starting Test: " + featureName + " - " + scenarioName);
Intents.init();
}
@OnFinishTest()
public void onFinishTest(String featureName, String scenarioName) {
getInstrumentation().waitForIdleSync();
| if (LoginScreen.ActivityInstance != null) { |
data-integrations/salesforce | src/e2e-test/java/io/cdap/plugin/salesforcebatchsource/locators/SalesforcePropertiesPage.java | // Path: src/e2e-test/java/io/cdap/plugin/utils/SchemaFieldTypeMapping.java
// public class SchemaFieldTypeMapping {
// private final String field;
// private final String type;
//
// public SchemaFieldTypeMapping(String field, String type) {
// this.field = field;
// this.type = type;
// }
//
// public String getField() {
// return field;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SalesforceBatchSourceProperty.java
// public enum SalesforceBatchSourceProperty {
// REFERENCE_NAME("referenceName", PluginPropertyUtils.errorProp("required.property.referencename")),
// SOQL_QUERY("query", PluginPropertyUtils.errorProp("required.property.soqlorsobjectname"));
//
// public final String dataCyAttributeValue;
// public String propertyMissingValidationMessage;
//
// SalesforceBatchSourceProperty(String value) {
// this.dataCyAttributeValue = value;
// }
//
// SalesforceBatchSourceProperty(String value, String propertyMissingValidationMessage) {
// this.dataCyAttributeValue = value;
// this.propertyMissingValidationMessage = propertyMissingValidationMessage;
// }
// }
| import io.cdap.e2e.utils.SeleniumDriver;
import io.cdap.plugin.utils.SchemaFieldTypeMapping;
import io.cdap.plugin.utils.enums.SalesforceBatchSourceProperty;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How; | @FindBy(how = How.XPATH, using = "//div[@data-cy='duration']//div[@data-cy='value']//div")
public static WebElement durationUnitSelector;
@FindBy(how = How.XPATH, using = "//div[@data-cy='offset']//div[@data-cy='key']//input")
public static WebElement offsetInput;
@FindBy(how = How.XPATH, using = "//div[@data-cy='offset']//div[@data-cy='value']//div")
public static WebElement offsetUnitSelector;
// Salesforce Batch Source - Properties page - Advanced section
@FindBy(how = How.XPATH, using = "//div[@data-cy='switch-enablePKChunk']")
public static WebElement enablePkChunkingToggle;
@FindBy(how = How.XPATH, using = "//input[@data-cy='chunkSize']")
public static WebElement chunkSizeInput;
@FindBy(how = How.XPATH, using = "//input[@data-cy='parent']")
public static WebElement sObjectParentNameInput;
@FindBy(how = How.XPATH, using = "//span[contains(@class, 'text-success')]" +
"[normalize-space(text())= 'No errors found.']")
public static WebElement noErrorsFoundSuccessMessage;
@FindBy(how = How.XPATH, using = "//a[./span[contains(@class, 'fa-remove')]]")
public static WebElement closePropertiesPageButton;
@FindBy(how = How.XPATH, using = "//h2[contains(text(), 'Errors')]" +
"/following-sibling::div[contains(@class, 'text-danger')]//li")
public static WebElement errorMessageOnHeader;
| // Path: src/e2e-test/java/io/cdap/plugin/utils/SchemaFieldTypeMapping.java
// public class SchemaFieldTypeMapping {
// private final String field;
// private final String type;
//
// public SchemaFieldTypeMapping(String field, String type) {
// this.field = field;
// this.type = type;
// }
//
// public String getField() {
// return field;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SalesforceBatchSourceProperty.java
// public enum SalesforceBatchSourceProperty {
// REFERENCE_NAME("referenceName", PluginPropertyUtils.errorProp("required.property.referencename")),
// SOQL_QUERY("query", PluginPropertyUtils.errorProp("required.property.soqlorsobjectname"));
//
// public final String dataCyAttributeValue;
// public String propertyMissingValidationMessage;
//
// SalesforceBatchSourceProperty(String value) {
// this.dataCyAttributeValue = value;
// }
//
// SalesforceBatchSourceProperty(String value, String propertyMissingValidationMessage) {
// this.dataCyAttributeValue = value;
// this.propertyMissingValidationMessage = propertyMissingValidationMessage;
// }
// }
// Path: src/e2e-test/java/io/cdap/plugin/salesforcebatchsource/locators/SalesforcePropertiesPage.java
import io.cdap.e2e.utils.SeleniumDriver;
import io.cdap.plugin.utils.SchemaFieldTypeMapping;
import io.cdap.plugin.utils.enums.SalesforceBatchSourceProperty;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
@FindBy(how = How.XPATH, using = "//div[@data-cy='duration']//div[@data-cy='value']//div")
public static WebElement durationUnitSelector;
@FindBy(how = How.XPATH, using = "//div[@data-cy='offset']//div[@data-cy='key']//input")
public static WebElement offsetInput;
@FindBy(how = How.XPATH, using = "//div[@data-cy='offset']//div[@data-cy='value']//div")
public static WebElement offsetUnitSelector;
// Salesforce Batch Source - Properties page - Advanced section
@FindBy(how = How.XPATH, using = "//div[@data-cy='switch-enablePKChunk']")
public static WebElement enablePkChunkingToggle;
@FindBy(how = How.XPATH, using = "//input[@data-cy='chunkSize']")
public static WebElement chunkSizeInput;
@FindBy(how = How.XPATH, using = "//input[@data-cy='parent']")
public static WebElement sObjectParentNameInput;
@FindBy(how = How.XPATH, using = "//span[contains(@class, 'text-success')]" +
"[normalize-space(text())= 'No errors found.']")
public static WebElement noErrorsFoundSuccessMessage;
@FindBy(how = How.XPATH, using = "//a[./span[contains(@class, 'fa-remove')]]")
public static WebElement closePropertiesPageButton;
@FindBy(how = How.XPATH, using = "//h2[contains(text(), 'Errors')]" +
"/following-sibling::div[contains(@class, 'text-danger')]//li")
public static WebElement errorMessageOnHeader;
| public static WebElement getSchemaFieldTypeMappingElement(SchemaFieldTypeMapping schemaFieldTypeMapping) { |
data-integrations/salesforce | src/e2e-test/java/io/cdap/plugin/salesforcebatchsource/locators/SalesforcePropertiesPage.java | // Path: src/e2e-test/java/io/cdap/plugin/utils/SchemaFieldTypeMapping.java
// public class SchemaFieldTypeMapping {
// private final String field;
// private final String type;
//
// public SchemaFieldTypeMapping(String field, String type) {
// this.field = field;
// this.type = type;
// }
//
// public String getField() {
// return field;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SalesforceBatchSourceProperty.java
// public enum SalesforceBatchSourceProperty {
// REFERENCE_NAME("referenceName", PluginPropertyUtils.errorProp("required.property.referencename")),
// SOQL_QUERY("query", PluginPropertyUtils.errorProp("required.property.soqlorsobjectname"));
//
// public final String dataCyAttributeValue;
// public String propertyMissingValidationMessage;
//
// SalesforceBatchSourceProperty(String value) {
// this.dataCyAttributeValue = value;
// }
//
// SalesforceBatchSourceProperty(String value, String propertyMissingValidationMessage) {
// this.dataCyAttributeValue = value;
// this.propertyMissingValidationMessage = propertyMissingValidationMessage;
// }
// }
| import io.cdap.e2e.utils.SeleniumDriver;
import io.cdap.plugin.utils.SchemaFieldTypeMapping;
import io.cdap.plugin.utils.enums.SalesforceBatchSourceProperty;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How; | public static WebElement offsetUnitSelector;
// Salesforce Batch Source - Properties page - Advanced section
@FindBy(how = How.XPATH, using = "//div[@data-cy='switch-enablePKChunk']")
public static WebElement enablePkChunkingToggle;
@FindBy(how = How.XPATH, using = "//input[@data-cy='chunkSize']")
public static WebElement chunkSizeInput;
@FindBy(how = How.XPATH, using = "//input[@data-cy='parent']")
public static WebElement sObjectParentNameInput;
@FindBy(how = How.XPATH, using = "//span[contains(@class, 'text-success')]" +
"[normalize-space(text())= 'No errors found.']")
public static WebElement noErrorsFoundSuccessMessage;
@FindBy(how = How.XPATH, using = "//a[./span[contains(@class, 'fa-remove')]]")
public static WebElement closePropertiesPageButton;
@FindBy(how = How.XPATH, using = "//h2[contains(text(), 'Errors')]" +
"/following-sibling::div[contains(@class, 'text-danger')]//li")
public static WebElement errorMessageOnHeader;
public static WebElement getSchemaFieldTypeMappingElement(SchemaFieldTypeMapping schemaFieldTypeMapping) {
String xpath = "//div[contains(@data-cy,'schema-row')]" +
"//input[@value='" + schemaFieldTypeMapping.getField() + "']" +
"/following-sibling::div//select[@title='" + schemaFieldTypeMapping.getType() + "']";
return SeleniumDriver.getDriver().findElement(By.xpath(xpath));
}
| // Path: src/e2e-test/java/io/cdap/plugin/utils/SchemaFieldTypeMapping.java
// public class SchemaFieldTypeMapping {
// private final String field;
// private final String type;
//
// public SchemaFieldTypeMapping(String field, String type) {
// this.field = field;
// this.type = type;
// }
//
// public String getField() {
// return field;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SalesforceBatchSourceProperty.java
// public enum SalesforceBatchSourceProperty {
// REFERENCE_NAME("referenceName", PluginPropertyUtils.errorProp("required.property.referencename")),
// SOQL_QUERY("query", PluginPropertyUtils.errorProp("required.property.soqlorsobjectname"));
//
// public final String dataCyAttributeValue;
// public String propertyMissingValidationMessage;
//
// SalesforceBatchSourceProperty(String value) {
// this.dataCyAttributeValue = value;
// }
//
// SalesforceBatchSourceProperty(String value, String propertyMissingValidationMessage) {
// this.dataCyAttributeValue = value;
// this.propertyMissingValidationMessage = propertyMissingValidationMessage;
// }
// }
// Path: src/e2e-test/java/io/cdap/plugin/salesforcebatchsource/locators/SalesforcePropertiesPage.java
import io.cdap.e2e.utils.SeleniumDriver;
import io.cdap.plugin.utils.SchemaFieldTypeMapping;
import io.cdap.plugin.utils.enums.SalesforceBatchSourceProperty;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public static WebElement offsetUnitSelector;
// Salesforce Batch Source - Properties page - Advanced section
@FindBy(how = How.XPATH, using = "//div[@data-cy='switch-enablePKChunk']")
public static WebElement enablePkChunkingToggle;
@FindBy(how = How.XPATH, using = "//input[@data-cy='chunkSize']")
public static WebElement chunkSizeInput;
@FindBy(how = How.XPATH, using = "//input[@data-cy='parent']")
public static WebElement sObjectParentNameInput;
@FindBy(how = How.XPATH, using = "//span[contains(@class, 'text-success')]" +
"[normalize-space(text())= 'No errors found.']")
public static WebElement noErrorsFoundSuccessMessage;
@FindBy(how = How.XPATH, using = "//a[./span[contains(@class, 'fa-remove')]]")
public static WebElement closePropertiesPageButton;
@FindBy(how = How.XPATH, using = "//h2[contains(text(), 'Errors')]" +
"/following-sibling::div[contains(@class, 'text-danger')]//li")
public static WebElement errorMessageOnHeader;
public static WebElement getSchemaFieldTypeMappingElement(SchemaFieldTypeMapping schemaFieldTypeMapping) {
String xpath = "//div[contains(@data-cy,'schema-row')]" +
"//input[@value='" + schemaFieldTypeMapping.getField() + "']" +
"/following-sibling::div//select[@title='" + schemaFieldTypeMapping.getType() + "']";
return SeleniumDriver.getDriver().findElement(By.xpath(xpath));
}
| public static WebElement getPropertyInlineErrorMessage(SalesforceBatchSourceProperty propertyName) { |
data-integrations/salesforce | src/main/java/io/cdap/plugin/salesforce/SalesforceSchemaUtil.java | // Path: src/main/java/io/cdap/plugin/salesforce/authenticator/AuthenticatorCredentials.java
// public class AuthenticatorCredentials implements Serializable {
//
// private final OAuthInfo oAuthInfo;
// private final String username;
// private final String password;
// private final String consumerKey;
// private final String consumerSecret;
// private final String loginUrl;
//
// public AuthenticatorCredentials(OAuthInfo oAuthInfo) {
// this(Objects.requireNonNull(oAuthInfo), null, null, null, null, null);
// }
//
// public AuthenticatorCredentials(String username, String password,
// String consumerKey, String consumerSecret, String loginUrl) {
// this(null, Objects.requireNonNull(username), Objects.requireNonNull(password), Objects.requireNonNull(consumerKey),
// Objects.requireNonNull(consumerSecret), Objects.requireNonNull(loginUrl));
// }
//
// private AuthenticatorCredentials(@Nullable OAuthInfo oAuthInfo,
// @Nullable String username,
// @Nullable String password,
// @Nullable String consumerKey,
// @Nullable String consumerSecret,
// @Nullable String loginUrl) {
// this.oAuthInfo = oAuthInfo;
// this.username = username;
// this.password = password;
// this.consumerKey = consumerKey;
// this.consumerSecret = consumerSecret;
// this.loginUrl = loginUrl;
// }
//
// @Nullable
// public OAuthInfo getOAuthInfo() {
// return oAuthInfo;
// }
//
// @Nullable
// public String getUsername() {
// return username;
// }
//
// @Nullable
// public String getPassword() {
// return password;
// }
//
// @Nullable
// public String getConsumerKey() {
// return consumerKey;
// }
//
// @Nullable
// public String getConsumerSecret() {
// return consumerSecret;
// }
//
// @Nullable
// public String getLoginUrl() {
// return loginUrl;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// AuthenticatorCredentials that = (AuthenticatorCredentials) o;
//
// return Objects.equals(username, that.username) &&
// Objects.equals(password, that.password) &&
// Objects.equals(consumerKey, that.consumerKey) &&
// Objects.equals(consumerSecret, that.consumerSecret) &&
// Objects.equals(loginUrl, that.loginUrl);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(username, password, consumerKey, consumerSecret, loginUrl);
// }
// }
| import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.sforce.soap.partner.Field;
import com.sforce.soap.partner.FieldType;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.etl.api.FailureCollector;
import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects; |
private static final Schema DEFAULT_SCHEMA = Schema.of(Schema.Type.STRING);
private static final Pattern AVRO_NAME_START_PATTERN = Pattern.compile("^[A-Za-z_]");
private static final Pattern AVRO_NAME_REPLACE_PATTERN = Pattern.compile("[^A-Za-z0-9_]");
/**
* Normalize the given field name to be compatible with
* <a href="https://avro.apache.org/docs/current/spec.html#names">Avro names</a>
*/
public static String normalizeAvroName(String name) {
String finalName = name;
// Make sure the name starts with allowed character
if (!AVRO_NAME_START_PATTERN.matcher(name).find()) {
finalName = "A" + finalName;
}
// Replace any not allowed characters with "_".
return AVRO_NAME_REPLACE_PATTERN.matcher(finalName).replaceAll("_");
}
/**
* Connects to Salesforce and obtains description of sObjects needed to determine schema field types.
* Based on this information, creates schema for the fields used in sObject descriptor.
*
* @param credentials connection credentials
* @param sObjectDescriptor sObject descriptor
* @return CDAP schema
* @throws ConnectionException if unable to connect to Salesforce
*/ | // Path: src/main/java/io/cdap/plugin/salesforce/authenticator/AuthenticatorCredentials.java
// public class AuthenticatorCredentials implements Serializable {
//
// private final OAuthInfo oAuthInfo;
// private final String username;
// private final String password;
// private final String consumerKey;
// private final String consumerSecret;
// private final String loginUrl;
//
// public AuthenticatorCredentials(OAuthInfo oAuthInfo) {
// this(Objects.requireNonNull(oAuthInfo), null, null, null, null, null);
// }
//
// public AuthenticatorCredentials(String username, String password,
// String consumerKey, String consumerSecret, String loginUrl) {
// this(null, Objects.requireNonNull(username), Objects.requireNonNull(password), Objects.requireNonNull(consumerKey),
// Objects.requireNonNull(consumerSecret), Objects.requireNonNull(loginUrl));
// }
//
// private AuthenticatorCredentials(@Nullable OAuthInfo oAuthInfo,
// @Nullable String username,
// @Nullable String password,
// @Nullable String consumerKey,
// @Nullable String consumerSecret,
// @Nullable String loginUrl) {
// this.oAuthInfo = oAuthInfo;
// this.username = username;
// this.password = password;
// this.consumerKey = consumerKey;
// this.consumerSecret = consumerSecret;
// this.loginUrl = loginUrl;
// }
//
// @Nullable
// public OAuthInfo getOAuthInfo() {
// return oAuthInfo;
// }
//
// @Nullable
// public String getUsername() {
// return username;
// }
//
// @Nullable
// public String getPassword() {
// return password;
// }
//
// @Nullable
// public String getConsumerKey() {
// return consumerKey;
// }
//
// @Nullable
// public String getConsumerSecret() {
// return consumerSecret;
// }
//
// @Nullable
// public String getLoginUrl() {
// return loginUrl;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// AuthenticatorCredentials that = (AuthenticatorCredentials) o;
//
// return Objects.equals(username, that.username) &&
// Objects.equals(password, that.password) &&
// Objects.equals(consumerKey, that.consumerKey) &&
// Objects.equals(consumerSecret, that.consumerSecret) &&
// Objects.equals(loginUrl, that.loginUrl);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(username, password, consumerKey, consumerSecret, loginUrl);
// }
// }
// Path: src/main/java/io/cdap/plugin/salesforce/SalesforceSchemaUtil.java
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.sforce.soap.partner.Field;
import com.sforce.soap.partner.FieldType;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.etl.api.FailureCollector;
import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
private static final Schema DEFAULT_SCHEMA = Schema.of(Schema.Type.STRING);
private static final Pattern AVRO_NAME_START_PATTERN = Pattern.compile("^[A-Za-z_]");
private static final Pattern AVRO_NAME_REPLACE_PATTERN = Pattern.compile("[^A-Za-z0-9_]");
/**
* Normalize the given field name to be compatible with
* <a href="https://avro.apache.org/docs/current/spec.html#names">Avro names</a>
*/
public static String normalizeAvroName(String name) {
String finalName = name;
// Make sure the name starts with allowed character
if (!AVRO_NAME_START_PATTERN.matcher(name).find()) {
finalName = "A" + finalName;
}
// Replace any not allowed characters with "_".
return AVRO_NAME_REPLACE_PATTERN.matcher(finalName).replaceAll("_");
}
/**
* Connects to Salesforce and obtains description of sObjects needed to determine schema field types.
* Based on this information, creates schema for the fields used in sObject descriptor.
*
* @param credentials connection credentials
* @param sObjectDescriptor sObject descriptor
* @return CDAP schema
* @throws ConnectionException if unable to connect to Salesforce
*/ | public static Schema getSchema(AuthenticatorCredentials credentials, SObjectDescriptor sObjectDescriptor) |
data-integrations/salesforce | src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/actions/SalesforceMultiObjectsPropertiesPageActions.java | // Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/locators/SalesforceMultiObjectsPropertiesPage.java
// public class SalesforceMultiObjectsPropertiesPage {
//
// // SalesforceMultiObjects Batch Source - Properties page
// @FindBy(how = How.XPATH, using = "//div[contains(@class, 'label-input-container')]//input")
// public static WebElement labelInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Reference section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='referenceName']")
// public static WebElement referenceInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Authentication section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='username']")
// public static WebElement usernameInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='password']")
// public static WebElement passwordInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='securityToken']")
// public static WebElement securityTokenInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerKey']")
// public static WebElement consumerKeyInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerSecret']")
// public static WebElement consumerSecretInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='loginUrl']")
// public static WebElement loginUrlInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - SObject specification section
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//input")
// public static List<WebElement> sObjectNameInputsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//input")
// public static List<WebElement> sObjectNameInputsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInBlackList;
//
// // SalesforceMultiObjects Batch Source - Properties page - Incremental Load Properties section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeAfter']")
// public static WebElement lastModifiedAfterInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeBefore']")
// public static WebElement lastModifiedBeforeInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Advanced section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='sObjectNameField']")
// public static WebElement sObjectNameFieldInput;
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SObjects.java
// public enum SObjects {
// ACCOUNT("Account"),
// CONTACT("Contact"),
// LEAD("Lead"),
// OPPORTUNITY("Opportunity"),
// BLAHBLAH("blahblah"),
// ACCOUNTZZ("Accountzz"),
// LEADSS("Leadss");
//
// public final String value;
//
// SObjects(String value) {
// this.value = value;
// }
// }
| import io.cdap.e2e.utils.AssertionHelper;
import io.cdap.e2e.utils.PluginPropertyUtils;
import io.cdap.e2e.utils.SeleniumHelper;
import io.cdap.plugin.salesforcemultiobjectsbatchsource.locators.SalesforceMultiObjectsPropertiesPage;
import io.cdap.plugin.utils.enums.SObjects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; | /*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforcemultiobjectsbatchsource.actions;
/**
* Salesforce MultiObjects batch source plugin - Actions.
*/
public class SalesforceMultiObjectsPropertiesPageActions {
private static final Logger logger = LoggerFactory.getLogger(SalesforceMultiObjectsPropertiesPageActions.class);
static { | // Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/locators/SalesforceMultiObjectsPropertiesPage.java
// public class SalesforceMultiObjectsPropertiesPage {
//
// // SalesforceMultiObjects Batch Source - Properties page
// @FindBy(how = How.XPATH, using = "//div[contains(@class, 'label-input-container')]//input")
// public static WebElement labelInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Reference section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='referenceName']")
// public static WebElement referenceInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Authentication section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='username']")
// public static WebElement usernameInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='password']")
// public static WebElement passwordInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='securityToken']")
// public static WebElement securityTokenInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerKey']")
// public static WebElement consumerKeyInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerSecret']")
// public static WebElement consumerSecretInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='loginUrl']")
// public static WebElement loginUrlInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - SObject specification section
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//input")
// public static List<WebElement> sObjectNameInputsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//input")
// public static List<WebElement> sObjectNameInputsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInBlackList;
//
// // SalesforceMultiObjects Batch Source - Properties page - Incremental Load Properties section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeAfter']")
// public static WebElement lastModifiedAfterInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeBefore']")
// public static WebElement lastModifiedBeforeInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Advanced section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='sObjectNameField']")
// public static WebElement sObjectNameFieldInput;
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SObjects.java
// public enum SObjects {
// ACCOUNT("Account"),
// CONTACT("Contact"),
// LEAD("Lead"),
// OPPORTUNITY("Opportunity"),
// BLAHBLAH("blahblah"),
// ACCOUNTZZ("Accountzz"),
// LEADSS("Leadss");
//
// public final String value;
//
// SObjects(String value) {
// this.value = value;
// }
// }
// Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/actions/SalesforceMultiObjectsPropertiesPageActions.java
import io.cdap.e2e.utils.AssertionHelper;
import io.cdap.e2e.utils.PluginPropertyUtils;
import io.cdap.e2e.utils.SeleniumHelper;
import io.cdap.plugin.salesforcemultiobjectsbatchsource.locators.SalesforceMultiObjectsPropertiesPage;
import io.cdap.plugin.utils.enums.SObjects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforcemultiobjectsbatchsource.actions;
/**
* Salesforce MultiObjects batch source plugin - Actions.
*/
public class SalesforceMultiObjectsPropertiesPageActions {
private static final Logger logger = LoggerFactory.getLogger(SalesforceMultiObjectsPropertiesPageActions.class);
static { | SeleniumHelper.getPropertiesLocators(SalesforceMultiObjectsPropertiesPage.class); |
data-integrations/salesforce | src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/actions/SalesforceMultiObjectsPropertiesPageActions.java | // Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/locators/SalesforceMultiObjectsPropertiesPage.java
// public class SalesforceMultiObjectsPropertiesPage {
//
// // SalesforceMultiObjects Batch Source - Properties page
// @FindBy(how = How.XPATH, using = "//div[contains(@class, 'label-input-container')]//input")
// public static WebElement labelInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Reference section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='referenceName']")
// public static WebElement referenceInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Authentication section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='username']")
// public static WebElement usernameInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='password']")
// public static WebElement passwordInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='securityToken']")
// public static WebElement securityTokenInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerKey']")
// public static WebElement consumerKeyInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerSecret']")
// public static WebElement consumerSecretInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='loginUrl']")
// public static WebElement loginUrlInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - SObject specification section
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//input")
// public static List<WebElement> sObjectNameInputsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//input")
// public static List<WebElement> sObjectNameInputsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInBlackList;
//
// // SalesforceMultiObjects Batch Source - Properties page - Incremental Load Properties section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeAfter']")
// public static WebElement lastModifiedAfterInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeBefore']")
// public static WebElement lastModifiedBeforeInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Advanced section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='sObjectNameField']")
// public static WebElement sObjectNameFieldInput;
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SObjects.java
// public enum SObjects {
// ACCOUNT("Account"),
// CONTACT("Contact"),
// LEAD("Lead"),
// OPPORTUNITY("Opportunity"),
// BLAHBLAH("blahblah"),
// ACCOUNTZZ("Accountzz"),
// LEADSS("Leadss");
//
// public final String value;
//
// SObjects(String value) {
// this.value = value;
// }
// }
| import io.cdap.e2e.utils.AssertionHelper;
import io.cdap.e2e.utils.PluginPropertyUtils;
import io.cdap.e2e.utils.SeleniumHelper;
import io.cdap.plugin.salesforcemultiobjectsbatchsource.locators.SalesforceMultiObjectsPropertiesPage;
import io.cdap.plugin.utils.enums.SObjects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; | /*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforcemultiobjectsbatchsource.actions;
/**
* Salesforce MultiObjects batch source plugin - Actions.
*/
public class SalesforceMultiObjectsPropertiesPageActions {
private static final Logger logger = LoggerFactory.getLogger(SalesforceMultiObjectsPropertiesPageActions.class);
static {
SeleniumHelper.getPropertiesLocators(SalesforceMultiObjectsPropertiesPage.class);
}
| // Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/locators/SalesforceMultiObjectsPropertiesPage.java
// public class SalesforceMultiObjectsPropertiesPage {
//
// // SalesforceMultiObjects Batch Source - Properties page
// @FindBy(how = How.XPATH, using = "//div[contains(@class, 'label-input-container')]//input")
// public static WebElement labelInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Reference section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='referenceName']")
// public static WebElement referenceInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Authentication section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='username']")
// public static WebElement usernameInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='password']")
// public static WebElement passwordInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='securityToken']")
// public static WebElement securityTokenInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerKey']")
// public static WebElement consumerKeyInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='consumerSecret']")
// public static WebElement consumerSecretInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='loginUrl']")
// public static WebElement loginUrlInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - SObject specification section
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//input")
// public static List<WebElement> sObjectNameInputsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='whiteList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInWhiteList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//input")
// public static List<WebElement> sObjectNameInputsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='add-row']")
// public static List<WebElement> sObjectNameAddRowButtonsInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']" +
// "//following-sibling::div[contains(@class, 'propertyError')]")
// public static WebElement propertyErrorInBlackList;
//
// @FindBy(how = How.XPATH, using = "//div[@data-cy='blackList']//button[@data-cy='remove-row']")
// public static List<WebElement> sObjectNameRemoveRowButtonsInBlackList;
//
// // SalesforceMultiObjects Batch Source - Properties page - Incremental Load Properties section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeAfter']")
// public static WebElement lastModifiedAfterInput;
//
// @FindBy(how = How.XPATH, using = "//input[@data-cy='datetimeBefore']")
// public static WebElement lastModifiedBeforeInput;
//
// // SalesforceMultiObjects Batch Source - Properties page - Advanced section
// @FindBy(how = How.XPATH, using = "//input[@data-cy='sObjectNameField']")
// public static WebElement sObjectNameFieldInput;
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SObjects.java
// public enum SObjects {
// ACCOUNT("Account"),
// CONTACT("Contact"),
// LEAD("Lead"),
// OPPORTUNITY("Opportunity"),
// BLAHBLAH("blahblah"),
// ACCOUNTZZ("Accountzz"),
// LEADSS("Leadss");
//
// public final String value;
//
// SObjects(String value) {
// this.value = value;
// }
// }
// Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/actions/SalesforceMultiObjectsPropertiesPageActions.java
import io.cdap.e2e.utils.AssertionHelper;
import io.cdap.e2e.utils.PluginPropertyUtils;
import io.cdap.e2e.utils.SeleniumHelper;
import io.cdap.plugin.salesforcemultiobjectsbatchsource.locators.SalesforceMultiObjectsPropertiesPage;
import io.cdap.plugin.utils.enums.SObjects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforcemultiobjectsbatchsource.actions;
/**
* Salesforce MultiObjects batch source plugin - Actions.
*/
public class SalesforceMultiObjectsPropertiesPageActions {
private static final Logger logger = LoggerFactory.getLogger(SalesforceMultiObjectsPropertiesPageActions.class);
static {
SeleniumHelper.getPropertiesLocators(SalesforceMultiObjectsPropertiesPage.class);
}
| public static void fillWhiteListWithSObjectNames(List<SObjects> sObjectNames) { |
data-integrations/salesforce | src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/stepsdesign/DesignTimeSteps.java | // Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/actions/SalesforceMultiObjectsPropertiesPageActions.java
// public class SalesforceMultiObjectsPropertiesPageActions {
// private static final Logger logger = LoggerFactory.getLogger(SalesforceMultiObjectsPropertiesPageActions.class);
//
// static {
// SeleniumHelper.getPropertiesLocators(SalesforceMultiObjectsPropertiesPage.class);
// }
//
// public static void fillWhiteListWithSObjectNames(List<SObjects> sObjectNames) {
// int totalSObjects = sObjectNames.size();
//
// for (int i = 0; i < totalSObjects - 1; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameAddRowButtonsInWhiteList.get(i).click();
// }
//
// for (int i = 0; i < totalSObjects; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameInputsInWhiteList.get(i).sendKeys(sObjectNames.get(i).value);
// }
// }
//
// public static void fillBlackListWithSObjectNames(List<SObjects> sObjectNames) {
// int totalSObjects = sObjectNames.size();
//
// for (int i = 0; i < totalSObjects - 1; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameAddRowButtonsInBlackList.get(i).click();
// }
//
// for (int i = 0; i < totalSObjects; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameInputsInBlackList.get(i).sendKeys(sObjectNames.get(i).value);
// }
// }
//
// public static void verifyInvalidSObjectNameValidationMessageForWhiteList(List<SObjects> whiteListedSObjects) {
// String invalidSObjectNameValidationMessage = PluginPropertyUtils.errorProp("invalid.sobjectnames");
//
// if (whiteListedSObjects.size() > 0) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInWhiteList,
// invalidSObjectNameValidationMessage);
//
// for (SObjects whiteListedSObject : whiteListedSObjects) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInWhiteList,
// whiteListedSObject.value);
// }
// }
// }
//
// public static void verifyInvalidSObjectNameValidationMessageForBlackList(List<SObjects> blackListedSObjects) {
// String invalidSObjectNameValidationMessage = PluginPropertyUtils.errorProp("invalid.sobjectnames");
//
// if (blackListedSObjects.size() > 0) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInBlackList,
// invalidSObjectNameValidationMessage);
//
// for (SObjects blackListedSObject : blackListedSObjects) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInBlackList,
// blackListedSObject.value);
// }
// }
// }
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SObjects.java
// public enum SObjects {
// ACCOUNT("Account"),
// CONTACT("Contact"),
// LEAD("Lead"),
// OPPORTUNITY("Opportunity"),
// BLAHBLAH("blahblah"),
// ACCOUNTZZ("Accountzz"),
// LEADSS("Leadss");
//
// public final String value;
//
// SObjects(String value) {
// this.value = value;
// }
// }
| import io.cdap.plugin.salesforcemultiobjectsbatchsource.actions.SalesforceMultiObjectsPropertiesPageActions;
import io.cdap.plugin.utils.enums.SObjects;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforcemultiobjectsbatchsource.stepsdesign;
/**
* Design-time steps of Salesforce MultiObjects Batch Source plugin.
*/
public class DesignTimeSteps {
List<SObjects> whiteListedSObjects = new ArrayList<>();
List<SObjects> blackListedSObjects = new ArrayList<>();
@When("fill White List with below listed SObjects:")
public void fillWhiteList(DataTable table) {
List<String> list = table.asList();
for (String sObject : list) {
whiteListedSObjects.add(SObjects.valueOf(sObject));
}
| // Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/actions/SalesforceMultiObjectsPropertiesPageActions.java
// public class SalesforceMultiObjectsPropertiesPageActions {
// private static final Logger logger = LoggerFactory.getLogger(SalesforceMultiObjectsPropertiesPageActions.class);
//
// static {
// SeleniumHelper.getPropertiesLocators(SalesforceMultiObjectsPropertiesPage.class);
// }
//
// public static void fillWhiteListWithSObjectNames(List<SObjects> sObjectNames) {
// int totalSObjects = sObjectNames.size();
//
// for (int i = 0; i < totalSObjects - 1; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameAddRowButtonsInWhiteList.get(i).click();
// }
//
// for (int i = 0; i < totalSObjects; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameInputsInWhiteList.get(i).sendKeys(sObjectNames.get(i).value);
// }
// }
//
// public static void fillBlackListWithSObjectNames(List<SObjects> sObjectNames) {
// int totalSObjects = sObjectNames.size();
//
// for (int i = 0; i < totalSObjects - 1; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameAddRowButtonsInBlackList.get(i).click();
// }
//
// for (int i = 0; i < totalSObjects; i++) {
// SalesforceMultiObjectsPropertiesPage.sObjectNameInputsInBlackList.get(i).sendKeys(sObjectNames.get(i).value);
// }
// }
//
// public static void verifyInvalidSObjectNameValidationMessageForWhiteList(List<SObjects> whiteListedSObjects) {
// String invalidSObjectNameValidationMessage = PluginPropertyUtils.errorProp("invalid.sobjectnames");
//
// if (whiteListedSObjects.size() > 0) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInWhiteList,
// invalidSObjectNameValidationMessage);
//
// for (SObjects whiteListedSObject : whiteListedSObjects) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInWhiteList,
// whiteListedSObject.value);
// }
// }
// }
//
// public static void verifyInvalidSObjectNameValidationMessageForBlackList(List<SObjects> blackListedSObjects) {
// String invalidSObjectNameValidationMessage = PluginPropertyUtils.errorProp("invalid.sobjectnames");
//
// if (blackListedSObjects.size() > 0) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInBlackList,
// invalidSObjectNameValidationMessage);
//
// for (SObjects blackListedSObject : blackListedSObjects) {
// AssertionHelper.verifyElementContainsText(SalesforceMultiObjectsPropertiesPage.propertyErrorInBlackList,
// blackListedSObject.value);
// }
// }
// }
// }
//
// Path: src/e2e-test/java/io/cdap/plugin/utils/enums/SObjects.java
// public enum SObjects {
// ACCOUNT("Account"),
// CONTACT("Contact"),
// LEAD("Lead"),
// OPPORTUNITY("Opportunity"),
// BLAHBLAH("blahblah"),
// ACCOUNTZZ("Accountzz"),
// LEADSS("Leadss");
//
// public final String value;
//
// SObjects(String value) {
// this.value = value;
// }
// }
// Path: src/e2e-test/java/io/cdap/plugin/salesforcemultiobjectsbatchsource/stepsdesign/DesignTimeSteps.java
import io.cdap.plugin.salesforcemultiobjectsbatchsource.actions.SalesforceMultiObjectsPropertiesPageActions;
import io.cdap.plugin.utils.enums.SObjects;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforcemultiobjectsbatchsource.stepsdesign;
/**
* Design-time steps of Salesforce MultiObjects Batch Source plugin.
*/
public class DesignTimeSteps {
List<SObjects> whiteListedSObjects = new ArrayList<>();
List<SObjects> blackListedSObjects = new ArrayList<>();
@When("fill White List with below listed SObjects:")
public void fillWhiteList(DataTable table) {
List<String> list = table.asList();
for (String sObject : list) {
whiteListedSObjects.add(SObjects.valueOf(sObject));
}
| SalesforceMultiObjectsPropertiesPageActions.fillWhiteListWithSObjectNames(whiteListedSObjects); |
data-integrations/salesforce | src/main/java/io/cdap/plugin/salesforce/authenticator/Authenticator.java | // Path: src/main/java/io/cdap/plugin/salesforce/SalesforceConstants.java
// public class SalesforceConstants {
//
// public static final String API_VERSION = "53.0";
// public static final String REFERENCE_NAME_DELIMITER = ".";
//
// public static final String PROPERTY_CONSUMER_KEY = "consumerKey";
// public static final String PROPERTY_CONSUMER_SECRET = "consumerSecret";
// public static final String PROPERTY_USERNAME = "username";
// public static final String PROPERTY_PASSWORD = "password";
// public static final String PROPERTY_SECURITY_TOKEN = "securityToken";
// public static final String PROPERTY_LOGIN_URL = "loginUrl";
// public static final String PROPERTY_OAUTH_INFO = "oAuthInfo";
//
// public static final String CONFIG_OAUTH_TOKEN = "mapred.salesforce.oauth.token";
// public static final String CONFIG_OAUTH_INSTANCE_URL = "mapred.salesforce.oauth.instance.url";
// public static final String CONFIG_CONSUMER_KEY = "mapred.salesforce.consumer.key";
// public static final String CONFIG_PASSWORD = "mapred.salesforce.password";
// public static final String CONFIG_USERNAME = "mapred.salesforce.user";
// public static final String CONFIG_CONSUMER_SECRET = "mapred.salesforce.consumer.secret";
// public static final String CONFIG_LOGIN_URL = "mapred.salesforce.login.url";
//
// public static final int RANGE_FILTER_MIN_VALUE = 0;
// public static final int SOQL_MAX_LENGTH = 20000;
// }
//
// Path: src/main/java/io/cdap/plugin/salesforce/plugin/OAuthInfo.java
// public final class OAuthInfo {
//
// private final String accessToken;
// private final String instanceURL;
//
// public OAuthInfo(String accessToken, String instanceURL) {
// this.accessToken = accessToken;
// this.instanceURL = instanceURL;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public String getInstanceURL() {
// return instanceURL;
// }
// }
| import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.sforce.ws.ConnectorConfig;
import io.cdap.plugin.salesforce.SalesforceConstants;
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory; | /*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.authenticator;
/**
* Authentication to Salesforce via oauth2
*/
public class Authenticator {
private static final Gson GSON = new Gson();
/**
* Authenticates via oauth2 to salesforce and returns a connectorConfig
* which can be used by salesforce libraries to make a connection.
*
* @param credentials information to log in
*
* @return ConnectorConfig which can be used to create BulkConnection and PartnerConnection
*/
public static ConnectorConfig createConnectorConfig(AuthenticatorCredentials credentials) {
try { | // Path: src/main/java/io/cdap/plugin/salesforce/SalesforceConstants.java
// public class SalesforceConstants {
//
// public static final String API_VERSION = "53.0";
// public static final String REFERENCE_NAME_DELIMITER = ".";
//
// public static final String PROPERTY_CONSUMER_KEY = "consumerKey";
// public static final String PROPERTY_CONSUMER_SECRET = "consumerSecret";
// public static final String PROPERTY_USERNAME = "username";
// public static final String PROPERTY_PASSWORD = "password";
// public static final String PROPERTY_SECURITY_TOKEN = "securityToken";
// public static final String PROPERTY_LOGIN_URL = "loginUrl";
// public static final String PROPERTY_OAUTH_INFO = "oAuthInfo";
//
// public static final String CONFIG_OAUTH_TOKEN = "mapred.salesforce.oauth.token";
// public static final String CONFIG_OAUTH_INSTANCE_URL = "mapred.salesforce.oauth.instance.url";
// public static final String CONFIG_CONSUMER_KEY = "mapred.salesforce.consumer.key";
// public static final String CONFIG_PASSWORD = "mapred.salesforce.password";
// public static final String CONFIG_USERNAME = "mapred.salesforce.user";
// public static final String CONFIG_CONSUMER_SECRET = "mapred.salesforce.consumer.secret";
// public static final String CONFIG_LOGIN_URL = "mapred.salesforce.login.url";
//
// public static final int RANGE_FILTER_MIN_VALUE = 0;
// public static final int SOQL_MAX_LENGTH = 20000;
// }
//
// Path: src/main/java/io/cdap/plugin/salesforce/plugin/OAuthInfo.java
// public final class OAuthInfo {
//
// private final String accessToken;
// private final String instanceURL;
//
// public OAuthInfo(String accessToken, String instanceURL) {
// this.accessToken = accessToken;
// this.instanceURL = instanceURL;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public String getInstanceURL() {
// return instanceURL;
// }
// }
// Path: src/main/java/io/cdap/plugin/salesforce/authenticator/Authenticator.java
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.sforce.ws.ConnectorConfig;
import io.cdap.plugin.salesforce.SalesforceConstants;
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.authenticator;
/**
* Authentication to Salesforce via oauth2
*/
public class Authenticator {
private static final Gson GSON = new Gson();
/**
* Authenticates via oauth2 to salesforce and returns a connectorConfig
* which can be used by salesforce libraries to make a connection.
*
* @param credentials information to log in
*
* @return ConnectorConfig which can be used to create BulkConnection and PartnerConnection
*/
public static ConnectorConfig createConnectorConfig(AuthenticatorCredentials credentials) {
try { | OAuthInfo oAuthInfo = getOAuthInfo(credentials); |
data-integrations/salesforce | src/main/java/io/cdap/plugin/salesforce/authenticator/Authenticator.java | // Path: src/main/java/io/cdap/plugin/salesforce/SalesforceConstants.java
// public class SalesforceConstants {
//
// public static final String API_VERSION = "53.0";
// public static final String REFERENCE_NAME_DELIMITER = ".";
//
// public static final String PROPERTY_CONSUMER_KEY = "consumerKey";
// public static final String PROPERTY_CONSUMER_SECRET = "consumerSecret";
// public static final String PROPERTY_USERNAME = "username";
// public static final String PROPERTY_PASSWORD = "password";
// public static final String PROPERTY_SECURITY_TOKEN = "securityToken";
// public static final String PROPERTY_LOGIN_URL = "loginUrl";
// public static final String PROPERTY_OAUTH_INFO = "oAuthInfo";
//
// public static final String CONFIG_OAUTH_TOKEN = "mapred.salesforce.oauth.token";
// public static final String CONFIG_OAUTH_INSTANCE_URL = "mapred.salesforce.oauth.instance.url";
// public static final String CONFIG_CONSUMER_KEY = "mapred.salesforce.consumer.key";
// public static final String CONFIG_PASSWORD = "mapred.salesforce.password";
// public static final String CONFIG_USERNAME = "mapred.salesforce.user";
// public static final String CONFIG_CONSUMER_SECRET = "mapred.salesforce.consumer.secret";
// public static final String CONFIG_LOGIN_URL = "mapred.salesforce.login.url";
//
// public static final int RANGE_FILTER_MIN_VALUE = 0;
// public static final int SOQL_MAX_LENGTH = 20000;
// }
//
// Path: src/main/java/io/cdap/plugin/salesforce/plugin/OAuthInfo.java
// public final class OAuthInfo {
//
// private final String accessToken;
// private final String instanceURL;
//
// public OAuthInfo(String accessToken, String instanceURL) {
// this.accessToken = accessToken;
// this.instanceURL = instanceURL;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public String getInstanceURL() {
// return instanceURL;
// }
// }
| import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.sforce.ws.ConnectorConfig;
import io.cdap.plugin.salesforce.SalesforceConstants;
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory; | /*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.authenticator;
/**
* Authentication to Salesforce via oauth2
*/
public class Authenticator {
private static final Gson GSON = new Gson();
/**
* Authenticates via oauth2 to salesforce and returns a connectorConfig
* which can be used by salesforce libraries to make a connection.
*
* @param credentials information to log in
*
* @return ConnectorConfig which can be used to create BulkConnection and PartnerConnection
*/
public static ConnectorConfig createConnectorConfig(AuthenticatorCredentials credentials) {
try {
OAuthInfo oAuthInfo = getOAuthInfo(credentials);
ConnectorConfig connectorConfig = new ConnectorConfig();
connectorConfig.setSessionId(oAuthInfo.getAccessToken()); | // Path: src/main/java/io/cdap/plugin/salesforce/SalesforceConstants.java
// public class SalesforceConstants {
//
// public static final String API_VERSION = "53.0";
// public static final String REFERENCE_NAME_DELIMITER = ".";
//
// public static final String PROPERTY_CONSUMER_KEY = "consumerKey";
// public static final String PROPERTY_CONSUMER_SECRET = "consumerSecret";
// public static final String PROPERTY_USERNAME = "username";
// public static final String PROPERTY_PASSWORD = "password";
// public static final String PROPERTY_SECURITY_TOKEN = "securityToken";
// public static final String PROPERTY_LOGIN_URL = "loginUrl";
// public static final String PROPERTY_OAUTH_INFO = "oAuthInfo";
//
// public static final String CONFIG_OAUTH_TOKEN = "mapred.salesforce.oauth.token";
// public static final String CONFIG_OAUTH_INSTANCE_URL = "mapred.salesforce.oauth.instance.url";
// public static final String CONFIG_CONSUMER_KEY = "mapred.salesforce.consumer.key";
// public static final String CONFIG_PASSWORD = "mapred.salesforce.password";
// public static final String CONFIG_USERNAME = "mapred.salesforce.user";
// public static final String CONFIG_CONSUMER_SECRET = "mapred.salesforce.consumer.secret";
// public static final String CONFIG_LOGIN_URL = "mapred.salesforce.login.url";
//
// public static final int RANGE_FILTER_MIN_VALUE = 0;
// public static final int SOQL_MAX_LENGTH = 20000;
// }
//
// Path: src/main/java/io/cdap/plugin/salesforce/plugin/OAuthInfo.java
// public final class OAuthInfo {
//
// private final String accessToken;
// private final String instanceURL;
//
// public OAuthInfo(String accessToken, String instanceURL) {
// this.accessToken = accessToken;
// this.instanceURL = instanceURL;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public String getInstanceURL() {
// return instanceURL;
// }
// }
// Path: src/main/java/io/cdap/plugin/salesforce/authenticator/Authenticator.java
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.sforce.ws.ConnectorConfig;
import io.cdap.plugin.salesforce.SalesforceConstants;
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.authenticator;
/**
* Authentication to Salesforce via oauth2
*/
public class Authenticator {
private static final Gson GSON = new Gson();
/**
* Authenticates via oauth2 to salesforce and returns a connectorConfig
* which can be used by salesforce libraries to make a connection.
*
* @param credentials information to log in
*
* @return ConnectorConfig which can be used to create BulkConnection and PartnerConnection
*/
public static ConnectorConfig createConnectorConfig(AuthenticatorCredentials credentials) {
try {
OAuthInfo oAuthInfo = getOAuthInfo(credentials);
ConnectorConfig connectorConfig = new ConnectorConfig();
connectorConfig.setSessionId(oAuthInfo.getAccessToken()); | String apiVersion = SalesforceConstants.API_VERSION; |
data-integrations/salesforce | src/test/java/io/cdap/plugin/salesforce/plugin/source/batch/SalesforceMultiSourceConfigBuilder.java | // Path: src/main/java/io/cdap/plugin/salesforce/plugin/OAuthInfo.java
// public final class OAuthInfo {
//
// private final String accessToken;
// private final String instanceURL;
//
// public OAuthInfo(String accessToken, String instanceURL) {
// this.accessToken = accessToken;
// this.instanceURL = instanceURL;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public String getInstanceURL() {
// return instanceURL;
// }
// }
| import io.cdap.plugin.salesforce.plugin.OAuthInfo; | /*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.plugin.source.batch;
public class SalesforceMultiSourceConfigBuilder {
private String referenceName;
private String consumerKey;
private String consumerSecret;
private String username;
private String password;
private String loginUrl;
private String datetimeAfter;
private String datetimeBefore;
private String duration;
private String offset;
private String whiteList;
private String blackList;
private String sObjectNameField;
private String securityToken; | // Path: src/main/java/io/cdap/plugin/salesforce/plugin/OAuthInfo.java
// public final class OAuthInfo {
//
// private final String accessToken;
// private final String instanceURL;
//
// public OAuthInfo(String accessToken, String instanceURL) {
// this.accessToken = accessToken;
// this.instanceURL = instanceURL;
// }
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public String getInstanceURL() {
// return instanceURL;
// }
// }
// Path: src/test/java/io/cdap/plugin/salesforce/plugin/source/batch/SalesforceMultiSourceConfigBuilder.java
import io.cdap.plugin.salesforce.plugin.OAuthInfo;
/*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.plugin.source.batch;
public class SalesforceMultiSourceConfigBuilder {
private String referenceName;
private String consumerKey;
private String consumerSecret;
private String username;
private String password;
private String loginUrl;
private String datetimeAfter;
private String datetimeBefore;
private String duration;
private String offset;
private String whiteList;
private String blackList;
private String sObjectNameField;
private String securityToken; | private OAuthInfo oAuthInfo; |
data-integrations/salesforce | src/main/java/io/cdap/plugin/salesforce/SalesforceQueryUtil.java | // Path: src/main/java/io/cdap/plugin/salesforce/parser/SalesforceQueryParser.java
// public class SalesforceQueryParser {
//
// /**
// * Parses given SOQL query and retrieves top sObject information and its fields information.
// *
// * @param query SOQL query
// * @return sObject descriptor
// */
// public static SObjectDescriptor getObjectDescriptorFromQuery(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor visitor = new SalesforceQueryVisitor();
// return visitor.visit(parser.statement());
// }
//
// /**
// * Returns part of SOQL query after select statement.
// *
// * @param query SOQL query
// * @return from statement
// */
// public static String getFromStatement(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor.FromStatementVisitor visitor = new SalesforceQueryVisitor.FromStatementVisitor();
// return visitor.visit(parser.statement());
// }
//
// /**
// * Checks if query has restricted syntax that cannot be processed by Bulk API.
// *
// * @param query SOQL query
// * @return true if query has restricted syntax, false otherwise
// */
// public static boolean isRestrictedQuery(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor.RestrictedQueryVisitor visitor = new SalesforceQueryVisitor.RestrictedQueryVisitor();
// return visitor.visit(parser.statement());
// }
//
// /**
// * Checks if query has restricted syntax that cannot be processed by Bulk API with PK Enable.
// *
// * @param query SOQL query
// * @return true if query has restricted syntax, false otherwise
// */
// public static boolean isRestrictedPKQuery(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor.RestrictedPKQueryVisitor visitor = new SalesforceQueryVisitor.RestrictedPKQueryVisitor();
// return visitor.visit(parser.statement());
// }
//
// private static SOQLParser initParser(String query) {
// SOQLLexer lexer = new SOQLLexer(CharStreams.fromString(query));
// lexer.removeErrorListeners();
// lexer.addErrorListener(ThrowingErrorListener.INSTANCE);
//
// CommonTokenStream tokens = new CommonTokenStream(lexer);
// SOQLParser parser = new SOQLParser(tokens);
// parser.removeErrorListeners();
// parser.addErrorListener(ThrowingErrorListener.INSTANCE);
//
// return parser;
// }
//
// /**
// * Error listener which throws exception when parsing error happens, instead of just default writing to stderr.
// */
// private static class ThrowingErrorListener extends BaseErrorListener {
//
// static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();
//
// @Override
// public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
// int line, int charPositionInLine, String msg, RecognitionException e) {
// StringBuilder builder = new StringBuilder();
// builder.append("Line [").append(line).append("]");
// builder.append(", position [").append(charPositionInLine).append("]");
// if (offendingSymbol != null) {
// builder.append(", offending symbol ").append(offendingSymbol);
// }
// if (msg != null) {
// builder.append(": ").append(msg);
// }
// throw new SOQLParsingException(builder.toString());
// }
// }
//
// }
| import io.cdap.plugin.salesforce.parser.SalesforceQueryParser;
import java.time.format.DateTimeFormatter;
import java.util.List; | /*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce;
/**
* Provides Salesforce query utility methods.
*/
public class SalesforceQueryUtil {
private static final String LESS_THAN = "<";
private static final String GREATER_THAN_OR_EQUAL = ">=";
private static final String SELECT = "SELECT ";
private static final String FROM = " FROM ";
private static final String WHERE = " WHERE ";
private static final String AND = " AND ";
private static final String FIELD_LAST_MODIFIED_DATE = "LastModifiedDate";
private static final String FIELD_ID = "Id";
/**
* Creates SObject query with filter if provided.
*
* @param fields query fields
* @param sObjectName SObject name
* @param filterDescriptor SObject date filter descriptor
* @return SOQL with filter if SObjectFilterDescriptor type is not NoOp
*/
public static String createSObjectQuery(List<String> fields, String sObjectName,
SObjectFilterDescriptor filterDescriptor) {
StringBuilder query = new StringBuilder()
.append(SELECT).append(String.join(",", fields))
.append(FROM).append(sObjectName);
if (!filterDescriptor.isNoOp()) {
query.append(WHERE).append(generateSObjectFilter(filterDescriptor));
}
return query.toString();
}
/**
* Checks if query length is less than SOQL max length limit.
*
* @param query SOQL query
* @return true if SOQL length less than max allowed
*/
public static boolean isQueryUnderLengthLimit(String query) {
return query.length() < SalesforceConstants.SOQL_MAX_LENGTH;
}
/**
* Creates SObject IDs query based on initial query. Replaces all query fields with {@link #FIELD_ID} in SELECT
* clause but leaves other clauses as is.
* <p/>
* Example:
* <ul>
* <li>Initial query: `SELECT Name, LastModifiedDate FROM Opportunity WHERE Name LIKE 'S_%'`</li>
* <li>Result query: `SELECT Id FROM Opportunity WHERE Name LIKE 'S_%'`</li>
* </ul>
*
* @param query initial query
* @return SObject IDs query
*/
public static String createSObjectIdQuery(String query) { | // Path: src/main/java/io/cdap/plugin/salesforce/parser/SalesforceQueryParser.java
// public class SalesforceQueryParser {
//
// /**
// * Parses given SOQL query and retrieves top sObject information and its fields information.
// *
// * @param query SOQL query
// * @return sObject descriptor
// */
// public static SObjectDescriptor getObjectDescriptorFromQuery(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor visitor = new SalesforceQueryVisitor();
// return visitor.visit(parser.statement());
// }
//
// /**
// * Returns part of SOQL query after select statement.
// *
// * @param query SOQL query
// * @return from statement
// */
// public static String getFromStatement(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor.FromStatementVisitor visitor = new SalesforceQueryVisitor.FromStatementVisitor();
// return visitor.visit(parser.statement());
// }
//
// /**
// * Checks if query has restricted syntax that cannot be processed by Bulk API.
// *
// * @param query SOQL query
// * @return true if query has restricted syntax, false otherwise
// */
// public static boolean isRestrictedQuery(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor.RestrictedQueryVisitor visitor = new SalesforceQueryVisitor.RestrictedQueryVisitor();
// return visitor.visit(parser.statement());
// }
//
// /**
// * Checks if query has restricted syntax that cannot be processed by Bulk API with PK Enable.
// *
// * @param query SOQL query
// * @return true if query has restricted syntax, false otherwise
// */
// public static boolean isRestrictedPKQuery(String query) {
// SOQLParser parser = initParser(query);
// SalesforceQueryVisitor.RestrictedPKQueryVisitor visitor = new SalesforceQueryVisitor.RestrictedPKQueryVisitor();
// return visitor.visit(parser.statement());
// }
//
// private static SOQLParser initParser(String query) {
// SOQLLexer lexer = new SOQLLexer(CharStreams.fromString(query));
// lexer.removeErrorListeners();
// lexer.addErrorListener(ThrowingErrorListener.INSTANCE);
//
// CommonTokenStream tokens = new CommonTokenStream(lexer);
// SOQLParser parser = new SOQLParser(tokens);
// parser.removeErrorListeners();
// parser.addErrorListener(ThrowingErrorListener.INSTANCE);
//
// return parser;
// }
//
// /**
// * Error listener which throws exception when parsing error happens, instead of just default writing to stderr.
// */
// private static class ThrowingErrorListener extends BaseErrorListener {
//
// static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();
//
// @Override
// public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
// int line, int charPositionInLine, String msg, RecognitionException e) {
// StringBuilder builder = new StringBuilder();
// builder.append("Line [").append(line).append("]");
// builder.append(", position [").append(charPositionInLine).append("]");
// if (offendingSymbol != null) {
// builder.append(", offending symbol ").append(offendingSymbol);
// }
// if (msg != null) {
// builder.append(": ").append(msg);
// }
// throw new SOQLParsingException(builder.toString());
// }
// }
//
// }
// Path: src/main/java/io/cdap/plugin/salesforce/SalesforceQueryUtil.java
import io.cdap.plugin.salesforce.parser.SalesforceQueryParser;
import java.time.format.DateTimeFormatter;
import java.util.List;
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce;
/**
* Provides Salesforce query utility methods.
*/
public class SalesforceQueryUtil {
private static final String LESS_THAN = "<";
private static final String GREATER_THAN_OR_EQUAL = ">=";
private static final String SELECT = "SELECT ";
private static final String FROM = " FROM ";
private static final String WHERE = " WHERE ";
private static final String AND = " AND ";
private static final String FIELD_LAST_MODIFIED_DATE = "LastModifiedDate";
private static final String FIELD_ID = "Id";
/**
* Creates SObject query with filter if provided.
*
* @param fields query fields
* @param sObjectName SObject name
* @param filterDescriptor SObject date filter descriptor
* @return SOQL with filter if SObjectFilterDescriptor type is not NoOp
*/
public static String createSObjectQuery(List<String> fields, String sObjectName,
SObjectFilterDescriptor filterDescriptor) {
StringBuilder query = new StringBuilder()
.append(SELECT).append(String.join(",", fields))
.append(FROM).append(sObjectName);
if (!filterDescriptor.isNoOp()) {
query.append(WHERE).append(generateSObjectFilter(filterDescriptor));
}
return query.toString();
}
/**
* Checks if query length is less than SOQL max length limit.
*
* @param query SOQL query
* @return true if SOQL length less than max allowed
*/
public static boolean isQueryUnderLengthLimit(String query) {
return query.length() < SalesforceConstants.SOQL_MAX_LENGTH;
}
/**
* Creates SObject IDs query based on initial query. Replaces all query fields with {@link #FIELD_ID} in SELECT
* clause but leaves other clauses as is.
* <p/>
* Example:
* <ul>
* <li>Initial query: `SELECT Name, LastModifiedDate FROM Opportunity WHERE Name LIKE 'S_%'`</li>
* <li>Result query: `SELECT Id FROM Opportunity WHERE Name LIKE 'S_%'`</li>
* </ul>
*
* @param query initial query
* @return SObject IDs query
*/
public static String createSObjectIdQuery(String query) { | String fromStatement = SalesforceQueryParser.getFromStatement(query); |
data-integrations/salesforce | src/main/java/io/cdap/plugin/salesforce/plugin/source/streaming/SalesforceReceiver.java | // Path: src/main/java/io/cdap/plugin/salesforce/authenticator/AuthenticatorCredentials.java
// public class AuthenticatorCredentials implements Serializable {
//
// private final OAuthInfo oAuthInfo;
// private final String username;
// private final String password;
// private final String consumerKey;
// private final String consumerSecret;
// private final String loginUrl;
//
// public AuthenticatorCredentials(OAuthInfo oAuthInfo) {
// this(Objects.requireNonNull(oAuthInfo), null, null, null, null, null);
// }
//
// public AuthenticatorCredentials(String username, String password,
// String consumerKey, String consumerSecret, String loginUrl) {
// this(null, Objects.requireNonNull(username), Objects.requireNonNull(password), Objects.requireNonNull(consumerKey),
// Objects.requireNonNull(consumerSecret), Objects.requireNonNull(loginUrl));
// }
//
// private AuthenticatorCredentials(@Nullable OAuthInfo oAuthInfo,
// @Nullable String username,
// @Nullable String password,
// @Nullable String consumerKey,
// @Nullable String consumerSecret,
// @Nullable String loginUrl) {
// this.oAuthInfo = oAuthInfo;
// this.username = username;
// this.password = password;
// this.consumerKey = consumerKey;
// this.consumerSecret = consumerSecret;
// this.loginUrl = loginUrl;
// }
//
// @Nullable
// public OAuthInfo getOAuthInfo() {
// return oAuthInfo;
// }
//
// @Nullable
// public String getUsername() {
// return username;
// }
//
// @Nullable
// public String getPassword() {
// return password;
// }
//
// @Nullable
// public String getConsumerKey() {
// return consumerKey;
// }
//
// @Nullable
// public String getConsumerSecret() {
// return consumerSecret;
// }
//
// @Nullable
// public String getLoginUrl() {
// return loginUrl;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// AuthenticatorCredentials that = (AuthenticatorCredentials) o;
//
// return Objects.equals(username, that.username) &&
// Objects.equals(password, that.password) &&
// Objects.equals(consumerKey, that.consumerKey) &&
// Objects.equals(consumerSecret, that.consumerSecret) &&
// Objects.equals(loginUrl, that.loginUrl);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(username, password, consumerKey, consumerSecret, loginUrl);
// }
// }
| import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.receiver.Receiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit; | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.plugin.source.streaming;
/**
* Implementation of Spark receiver to receive Salesforce push topic events
*/
public class SalesforceReceiver extends Receiver<String> {
private static final Logger LOG = LoggerFactory.getLogger(SalesforceReceiver.class);
private static final String RECEIVER_THREAD_NAME = "salesforce_streaming_api_listener";
// every x seconds thread wakes up and checks if stream is not yet stopped
private static final long GET_MESSAGE_TIMEOUT_SECONDS = 2;
| // Path: src/main/java/io/cdap/plugin/salesforce/authenticator/AuthenticatorCredentials.java
// public class AuthenticatorCredentials implements Serializable {
//
// private final OAuthInfo oAuthInfo;
// private final String username;
// private final String password;
// private final String consumerKey;
// private final String consumerSecret;
// private final String loginUrl;
//
// public AuthenticatorCredentials(OAuthInfo oAuthInfo) {
// this(Objects.requireNonNull(oAuthInfo), null, null, null, null, null);
// }
//
// public AuthenticatorCredentials(String username, String password,
// String consumerKey, String consumerSecret, String loginUrl) {
// this(null, Objects.requireNonNull(username), Objects.requireNonNull(password), Objects.requireNonNull(consumerKey),
// Objects.requireNonNull(consumerSecret), Objects.requireNonNull(loginUrl));
// }
//
// private AuthenticatorCredentials(@Nullable OAuthInfo oAuthInfo,
// @Nullable String username,
// @Nullable String password,
// @Nullable String consumerKey,
// @Nullable String consumerSecret,
// @Nullable String loginUrl) {
// this.oAuthInfo = oAuthInfo;
// this.username = username;
// this.password = password;
// this.consumerKey = consumerKey;
// this.consumerSecret = consumerSecret;
// this.loginUrl = loginUrl;
// }
//
// @Nullable
// public OAuthInfo getOAuthInfo() {
// return oAuthInfo;
// }
//
// @Nullable
// public String getUsername() {
// return username;
// }
//
// @Nullable
// public String getPassword() {
// return password;
// }
//
// @Nullable
// public String getConsumerKey() {
// return consumerKey;
// }
//
// @Nullable
// public String getConsumerSecret() {
// return consumerSecret;
// }
//
// @Nullable
// public String getLoginUrl() {
// return loginUrl;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// AuthenticatorCredentials that = (AuthenticatorCredentials) o;
//
// return Objects.equals(username, that.username) &&
// Objects.equals(password, that.password) &&
// Objects.equals(consumerKey, that.consumerKey) &&
// Objects.equals(consumerSecret, that.consumerSecret) &&
// Objects.equals(loginUrl, that.loginUrl);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(username, password, consumerKey, consumerSecret, loginUrl);
// }
// }
// Path: src/main/java/io/cdap/plugin/salesforce/plugin/source/streaming/SalesforceReceiver.java
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.receiver.Receiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.salesforce.plugin.source.streaming;
/**
* Implementation of Spark receiver to receive Salesforce push topic events
*/
public class SalesforceReceiver extends Receiver<String> {
private static final Logger LOG = LoggerFactory.getLogger(SalesforceReceiver.class);
private static final String RECEIVER_THREAD_NAME = "salesforce_streaming_api_listener";
// every x seconds thread wakes up and checks if stream is not yet stopped
private static final long GET_MESSAGE_TIMEOUT_SECONDS = 2;
| private final AuthenticatorCredentials credentials; |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/RC4CryptoAPIProvider.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
| import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter; | /*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl.office;
/**
*
* @author James Ahlborn
*/
public class RC4CryptoAPIProvider extends StreamCipherProvider
{
private static final Set<EncryptionHeader.CryptoAlgorithm> VALID_CRYPTO_ALGOS =
EnumSet.of(EncryptionHeader.CryptoAlgorithm.RC4);
private static final Set<EncryptionHeader.HashAlgorithm> VALID_HASH_ALGOS =
EnumSet.of(EncryptionHeader.HashAlgorithm.SHA1);
private final EncryptionHeader _header;
private final EncryptionVerifier _verifier;
private final byte[] _baseHash;
private final int _encKeyByteSize;
public RC4CryptoAPIProvider(PageChannel channel, byte[] encodingKey,
ByteBuffer encProvBuf, byte[] pwdBytes)
{
super(channel, encodingKey);
_header = EncryptionHeader.read(encProvBuf, VALID_CRYPTO_ALGOS,
VALID_HASH_ALGOS);
_verifier = new EncryptionVerifier(encProvBuf, _header.getCryptoAlgorithm());
// OC: 2.3.5.2 (part 1)
_baseHash = hash(getDigest(), _verifier.getSalt(), pwdBytes);
_encKeyByteSize = bits2bytes(_header.getKeySize());
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new SHA1Digest();
}
@Override | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/RC4CryptoAPIProvider.java
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter;
/*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl.office;
/**
*
* @author James Ahlborn
*/
public class RC4CryptoAPIProvider extends StreamCipherProvider
{
private static final Set<EncryptionHeader.CryptoAlgorithm> VALID_CRYPTO_ALGOS =
EnumSet.of(EncryptionHeader.CryptoAlgorithm.RC4);
private static final Set<EncryptionHeader.HashAlgorithm> VALID_HASH_ALGOS =
EnumSet.of(EncryptionHeader.HashAlgorithm.SHA1);
private final EncryptionHeader _header;
private final EncryptionVerifier _verifier;
private final byte[] _baseHash;
private final int _encKeyByteSize;
public RC4CryptoAPIProvider(PageChannel channel, byte[] encodingKey,
ByteBuffer encProvBuf, byte[] pwdBytes)
{
super(channel, encodingKey);
_header = EncryptionHeader.read(encProvBuf, VALID_CRYPTO_ALGOS,
VALID_HASH_ALGOS);
_verifier = new EncryptionVerifier(encProvBuf, _header.getCryptoAlgorithm());
// OC: 2.3.5.2 (part 1)
_baseHash = hash(getDigest(), _verifier.getSalt(), pwdBytes);
_encKeyByteSize = bits2bytes(_header.getKeySize());
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new SHA1Digest();
}
@Override | protected StreamCipherCompat initCipher() { |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/RC4CryptoAPIProvider.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
| import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter; | private final int _encKeyByteSize;
public RC4CryptoAPIProvider(PageChannel channel, byte[] encodingKey,
ByteBuffer encProvBuf, byte[] pwdBytes)
{
super(channel, encodingKey);
_header = EncryptionHeader.read(encProvBuf, VALID_CRYPTO_ALGOS,
VALID_HASH_ALGOS);
_verifier = new EncryptionVerifier(encProvBuf, _header.getCryptoAlgorithm());
// OC: 2.3.5.2 (part 1)
_baseHash = hash(getDigest(), _verifier.getSalt(), pwdBytes);
_encKeyByteSize = bits2bytes(_header.getKeySize());
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new SHA1Digest();
}
@Override
protected StreamCipherCompat initCipher() { | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/RC4CryptoAPIProvider.java
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter;
private final int _encKeyByteSize;
public RC4CryptoAPIProvider(PageChannel channel, byte[] encodingKey,
ByteBuffer encProvBuf, byte[] pwdBytes)
{
super(channel, encodingKey);
_header = EncryptionHeader.read(encProvBuf, VALID_CRYPTO_ALGOS,
VALID_HASH_ALGOS);
_verifier = new EncryptionVerifier(encProvBuf, _header.getCryptoAlgorithm());
// OC: 2.3.5.2 (part 1)
_baseHash = hash(getDigest(), _verifier.getSalt(), pwdBytes);
_encKeyByteSize = bits2bytes(_header.getKeySize());
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new SHA1Digest();
}
@Override
protected StreamCipherCompat initCipher() { | return StreamCipherFactory.newRC4Engine(); |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/EncryptionHeader.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCryptoConfigurationException.java
// public class InvalidCryptoConfigurationException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCryptoConfigurationException(String msg) {
// super(msg);
// }
//
// public InvalidCryptoConfigurationException(String msg, Throwable t) {
// super(msg, t);
// }
// }
| import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Set;
import com.healthmarketscience.jackcess.crypt.InvalidCryptoConfigurationException;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CustomToStringStyle;
import com.healthmarketscience.jackcess.impl.UnsupportedCodecException;
import org.apache.commons.lang3.builder.ToStringBuilder; | public int getKeySize() {
return _keySize;
}
public int getProviderType() {
return _providerType;
}
public String getCspName() {
return _cspName;
}
public static EncryptionHeader read(ByteBuffer encProvBuf,
Set<CryptoAlgorithm> validCryptoAlgos,
Set<HashAlgorithm> validHashAlgos)
{
// read length of header
int headerLen = encProvBuf.getInt();
// read header (temporarily narrowing buf to header)
int origLimit = encProvBuf.limit();
int startPos = encProvBuf.position();
encProvBuf.limit(startPos + headerLen);
EncryptionHeader header = null;
try {
header = new EncryptionHeader(encProvBuf);
// verify parameters
if(!validCryptoAlgos.contains(header.getCryptoAlgorithm())) { | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCryptoConfigurationException.java
// public class InvalidCryptoConfigurationException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCryptoConfigurationException(String msg) {
// super(msg);
// }
//
// public InvalidCryptoConfigurationException(String msg, Throwable t) {
// super(msg, t);
// }
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/EncryptionHeader.java
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Set;
import com.healthmarketscience.jackcess.crypt.InvalidCryptoConfigurationException;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CustomToStringStyle;
import com.healthmarketscience.jackcess.impl.UnsupportedCodecException;
import org.apache.commons.lang3.builder.ToStringBuilder;
public int getKeySize() {
return _keySize;
}
public int getProviderType() {
return _providerType;
}
public String getCspName() {
return _cspName;
}
public static EncryptionHeader read(ByteBuffer encProvBuf,
Set<CryptoAlgorithm> validCryptoAlgos,
Set<HashAlgorithm> validHashAlgos)
{
// read length of header
int headerLen = encProvBuf.getInt();
// read header (temporarily narrowing buf to header)
int origLimit = encProvBuf.limit();
int startPos = encProvBuf.position();
encProvBuf.limit(startPos + headerLen);
EncryptionHeader header = null;
try {
header = new EncryptionHeader(encProvBuf);
// verify parameters
if(!validCryptoAlgos.contains(header.getCryptoAlgorithm())) { | throw new InvalidCryptoConfigurationException( |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/BaseCryptCodecHandler.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
| import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.PageChannel;
import com.healthmarketscience.jackcess.impl.TempBufferHolder;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.InvalidCipherTextException; | /*
Copyright (c) 2010 Vladimir Berezniker
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl;
/**
* Common CodecHandler support.
*
* @author Vladimir Berezniker
*/
public abstract class BaseCryptCodecHandler implements CodecHandler
{
public static final boolean CIPHER_DECRYPT_MODE = false;
public static final boolean CIPHER_ENCRYPT_MODE = true;
private final PageChannel _channel;
private final byte[] _encodingKey;
private final KeyCache<CipherParameters> _paramCache =
new KeyCache<CipherParameters>() {
@Override protected CipherParameters computeKey(int pageNumber) {
return computeCipherParams(pageNumber);
}
};
private TempBufferHolder _tempBufH;
protected BaseCryptCodecHandler(PageChannel channel, byte[] encodingKey) {
_channel = channel;
_encodingKey = encodingKey;
}
protected CipherParameters getCipherParams(int pageNumber) {
return _paramCache.get(pageNumber);
}
protected byte[] getEncodingKey() {
return _encodingKey;
}
| // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/BaseCryptCodecHandler.java
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.PageChannel;
import com.healthmarketscience.jackcess.impl.TempBufferHolder;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.InvalidCipherTextException;
/*
Copyright (c) 2010 Vladimir Berezniker
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl;
/**
* Common CodecHandler support.
*
* @author Vladimir Berezniker
*/
public abstract class BaseCryptCodecHandler implements CodecHandler
{
public static final boolean CIPHER_DECRYPT_MODE = false;
public static final boolean CIPHER_ENCRYPT_MODE = true;
private final PageChannel _channel;
private final byte[] _encodingKey;
private final KeyCache<CipherParameters> _paramCache =
new KeyCache<CipherParameters>() {
@Override protected CipherParameters computeKey(int pageNumber) {
return computeCipherParams(pageNumber);
}
};
private TempBufferHolder _tempBufH;
protected BaseCryptCodecHandler(PageChannel channel, byte[] encodingKey) {
_channel = channel;
_encodingKey = encodingKey;
}
protected CipherParameters getCipherParams(int pageNumber) {
return _paramCache.get(pageNumber);
}
protected byte[] getEncodingKey() {
return _encodingKey;
}
| protected StreamCipherCompat getStreamCipher() { |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/MSISAMCryptCodecHandler.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCredentialsException.java
// public class InvalidCredentialsException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCredentialsException(String msg) {
// super(msg);
// }
//
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
| import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.function.Supplier;
import com.healthmarketscience.jackcess.crypt.InvalidCredentialsException;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.ColumnImpl;
import com.healthmarketscience.jackcess.impl.DatabaseImpl;
import com.healthmarketscience.jackcess.impl.JetFormat;
import com.healthmarketscience.jackcess.impl.PageChannel; | ByteBuffer buffer = readHeaderPage(channel);
if ((buffer.get(ENCRYPTION_FLAGS_OFFSET) & NEW_ENCRYPTION) != 0) {
return new MSISAMCryptCodecHandler(channel, callback.get(), charset, buffer);
}
// old MSISAM dbs use jet-style encryption w/ a different key
return new JetCryptCodecHandler(channel,
getOldDecryptionKey(buffer, channel.getFormat())) {
@Override
protected int getMaxEncodedPage() {
return MSISAM_MAX_ENCRYPTED_PAGE;
}
};
}
@Override
protected KeyParameter computeCipherParams(int pageNumber) {
return new KeyParameter(
applyPageNumber(_baseHash, PASSWORD_DIGEST_LENGTH, pageNumber));
}
@Override
protected int getMaxEncodedPage() {
return MSISAM_MAX_ENCRYPTED_PAGE;
}
private void verifyPassword(ByteBuffer buffer, byte[] testEncodingKey,
byte[] testBytes)
{ | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCredentialsException.java
// public class InvalidCredentialsException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCredentialsException(String msg) {
// super(msg);
// }
//
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/MSISAMCryptCodecHandler.java
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.function.Supplier;
import com.healthmarketscience.jackcess.crypt.InvalidCredentialsException;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.ColumnImpl;
import com.healthmarketscience.jackcess.impl.DatabaseImpl;
import com.healthmarketscience.jackcess.impl.JetFormat;
import com.healthmarketscience.jackcess.impl.PageChannel;
ByteBuffer buffer = readHeaderPage(channel);
if ((buffer.get(ENCRYPTION_FLAGS_OFFSET) & NEW_ENCRYPTION) != 0) {
return new MSISAMCryptCodecHandler(channel, callback.get(), charset, buffer);
}
// old MSISAM dbs use jet-style encryption w/ a different key
return new JetCryptCodecHandler(channel,
getOldDecryptionKey(buffer, channel.getFormat())) {
@Override
protected int getMaxEncodedPage() {
return MSISAM_MAX_ENCRYPTED_PAGE;
}
};
}
@Override
protected KeyParameter computeCipherParams(int pageNumber) {
return new KeyParameter(
applyPageNumber(_baseHash, PASSWORD_DIGEST_LENGTH, pageNumber));
}
@Override
protected int getMaxEncodedPage() {
return MSISAM_MAX_ENCRYPTED_PAGE;
}
private void verifyPassword(ByteBuffer buffer, byte[] testEncodingKey,
byte[] testBytes)
{ | StreamCipherCompat engine = decryptInit(getStreamCipher(), |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/MSISAMCryptCodecHandler.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCredentialsException.java
// public class InvalidCredentialsException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCredentialsException(String msg) {
// super(msg);
// }
//
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
| import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.function.Supplier;
import com.healthmarketscience.jackcess.crypt.InvalidCredentialsException;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.ColumnImpl;
import com.healthmarketscience.jackcess.impl.DatabaseImpl;
import com.healthmarketscience.jackcess.impl.JetFormat;
import com.healthmarketscience.jackcess.impl.PageChannel; | }
};
}
@Override
protected KeyParameter computeCipherParams(int pageNumber) {
return new KeyParameter(
applyPageNumber(_baseHash, PASSWORD_DIGEST_LENGTH, pageNumber));
}
@Override
protected int getMaxEncodedPage() {
return MSISAM_MAX_ENCRYPTED_PAGE;
}
private void verifyPassword(ByteBuffer buffer, byte[] testEncodingKey,
byte[] testBytes)
{
StreamCipherCompat engine = decryptInit(getStreamCipher(),
new KeyParameter(testEncodingKey));
byte[] encrypted4BytesCheck = getPasswordTestBytes(buffer);
if(isBlankKey(encrypted4BytesCheck)) {
// no password?
return;
}
byte[] decrypted4BytesCheck = decryptBytes(engine, encrypted4BytesCheck);
if (!Arrays.equals(decrypted4BytesCheck, testBytes)) { | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCredentialsException.java
// public class InvalidCredentialsException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCredentialsException(String msg) {
// super(msg);
// }
//
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/MSISAMCryptCodecHandler.java
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.params.KeyParameter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.function.Supplier;
import com.healthmarketscience.jackcess.crypt.InvalidCredentialsException;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.ColumnImpl;
import com.healthmarketscience.jackcess.impl.DatabaseImpl;
import com.healthmarketscience.jackcess.impl.JetFormat;
import com.healthmarketscience.jackcess.impl.PageChannel;
}
};
}
@Override
protected KeyParameter computeCipherParams(int pageNumber) {
return new KeyParameter(
applyPageNumber(_baseHash, PASSWORD_DIGEST_LENGTH, pageNumber));
}
@Override
protected int getMaxEncodedPage() {
return MSISAM_MAX_ENCRYPTED_PAGE;
}
private void verifyPassword(ByteBuffer buffer, byte[] testEncodingKey,
byte[] testBytes)
{
StreamCipherCompat engine = decryptInit(getStreamCipher(),
new KeyParameter(testEncodingKey));
byte[] encrypted4BytesCheck = getPasswordTestBytes(buffer);
if(isBlankKey(encrypted4BytesCheck)) {
// no password?
return;
}
byte[] decrypted4BytesCheck = decryptBytes(engine, encrypted4BytesCheck);
if (!Arrays.equals(decrypted4BytesCheck, testBytes)) { | throw new InvalidCredentialsException("Incorrect password provided"); |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/BaseJetCryptCodecHandler.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
| import java.nio.ByteBuffer;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.PageChannel; | /*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl;
/**
* Base CodecHandler support for Jet RC4 encryption based CodecHandlers.
*
* @author James Ahlborn
*/
public abstract class BaseJetCryptCodecHandler extends BaseCryptCodecHandler
{ | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/BaseJetCryptCodecHandler.java
import java.nio.ByteBuffer;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.PageChannel;
/*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl;
/**
* Base CodecHandler support for Jet RC4 encryption based CodecHandlers.
*
* @author James Ahlborn
*/
public abstract class BaseJetCryptCodecHandler extends BaseCryptCodecHandler
{ | private StreamCipherCompat _engine; |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/BaseJetCryptCodecHandler.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
| import java.nio.ByteBuffer;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.PageChannel; | /*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl;
/**
* Base CodecHandler support for Jet RC4 encryption based CodecHandlers.
*
* @author James Ahlborn
*/
public abstract class BaseJetCryptCodecHandler extends BaseCryptCodecHandler
{
private StreamCipherCompat _engine;
protected BaseJetCryptCodecHandler(PageChannel channel, byte[] encodingKey) {
super(channel, encodingKey);
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
public boolean canDecodeInline() {
// RC4 ciphers can decode on top of the input buffer
return true;
}
@Override
protected final StreamCipherCompat getStreamCipher() {
if(_engine == null) { | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/BaseJetCryptCodecHandler.java
import java.nio.ByteBuffer;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.CodecHandler;
import com.healthmarketscience.jackcess.impl.PageChannel;
/*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl;
/**
* Base CodecHandler support for Jet RC4 encryption based CodecHandlers.
*
* @author James Ahlborn
*/
public abstract class BaseJetCryptCodecHandler extends BaseCryptCodecHandler
{
private StreamCipherCompat _engine;
protected BaseJetCryptCodecHandler(PageChannel channel, byte[] encodingKey) {
super(channel, encodingKey);
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
public boolean canDecodeInline() {
// RC4 ciphers can decode on top of the input buffer
return true;
}
@Override
protected final StreamCipherCompat getStreamCipher() {
if(_engine == null) { | _engine = StreamCipherFactory.newRC4Engine(); |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/OfficeBinaryDocRC4Provider.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
| import java.nio.ByteBuffer;
import java.util.Arrays;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.params.KeyParameter; | /*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl.office;
/**
*
* @author James Ahlborn
*/
public class OfficeBinaryDocRC4Provider extends StreamCipherProvider
{
private final byte[] _encVerifier = new byte[16];
private final byte[] _encVerifierHash = new byte[16];
private final byte[] _baseHash;
public OfficeBinaryDocRC4Provider(PageChannel channel, byte[] encodingKey,
ByteBuffer encProvBuf, byte[] pwdBytes)
{
super(channel, encodingKey);
// OC: 2.3.6.1
byte[] salt = new byte[16];
encProvBuf.get(salt);
encProvBuf.get(_encVerifier);
encProvBuf.get(_encVerifierHash);
// OC: 2.3.6.2 (Part 1)
byte[] fillHash = ByteUtil.concat(hash(getDigest(), pwdBytes, 5), salt);
byte[] intBuf = new byte[336];
for(int i = 0; i < intBuf.length; i += fillHash.length) {
System.arraycopy(fillHash, 0, intBuf, i, fillHash.length);
}
_baseHash = hash(getDigest(), intBuf, 5);
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new MD5Digest();
}
@Override | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/OfficeBinaryDocRC4Provider.java
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.params.KeyParameter;
/*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl.office;
/**
*
* @author James Ahlborn
*/
public class OfficeBinaryDocRC4Provider extends StreamCipherProvider
{
private final byte[] _encVerifier = new byte[16];
private final byte[] _encVerifierHash = new byte[16];
private final byte[] _baseHash;
public OfficeBinaryDocRC4Provider(PageChannel channel, byte[] encodingKey,
ByteBuffer encProvBuf, byte[] pwdBytes)
{
super(channel, encodingKey);
// OC: 2.3.6.1
byte[] salt = new byte[16];
encProvBuf.get(salt);
encProvBuf.get(_encVerifier);
encProvBuf.get(_encVerifierHash);
// OC: 2.3.6.2 (Part 1)
byte[] fillHash = ByteUtil.concat(hash(getDigest(), pwdBytes, 5), salt);
byte[] intBuf = new byte[336];
for(int i = 0; i < intBuf.length; i += fillHash.length) {
System.arraycopy(fillHash, 0, intBuf, i, fillHash.length);
}
_baseHash = hash(getDigest(), intBuf, 5);
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new MD5Digest();
}
@Override | protected StreamCipherCompat initCipher() { |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/OfficeBinaryDocRC4Provider.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
| import java.nio.ByteBuffer;
import java.util.Arrays;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.params.KeyParameter; | // OC: 2.3.6.1
byte[] salt = new byte[16];
encProvBuf.get(salt);
encProvBuf.get(_encVerifier);
encProvBuf.get(_encVerifierHash);
// OC: 2.3.6.2 (Part 1)
byte[] fillHash = ByteUtil.concat(hash(getDigest(), pwdBytes, 5), salt);
byte[] intBuf = new byte[336];
for(int i = 0; i < intBuf.length; i += fillHash.length) {
System.arraycopy(fillHash, 0, intBuf, i, fillHash.length);
}
_baseHash = hash(getDigest(), intBuf, 5);
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new MD5Digest();
}
@Override
protected StreamCipherCompat initCipher() { | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherCompat.java
// public interface StreamCipherCompat
// {
// public String getAlgorithmName();
//
// public void init(boolean forEncryption, CipherParameters params);
//
// public byte returnByte(byte in);
//
// public int processStreamBytes(byte[] in, int inOff,
// int len, byte[] out, int outOff);
//
// public void reset();
// }
//
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/util/StreamCipherFactory.java
// public abstract class StreamCipherFactory
// {
// /** compatible factory for RC4Engine instances */
// private static final StreamCipherFactory RC4_ENGINE_FACTORY;
// static {
// StreamCipherFactory factory = null;
// try {
// // first, attempt to load a 1.51+ compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineCompat$Factory");
// } catch(Throwable t) {
// // failed, try legacy version
// }
//
// if(factory == null) {
// try {
// // now, attempt to load a 1.50 and earlier compatible factory instance
// factory = loadFactory("com.healthmarketscience.jackcess.crypt.util.RC4EngineLegacy$Factory");
// } catch(Throwable e) {
// // sorry, no dice
// throw new IllegalStateException("Incompatible bouncycastle version", e);
// }
// }
//
// RC4_ENGINE_FACTORY = factory;
// }
//
// protected StreamCipherFactory() {}
//
// public static StreamCipherCompat newRC4Engine() {
// return RC4_ENGINE_FACTORY.newInstance();
// }
//
// private static StreamCipherFactory loadFactory(String className)
// throws Exception
// {
// Class<?> factoryClass = Class.forName(className);
// StreamCipherFactory factory = (StreamCipherFactory)factoryClass.newInstance();
// // verify that the engine is functional
// if(factory.newInstance() == null) {
// throw new IllegalStateException("EngineFactory " + className +
// " not functional");
// }
// return factory;
// }
//
// public abstract StreamCipherCompat newInstance();
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/OfficeBinaryDocRC4Provider.java
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherCompat;
import com.healthmarketscience.jackcess.crypt.util.StreamCipherFactory;
import com.healthmarketscience.jackcess.impl.ByteUtil;
import com.healthmarketscience.jackcess.impl.PageChannel;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.params.KeyParameter;
// OC: 2.3.6.1
byte[] salt = new byte[16];
encProvBuf.get(salt);
encProvBuf.get(_encVerifier);
encProvBuf.get(_encVerifierHash);
// OC: 2.3.6.2 (Part 1)
byte[] fillHash = ByteUtil.concat(hash(getDigest(), pwdBytes, 5), salt);
byte[] intBuf = new byte[336];
for(int i = 0; i < intBuf.length; i += fillHash.length) {
System.arraycopy(fillHash, 0, intBuf, i, fillHash.length);
}
_baseHash = hash(getDigest(), intBuf, 5);
}
@Override
public boolean canEncodePartialPage() {
// RC4 ciphers are not influenced by the page contents, so we can easily
// encode part of the buffer.
return true;
}
@Override
protected Digest initDigest() {
return new MD5Digest();
}
@Override
protected StreamCipherCompat initCipher() { | return StreamCipherFactory.newRC4Engine(); |
jahlborn/jackcessencrypt | src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/EncryptionVerifier.java | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCryptoConfigurationException.java
// public class InvalidCryptoConfigurationException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCryptoConfigurationException(String msg) {
// super(msg);
// }
//
// public InvalidCryptoConfigurationException(String msg, Throwable t) {
// super(msg, t);
// }
// }
| import java.nio.ByteBuffer;
import com.healthmarketscience.jackcess.crypt.InvalidCryptoConfigurationException;
import com.healthmarketscience.jackcess.impl.ByteUtil; | /*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl.office;
/**
*
* @author James Ahlborn
*/
public class EncryptionVerifier
{
private final static int SALT_SIZE = 16;
private final static int ENC_VERIFIER_SIZE = 16;
private final int _saltSize;
private final byte[] _salt;
private final byte[] _encryptedVerifier;
private final int _verifierHashSize;
private final byte[] _encryptedVerifierHash;
public EncryptionVerifier(ByteBuffer buffer,
EncryptionHeader.CryptoAlgorithm cryptoAlg)
{
// OC: 2.3.3 EncryptionVerifier Structure
_saltSize = buffer.getInt();
if(_saltSize != SALT_SIZE) { | // Path: src/main/java/com/healthmarketscience/jackcess/crypt/InvalidCryptoConfigurationException.java
// public class InvalidCryptoConfigurationException extends IllegalStateException
// {
// private static final long serialVersionUID = 20170130L;
//
// public InvalidCryptoConfigurationException(String msg) {
// super(msg);
// }
//
// public InvalidCryptoConfigurationException(String msg, Throwable t) {
// super(msg, t);
// }
// }
// Path: src/main/java/com/healthmarketscience/jackcess/crypt/impl/office/EncryptionVerifier.java
import java.nio.ByteBuffer;
import com.healthmarketscience.jackcess.crypt.InvalidCryptoConfigurationException;
import com.healthmarketscience.jackcess.impl.ByteUtil;
/*
Copyright (c) 2013 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.crypt.impl.office;
/**
*
* @author James Ahlborn
*/
public class EncryptionVerifier
{
private final static int SALT_SIZE = 16;
private final static int ENC_VERIFIER_SIZE = 16;
private final int _saltSize;
private final byte[] _salt;
private final byte[] _encryptedVerifier;
private final int _verifierHashSize;
private final byte[] _encryptedVerifierHash;
public EncryptionVerifier(ByteBuffer buffer,
EncryptionHeader.CryptoAlgorithm cryptoAlg)
{
// OC: 2.3.3 EncryptionVerifier Structure
_saltSize = buffer.getInt();
if(_saltSize != SALT_SIZE) { | throw new InvalidCryptoConfigurationException("salt size " + _saltSize + " must be " + SALT_SIZE); |
CheetaTech/ColorHub | app/src/main/java/cheetatech/com/colorhub/adapters/YourColorAdapter.java | // Path: app/src/main/java/cheetatech/com/colorhub/realm/RealmX.java
// public class RealmX {
//
// private static Realm realm;
//
// private static void getRealm(){
// try {
// realm = Realm.getDefaultInstance();
// }catch (Exception e){
// Log.e("TAG","Exception Exception " + e.getMessage());
// // RealmConfiguration config = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
// // realm = Realm.getInstance(config);
// }
// }
//
// public static Realm realm(){
// if(realm == null)
// getRealm();
// return realm;
// }
//
//
// public static void closeRealm(){
// if(realm != null){
// if(!realm.isClosed()){
// realm.close();
// }
// }
// }
//
//
// public static void save(final SavedObject object) {
// getRealm();
// realm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// realm.copyToRealm(object);
// //closeRealm();
// }
// });
// }
//
// public static void list(){
// getRealm();
// RealmResults<SavedObject> res = realm.where(SavedObject.class)
// .findAll();
//
// for (SavedObject s : res ) {
// Log.e("TAG", "list: " + s.getName() );
// for (Model m : s.getList() ) {
// Log.e("TAG", "list::: " + m.getColorCode() );
// }
// Log.e("TAG", "---------------------" );
// }
//
// //closeRealm();
// }
//
// public static RealmResults<SavedObject> getObject(){
// RealmResults<SavedObject> res = realm.where(SavedObject.class).findAll();
// return res;
// }
//
// public static SavedObject getObject(String name){
// SavedObject res = realm.where(SavedObject.class)
// .equalTo("name",name)
// .findFirst();
// return res;
// }
//
// public static void setList(final String name, List<Model> list){
// final RealmList<Model> realmList = new RealmList<>();
// realmList.addAll(list);
// realm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// SavedObject res = realm.where(SavedObject.class)
// .equalTo("name",name)
// .findFirst();
// res.setList(realmList);
// Log.e("TAG", "execute: execute" );
// }
// });
// }
//
// public static void deleteObject(final String name) {
//
// realm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// RealmResults<SavedObject> list = realm.where(SavedObject.class).equalTo("name",name).findAll();
// list.deleteAllFromRealm();
// }
// });
// }
// }
//
// Path: app/src/main/java/cheetatech/com/colorhub/realm/SavedObject.java
// public class SavedObject extends RealmObject {
//
// private String name;
// private RealmList<Model> list;
//
// public SavedObject(){}
//
// public SavedObject(String name, RealmList<Model> list){
// setName(name);
// setList(list);
// }
// public SavedObject(RealmList<Model> list){
// setList(list);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Model> getList() {
// return list;
// }
//
// public void addList(List<Model> lists){
// RealmX.realm().beginTransaction();
// this.list.clear();
// this.list.addAll(lists);
// RealmX.realm().commitTransaction();
// }
//
// public void setList(RealmList<Model> list) {
// this.list = list;
// }
//
// public void setNameQuery(String name){
// RealmX.realm().beginTransaction();
// this.name = name;
// RealmX.realm().commitTransaction();
// }
//
// }
| import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import cheetatech.com.colorhub.R;
import cheetatech.com.colorhub.models.Model;
import cheetatech.com.colorhub.realm.RealmX;
import cheetatech.com.colorhub.realm.SavedObject; | package cheetatech.com.colorhub.adapters;
/**
* Created by erkan on 21.03.2017.
*/
public class YourColorAdapter extends RecyclerView.Adapter<YourColorAdapter.ViewHolder>{
private int sayac = 0; | // Path: app/src/main/java/cheetatech/com/colorhub/realm/RealmX.java
// public class RealmX {
//
// private static Realm realm;
//
// private static void getRealm(){
// try {
// realm = Realm.getDefaultInstance();
// }catch (Exception e){
// Log.e("TAG","Exception Exception " + e.getMessage());
// // RealmConfiguration config = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
// // realm = Realm.getInstance(config);
// }
// }
//
// public static Realm realm(){
// if(realm == null)
// getRealm();
// return realm;
// }
//
//
// public static void closeRealm(){
// if(realm != null){
// if(!realm.isClosed()){
// realm.close();
// }
// }
// }
//
//
// public static void save(final SavedObject object) {
// getRealm();
// realm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// realm.copyToRealm(object);
// //closeRealm();
// }
// });
// }
//
// public static void list(){
// getRealm();
// RealmResults<SavedObject> res = realm.where(SavedObject.class)
// .findAll();
//
// for (SavedObject s : res ) {
// Log.e("TAG", "list: " + s.getName() );
// for (Model m : s.getList() ) {
// Log.e("TAG", "list::: " + m.getColorCode() );
// }
// Log.e("TAG", "---------------------" );
// }
//
// //closeRealm();
// }
//
// public static RealmResults<SavedObject> getObject(){
// RealmResults<SavedObject> res = realm.where(SavedObject.class).findAll();
// return res;
// }
//
// public static SavedObject getObject(String name){
// SavedObject res = realm.where(SavedObject.class)
// .equalTo("name",name)
// .findFirst();
// return res;
// }
//
// public static void setList(final String name, List<Model> list){
// final RealmList<Model> realmList = new RealmList<>();
// realmList.addAll(list);
// realm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// SavedObject res = realm.where(SavedObject.class)
// .equalTo("name",name)
// .findFirst();
// res.setList(realmList);
// Log.e("TAG", "execute: execute" );
// }
// });
// }
//
// public static void deleteObject(final String name) {
//
// realm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// RealmResults<SavedObject> list = realm.where(SavedObject.class).equalTo("name",name).findAll();
// list.deleteAllFromRealm();
// }
// });
// }
// }
//
// Path: app/src/main/java/cheetatech/com/colorhub/realm/SavedObject.java
// public class SavedObject extends RealmObject {
//
// private String name;
// private RealmList<Model> list;
//
// public SavedObject(){}
//
// public SavedObject(String name, RealmList<Model> list){
// setName(name);
// setList(list);
// }
// public SavedObject(RealmList<Model> list){
// setList(list);
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Model> getList() {
// return list;
// }
//
// public void addList(List<Model> lists){
// RealmX.realm().beginTransaction();
// this.list.clear();
// this.list.addAll(lists);
// RealmX.realm().commitTransaction();
// }
//
// public void setList(RealmList<Model> list) {
// this.list = list;
// }
//
// public void setNameQuery(String name){
// RealmX.realm().beginTransaction();
// this.name = name;
// RealmX.realm().commitTransaction();
// }
//
// }
// Path: app/src/main/java/cheetatech/com/colorhub/adapters/YourColorAdapter.java
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import cheetatech.com.colorhub.R;
import cheetatech.com.colorhub.models.Model;
import cheetatech.com.colorhub.realm.RealmX;
import cheetatech.com.colorhub.realm.SavedObject;
package cheetatech.com.colorhub.adapters;
/**
* Created by erkan on 21.03.2017.
*/
public class YourColorAdapter extends RecyclerView.Adapter<YourColorAdapter.ViewHolder>{
private int sayac = 0; | private List<SavedObject> mDataset; |
CheetaTech/ColorHub | app/src/main/java/cheetatech/com/colorhub/controller/ColorArrayController.java | // Path: app/src/main/java/cheetatech/com/colorhub/defines/MaterialColorInfo.java
// public class MaterialColorInfo {
// private List<ColorInfo> colorInfoList = new ArrayList<ColorInfo>();
//
// public MaterialColorInfo()
// {
// colorInfoList = new ArrayList<ColorInfo>();
// }
//
// public MaterialColorInfo(List<ColorInfo> colorInfos)
// {
// this.colorInfoList.addAll(colorInfos);
// }
// public List<ColorInfo> getColorInfoList()
// {
// return this.colorInfoList;
// }
// public ColorInfo getColorInfo(int index)
// {
// if(index > this.colorInfoList.size())
// return null;
// return this.colorInfoList.get(index);
// }
//
// public void setColorInfoList(List<ColorInfo> colorInfoList)
// {
// this.colorInfoList = colorInfoList;
// }
//
// }
| import android.content.res.Resources;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cheetatech.com.colorhub.R;
import cheetatech.com.colorhub.defines.ColorInfo;
import cheetatech.com.colorhub.defines.MaterialColorInfo;
import cheetatech.com.colorhub.drawer.ColorSelect; | package cheetatech.com.colorhub.controller;
public class ColorArrayController {
private List<ColorInfo> materialList = null;
private List<ColorInfo> flatList = null;
private List<ColorInfo> socialList = null;
private List<ColorInfo> metroList = null;
private List<ColorInfo> htmlList = null;
private String[] headerColorList = null;
| // Path: app/src/main/java/cheetatech/com/colorhub/defines/MaterialColorInfo.java
// public class MaterialColorInfo {
// private List<ColorInfo> colorInfoList = new ArrayList<ColorInfo>();
//
// public MaterialColorInfo()
// {
// colorInfoList = new ArrayList<ColorInfo>();
// }
//
// public MaterialColorInfo(List<ColorInfo> colorInfos)
// {
// this.colorInfoList.addAll(colorInfos);
// }
// public List<ColorInfo> getColorInfoList()
// {
// return this.colorInfoList;
// }
// public ColorInfo getColorInfo(int index)
// {
// if(index > this.colorInfoList.size())
// return null;
// return this.colorInfoList.get(index);
// }
//
// public void setColorInfoList(List<ColorInfo> colorInfoList)
// {
// this.colorInfoList = colorInfoList;
// }
//
// }
// Path: app/src/main/java/cheetatech/com/colorhub/controller/ColorArrayController.java
import android.content.res.Resources;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cheetatech.com.colorhub.R;
import cheetatech.com.colorhub.defines.ColorInfo;
import cheetatech.com.colorhub.defines.MaterialColorInfo;
import cheetatech.com.colorhub.drawer.ColorSelect;
package cheetatech.com.colorhub.controller;
public class ColorArrayController {
private List<ColorInfo> materialList = null;
private List<ColorInfo> flatList = null;
private List<ColorInfo> socialList = null;
private List<ColorInfo> metroList = null;
private List<ColorInfo> htmlList = null;
private String[] headerColorList = null;
| private List<MaterialColorInfo> materialColorInfoList = null; |
Omega-R/OmegaRecyclerView | omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/SwipeMenuLayout.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeFractionListener.java
// public interface SwipeFractionListener {
//
// void onSwipeMenuFraction(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction, float fraction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeSwitchListener.java
// public interface SwipeSwitchListener {
//
// void onSwipeMenuOpened(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// void onSwipeMenuClosed(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/swiper/Swiper.java
// public abstract class Swiper {
//
// protected static final int BEGIN_DIRECTION = 1;
// protected static final int END_DIRECTION = -1;
//
// private int direction;
// private View menuView;
// protected Checker mChecker;
//
// public Swiper(int direction, View menuView){
// this.direction = direction;
// this.menuView = menuView;
// mChecker = new Checker();
// }
//
// public abstract boolean isMenuOpen(final int scrollDis);
// public abstract boolean isMenuOpenNotEqual(final int scrollDis);
// public abstract void autoOpenMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract void autoCloseMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract Checker checkXY(int x, int y);
// public abstract boolean isClickOnContentView(View contentView, float clickPoint);
//
// public boolean isNotInPlace(final int scrollDis) {
// return scrollDis != 0;
// }
//
// public int getDirection() {
// return direction;
// }
//
// public View getMenuView() {
// return menuView;
// }
//
// public int getMenuWidth(){
// return getMenuView().getWidth();
// }
//
// public int getMenuHeight(){
// return getMenuView().getHeight();
// }
//
// public static final class Checker{
// public int x;
// public int y;
// public boolean shouldResetSwiper;
// }
//
// }
| import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.OverScroller;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeFractionListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeSwitchListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.swiper.Swiper; | package com.omega_r.libs.omegarecyclerview.swipe_menu;
public abstract class SwipeMenuLayout extends FrameLayout {
public static final int DEFAULT_SCROLLER_DURATION = 250;
public static final float DEFAULT_AUTO_OPEN_PERCENT = 0.5f;
protected float mAutoOpenPercent = DEFAULT_AUTO_OPEN_PERCENT;
protected int mScrollerDuration = DEFAULT_SCROLLER_DURATION;
protected int mScaledTouchSlop;
protected int mLastX;
protected int mLastY;
protected int mDownX;
protected int mDownY;
@Nullable
protected View mContentView;
@Nullable | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeFractionListener.java
// public interface SwipeFractionListener {
//
// void onSwipeMenuFraction(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction, float fraction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeSwitchListener.java
// public interface SwipeSwitchListener {
//
// void onSwipeMenuOpened(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// void onSwipeMenuClosed(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/swiper/Swiper.java
// public abstract class Swiper {
//
// protected static final int BEGIN_DIRECTION = 1;
// protected static final int END_DIRECTION = -1;
//
// private int direction;
// private View menuView;
// protected Checker mChecker;
//
// public Swiper(int direction, View menuView){
// this.direction = direction;
// this.menuView = menuView;
// mChecker = new Checker();
// }
//
// public abstract boolean isMenuOpen(final int scrollDis);
// public abstract boolean isMenuOpenNotEqual(final int scrollDis);
// public abstract void autoOpenMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract void autoCloseMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract Checker checkXY(int x, int y);
// public abstract boolean isClickOnContentView(View contentView, float clickPoint);
//
// public boolean isNotInPlace(final int scrollDis) {
// return scrollDis != 0;
// }
//
// public int getDirection() {
// return direction;
// }
//
// public View getMenuView() {
// return menuView;
// }
//
// public int getMenuWidth(){
// return getMenuView().getWidth();
// }
//
// public int getMenuHeight(){
// return getMenuView().getHeight();
// }
//
// public static final class Checker{
// public int x;
// public int y;
// public boolean shouldResetSwiper;
// }
//
// }
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/SwipeMenuLayout.java
import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.OverScroller;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeFractionListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeSwitchListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.swiper.Swiper;
package com.omega_r.libs.omegarecyclerview.swipe_menu;
public abstract class SwipeMenuLayout extends FrameLayout {
public static final int DEFAULT_SCROLLER_DURATION = 250;
public static final float DEFAULT_AUTO_OPEN_PERCENT = 0.5f;
protected float mAutoOpenPercent = DEFAULT_AUTO_OPEN_PERCENT;
protected int mScrollerDuration = DEFAULT_SCROLLER_DURATION;
protected int mScaledTouchSlop;
protected int mLastX;
protected int mLastY;
protected int mDownX;
protected int mDownY;
@Nullable
protected View mContentView;
@Nullable | protected Swiper mBeginSwiper; |
Omega-R/OmegaRecyclerView | omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/SwipeMenuLayout.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeFractionListener.java
// public interface SwipeFractionListener {
//
// void onSwipeMenuFraction(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction, float fraction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeSwitchListener.java
// public interface SwipeSwitchListener {
//
// void onSwipeMenuOpened(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// void onSwipeMenuClosed(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/swiper/Swiper.java
// public abstract class Swiper {
//
// protected static final int BEGIN_DIRECTION = 1;
// protected static final int END_DIRECTION = -1;
//
// private int direction;
// private View menuView;
// protected Checker mChecker;
//
// public Swiper(int direction, View menuView){
// this.direction = direction;
// this.menuView = menuView;
// mChecker = new Checker();
// }
//
// public abstract boolean isMenuOpen(final int scrollDis);
// public abstract boolean isMenuOpenNotEqual(final int scrollDis);
// public abstract void autoOpenMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract void autoCloseMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract Checker checkXY(int x, int y);
// public abstract boolean isClickOnContentView(View contentView, float clickPoint);
//
// public boolean isNotInPlace(final int scrollDis) {
// return scrollDis != 0;
// }
//
// public int getDirection() {
// return direction;
// }
//
// public View getMenuView() {
// return menuView;
// }
//
// public int getMenuWidth(){
// return getMenuView().getWidth();
// }
//
// public int getMenuHeight(){
// return getMenuView().getHeight();
// }
//
// public static final class Checker{
// public int x;
// public int y;
// public boolean shouldResetSwiper;
// }
//
// }
| import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.OverScroller;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeFractionListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeSwitchListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.swiper.Swiper; | package com.omega_r.libs.omegarecyclerview.swipe_menu;
public abstract class SwipeMenuLayout extends FrameLayout {
public static final int DEFAULT_SCROLLER_DURATION = 250;
public static final float DEFAULT_AUTO_OPEN_PERCENT = 0.5f;
protected float mAutoOpenPercent = DEFAULT_AUTO_OPEN_PERCENT;
protected int mScrollerDuration = DEFAULT_SCROLLER_DURATION;
protected int mScaledTouchSlop;
protected int mLastX;
protected int mLastY;
protected int mDownX;
protected int mDownY;
@Nullable
protected View mContentView;
@Nullable
protected Swiper mBeginSwiper;
@Nullable
protected Swiper mEndSwiper;
@Nullable
protected Swiper mCurrentSwiper;
protected boolean shouldResetSwiper;
protected boolean mDragging;
protected boolean swipeEnable = true;
protected OverScroller mScroller;
protected Interpolator mInterpolator;
protected VelocityTracker mVelocityTracker;
protected int mScaledMinimumFlingVelocity;
protected int mScaledMaximumFlingVelocity; | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeFractionListener.java
// public interface SwipeFractionListener {
//
// void onSwipeMenuFraction(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction, float fraction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeSwitchListener.java
// public interface SwipeSwitchListener {
//
// void onSwipeMenuOpened(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// void onSwipeMenuClosed(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/swiper/Swiper.java
// public abstract class Swiper {
//
// protected static final int BEGIN_DIRECTION = 1;
// protected static final int END_DIRECTION = -1;
//
// private int direction;
// private View menuView;
// protected Checker mChecker;
//
// public Swiper(int direction, View menuView){
// this.direction = direction;
// this.menuView = menuView;
// mChecker = new Checker();
// }
//
// public abstract boolean isMenuOpen(final int scrollDis);
// public abstract boolean isMenuOpenNotEqual(final int scrollDis);
// public abstract void autoOpenMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract void autoCloseMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract Checker checkXY(int x, int y);
// public abstract boolean isClickOnContentView(View contentView, float clickPoint);
//
// public boolean isNotInPlace(final int scrollDis) {
// return scrollDis != 0;
// }
//
// public int getDirection() {
// return direction;
// }
//
// public View getMenuView() {
// return menuView;
// }
//
// public int getMenuWidth(){
// return getMenuView().getWidth();
// }
//
// public int getMenuHeight(){
// return getMenuView().getHeight();
// }
//
// public static final class Checker{
// public int x;
// public int y;
// public boolean shouldResetSwiper;
// }
//
// }
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/SwipeMenuLayout.java
import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.OverScroller;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeFractionListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeSwitchListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.swiper.Swiper;
package com.omega_r.libs.omegarecyclerview.swipe_menu;
public abstract class SwipeMenuLayout extends FrameLayout {
public static final int DEFAULT_SCROLLER_DURATION = 250;
public static final float DEFAULT_AUTO_OPEN_PERCENT = 0.5f;
protected float mAutoOpenPercent = DEFAULT_AUTO_OPEN_PERCENT;
protected int mScrollerDuration = DEFAULT_SCROLLER_DURATION;
protected int mScaledTouchSlop;
protected int mLastX;
protected int mLastY;
protected int mDownX;
protected int mDownY;
@Nullable
protected View mContentView;
@Nullable
protected Swiper mBeginSwiper;
@Nullable
protected Swiper mEndSwiper;
@Nullable
protected Swiper mCurrentSwiper;
protected boolean shouldResetSwiper;
protected boolean mDragging;
protected boolean swipeEnable = true;
protected OverScroller mScroller;
protected Interpolator mInterpolator;
protected VelocityTracker mVelocityTracker;
protected int mScaledMinimumFlingVelocity;
protected int mScaledMaximumFlingVelocity; | protected SwipeSwitchListener mSwipeSwitchListener; |
Omega-R/OmegaRecyclerView | omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/SwipeMenuLayout.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeFractionListener.java
// public interface SwipeFractionListener {
//
// void onSwipeMenuFraction(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction, float fraction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeSwitchListener.java
// public interface SwipeSwitchListener {
//
// void onSwipeMenuOpened(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// void onSwipeMenuClosed(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/swiper/Swiper.java
// public abstract class Swiper {
//
// protected static final int BEGIN_DIRECTION = 1;
// protected static final int END_DIRECTION = -1;
//
// private int direction;
// private View menuView;
// protected Checker mChecker;
//
// public Swiper(int direction, View menuView){
// this.direction = direction;
// this.menuView = menuView;
// mChecker = new Checker();
// }
//
// public abstract boolean isMenuOpen(final int scrollDis);
// public abstract boolean isMenuOpenNotEqual(final int scrollDis);
// public abstract void autoOpenMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract void autoCloseMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract Checker checkXY(int x, int y);
// public abstract boolean isClickOnContentView(View contentView, float clickPoint);
//
// public boolean isNotInPlace(final int scrollDis) {
// return scrollDis != 0;
// }
//
// public int getDirection() {
// return direction;
// }
//
// public View getMenuView() {
// return menuView;
// }
//
// public int getMenuWidth(){
// return getMenuView().getWidth();
// }
//
// public int getMenuHeight(){
// return getMenuView().getHeight();
// }
//
// public static final class Checker{
// public int x;
// public int y;
// public boolean shouldResetSwiper;
// }
//
// }
| import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.OverScroller;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeFractionListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeSwitchListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.swiper.Swiper; | package com.omega_r.libs.omegarecyclerview.swipe_menu;
public abstract class SwipeMenuLayout extends FrameLayout {
public static final int DEFAULT_SCROLLER_DURATION = 250;
public static final float DEFAULT_AUTO_OPEN_PERCENT = 0.5f;
protected float mAutoOpenPercent = DEFAULT_AUTO_OPEN_PERCENT;
protected int mScrollerDuration = DEFAULT_SCROLLER_DURATION;
protected int mScaledTouchSlop;
protected int mLastX;
protected int mLastY;
protected int mDownX;
protected int mDownY;
@Nullable
protected View mContentView;
@Nullable
protected Swiper mBeginSwiper;
@Nullable
protected Swiper mEndSwiper;
@Nullable
protected Swiper mCurrentSwiper;
protected boolean shouldResetSwiper;
protected boolean mDragging;
protected boolean swipeEnable = true;
protected OverScroller mScroller;
protected Interpolator mInterpolator;
protected VelocityTracker mVelocityTracker;
protected int mScaledMinimumFlingVelocity;
protected int mScaledMaximumFlingVelocity;
protected SwipeSwitchListener mSwipeSwitchListener; | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeFractionListener.java
// public interface SwipeFractionListener {
//
// void onSwipeMenuFraction(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction, float fraction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/listener/SwipeSwitchListener.java
// public interface SwipeSwitchListener {
//
// void onSwipeMenuOpened(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// void onSwipeMenuClosed(SwipeMenuLayout swipeMenuLayout, SwipeDirection direction);
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/swiper/Swiper.java
// public abstract class Swiper {
//
// protected static final int BEGIN_DIRECTION = 1;
// protected static final int END_DIRECTION = -1;
//
// private int direction;
// private View menuView;
// protected Checker mChecker;
//
// public Swiper(int direction, View menuView){
// this.direction = direction;
// this.menuView = menuView;
// mChecker = new Checker();
// }
//
// public abstract boolean isMenuOpen(final int scrollDis);
// public abstract boolean isMenuOpenNotEqual(final int scrollDis);
// public abstract void autoOpenMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract void autoCloseMenu(OverScroller scroller, int scrollDis, int duration);
// public abstract Checker checkXY(int x, int y);
// public abstract boolean isClickOnContentView(View contentView, float clickPoint);
//
// public boolean isNotInPlace(final int scrollDis) {
// return scrollDis != 0;
// }
//
// public int getDirection() {
// return direction;
// }
//
// public View getMenuView() {
// return menuView;
// }
//
// public int getMenuWidth(){
// return getMenuView().getWidth();
// }
//
// public int getMenuHeight(){
// return getMenuView().getHeight();
// }
//
// public static final class Checker{
// public int x;
// public int y;
// public boolean shouldResetSwiper;
// }
//
// }
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/swipe_menu/SwipeMenuLayout.java
import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.OverScroller;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeFractionListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.listener.SwipeSwitchListener;
import com.omega_r.libs.omegarecyclerview.swipe_menu.swiper.Swiper;
package com.omega_r.libs.omegarecyclerview.swipe_menu;
public abstract class SwipeMenuLayout extends FrameLayout {
public static final int DEFAULT_SCROLLER_DURATION = 250;
public static final float DEFAULT_AUTO_OPEN_PERCENT = 0.5f;
protected float mAutoOpenPercent = DEFAULT_AUTO_OPEN_PERCENT;
protected int mScrollerDuration = DEFAULT_SCROLLER_DURATION;
protected int mScaledTouchSlop;
protected int mLastX;
protected int mLastY;
protected int mDownX;
protected int mDownY;
@Nullable
protected View mContentView;
@Nullable
protected Swiper mBeginSwiper;
@Nullable
protected Swiper mEndSwiper;
@Nullable
protected Swiper mCurrentSwiper;
protected boolean shouldResetSwiper;
protected boolean mDragging;
protected boolean swipeEnable = true;
protected OverScroller mScroller;
protected Interpolator mInterpolator;
protected VelocityTracker mVelocityTracker;
protected int mScaledMinimumFlingVelocity;
protected int mScaledMaximumFlingVelocity;
protected SwipeSwitchListener mSwipeSwitchListener; | protected SwipeFractionListener mSwipeFractionListener; |
Omega-R/OmegaRecyclerView | omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/StickyDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
| import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.util.HashMap;
import java.util.Map;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout;
import static java.lang.Math.abs; | float eventY = ev.getY();
if (abs(mActionDownX - eventX) <= CLICK_MOVE_BIAS && abs(mActionDownY - eventY) <= CLICK_MOVE_BIAS) {
mStickyAdapter.onClickStickyViewHolder(mClickedStickyId);
}
}
break;
}
return super.onTouchEvent(parent, ev, defaultResult);
}
private boolean handleActionDown(@NonNull RecyclerView parent, @NonNull final MotionEvent ev, boolean defaultResult) {
int eventX = (int) ev.getX();
int eventY = (int) ev.getY();
for (Long stickyId : mStickyRectMap.keySet()) {
Rect rect = mStickyRectMap.get(stickyId);
if (stickyId != NO_STICKY_ID && rect != null && !rect.isEmpty() && rect.contains(eventX, eventY)) {
mClickedStickyId = stickyId;
return true;
}
}
return defaultResult;
}
@Override
public final void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.onDrawOver(canvas, parent, state);
invalidateRectMap();
int count = parent.getChildCount();
long previousStickerId = -1; | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/StickyDecoration.java
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.util.HashMap;
import java.util.Map;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout;
import static java.lang.Math.abs;
float eventY = ev.getY();
if (abs(mActionDownX - eventX) <= CLICK_MOVE_BIAS && abs(mActionDownY - eventY) <= CLICK_MOVE_BIAS) {
mStickyAdapter.onClickStickyViewHolder(mClickedStickyId);
}
}
break;
}
return super.onTouchEvent(parent, ev, defaultResult);
}
private boolean handleActionDown(@NonNull RecyclerView parent, @NonNull final MotionEvent ev, boolean defaultResult) {
int eventX = (int) ev.getX();
int eventY = (int) ev.getY();
for (Long stickyId : mStickyRectMap.keySet()) {
Rect rect = mStickyRectMap.get(stickyId);
if (stickyId != NO_STICKY_ID && rect != null && !rect.isEmpty() && rect.contains(eventX, eventY)) {
mClickedStickyId = stickyId;
return true;
}
}
return defaultResult;
}
@Override
public final void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.onDrawOver(canvas, parent, state);
invalidateRectMap();
int count = parent.getChildCount();
long previousStickerId = -1; | if (isReverseLayout(parent)) { |
Omega-R/OmegaRecyclerView | omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/BaseSpaceItemDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/decoration_helpers/DividerDecorationHelper.java
// @SuppressWarnings("StaticInitializerReferencesSubClass")
// public abstract class DividerDecorationHelper {
//
// DividerDecorationHelper() {
// // nothing
// }
//
// private static final NormalVerticalDividerDecorationHelper sNormalVerticalDividerDecorationHelper = new NormalVerticalDividerDecorationHelper();
// private static final ReverseVerticalDividerDecorationHelper sReverseVerticalDividerDecorationHelper = new ReverseVerticalDividerDecorationHelper();
// private static final NormalHorizontalDividerDecorationHelper sNormalHorizontalDividerDecorationHelper = new NormalHorizontalDividerDecorationHelper();
// private static final ReverseHorizontalDividerDecorationHelper sReverseHorizontalDividerDecorationHelper = new ReverseHorizontalDividerDecorationHelper();
//
// @NonNull
// public static DividerDecorationHelper getHelper(int orientation, RecyclerView parent) {
// if (!(parent.getLayoutManager() instanceof LinearLayoutManager)) {
// return sNormalVerticalDividerDecorationHelper;
// }
// LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
// boolean isReversed = layoutManager.getReverseLayout();
//
// switch (orientation) {
// default:
// case Orientation.VERTICAL:
// if (isReversed) return sReverseVerticalDividerDecorationHelper;
// return sNormalVerticalDividerDecorationHelper;
// case Orientation.HORIZONTAL:
// if (isReversed) return sReverseHorizontalDividerDecorationHelper;
// return sNormalHorizontalDividerDecorationHelper;
// }
// }
//
// public abstract void setStart(Rect rect, int start);
//
// public abstract void setEnd(Rect rect, int end);
//
// public abstract int getStart(Rect rect);
//
// public abstract int getEnd(Rect rect);
//
// public abstract void setOtherStart(Rect rect, int start);
//
// public abstract void setOtherEnd(Rect rect, int end);
//
// public abstract int getOtherStart(Rect rect);
//
// public abstract int getOtherEnd(Rect rect);
//
// public int getOffset(int offset) {
// return offset;
// }
//
// }
| import android.graphics.Rect;
import com.omega_r.libs.omegarecyclerview.item_decoration.decoration_helpers.DividerDecorationHelper;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView; | package com.omega_r.libs.omegarecyclerview.item_decoration;
public class BaseSpaceItemDecoration extends BaseItemDecoration {
private final int mItemSpace;
public BaseSpaceItemDecoration(int showDivider, int space) {
super(showDivider);
mItemSpace = space;
}
@Override
void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent, | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/decoration_helpers/DividerDecorationHelper.java
// @SuppressWarnings("StaticInitializerReferencesSubClass")
// public abstract class DividerDecorationHelper {
//
// DividerDecorationHelper() {
// // nothing
// }
//
// private static final NormalVerticalDividerDecorationHelper sNormalVerticalDividerDecorationHelper = new NormalVerticalDividerDecorationHelper();
// private static final ReverseVerticalDividerDecorationHelper sReverseVerticalDividerDecorationHelper = new ReverseVerticalDividerDecorationHelper();
// private static final NormalHorizontalDividerDecorationHelper sNormalHorizontalDividerDecorationHelper = new NormalHorizontalDividerDecorationHelper();
// private static final ReverseHorizontalDividerDecorationHelper sReverseHorizontalDividerDecorationHelper = new ReverseHorizontalDividerDecorationHelper();
//
// @NonNull
// public static DividerDecorationHelper getHelper(int orientation, RecyclerView parent) {
// if (!(parent.getLayoutManager() instanceof LinearLayoutManager)) {
// return sNormalVerticalDividerDecorationHelper;
// }
// LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
// boolean isReversed = layoutManager.getReverseLayout();
//
// switch (orientation) {
// default:
// case Orientation.VERTICAL:
// if (isReversed) return sReverseVerticalDividerDecorationHelper;
// return sNormalVerticalDividerDecorationHelper;
// case Orientation.HORIZONTAL:
// if (isReversed) return sReverseHorizontalDividerDecorationHelper;
// return sNormalHorizontalDividerDecorationHelper;
// }
// }
//
// public abstract void setStart(Rect rect, int start);
//
// public abstract void setEnd(Rect rect, int end);
//
// public abstract int getStart(Rect rect);
//
// public abstract int getEnd(Rect rect);
//
// public abstract void setOtherStart(Rect rect, int start);
//
// public abstract void setOtherEnd(Rect rect, int end);
//
// public abstract int getOtherStart(Rect rect);
//
// public abstract int getOtherEnd(Rect rect);
//
// public int getOffset(int offset) {
// return offset;
// }
//
// }
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/BaseSpaceItemDecoration.java
import android.graphics.Rect;
import com.omega_r.libs.omegarecyclerview.item_decoration.decoration_helpers.DividerDecorationHelper;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
package com.omega_r.libs.omegarecyclerview.item_decoration;
public class BaseSpaceItemDecoration extends BaseItemDecoration {
private final int mItemSpace;
public BaseSpaceItemDecoration(int showDivider, int space) {
super(showDivider);
mItemSpace = space;
}
@Override
void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent, | @NonNull DividerDecorationHelper helper, int position, int itemCount) { |
Omega-R/OmegaRecyclerView | omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableSpaceItemDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/BaseSpaceItemDecoration.java
// public class BaseSpaceItemDecoration extends BaseItemDecoration {
//
// private final int mItemSpace;
//
// public BaseSpaceItemDecoration(int showDivider, int space) {
// super(showDivider);
// mItemSpace = space;
// }
//
// @Override
// void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent,
// @NonNull DividerDecorationHelper helper, int position, int itemCount) {
// int countBeginEndPositions = getCountBeginEndPositions(parent);
// int itemSpace = getItemSpace(parent, position, itemCount);
//
// if (isShowBeginDivider() || countBeginEndPositions <= position) helper.setStart(outRect, itemSpace);
// if (isShowEndDivider() && position == itemCount - countBeginEndPositions) helper.setEnd(outRect, itemSpace);
//
// if (countBeginEndPositions > 1) {
// if (position % countBeginEndPositions != 0 || isShowBeginDivider()) helper.setOtherStart(outRect, itemSpace);
// if (position / (countBeginEndPositions - 1) > 0 && isShowEndDivider()) helper.setOtherEnd(outRect, itemSpace);
// }
// }
//
// protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
// return mItemSpace;
// }
//
// private int getCountBeginEndPositions(RecyclerView recyclerView) {
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager instanceof GridLayoutManager) {
// return ((GridLayoutManager) layoutManager).getSpanCount();
// } else return 1;
// }
//
// }
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_CHILD = 238957;
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_GROUP = 238956;
| import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.item_decoration.BaseSpaceItemDecoration;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_CHILD;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_GROUP; | package com.omega_r.libs.omegarecyclerview_expandable;
@SuppressWarnings("rawtypes")
public class ExpandableSpaceItemDecoration extends BaseSpaceItemDecoration {
private int mGroupItemSpace = 0;
public ExpandableSpaceItemDecoration(int showDivider, int itemSpace) {
super(showDivider, itemSpace);
}
public void setGroupSpace(int groupSpace) {
mGroupItemSpace = groupSpace;
}
@Override
protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter == null) return super.getItemSpace(parent, position, itemCount);
int viewType = adapter.getItemViewType(position);
switch (viewType) { | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/BaseSpaceItemDecoration.java
// public class BaseSpaceItemDecoration extends BaseItemDecoration {
//
// private final int mItemSpace;
//
// public BaseSpaceItemDecoration(int showDivider, int space) {
// super(showDivider);
// mItemSpace = space;
// }
//
// @Override
// void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent,
// @NonNull DividerDecorationHelper helper, int position, int itemCount) {
// int countBeginEndPositions = getCountBeginEndPositions(parent);
// int itemSpace = getItemSpace(parent, position, itemCount);
//
// if (isShowBeginDivider() || countBeginEndPositions <= position) helper.setStart(outRect, itemSpace);
// if (isShowEndDivider() && position == itemCount - countBeginEndPositions) helper.setEnd(outRect, itemSpace);
//
// if (countBeginEndPositions > 1) {
// if (position % countBeginEndPositions != 0 || isShowBeginDivider()) helper.setOtherStart(outRect, itemSpace);
// if (position / (countBeginEndPositions - 1) > 0 && isShowEndDivider()) helper.setOtherEnd(outRect, itemSpace);
// }
// }
//
// protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
// return mItemSpace;
// }
//
// private int getCountBeginEndPositions(RecyclerView recyclerView) {
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager instanceof GridLayoutManager) {
// return ((GridLayoutManager) layoutManager).getSpanCount();
// } else return 1;
// }
//
// }
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_CHILD = 238957;
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_GROUP = 238956;
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableSpaceItemDecoration.java
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.item_decoration.BaseSpaceItemDecoration;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_CHILD;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_GROUP;
package com.omega_r.libs.omegarecyclerview_expandable;
@SuppressWarnings("rawtypes")
public class ExpandableSpaceItemDecoration extends BaseSpaceItemDecoration {
private int mGroupItemSpace = 0;
public ExpandableSpaceItemDecoration(int showDivider, int itemSpace) {
super(showDivider, itemSpace);
}
public void setGroupSpace(int groupSpace) {
mGroupItemSpace = groupSpace;
}
@Override
protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter == null) return super.getItemSpace(parent, position, itemCount);
int viewType = adapter.getItemViewType(position);
switch (viewType) { | case VH_TYPE_GROUP: |
Omega-R/OmegaRecyclerView | omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableSpaceItemDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/BaseSpaceItemDecoration.java
// public class BaseSpaceItemDecoration extends BaseItemDecoration {
//
// private final int mItemSpace;
//
// public BaseSpaceItemDecoration(int showDivider, int space) {
// super(showDivider);
// mItemSpace = space;
// }
//
// @Override
// void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent,
// @NonNull DividerDecorationHelper helper, int position, int itemCount) {
// int countBeginEndPositions = getCountBeginEndPositions(parent);
// int itemSpace = getItemSpace(parent, position, itemCount);
//
// if (isShowBeginDivider() || countBeginEndPositions <= position) helper.setStart(outRect, itemSpace);
// if (isShowEndDivider() && position == itemCount - countBeginEndPositions) helper.setEnd(outRect, itemSpace);
//
// if (countBeginEndPositions > 1) {
// if (position % countBeginEndPositions != 0 || isShowBeginDivider()) helper.setOtherStart(outRect, itemSpace);
// if (position / (countBeginEndPositions - 1) > 0 && isShowEndDivider()) helper.setOtherEnd(outRect, itemSpace);
// }
// }
//
// protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
// return mItemSpace;
// }
//
// private int getCountBeginEndPositions(RecyclerView recyclerView) {
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager instanceof GridLayoutManager) {
// return ((GridLayoutManager) layoutManager).getSpanCount();
// } else return 1;
// }
//
// }
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_CHILD = 238957;
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_GROUP = 238956;
| import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.item_decoration.BaseSpaceItemDecoration;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_CHILD;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_GROUP; | package com.omega_r.libs.omegarecyclerview_expandable;
@SuppressWarnings("rawtypes")
public class ExpandableSpaceItemDecoration extends BaseSpaceItemDecoration {
private int mGroupItemSpace = 0;
public ExpandableSpaceItemDecoration(int showDivider, int itemSpace) {
super(showDivider, itemSpace);
}
public void setGroupSpace(int groupSpace) {
mGroupItemSpace = groupSpace;
}
@Override
protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter == null) return super.getItemSpace(parent, position, itemCount);
int viewType = adapter.getItemViewType(position);
switch (viewType) {
case VH_TYPE_GROUP:
return mGroupItemSpace; | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/item_decoration/BaseSpaceItemDecoration.java
// public class BaseSpaceItemDecoration extends BaseItemDecoration {
//
// private final int mItemSpace;
//
// public BaseSpaceItemDecoration(int showDivider, int space) {
// super(showDivider);
// mItemSpace = space;
// }
//
// @Override
// void getItemOffset(@NonNull Rect outRect, @NonNull RecyclerView parent,
// @NonNull DividerDecorationHelper helper, int position, int itemCount) {
// int countBeginEndPositions = getCountBeginEndPositions(parent);
// int itemSpace = getItemSpace(parent, position, itemCount);
//
// if (isShowBeginDivider() || countBeginEndPositions <= position) helper.setStart(outRect, itemSpace);
// if (isShowEndDivider() && position == itemCount - countBeginEndPositions) helper.setEnd(outRect, itemSpace);
//
// if (countBeginEndPositions > 1) {
// if (position % countBeginEndPositions != 0 || isShowBeginDivider()) helper.setOtherStart(outRect, itemSpace);
// if (position / (countBeginEndPositions - 1) > 0 && isShowEndDivider()) helper.setOtherEnd(outRect, itemSpace);
// }
// }
//
// protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
// return mItemSpace;
// }
//
// private int getCountBeginEndPositions(RecyclerView recyclerView) {
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager instanceof GridLayoutManager) {
// return ((GridLayoutManager) layoutManager).getSpanCount();
// } else return 1;
// }
//
// }
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_CHILD = 238957;
//
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/OmegaExpandableRecyclerView.java
// static final int VH_TYPE_GROUP = 238956;
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableSpaceItemDecoration.java
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.item_decoration.BaseSpaceItemDecoration;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_CHILD;
import static com.omega_r.libs.omegarecyclerview_expandable.OmegaExpandableRecyclerView.Adapter.VH_TYPE_GROUP;
package com.omega_r.libs.omegarecyclerview_expandable;
@SuppressWarnings("rawtypes")
public class ExpandableSpaceItemDecoration extends BaseSpaceItemDecoration {
private int mGroupItemSpace = 0;
public ExpandableSpaceItemDecoration(int showDivider, int itemSpace) {
super(showDivider, itemSpace);
}
public void setGroupSpace(int groupSpace) {
mGroupItemSpace = groupSpace;
}
@Override
protected int getItemSpace(@NonNull RecyclerView parent, int position, int itemCount) {
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter == null) return super.getItemSpace(parent, position, itemCount);
int viewType = adapter.getItemViewType(position);
switch (viewType) {
case VH_TYPE_GROUP:
return mGroupItemSpace; | case VH_TYPE_CHILD: |
Omega-R/OmegaRecyclerView | omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableStickyDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/BaseStickyDecoration.java
// @SuppressWarnings("rawtypes")
// public abstract class BaseStickyDecoration extends RecyclerView.ItemDecoration {
//
// public static final long NO_STICKY_ID = -1L;
//
// @Nullable
// protected StickyAdapter mStickyAdapter;
// protected int mItemSpace;
//
// public BaseStickyDecoration(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public boolean onTouchEvent(@NonNull RecyclerView parent, @NonNull MotionEvent ev, boolean defaultResult) {
// return defaultResult;
// }
//
// @CallSuper
// public final void setStickyAdapter(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public final void setItemSpace(int itemSpace) {
// mItemSpace = itemSpace;
// }
//
// protected final boolean hasSticker(int position) {
// return mStickyAdapter != null && mStickyAdapter.getStickyId(position) != NO_STICKY_ID;
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/StickyAdapter.java
// public interface StickyAdapter<T extends RecyclerView.ViewHolder> {
//
// long getStickyId(int position);
//
// T onCreateStickyViewHolder(ViewGroup parent);
//
// void onBindStickyViewHolder(T viewHolder, int position);
//
// void onClickStickyViewHolder(long id);
//
// interface Mode {
//
// int HEADER = 0;
// int MIDDLE = 1;
//
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
| import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.BaseStickyDecoration;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.StickyAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout; | package com.omega_r.libs.omegarecyclerview_expandable;
public class ExpandableStickyDecoration extends BaseStickyDecoration {
private static final int OFFSET_NOT_FOUND = Integer.MIN_VALUE;
private final Rect mViewRect = new Rect();
@Nullable
private OmegaExpandableRecyclerView.Adapter mExpandableAdapter;
private final Map<Long, OmegaExpandableRecyclerView.BaseViewHolder> mGroupHeaderHolders = new HashMap<>();
private final Map<Long, RecyclerView.ViewHolder> mStickyHeaderHolders = new HashMap<>();
private final DrawingInfo mDrawingInfo = new DrawingInfo();
private final SparseArray<Pair<Integer, View>> mRecyclerViewItemsByAdapterPosition = new SparseArray<>();
private final List<Integer> mAdapterPositions = new ArrayList<>();
| // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/BaseStickyDecoration.java
// @SuppressWarnings("rawtypes")
// public abstract class BaseStickyDecoration extends RecyclerView.ItemDecoration {
//
// public static final long NO_STICKY_ID = -1L;
//
// @Nullable
// protected StickyAdapter mStickyAdapter;
// protected int mItemSpace;
//
// public BaseStickyDecoration(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public boolean onTouchEvent(@NonNull RecyclerView parent, @NonNull MotionEvent ev, boolean defaultResult) {
// return defaultResult;
// }
//
// @CallSuper
// public final void setStickyAdapter(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public final void setItemSpace(int itemSpace) {
// mItemSpace = itemSpace;
// }
//
// protected final boolean hasSticker(int position) {
// return mStickyAdapter != null && mStickyAdapter.getStickyId(position) != NO_STICKY_ID;
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/StickyAdapter.java
// public interface StickyAdapter<T extends RecyclerView.ViewHolder> {
//
// long getStickyId(int position);
//
// T onCreateStickyViewHolder(ViewGroup parent);
//
// void onBindStickyViewHolder(T viewHolder, int position);
//
// void onClickStickyViewHolder(long id);
//
// interface Mode {
//
// int HEADER = 0;
// int MIDDLE = 1;
//
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableStickyDecoration.java
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.BaseStickyDecoration;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.StickyAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout;
package com.omega_r.libs.omegarecyclerview_expandable;
public class ExpandableStickyDecoration extends BaseStickyDecoration {
private static final int OFFSET_NOT_FOUND = Integer.MIN_VALUE;
private final Rect mViewRect = new Rect();
@Nullable
private OmegaExpandableRecyclerView.Adapter mExpandableAdapter;
private final Map<Long, OmegaExpandableRecyclerView.BaseViewHolder> mGroupHeaderHolders = new HashMap<>();
private final Map<Long, RecyclerView.ViewHolder> mStickyHeaderHolders = new HashMap<>();
private final DrawingInfo mDrawingInfo = new DrawingInfo();
private final SparseArray<Pair<Integer, View>> mRecyclerViewItemsByAdapterPosition = new SparseArray<>();
private final List<Integer> mAdapterPositions = new ArrayList<>();
| ExpandableStickyDecoration(@Nullable StickyAdapter adapter, |
Omega-R/OmegaRecyclerView | omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableStickyDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/BaseStickyDecoration.java
// @SuppressWarnings("rawtypes")
// public abstract class BaseStickyDecoration extends RecyclerView.ItemDecoration {
//
// public static final long NO_STICKY_ID = -1L;
//
// @Nullable
// protected StickyAdapter mStickyAdapter;
// protected int mItemSpace;
//
// public BaseStickyDecoration(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public boolean onTouchEvent(@NonNull RecyclerView parent, @NonNull MotionEvent ev, boolean defaultResult) {
// return defaultResult;
// }
//
// @CallSuper
// public final void setStickyAdapter(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public final void setItemSpace(int itemSpace) {
// mItemSpace = itemSpace;
// }
//
// protected final boolean hasSticker(int position) {
// return mStickyAdapter != null && mStickyAdapter.getStickyId(position) != NO_STICKY_ID;
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/StickyAdapter.java
// public interface StickyAdapter<T extends RecyclerView.ViewHolder> {
//
// long getStickyId(int position);
//
// T onCreateStickyViewHolder(ViewGroup parent);
//
// void onBindStickyViewHolder(T viewHolder, int position);
//
// void onClickStickyViewHolder(long id);
//
// interface Mode {
//
// int HEADER = 0;
// int MIDDLE = 1;
//
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
| import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.BaseStickyDecoration;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.StickyAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout; |
private final DrawingInfo mDrawingInfo = new DrawingInfo();
private final SparseArray<Pair<Integer, View>> mRecyclerViewItemsByAdapterPosition = new SparseArray<>();
private final List<Integer> mAdapterPositions = new ArrayList<>();
ExpandableStickyDecoration(@Nullable StickyAdapter adapter,
@Nullable OmegaExpandableRecyclerView.Adapter expandableAdapter) {
super(adapter);
mExpandableAdapter = expandableAdapter;
}
void setExpandableAdapter(@Nullable OmegaExpandableRecyclerView.Adapter adapter) {
mExpandableAdapter = adapter;
}
@Override
public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
mDrawingInfo.reset();
mRecyclerViewItemsByAdapterPosition.clear();
mAdapterPositions.clear();
for (int layoutPos = 0; layoutPos < parent.getChildCount(); layoutPos++) {
View child = parent.getChildAt(layoutPos);
int adapterPosition = parent.getChildAdapterPosition(child);
mRecyclerViewItemsByAdapterPosition.put(adapterPosition, Pair.create(layoutPos, child));
mAdapterPositions.add(adapterPosition);
}
Collections.sort(mAdapterPositions);
| // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/BaseStickyDecoration.java
// @SuppressWarnings("rawtypes")
// public abstract class BaseStickyDecoration extends RecyclerView.ItemDecoration {
//
// public static final long NO_STICKY_ID = -1L;
//
// @Nullable
// protected StickyAdapter mStickyAdapter;
// protected int mItemSpace;
//
// public BaseStickyDecoration(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public boolean onTouchEvent(@NonNull RecyclerView parent, @NonNull MotionEvent ev, boolean defaultResult) {
// return defaultResult;
// }
//
// @CallSuper
// public final void setStickyAdapter(@Nullable StickyAdapter adapter) {
// mStickyAdapter = adapter;
// }
//
// public final void setItemSpace(int itemSpace) {
// mItemSpace = itemSpace;
// }
//
// protected final boolean hasSticker(int position) {
// return mStickyAdapter != null && mStickyAdapter.getStickyId(position) != NO_STICKY_ID;
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/StickyAdapter.java
// public interface StickyAdapter<T extends RecyclerView.ViewHolder> {
//
// long getStickyId(int position);
//
// T onCreateStickyViewHolder(ViewGroup parent);
//
// void onBindStickyViewHolder(T viewHolder, int position);
//
// void onClickStickyViewHolder(long id);
//
// interface Mode {
//
// int HEADER = 0;
// int MIDDLE = 1;
//
// }
//
// }
//
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
// Path: omegarecyclerview_expandable/src/main/java/com/omega_r/libs/omegarecyclerview_expandable/ExpandableStickyDecoration.java
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.BaseStickyDecoration;
import com.omega_r.libs.omegarecyclerview.sticky_decoration.StickyAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout;
private final DrawingInfo mDrawingInfo = new DrawingInfo();
private final SparseArray<Pair<Integer, View>> mRecyclerViewItemsByAdapterPosition = new SparseArray<>();
private final List<Integer> mAdapterPositions = new ArrayList<>();
ExpandableStickyDecoration(@Nullable StickyAdapter adapter,
@Nullable OmegaExpandableRecyclerView.Adapter expandableAdapter) {
super(adapter);
mExpandableAdapter = expandableAdapter;
}
void setExpandableAdapter(@Nullable OmegaExpandableRecyclerView.Adapter adapter) {
mExpandableAdapter = adapter;
}
@Override
public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
mDrawingInfo.reset();
mRecyclerViewItemsByAdapterPosition.clear();
mAdapterPositions.clear();
for (int layoutPos = 0; layoutPos < parent.getChildCount(); layoutPos++) {
View child = parent.getChildAt(layoutPos);
int adapterPosition = parent.getChildAdapterPosition(child);
mRecyclerViewItemsByAdapterPosition.put(adapterPosition, Pair.create(layoutPos, child));
mAdapterPositions.add(adapterPosition);
}
Collections.sort(mAdapterPositions);
| if (isReverseLayout(parent)) { |
Omega-R/OmegaRecyclerView | app/src/main/java/com/omega_r/omegarecyclerview/MainActivity.java | // Path: app/src/main/java/com/omega_r/omegarecyclerview/fastscroll_example/FastScrollActivity.java
// public class FastScrollActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_fastscroll);
// RecyclerView recyclerView = findViewById(R.id.recyclerview);
// recyclerView.setAdapter(new FastScrollAdapter());
// }
//
// }
| import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import com.omega_r.libs.omegaintentbuilder.AppOmegaIntentBuilder;
import com.omega_r.libs.omegaintentbuilder.OmegaIntentBuilder;
import com.omega_r.omegarecyclerview.fastscroll_example.FastScrollActivity; | .appActivities()
.paginationActivity()
.startActivity();
break;
case R.id.button_sections:
AppOmegaIntentBuilder.from(this)
.appActivities()
.sectionsActivity()
.startActivity();
break;
case R.id.button_viewpager:
AppOmegaIntentBuilder.from(this)
.appActivities()
.viewPagerActivity()
.startActivity();
break;
case R.id.button_list_adapter:
AppOmegaIntentBuilder.from(this)
.appActivities()
.listAdapterActivity()
.startActivity();
break;
case R.id.button_expandable_recyclerview:
AppOmegaIntentBuilder.from(this)
.appActivities()
.chooseExpandableActivity()
.startActivity();
break;
case R.id.button_fastscroll:
OmegaIntentBuilder.from(this) | // Path: app/src/main/java/com/omega_r/omegarecyclerview/fastscroll_example/FastScrollActivity.java
// public class FastScrollActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_fastscroll);
// RecyclerView recyclerView = findViewById(R.id.recyclerview);
// recyclerView.setAdapter(new FastScrollAdapter());
// }
//
// }
// Path: app/src/main/java/com/omega_r/omegarecyclerview/MainActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import com.omega_r.libs.omegaintentbuilder.AppOmegaIntentBuilder;
import com.omega_r.libs.omegaintentbuilder.OmegaIntentBuilder;
import com.omega_r.omegarecyclerview.fastscroll_example.FastScrollActivity;
.appActivities()
.paginationActivity()
.startActivity();
break;
case R.id.button_sections:
AppOmegaIntentBuilder.from(this)
.appActivities()
.sectionsActivity()
.startActivity();
break;
case R.id.button_viewpager:
AppOmegaIntentBuilder.from(this)
.appActivities()
.viewPagerActivity()
.startActivity();
break;
case R.id.button_list_adapter:
AppOmegaIntentBuilder.from(this)
.appActivities()
.listAdapterActivity()
.startActivity();
break;
case R.id.button_expandable_recyclerview:
AppOmegaIntentBuilder.from(this)
.appActivities()
.chooseExpandableActivity()
.startActivity();
break;
case R.id.button_fastscroll:
OmegaIntentBuilder.from(this) | .activity(FastScrollActivity.class) |
Omega-R/OmegaRecyclerView | omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/HeaderStickyDecoration.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
| import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout; | package com.omega_r.libs.omegarecyclerview.sticky_decoration;
@SuppressWarnings("rawtypes")
public class HeaderStickyDecoration extends StickyDecoration {
public HeaderStickyDecoration(StickyAdapter adapter) {
super(adapter);
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter == null) return;
int position = parent.getChildAdapterPosition(view);
int topOffset = 0;
if (position != RecyclerView.NO_POSITION && hasSticker(position)
&& showHeaderAboveItem(parent, position)) {
RecyclerView.ViewHolder stickyHolder = getStickyHolder(parent, position);
if(stickyHolder != null) {
View header = stickyHolder.itemView;
topOffset = header.getHeight(); | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/utils/ViewUtils.java
// public static boolean isReverseLayout(@Nullable RecyclerView recyclerView) {
// if (recyclerView == null) return false;
// RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
// if (layoutManager == null) return false;
// if (layoutManager instanceof LinearLayoutManager) {
// return ((LinearLayoutManager) layoutManager).getReverseLayout();
// }
// return false;
// }
// Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/sticky_decoration/HeaderStickyDecoration.java
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import static com.omega_r.libs.omegarecyclerview.utils.ViewUtils.isReverseLayout;
package com.omega_r.libs.omegarecyclerview.sticky_decoration;
@SuppressWarnings("rawtypes")
public class HeaderStickyDecoration extends StickyDecoration {
public HeaderStickyDecoration(StickyAdapter adapter) {
super(adapter);
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
RecyclerView.Adapter adapter = parent.getAdapter();
if (adapter == null) return;
int position = parent.getChildAdapterPosition(view);
int topOffset = 0;
if (position != RecyclerView.NO_POSITION && hasSticker(position)
&& showHeaderAboveItem(parent, position)) {
RecyclerView.ViewHolder stickyHolder = getStickyHolder(parent, position);
if(stickyHolder != null) {
View header = stickyHolder.itemView;
topOffset = header.getHeight(); | if (isReverseLayout(parent)) { |
Omega-R/OmegaRecyclerView | app/src/main/java/com/omega_r/omegarecyclerview/ListAdapterExample/ListAdapterActivity.java | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/BaseListAdapter.java
// public abstract class BaseListAdapter<T> extends OmegaRecyclerView.Adapter<BaseListAdapter<T>.ViewHolder> {
//
// private List<T> items;
//
// @Nullable
// private OnItemClickListener<T> clickListener;
//
// @Nullable
// private OnItemLongClickListener<T> longClickListener;
//
// public BaseListAdapter(@NonNull List<T> items,
// @Nullable OnItemClickListener<T> clickListener,
// @Nullable OnItemLongClickListener<T> longClickListener) {
// this.items = items;
// this.clickListener = clickListener;
// this.longClickListener = longClickListener;
// }
//
// public BaseListAdapter(@NonNull List<T> items, @Nullable OnItemClickListener<T> clickListener) {
// this(items, clickListener, null);
// }
//
// public BaseListAdapter(@NonNull List<T> items, @Nullable OnItemLongClickListener<T> longClickListener) {
// this(items, null, longClickListener);
// }
//
// public BaseListAdapter(@Nullable OnItemClickListener<T> clickListener, @Nullable OnItemLongClickListener<T> longClickListener) {
// this(Collections.<T>emptyList(), clickListener, longClickListener);
// }
//
// public BaseListAdapter(@NonNull List<T> items) {
// this(items, null, null);
// }
//
// public BaseListAdapter(@Nullable OnItemClickListener<T> clickListener) {
// this(Collections.<T>emptyList(), clickListener, null);
// }
//
// public BaseListAdapter(@Nullable OnItemLongClickListener<T> longClickListener) {
// this(Collections.<T>emptyList(), null, longClickListener);
// }
//
// public BaseListAdapter() {
// this(Collections.<T>emptyList(), null, null);
// }
//
// public final void setClickListener(@Nullable OnItemClickListener<T> clickListener) {
// this.clickListener = clickListener;
// tryNotifyDataSetChanged();
// }
//
// public final void setLongClickListener(@Nullable OnItemLongClickListener<T> longClickListener) {
// this.longClickListener = longClickListener;
// tryNotifyDataSetChanged();
// }
//
// public final void addItems(@NonNull List<T> items) {
// this.items.addAll(items);
// tryNotifyDataSetChanged();
// }
//
// public final void setItems(@NonNull List<T> items) {
// this.items = items;
// tryNotifyDataSetChanged();
// }
//
// protected final T getItem(int position) {
// return items.get(position);
// }
//
// protected final List<T> getItems() {
// return items;
// }
//
// private void onItemClick(T item) {
// if (clickListener != null) {
// clickListener.onItemClick(item);
// }
// }
//
// private void onLongItemClick(T item) {
// if (longClickListener != null) {
// longClickListener.onItemLongClick(item);
// }
// }
//
// @Override
// public void onBindViewHolder(@NonNull BaseListAdapter<T>.ViewHolder holder, int position) {
// holder.bind(getItem(position));
// }
//
// @Override
// public int getItemCount() {
// return items.size();
// }
//
// public abstract class ViewHolder extends OmegaRecyclerView.ViewHolder implements
// View.OnClickListener,
// View.OnLongClickListener {
//
// private T item;
//
// public ViewHolder(View v) {
// super(v);
// }
//
// public ViewHolder(ViewGroup parent, int res) {
// super(parent, res);
// }
//
// private void bind(T item) {
// this.item = item;
//
// if (clickListener != null) {
// itemView.setOnClickListener(this);
// }
//
// if (longClickListener != null) {
// itemView.setOnLongClickListener(this);
// }
//
// onBind(item);
// }
//
// protected abstract void onBind(T item);
//
// @NonNull
// protected T getItem() {
// return item;
// }
//
// @Override
// public void onClick(View v) {
// onItemClick(item);
// }
//
// @Override
// public boolean onLongClick(View v) {
// onLongItemClick(item);
// return true;
// }
// }
//
// public interface OnItemClickListener<T> {
// void onItemClick(T item);
// }
//
// public interface OnItemLongClickListener<T> {
// void onItemLongClick(T item);
// }
// }
| import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.widget.Toast;
import com.omega_r.libs.omegarecyclerview.BaseListAdapter;
import com.omega_r.omegarecyclerview.R;
import java.util.ArrayList;
import java.util.List;
import omega.com.annotations.OmegaActivity; | package com.omega_r.omegarecyclerview.ListAdapterExample;
@OmegaActivity
public class ListAdapterActivity extends AppCompatActivity implements | // Path: omegarecyclerview/src/main/java/com/omega_r/libs/omegarecyclerview/BaseListAdapter.java
// public abstract class BaseListAdapter<T> extends OmegaRecyclerView.Adapter<BaseListAdapter<T>.ViewHolder> {
//
// private List<T> items;
//
// @Nullable
// private OnItemClickListener<T> clickListener;
//
// @Nullable
// private OnItemLongClickListener<T> longClickListener;
//
// public BaseListAdapter(@NonNull List<T> items,
// @Nullable OnItemClickListener<T> clickListener,
// @Nullable OnItemLongClickListener<T> longClickListener) {
// this.items = items;
// this.clickListener = clickListener;
// this.longClickListener = longClickListener;
// }
//
// public BaseListAdapter(@NonNull List<T> items, @Nullable OnItemClickListener<T> clickListener) {
// this(items, clickListener, null);
// }
//
// public BaseListAdapter(@NonNull List<T> items, @Nullable OnItemLongClickListener<T> longClickListener) {
// this(items, null, longClickListener);
// }
//
// public BaseListAdapter(@Nullable OnItemClickListener<T> clickListener, @Nullable OnItemLongClickListener<T> longClickListener) {
// this(Collections.<T>emptyList(), clickListener, longClickListener);
// }
//
// public BaseListAdapter(@NonNull List<T> items) {
// this(items, null, null);
// }
//
// public BaseListAdapter(@Nullable OnItemClickListener<T> clickListener) {
// this(Collections.<T>emptyList(), clickListener, null);
// }
//
// public BaseListAdapter(@Nullable OnItemLongClickListener<T> longClickListener) {
// this(Collections.<T>emptyList(), null, longClickListener);
// }
//
// public BaseListAdapter() {
// this(Collections.<T>emptyList(), null, null);
// }
//
// public final void setClickListener(@Nullable OnItemClickListener<T> clickListener) {
// this.clickListener = clickListener;
// tryNotifyDataSetChanged();
// }
//
// public final void setLongClickListener(@Nullable OnItemLongClickListener<T> longClickListener) {
// this.longClickListener = longClickListener;
// tryNotifyDataSetChanged();
// }
//
// public final void addItems(@NonNull List<T> items) {
// this.items.addAll(items);
// tryNotifyDataSetChanged();
// }
//
// public final void setItems(@NonNull List<T> items) {
// this.items = items;
// tryNotifyDataSetChanged();
// }
//
// protected final T getItem(int position) {
// return items.get(position);
// }
//
// protected final List<T> getItems() {
// return items;
// }
//
// private void onItemClick(T item) {
// if (clickListener != null) {
// clickListener.onItemClick(item);
// }
// }
//
// private void onLongItemClick(T item) {
// if (longClickListener != null) {
// longClickListener.onItemLongClick(item);
// }
// }
//
// @Override
// public void onBindViewHolder(@NonNull BaseListAdapter<T>.ViewHolder holder, int position) {
// holder.bind(getItem(position));
// }
//
// @Override
// public int getItemCount() {
// return items.size();
// }
//
// public abstract class ViewHolder extends OmegaRecyclerView.ViewHolder implements
// View.OnClickListener,
// View.OnLongClickListener {
//
// private T item;
//
// public ViewHolder(View v) {
// super(v);
// }
//
// public ViewHolder(ViewGroup parent, int res) {
// super(parent, res);
// }
//
// private void bind(T item) {
// this.item = item;
//
// if (clickListener != null) {
// itemView.setOnClickListener(this);
// }
//
// if (longClickListener != null) {
// itemView.setOnLongClickListener(this);
// }
//
// onBind(item);
// }
//
// protected abstract void onBind(T item);
//
// @NonNull
// protected T getItem() {
// return item;
// }
//
// @Override
// public void onClick(View v) {
// onItemClick(item);
// }
//
// @Override
// public boolean onLongClick(View v) {
// onLongItemClick(item);
// return true;
// }
// }
//
// public interface OnItemClickListener<T> {
// void onItemClick(T item);
// }
//
// public interface OnItemLongClickListener<T> {
// void onItemLongClick(T item);
// }
// }
// Path: app/src/main/java/com/omega_r/omegarecyclerview/ListAdapterExample/ListAdapterActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.widget.Toast;
import com.omega_r.libs.omegarecyclerview.BaseListAdapter;
import com.omega_r.omegarecyclerview.R;
import java.util.ArrayList;
import java.util.List;
import omega.com.annotations.OmegaActivity;
package com.omega_r.omegarecyclerview.ListAdapterExample;
@OmegaActivity
public class ListAdapterActivity extends AppCompatActivity implements | BaseListAdapter.OnItemClickListener<String>, |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/widget/DragFrameLayout.java | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.Scroller;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil;
import java.lang.reflect.Field; | downX = lastX = event.getRawX();
downY = lastY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
onMove();
lastX = curX;
lastY = curY;
break;
case MotionEvent.ACTION_UP:
onScrollEdge();
break;
}
return true;
}
private void onMove() {
int dx = (int) (curX - lastX);
int dy = (int) (curY - lastY);
if (getLeft() + dx < margin_edge) {
dx = 0;
} else if (getLeft() + viewWidth + dx > width - margin_edge) {
dx = 0;
}
if (getTop() + dy < margin_edge) {
dy = 0;
} else if (getTop() + viewHeight + dy > height - margin_edge) {
dy = 0;
} | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/widget/DragFrameLayout.java
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.Scroller;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil;
import java.lang.reflect.Field;
downX = lastX = event.getRawX();
downY = lastY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
onMove();
lastX = curX;
lastY = curY;
break;
case MotionEvent.ACTION_UP:
onScrollEdge();
break;
}
return true;
}
private void onMove() {
int dx = (int) (curX - lastX);
int dy = (int) (curY - lastY);
if (getLeft() + dx < margin_edge) {
dx = 0;
} else if (getLeft() + viewWidth + dx > width - margin_edge) {
dx = 0;
}
if (getTop() + dy < margin_edge) {
dy = 0;
} else if (getTop() + viewHeight + dy > height - margin_edge) {
dy = 0;
} | LogUtil.e("onMove: getLeft=" + getLeft() + " dx=" + dx + " dy=" + dy); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/ScreenRecordActivity.java | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Toast;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date; | chronometer = (Chronometer) findViewById(R.id.update);
}
private void initViewsListener() {
record.setOnClickListener(this);
play.setOnClickListener(this);
textureView.setSurfaceTextureListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void init() {
metrics = this.getResources().getDisplayMetrics();
width = 720;
height = 1280;
//printInfo();
manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void printInfo() {
MediaCodecList list = new MediaCodecList(MediaCodecList.ALL_CODECS);
MediaCodecInfo[] codecInfos = list.getCodecInfos();
for (MediaCodecInfo info : codecInfos) {
if (info.isEncoder()) {
StringBuilder sb = new StringBuilder();
sb.append(info.getName() + " types=");
String[] supportedTypes = info.getSupportedTypes();
for (String string : supportedTypes) {
sb.append(" " + string);
} | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/ScreenRecordActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Toast;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
chronometer = (Chronometer) findViewById(R.id.update);
}
private void initViewsListener() {
record.setOnClickListener(this);
play.setOnClickListener(this);
textureView.setSurfaceTextureListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void init() {
metrics = this.getResources().getDisplayMetrics();
width = 720;
height = 1280;
//printInfo();
manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void printInfo() {
MediaCodecList list = new MediaCodecList(MediaCodecList.ALL_CODECS);
MediaCodecInfo[] codecInfos = list.getCodecInfos();
for (MediaCodecInfo info : codecInfos) {
if (info.isEncoder()) {
StringBuilder sb = new StringBuilder();
sb.append(info.getName() + " types=");
String[] supportedTypes = info.getSupportedTypes();
for (String string : supportedTypes) {
sb.append(" " + string);
} | LogUtil.e(sb.toString()); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/widget/TestTextView.java | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil; | package com.demo.amazing.widget;
/**
* Created by hzsunyj on 2017/11/27.
*/
public class TestTextView extends AppCompatTextView {
private String tag;
public TestTextView(Context context) {
super(context);
init(context, null);
}
public TestTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public TestTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TestTextView);
tag = array.getString(R.styleable.TestTextView_tag_name);
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int size = MeasureSpec.getSize(widthMeasureSpec); | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/widget/TestTextView.java
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil;
package com.demo.amazing.widget;
/**
* Created by hzsunyj on 2017/11/27.
*/
public class TestTextView extends AppCompatTextView {
private String tag;
public TestTextView(Context context) {
super(context);
init(context, null);
}
public TestTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public TestTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TestTextView);
tag = array.getString(R.styleable.TestTextView_tag_name);
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int size = MeasureSpec.getSize(widthMeasureSpec); | LogUtil.e("tag" + tag + " widthMeasureSpec=" + widthMeasureSpec + " mode=" + mode + " size=" + size); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/client/WSClient.java | // Path: app/src/main/java/com/demo/amazing/net/WSCallBack.java
// public interface WSCallBack {
//
// void isConnected();
//
// void onMessage(String text);
//
// void onFail(int code, String err);
//
// void close();
// }
//
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
// public class WSListener extends WebSocketListener {
//
// WSCallBack callBack;
//
// public WSListener(WSCallBack callBack) {
// this.callBack = callBack;
// }
//
// @Override
// public void onOpen(WebSocket webSocket, Response response) {
// callBack.isConnected();
// LogUtil.e("client onOpen");
// }
//
// @Override
// public void onMessage(WebSocket webSocket, String text) {
// callBack.onMessage(text);
// LogUtil.e("client onMessage=" + text);
// }
//
// @Override
// public void onMessage(WebSocket webSocket, ByteString bytes) {
// }
//
// @Override
// public void onClosed(WebSocket webSocket, int code, String reason) {
// LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
// }
//
// @Override
// public void onClosing(WebSocket webSocket, int code, String reason) {
// }
//
// @Override
// public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// LogUtil.e("client onFailure: t=" + t.getMessage());
// callBack.onFail(WSErrorCode.BROKEN, "net closed");
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
| import com.demo.amazing.net.WSCallBack;
import com.demo.amazing.net.WSListener;
import com.demo.amazing.net.config.WSErrorCode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket; | package com.demo.amazing.net.client;
/**
* web socket client
* Created by hzsunyj on 2017/8/28.
*/
public final class WSClient {
/**
* ok http client
*/
private OkHttpClient httpClient;
/**
* web socket
*/
private WebSocket webSocket;
/**
*
*/
private WSClient() {
httpClient = OkHttp.getInstance().getHttpClient();
}
/**
* @return
*/
public static WSClient getInstance() {
return new WSClient();
}
/**
* connect
*
* @param wsUrl
* @param callBack
*/ | // Path: app/src/main/java/com/demo/amazing/net/WSCallBack.java
// public interface WSCallBack {
//
// void isConnected();
//
// void onMessage(String text);
//
// void onFail(int code, String err);
//
// void close();
// }
//
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
// public class WSListener extends WebSocketListener {
//
// WSCallBack callBack;
//
// public WSListener(WSCallBack callBack) {
// this.callBack = callBack;
// }
//
// @Override
// public void onOpen(WebSocket webSocket, Response response) {
// callBack.isConnected();
// LogUtil.e("client onOpen");
// }
//
// @Override
// public void onMessage(WebSocket webSocket, String text) {
// callBack.onMessage(text);
// LogUtil.e("client onMessage=" + text);
// }
//
// @Override
// public void onMessage(WebSocket webSocket, ByteString bytes) {
// }
//
// @Override
// public void onClosed(WebSocket webSocket, int code, String reason) {
// LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
// }
//
// @Override
// public void onClosing(WebSocket webSocket, int code, String reason) {
// }
//
// @Override
// public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// LogUtil.e("client onFailure: t=" + t.getMessage());
// callBack.onFail(WSErrorCode.BROKEN, "net closed");
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
// Path: app/src/main/java/com/demo/amazing/net/client/WSClient.java
import com.demo.amazing.net.WSCallBack;
import com.demo.amazing.net.WSListener;
import com.demo.amazing.net.config.WSErrorCode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
package com.demo.amazing.net.client;
/**
* web socket client
* Created by hzsunyj on 2017/8/28.
*/
public final class WSClient {
/**
* ok http client
*/
private OkHttpClient httpClient;
/**
* web socket
*/
private WebSocket webSocket;
/**
*
*/
private WSClient() {
httpClient = OkHttp.getInstance().getHttpClient();
}
/**
* @return
*/
public static WSClient getInstance() {
return new WSClient();
}
/**
* connect
*
* @param wsUrl
* @param callBack
*/ | public void connect(String wsUrl, final WSCallBack callBack) { |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/client/WSClient.java | // Path: app/src/main/java/com/demo/amazing/net/WSCallBack.java
// public interface WSCallBack {
//
// void isConnected();
//
// void onMessage(String text);
//
// void onFail(int code, String err);
//
// void close();
// }
//
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
// public class WSListener extends WebSocketListener {
//
// WSCallBack callBack;
//
// public WSListener(WSCallBack callBack) {
// this.callBack = callBack;
// }
//
// @Override
// public void onOpen(WebSocket webSocket, Response response) {
// callBack.isConnected();
// LogUtil.e("client onOpen");
// }
//
// @Override
// public void onMessage(WebSocket webSocket, String text) {
// callBack.onMessage(text);
// LogUtil.e("client onMessage=" + text);
// }
//
// @Override
// public void onMessage(WebSocket webSocket, ByteString bytes) {
// }
//
// @Override
// public void onClosed(WebSocket webSocket, int code, String reason) {
// LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
// }
//
// @Override
// public void onClosing(WebSocket webSocket, int code, String reason) {
// }
//
// @Override
// public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// LogUtil.e("client onFailure: t=" + t.getMessage());
// callBack.onFail(WSErrorCode.BROKEN, "net closed");
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
| import com.demo.amazing.net.WSCallBack;
import com.demo.amazing.net.WSListener;
import com.demo.amazing.net.config.WSErrorCode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket; | package com.demo.amazing.net.client;
/**
* web socket client
* Created by hzsunyj on 2017/8/28.
*/
public final class WSClient {
/**
* ok http client
*/
private OkHttpClient httpClient;
/**
* web socket
*/
private WebSocket webSocket;
/**
*
*/
private WSClient() {
httpClient = OkHttp.getInstance().getHttpClient();
}
/**
* @return
*/
public static WSClient getInstance() {
return new WSClient();
}
/**
* connect
*
* @param wsUrl
* @param callBack
*/
public void connect(String wsUrl, final WSCallBack callBack) {
Request request = new Request.Builder().url(wsUrl).build(); | // Path: app/src/main/java/com/demo/amazing/net/WSCallBack.java
// public interface WSCallBack {
//
// void isConnected();
//
// void onMessage(String text);
//
// void onFail(int code, String err);
//
// void close();
// }
//
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
// public class WSListener extends WebSocketListener {
//
// WSCallBack callBack;
//
// public WSListener(WSCallBack callBack) {
// this.callBack = callBack;
// }
//
// @Override
// public void onOpen(WebSocket webSocket, Response response) {
// callBack.isConnected();
// LogUtil.e("client onOpen");
// }
//
// @Override
// public void onMessage(WebSocket webSocket, String text) {
// callBack.onMessage(text);
// LogUtil.e("client onMessage=" + text);
// }
//
// @Override
// public void onMessage(WebSocket webSocket, ByteString bytes) {
// }
//
// @Override
// public void onClosed(WebSocket webSocket, int code, String reason) {
// LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
// }
//
// @Override
// public void onClosing(WebSocket webSocket, int code, String reason) {
// }
//
// @Override
// public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// LogUtil.e("client onFailure: t=" + t.getMessage());
// callBack.onFail(WSErrorCode.BROKEN, "net closed");
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
// Path: app/src/main/java/com/demo/amazing/net/client/WSClient.java
import com.demo.amazing.net.WSCallBack;
import com.demo.amazing.net.WSListener;
import com.demo.amazing.net.config.WSErrorCode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
package com.demo.amazing.net.client;
/**
* web socket client
* Created by hzsunyj on 2017/8/28.
*/
public final class WSClient {
/**
* ok http client
*/
private OkHttpClient httpClient;
/**
* web socket
*/
private WebSocket webSocket;
/**
*
*/
private WSClient() {
httpClient = OkHttp.getInstance().getHttpClient();
}
/**
* @return
*/
public static WSClient getInstance() {
return new WSClient();
}
/**
* connect
*
* @param wsUrl
* @param callBack
*/
public void connect(String wsUrl, final WSCallBack callBack) {
Request request = new Request.Builder().url(wsUrl).build(); | webSocket = httpClient.newWebSocket(request, new WSListener(callBack)); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/client/WSClient.java | // Path: app/src/main/java/com/demo/amazing/net/WSCallBack.java
// public interface WSCallBack {
//
// void isConnected();
//
// void onMessage(String text);
//
// void onFail(int code, String err);
//
// void close();
// }
//
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
// public class WSListener extends WebSocketListener {
//
// WSCallBack callBack;
//
// public WSListener(WSCallBack callBack) {
// this.callBack = callBack;
// }
//
// @Override
// public void onOpen(WebSocket webSocket, Response response) {
// callBack.isConnected();
// LogUtil.e("client onOpen");
// }
//
// @Override
// public void onMessage(WebSocket webSocket, String text) {
// callBack.onMessage(text);
// LogUtil.e("client onMessage=" + text);
// }
//
// @Override
// public void onMessage(WebSocket webSocket, ByteString bytes) {
// }
//
// @Override
// public void onClosed(WebSocket webSocket, int code, String reason) {
// LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
// }
//
// @Override
// public void onClosing(WebSocket webSocket, int code, String reason) {
// }
//
// @Override
// public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// LogUtil.e("client onFailure: t=" + t.getMessage());
// callBack.onFail(WSErrorCode.BROKEN, "net closed");
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
| import com.demo.amazing.net.WSCallBack;
import com.demo.amazing.net.WSListener;
import com.demo.amazing.net.config.WSErrorCode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket; | package com.demo.amazing.net.client;
/**
* web socket client
* Created by hzsunyj on 2017/8/28.
*/
public final class WSClient {
/**
* ok http client
*/
private OkHttpClient httpClient;
/**
* web socket
*/
private WebSocket webSocket;
/**
*
*/
private WSClient() {
httpClient = OkHttp.getInstance().getHttpClient();
}
/**
* @return
*/
public static WSClient getInstance() {
return new WSClient();
}
/**
* connect
*
* @param wsUrl
* @param callBack
*/
public void connect(String wsUrl, final WSCallBack callBack) {
Request request = new Request.Builder().url(wsUrl).build();
webSocket = httpClient.newWebSocket(request, new WSListener(callBack));
}
/**
* dis connect
*/
public void disConnect() {
if (webSocket != null) { | // Path: app/src/main/java/com/demo/amazing/net/WSCallBack.java
// public interface WSCallBack {
//
// void isConnected();
//
// void onMessage(String text);
//
// void onFail(int code, String err);
//
// void close();
// }
//
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
// public class WSListener extends WebSocketListener {
//
// WSCallBack callBack;
//
// public WSListener(WSCallBack callBack) {
// this.callBack = callBack;
// }
//
// @Override
// public void onOpen(WebSocket webSocket, Response response) {
// callBack.isConnected();
// LogUtil.e("client onOpen");
// }
//
// @Override
// public void onMessage(WebSocket webSocket, String text) {
// callBack.onMessage(text);
// LogUtil.e("client onMessage=" + text);
// }
//
// @Override
// public void onMessage(WebSocket webSocket, ByteString bytes) {
// }
//
// @Override
// public void onClosed(WebSocket webSocket, int code, String reason) {
// LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
// }
//
// @Override
// public void onClosing(WebSocket webSocket, int code, String reason) {
// }
//
// @Override
// public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// LogUtil.e("client onFailure: t=" + t.getMessage());
// callBack.onFail(WSErrorCode.BROKEN, "net closed");
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
// Path: app/src/main/java/com/demo/amazing/net/client/WSClient.java
import com.demo.amazing.net.WSCallBack;
import com.demo.amazing.net.WSListener;
import com.demo.amazing.net.config.WSErrorCode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
package com.demo.amazing.net.client;
/**
* web socket client
* Created by hzsunyj on 2017/8/28.
*/
public final class WSClient {
/**
* ok http client
*/
private OkHttpClient httpClient;
/**
* web socket
*/
private WebSocket webSocket;
/**
*
*/
private WSClient() {
httpClient = OkHttp.getInstance().getHttpClient();
}
/**
* @return
*/
public static WSClient getInstance() {
return new WSClient();
}
/**
* connect
*
* @param wsUrl
* @param callBack
*/
public void connect(String wsUrl, final WSCallBack callBack) {
Request request = new Request.Builder().url(wsUrl).build();
webSocket = httpClient.newWebSocket(request, new WSListener(callBack));
}
/**
* dis connect
*/
public void disConnect() {
if (webSocket != null) { | webSocket.close(WSErrorCode.BROKEN, "broken"); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/WSListener.java | // Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import com.demo.amazing.net.config.WSErrorCode;
import com.demo.amazing.util.LogUtil;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString; | package com.demo.amazing.net;
/**
* Created by hzsunyj on 2017/8/28.
*/
public class WSListener extends WebSocketListener {
WSCallBack callBack;
public WSListener(WSCallBack callBack) {
this.callBack = callBack;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
callBack.isConnected(); | // Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
import com.demo.amazing.net.config.WSErrorCode;
import com.demo.amazing.util.LogUtil;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
package com.demo.amazing.net;
/**
* Created by hzsunyj on 2017/8/28.
*/
public class WSListener extends WebSocketListener {
WSCallBack callBack;
public WSListener(WSCallBack callBack) {
this.callBack = callBack;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
callBack.isConnected(); | LogUtil.e("client onOpen"); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/WSListener.java | // Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import com.demo.amazing.net.config.WSErrorCode;
import com.demo.amazing.util.LogUtil;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString; | package com.demo.amazing.net;
/**
* Created by hzsunyj on 2017/8/28.
*/
public class WSListener extends WebSocketListener {
WSCallBack callBack;
public WSListener(WSCallBack callBack) {
this.callBack = callBack;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
callBack.isConnected();
LogUtil.e("client onOpen");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
callBack.onMessage(text);
LogUtil.e("client onMessage=" + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
LogUtil.e("client onFailure: t=" + t.getMessage()); | // Path: app/src/main/java/com/demo/amazing/net/config/WSErrorCode.java
// public interface WSErrorCode {
//
// int NO_ERROR = 0;
//
// int CANCEL = 1;
//
// int SUCCESS = 200;
//
// int NET_CLOSE = 404;
//
// int BROKEN = 1000;
//
// int WS_URL_NOT_EXIST = 1001;
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/net/WSListener.java
import com.demo.amazing.net.config.WSErrorCode;
import com.demo.amazing.util.LogUtil;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
package com.demo.amazing.net;
/**
* Created by hzsunyj on 2017/8/28.
*/
public class WSListener extends WebSocketListener {
WSCallBack callBack;
public WSListener(WSCallBack callBack) {
this.callBack = callBack;
}
@Override
public void onOpen(WebSocket webSocket, Response response) {
callBack.isConnected();
LogUtil.e("client onOpen");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
callBack.onMessage(text);
LogUtil.e("client onMessage=" + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
LogUtil.e("client onClosed: code=" + code + " reason=" + reason);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
LogUtil.e("client onFailure: t=" + t.getMessage()); | callBack.onFail(WSErrorCode.BROKEN, "net closed"); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/EnterActivity.java | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList; | package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
| // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/EnterActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList;
package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
| private ArrayList<EnterData> list; |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/EnterActivity.java | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList; | package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
private ArrayList<EnterData> list;
private void findViews() {
activityList = findViewById(R.id.activity_list);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
findViews();
initRV();
}
private void initRV() {
preloadData();
activityList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
activityList.setLayoutManager(new LinearLayoutManager(this)); | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/EnterActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList;
package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
private ArrayList<EnterData> list;
private void findViews() {
activityList = findViewById(R.id.activity_list);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
findViews();
initRV();
}
private void initRV() {
preloadData();
activityList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
activityList.setLayoutManager(new LinearLayoutManager(this)); | activityList.setAdapter(new BaseAdapter(list, new EnterDelegate(), new OnItemClickListener<EnterData>() { |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/EnterActivity.java | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList; | package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
private ArrayList<EnterData> list;
private void findViews() {
activityList = findViewById(R.id.activity_list);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
findViews();
initRV();
}
private void initRV() {
preloadData();
activityList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
activityList.setLayoutManager(new LinearLayoutManager(this)); | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/EnterActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList;
package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
private ArrayList<EnterData> list;
private void findViews() {
activityList = findViewById(R.id.activity_list);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
findViews();
initRV();
}
private void initRV() {
preloadData();
activityList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
activityList.setLayoutManager(new LinearLayoutManager(this)); | activityList.setAdapter(new BaseAdapter(list, new EnterDelegate(), new OnItemClickListener<EnterData>() { |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/EnterActivity.java | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList; | package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
private ArrayList<EnterData> list;
private void findViews() {
activityList = findViewById(R.id.activity_list);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
findViews();
initRV();
}
private void initRV() {
preloadData();
activityList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
activityList.setLayoutManager(new LinearLayoutManager(this)); | // Path: app/src/main/java/com/demo/amazing/adpter/BaseAdapter.java
// public class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
//
// /**
// * data source
// */
// public List<T> dataList;
//
// /**
// * onClick onLongClick callback
// */
// public OnItemClickListener listener;
//
// /**
// * constructor view holder delegate
// */
// public BaseDelegate delegate;
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate) {
// this(dataList, delegate, null);
// }
//
// /**
// * constructor
// *
// * @param dataList
// * @param delegate
// * @param listener
// */
// public BaseAdapter(List<T> dataList, BaseDelegate delegate, OnItemClickListener listener) {
// checkData(dataList);
// this.delegate = delegate;
// this.listener = listener;
// }
//
// /**
// * just is empty
// *
// * @param dataList
// */
// private void checkData(List<T> dataList) {
// if (dataList == null) {
// dataList = Collections.emptyList();
// }
// this.dataList = dataList;
// }
//
// /**
// * set onclick & onLongClick callback
// *
// * @param listener
// */
// public void setOnItemClickListener(OnItemClickListener listener) {
// this.listener = listener;
// }
//
// /**
// * create view holder
// *
// * @param parent
// * @param viewType
// * @return
// */
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return delegate.onCreateViewHolder(parent, viewType);
// }
//
// /**
// * bind view holder
// *
// * @param holder
// * @param position
// */
// @Override
// public void onBindViewHolder(BaseViewHolder holder, final int position) {
// holder.onBindViewHolder(dataList.get(position));
// if (listener != null && holder.enable()) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// listener.onClick(v, dataList.get(position));
// }
// });
// holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
// @Override
// public boolean onLongClick(View v) {
// return listener.onLongClick(v, dataList.get(position));
// }
// });
// }
// }
//
// /**
// * get item count
// *
// * @return
// */
// @Override
// public int getItemCount() {
// return dataList.size();
// }
//
// /**
// * get item view type
// *
// * @param position
// * @return
// */
// @Override
// public int getItemViewType(int position) {
// return delegate.getItemViewType(dataList.get(position));
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/adpter/OnItemClickListener.java
// public interface OnItemClickListener<T> {
// void onClick(View v, T data);
//
// boolean onLongClick(View v, T data);
// }
//
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
// public class EnterData extends ItemData {
//
// public static final int DEFAULT_TAG = 0;
//
// public Class clazz;
//
// public EnterData(String desc, Class clazz) {
// super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc);
// this.clazz = clazz;
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/EnterActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.demo.amazing.R;
import com.demo.amazing.adpter.BaseAdapter;
import com.demo.amazing.adpter.EnterDelegate;
import com.demo.amazing.adpter.OnItemClickListener;
import com.demo.amazing.model.EnterData;
import java.util.ArrayList;
package com.demo.amazing.activity;
public class EnterActivity extends AppCompatActivity {
private RecyclerView activityList;
private ArrayList<EnterData> list;
private void findViews() {
activityList = findViewById(R.id.activity_list);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter);
findViews();
initRV();
}
private void initRV() {
preloadData();
activityList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
activityList.setLayoutManager(new LinearLayoutManager(this)); | activityList.setAdapter(new BaseAdapter(list, new EnterDelegate(), new OnItemClickListener<EnterData>() { |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/model/EnterData.java | // Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
| import com.demo.amazing.adpter.EnterDelegate; | package com.demo.amazing.model;
/**
* Created by hzsunyj on 2017/10/17.
*/
public class EnterData extends ItemData {
public static final int DEFAULT_TAG = 0;
public Class clazz;
public EnterData(String desc, Class clazz) { | // Path: app/src/main/java/com/demo/amazing/adpter/EnterDelegate.java
// public class EnterDelegate extends BaseDelegate<EnterData> {
//
// public static final int TEXT_HOLDER = 0;
//
// @Override
// public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return new EnterTextHolder(parent, getItemView(parent, viewType));
// }
// return null;
// }
//
// @Override
// public int getItemViewType(EnterData data) {
// return data.holderType;
// }
//
// @Override
// public int getLayoutId(int viewType) {
// switch (viewType) {
// case TEXT_HOLDER:
// return R.layout.view_holder_enter_text;
// }
// return 0;
// }
// }
// Path: app/src/main/java/com/demo/amazing/model/EnterData.java
import com.demo.amazing.adpter.EnterDelegate;
package com.demo.amazing.model;
/**
* Created by hzsunyj on 2017/10/17.
*/
public class EnterData extends ItemData {
public static final int DEFAULT_TAG = 0;
public Class clazz;
public EnterData(String desc, Class clazz) { | super(DEFAULT_TAG, EnterDelegate.TEXT_HOLDER, desc); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/FadingActivity.java | // Path: app/src/main/java/com/demo/amazing/widget/FadingTextView.java
// public class FadingTextView extends android.support.v7.widget.AppCompatTextView {
//
// private Paint paint;
//
// private int height;
//
// private int width;
//
// private RectF rectF;
//
// public FadingTextView(Context context) {
// super(context);
// }
//
// public FadingTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public FadingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// height = h;
// width = w;
// initPaint();
// rectF = new RectF(0, 0, w, h);
// }
//
// public void setFading(float alpha) {
// if (alpha < 0) {
// alpha = 0.0f;
// } else if (alpha > 1) {
// alpha = 1.0f;
// }
// int endC = Color.argb((int) (alpha * 255), 0, 0, 0);
// paint.setShader(new LinearGradient(0, 0, 0, height, 0X00000000, endC, Shader.TileMode.CLAMP));
// setAlpha(alpha);
// invalidate();
// }
//
// private void initPaint() {
// paint = new Paint();
// paint.setAntiAlias(true);
// //paint.setShader(new LinearGradient(0, 0, 0, height, 0X00000000, 0X00000000, Shader.TileMode.CLAMP));
// paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
// }
//
// @Override
// protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
// // if (height != 0) {
// // canvas.drawRoundRect(rectF, 30.0f, 30.0f, paint);
// // }
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.demo.amazing.R;
import com.demo.amazing.widget.FadingTextView;
import java.util.ArrayList;
import java.util.List;
import static com.demo.amazing.R.id.recycler_view; | public List<String> getDatas() {
datas = new ArrayList<>(50);
for (int i = 0; i < 50; ++i) {
datas.add(new String("我爱北京天安门" + i));
}
return datas;
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.DataViewHolder> {
@Override
public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new DataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.data_item_view,
parent, false));
}
@Override
public void onBindViewHolder(DataViewHolder holder, int position) {
holder.textView.setText(datas.get(position));
holder.itemView.setAlpha(1.0f);
}
@Override
public int getItemCount() {
return datas == null ? 0 : datas.size();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
| // Path: app/src/main/java/com/demo/amazing/widget/FadingTextView.java
// public class FadingTextView extends android.support.v7.widget.AppCompatTextView {
//
// private Paint paint;
//
// private int height;
//
// private int width;
//
// private RectF rectF;
//
// public FadingTextView(Context context) {
// super(context);
// }
//
// public FadingTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public FadingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// height = h;
// width = w;
// initPaint();
// rectF = new RectF(0, 0, w, h);
// }
//
// public void setFading(float alpha) {
// if (alpha < 0) {
// alpha = 0.0f;
// } else if (alpha > 1) {
// alpha = 1.0f;
// }
// int endC = Color.argb((int) (alpha * 255), 0, 0, 0);
// paint.setShader(new LinearGradient(0, 0, 0, height, 0X00000000, endC, Shader.TileMode.CLAMP));
// setAlpha(alpha);
// invalidate();
// }
//
// private void initPaint() {
// paint = new Paint();
// paint.setAntiAlias(true);
// //paint.setShader(new LinearGradient(0, 0, 0, height, 0X00000000, 0X00000000, Shader.TileMode.CLAMP));
// paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
// }
//
// @Override
// protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
// // if (height != 0) {
// // canvas.drawRoundRect(rectF, 30.0f, 30.0f, paint);
// // }
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/FadingActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.demo.amazing.R;
import com.demo.amazing.widget.FadingTextView;
import java.util.ArrayList;
import java.util.List;
import static com.demo.amazing.R.id.recycler_view;
public List<String> getDatas() {
datas = new ArrayList<>(50);
for (int i = 0; i < 50; ++i) {
datas.add(new String("我爱北京天安门" + i));
}
return datas;
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.DataViewHolder> {
@Override
public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new DataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.data_item_view,
parent, false));
}
@Override
public void onBindViewHolder(DataViewHolder holder, int position) {
holder.textView.setText(datas.get(position));
holder.itemView.setAlpha(1.0f);
}
@Override
public int getItemCount() {
return datas == null ? 0 : datas.size();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
| FadingTextView textView; |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/FallDownActivity.java | // Path: app/src/main/java/com/demo/amazing/widget/FallDownView.java
// public class FallDownView extends View {
//
// public static final int DEF_FALL_COUNT = 50;
//
// public static final int DEF_FALL_VIEW_KIND = 5;
//
// private int count;
//
// private int viewKind;
//
// private DownView[] downViews;
//
// private Paint paint;
//
// private Random random;
//
// private Bitmap bitmaps[];
//
// private int offsetY = 4;
//
// private boolean finished;
//
// private int viewWidth;
//
// private int viewHeight;
//
// public FallDownView(Context context) {
// super(context);
// init(context, null);
// }
//
// public FallDownView(Context context, @Nullable AttributeSet attrs) {
// super(context, attrs);
// init(context, attrs);
// }
//
// public FallDownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context, attrs);
// }
//
// private void init(Context context, AttributeSet attrs) {
// TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.FallDownView);
// int resourceId = array.getResourceId(R.styleable.FallDownView_fall_down_image, R.drawable.rtc_icon_flower1);
// count = array.getInt(R.styleable.FallDownView_fall_down_count, DEF_FALL_COUNT);
// viewKind = array.getInt(R.styleable.FallDownView_fall_down_kind, DEF_FALL_VIEW_KIND);
// array.recycle();
// initBitmaps(resourceId);
// }
//
// /**
// * @param resourceId
// */
// private void initBitmaps(int resourceId) {
// random = new Random();
// bitmaps = new Bitmap[DEF_FALL_VIEW_KIND];
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
// bitmaps[0] = bitmap;
// Matrix matrix = new Matrix();
// for (int i = 1; i < DEF_FALL_VIEW_KIND; ++i) {
// float scale = 1 + random.nextFloat();
// matrix.setScale(scale, scale);
// bitmaps[i] = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// }
// }
//
// @Override
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// viewWidth = getMeasuredWidth();
// viewHeight = getMeasuredHeight();
// }
//
// public void start() {
// initPaint();
// downViews = new DownView[count];
// float speed;
// for (int i = 0; i < count; ++i) {
// speed = (1 + random.nextFloat()) * offsetY;
// downViews[i] = new DownView(random.nextInt(viewWidth), -random.nextInt(viewHeight), speed, bitmaps[i %
// DEF_FALL_VIEW_KIND]);
// }
// finished = false;
// //invalidate();
// schedule(0);
// }
//
// private void initPaint() {
// paint = new Paint();
// paint.setAntiAlias(true);
// }
//
// @Override
// public void draw(Canvas canvas) {
// super.draw(canvas);
// if (finished) {
// return;
// }
// DownView downView;
// for (int i = 0; i < count; ++i) {
// downView = downViews[i];
// if (downView.y + downView.bitmap.getHeight() < 0 || downView.y > viewHeight) {
// continue;
// }
// canvas.drawBitmap(downView.bitmap, downView.x, downView.y, paint);
// }
// adjustCoordinate();
// }
//
// public void cancel() {
// finished = true;
// invalidate();
// }
//
// private void adjustCoordinate() {
// int outCount = 0;
// DownView downView;
// for (int i = 0; i < count; ++i) {
// downView = downViews[i];
// downView.y += downView.speed;
// if (downView.y > viewHeight) {
// outCount++;
// } else if (downView.y > 0) {
// downView.x += downView.getOffset();
// }
// }
// if (outCount == count) {
// finished = true;
// }
// }
//
// private Runnable runnable = new Runnable() {
// @Override
// public void run() {
// invalidate();
// if (!finished) {
// schedule(32);
// }
// }
// };
//
// private void schedule(int delay) {
// postDelayed(runnable, delay);
// }
//
// private class DownView {
// float x;
// float y;
// float speed;
// int angle;
// Bitmap bitmap;
//
// public DownView(float x, float y, float speed, Bitmap bitmap) {
// this.x = x;
// this.y = y;
// this.speed = speed;
// this.bitmap = bitmap;
// angle = 0;
// }
//
// public int getOffset() {
// angle += 2;
// return Math.sin(Math.PI * angle / 180) > 0 ? 2 : -2;
// }
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import com.demo.amazing.R;
import com.demo.amazing.widget.FallDownView; | package com.demo.amazing.activity;
public class FallDownActivity extends AppCompatActivity {
public static void start(Context context) {
Intent intent = new Intent(context, FallDownActivity.class);
context.startActivity(intent);
}
private FrameLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fall_down);
findViews();
}
private void findViews() {
root = (FrameLayout) findViewById(R.id.root); | // Path: app/src/main/java/com/demo/amazing/widget/FallDownView.java
// public class FallDownView extends View {
//
// public static final int DEF_FALL_COUNT = 50;
//
// public static final int DEF_FALL_VIEW_KIND = 5;
//
// private int count;
//
// private int viewKind;
//
// private DownView[] downViews;
//
// private Paint paint;
//
// private Random random;
//
// private Bitmap bitmaps[];
//
// private int offsetY = 4;
//
// private boolean finished;
//
// private int viewWidth;
//
// private int viewHeight;
//
// public FallDownView(Context context) {
// super(context);
// init(context, null);
// }
//
// public FallDownView(Context context, @Nullable AttributeSet attrs) {
// super(context, attrs);
// init(context, attrs);
// }
//
// public FallDownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context, attrs);
// }
//
// private void init(Context context, AttributeSet attrs) {
// TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.FallDownView);
// int resourceId = array.getResourceId(R.styleable.FallDownView_fall_down_image, R.drawable.rtc_icon_flower1);
// count = array.getInt(R.styleable.FallDownView_fall_down_count, DEF_FALL_COUNT);
// viewKind = array.getInt(R.styleable.FallDownView_fall_down_kind, DEF_FALL_VIEW_KIND);
// array.recycle();
// initBitmaps(resourceId);
// }
//
// /**
// * @param resourceId
// */
// private void initBitmaps(int resourceId) {
// random = new Random();
// bitmaps = new Bitmap[DEF_FALL_VIEW_KIND];
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
// bitmaps[0] = bitmap;
// Matrix matrix = new Matrix();
// for (int i = 1; i < DEF_FALL_VIEW_KIND; ++i) {
// float scale = 1 + random.nextFloat();
// matrix.setScale(scale, scale);
// bitmaps[i] = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// }
// }
//
// @Override
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// viewWidth = getMeasuredWidth();
// viewHeight = getMeasuredHeight();
// }
//
// public void start() {
// initPaint();
// downViews = new DownView[count];
// float speed;
// for (int i = 0; i < count; ++i) {
// speed = (1 + random.nextFloat()) * offsetY;
// downViews[i] = new DownView(random.nextInt(viewWidth), -random.nextInt(viewHeight), speed, bitmaps[i %
// DEF_FALL_VIEW_KIND]);
// }
// finished = false;
// //invalidate();
// schedule(0);
// }
//
// private void initPaint() {
// paint = new Paint();
// paint.setAntiAlias(true);
// }
//
// @Override
// public void draw(Canvas canvas) {
// super.draw(canvas);
// if (finished) {
// return;
// }
// DownView downView;
// for (int i = 0; i < count; ++i) {
// downView = downViews[i];
// if (downView.y + downView.bitmap.getHeight() < 0 || downView.y > viewHeight) {
// continue;
// }
// canvas.drawBitmap(downView.bitmap, downView.x, downView.y, paint);
// }
// adjustCoordinate();
// }
//
// public void cancel() {
// finished = true;
// invalidate();
// }
//
// private void adjustCoordinate() {
// int outCount = 0;
// DownView downView;
// for (int i = 0; i < count; ++i) {
// downView = downViews[i];
// downView.y += downView.speed;
// if (downView.y > viewHeight) {
// outCount++;
// } else if (downView.y > 0) {
// downView.x += downView.getOffset();
// }
// }
// if (outCount == count) {
// finished = true;
// }
// }
//
// private Runnable runnable = new Runnable() {
// @Override
// public void run() {
// invalidate();
// if (!finished) {
// schedule(32);
// }
// }
// };
//
// private void schedule(int delay) {
// postDelayed(runnable, delay);
// }
//
// private class DownView {
// float x;
// float y;
// float speed;
// int angle;
// Bitmap bitmap;
//
// public DownView(float x, float y, float speed, Bitmap bitmap) {
// this.x = x;
// this.y = y;
// this.speed = speed;
// this.bitmap = bitmap;
// angle = 0;
// }
//
// public int getOffset() {
// angle += 2;
// return Math.sin(Math.PI * angle / 180) > 0 ? 2 : -2;
// }
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/FallDownActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import com.demo.amazing.R;
import com.demo.amazing.widget.FallDownView;
package com.demo.amazing.activity;
public class FallDownActivity extends AppCompatActivity {
public static void start(Context context) {
Intent intent = new Intent(context, FallDownActivity.class);
context.startActivity(intent);
}
private FrameLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fall_down);
findViews();
}
private void findViews() {
root = (FrameLayout) findViewById(R.id.root); | final FallDownView child = new FallDownView(this); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/OpenGLActivity.java | // Path: app/src/main/java/com/demo/amazing/widget/MyGLSurfaceView.java
// public class MyGLSurfaceView extends GLSurfaceView {
//
// public static final float TOUCH_SCALE_FACTOR = 180.0f / 320;
// private Context context;
//
// public final MyRender render;
//
// public MyGLSurfaceView(Context context) {
// super(context);
// this.context = context;
// setEGLContextClientVersion(2);
// render = new MyRender();
// setRenderer(render);
// setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
// }
//
//
// private float previousX;
//
// private float previousY;
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// float x = event.getX();
// float y = event.getY();
//
// switch (event.getAction()) {
// case MotionEvent.ACTION_MOVE:
// float dx = x - previousX;
// float dy = y - previousY;
//
// if (y > getHeight() / 2) {
// dx = dx * -1;
// }
// if (x < getWidth() / 2) {
// dy = dy * -1;
// }
//
// render.setAngle(render.getAngle() + (dx + dy) * TOUCH_SCALE_FACTOR);
// requestRender();
// }
// previousX = x;
// previousY = y;
// return true;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.demo.amazing.widget.MyGLSurfaceView; | package com.demo.amazing.activity;
public class OpenGLActivity extends AppCompatActivity {
public static void start(Context context) {
Intent intent = new Intent(context, OpenGLActivity.class);
context.startActivity(intent);
}
| // Path: app/src/main/java/com/demo/amazing/widget/MyGLSurfaceView.java
// public class MyGLSurfaceView extends GLSurfaceView {
//
// public static final float TOUCH_SCALE_FACTOR = 180.0f / 320;
// private Context context;
//
// public final MyRender render;
//
// public MyGLSurfaceView(Context context) {
// super(context);
// this.context = context;
// setEGLContextClientVersion(2);
// render = new MyRender();
// setRenderer(render);
// setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
// }
//
//
// private float previousX;
//
// private float previousY;
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// float x = event.getX();
// float y = event.getY();
//
// switch (event.getAction()) {
// case MotionEvent.ACTION_MOVE:
// float dx = x - previousX;
// float dy = y - previousY;
//
// if (y > getHeight() / 2) {
// dx = dx * -1;
// }
// if (x < getWidth() / 2) {
// dy = dy * -1;
// }
//
// render.setAngle(render.getAngle() + (dx + dy) * TOUCH_SCALE_FACTOR);
// requestRender();
// }
// previousX = x;
// previousY = y;
// return true;
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/OpenGLActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.demo.amazing.widget.MyGLSurfaceView;
package com.demo.amazing.activity;
public class OpenGLActivity extends AppCompatActivity {
public static void start(Context context) {
Intent intent = new Intent(context, OpenGLActivity.class);
context.startActivity(intent);
}
| MyGLSurfaceView surfaceView; |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/bean/Triangle.java | // Path: app/src/main/java/com/demo/amazing/widget/MyRender.java
// public class MyRender implements GLSurfaceView.Renderer {
//
// private Triangle triangle;
//
// private Square square;
//
// private final float[] projectionMatrix = new float[16];
//
// private final float[] viewMatrix = new float[16];
//
// private final float[] mVPMatrix = new float[16];
//
// private final float[] RotationMatrix = new float[16];
//
// private volatile float angle;
//
// @Override
// public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
//
// triangle = new Triangle();
// square = new Square();
// }
//
// @Override
// public void onSurfaceChanged(GL10 gl, int width, int height) {
// GLES20.glViewport(0, 0, width, height);
//
// float ratio = (float) width / height;
//
// Matrix.frustumM(projectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
// }
//
// @Override
// public void onDrawFrame(GL10 gl) {
//
// float[] scratch = new float[16];
//
// GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
//
// Matrix.setLookAtM(viewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
//
// Matrix.multiplyMM(mVPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
//
// // long time = SystemClock.uptimeMillis() % 4000L;
// // float angle = 0.090f * ((int) time);
// // Log.e("angle", "angle=" + angle);
// Matrix.setRotateM(RotationMatrix, 0, angle, 0, 0, -1.0f);
//
// Matrix.multiplyMM(scratch, 0, mVPMatrix, 0, RotationMatrix, 0);
//
// triangle.draw(scratch);
// }
//
// public static int loadShader(int type, String shaderCode) {
// int shader = GLES20.glCreateShader(type);
//
// GLES20.glShaderSource(shader, shaderCode);
// GLES20.glCompileShader(shader);
// return shader;
// }
//
// public float getAngle() {
// return angle;
// }
//
// public void setAngle(float angle) {
// this.angle = angle;
// }
// }
| import android.opengl.GLES20;
import com.demo.amazing.widget.MyRender;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer; | package com.demo.amazing.bean;
/**
* Created by hzsunyj on 17/4/27.
*/
public class Triangle {
private FloatBuffer vertexBuffer;
static final int COORDS_PER_VERTEX = 3;
private final String vertexShaderCode =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition; " +
"void main(){" + "" +
" gl_Position = " +
"uMVPMatrix * vPosition;" + "}";
private final String fragmentShaderCode = "precision mediump float; " + "uniform vec4 vColor; " + "void main(){"
+ " gl_FragColor = vColor;" + "}";
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.622008459f, 0.0f, // top
-0.5f, -0.311004243f, 0.0f, // bottom left
0.5f, -0.311004243f, 0.0f // bottom right
};
private final int program;
private int positionHandle;
private int colorHandle;
private int mVPHandle;
private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4;
// Set color with red, green, blue and alpha (opacity) values
float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 1.0f};
//float color[] = {0.0f, 1.0f, 0.0f, 1.0f};
public Triangle() {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(triangleCoords.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuffer.asFloatBuffer();
vertexBuffer.put(triangleCoords);
vertexBuffer.position(0);
| // Path: app/src/main/java/com/demo/amazing/widget/MyRender.java
// public class MyRender implements GLSurfaceView.Renderer {
//
// private Triangle triangle;
//
// private Square square;
//
// private final float[] projectionMatrix = new float[16];
//
// private final float[] viewMatrix = new float[16];
//
// private final float[] mVPMatrix = new float[16];
//
// private final float[] RotationMatrix = new float[16];
//
// private volatile float angle;
//
// @Override
// public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
//
// triangle = new Triangle();
// square = new Square();
// }
//
// @Override
// public void onSurfaceChanged(GL10 gl, int width, int height) {
// GLES20.glViewport(0, 0, width, height);
//
// float ratio = (float) width / height;
//
// Matrix.frustumM(projectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
// }
//
// @Override
// public void onDrawFrame(GL10 gl) {
//
// float[] scratch = new float[16];
//
// GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
//
// Matrix.setLookAtM(viewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
//
// Matrix.multiplyMM(mVPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
//
// // long time = SystemClock.uptimeMillis() % 4000L;
// // float angle = 0.090f * ((int) time);
// // Log.e("angle", "angle=" + angle);
// Matrix.setRotateM(RotationMatrix, 0, angle, 0, 0, -1.0f);
//
// Matrix.multiplyMM(scratch, 0, mVPMatrix, 0, RotationMatrix, 0);
//
// triangle.draw(scratch);
// }
//
// public static int loadShader(int type, String shaderCode) {
// int shader = GLES20.glCreateShader(type);
//
// GLES20.glShaderSource(shader, shaderCode);
// GLES20.glCompileShader(shader);
// return shader;
// }
//
// public float getAngle() {
// return angle;
// }
//
// public void setAngle(float angle) {
// this.angle = angle;
// }
// }
// Path: app/src/main/java/com/demo/amazing/bean/Triangle.java
import android.opengl.GLES20;
import com.demo.amazing.widget.MyRender;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
package com.demo.amazing.bean;
/**
* Created by hzsunyj on 17/4/27.
*/
public class Triangle {
private FloatBuffer vertexBuffer;
static final int COORDS_PER_VERTEX = 3;
private final String vertexShaderCode =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition; " +
"void main(){" + "" +
" gl_Position = " +
"uMVPMatrix * vPosition;" + "}";
private final String fragmentShaderCode = "precision mediump float; " + "uniform vec4 vColor; " + "void main(){"
+ " gl_FragColor = vColor;" + "}";
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.622008459f, 0.0f, // top
-0.5f, -0.311004243f, 0.0f, // bottom left
0.5f, -0.311004243f, 0.0f // bottom right
};
private final int program;
private int positionHandle;
private int colorHandle;
private int mVPHandle;
private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4;
// Set color with red, green, blue and alpha (opacity) values
float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 1.0f};
//float color[] = {0.0f, 1.0f, 0.0f, 1.0f};
public Triangle() {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(triangleCoords.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuffer.asFloatBuffer();
vertexBuffer.put(triangleCoords);
vertexBuffer.position(0);
| int vertexShader = MyRender.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/bean/LinkPing.java | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
| import android.text.TextUtils;
import com.demo.amazing.net.action.Action;
import org.json.JSONException;
import org.json.JSONObject; | package com.demo.amazing.net.bean;
/**
* Created by hzsunyj on 2017/8/30.
*/
public class LinkPing {
public String linkData;
public String linkPing() {
if (!TextUtils.isEmpty(linkData)) {
return linkData;
}
JSONObject jsonObject = new JSONObject();
try { | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
// Path: app/src/main/java/com/demo/amazing/net/bean/LinkPing.java
import android.text.TextUtils;
import com.demo.amazing.net.action.Action;
import org.json.JSONException;
import org.json.JSONObject;
package com.demo.amazing.net.bean;
/**
* Created by hzsunyj on 2017/8/30.
*/
public class LinkPing {
public String linkData;
public String linkPing() {
if (!TextUtils.isEmpty(linkData)) {
return linkData;
}
JSONObject jsonObject = new JSONObject();
try { | jsonObject.putOpt("action", Action.LINK_ACTION); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/CameraActivity.java | // Path: app/src/main/java/com/demo/amazing/util/BitmapUtil.java
// public class BitmapUtil {
//
// public static Bitmap rotateBitmap(Context context, Bitmap bitmap, int degree) {
// Bitmap dest = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//
// Canvas canvas = new Canvas(dest);
// Matrix matrix = new Matrix();
// matrix.setRotate(degree, bitmap.getWidth() / 2, bitmap.getWidth() / 2);
// //matrix.setRotate(degree);
// Paint paint = new Paint();
// canvas.drawBitmap(bitmap, matrix, paint);
// paint.setAntiAlias(true);
// paint.setTextSize(28);
// paint.setColor(context.getResources().getColor(R.color.colorAccent));
// canvas.drawText("Image from", bitmap.getWidth() / 2, bitmap.getHeight() / 2, paint);
// return dest;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import com.demo.amazing.R;
import com.demo.amazing.util.BitmapUtil;
import com.demo.amazing.util.LogUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; |
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
release();
}
private void release() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
release();
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
try {
Camera.Size previewSize = camera.getParameters().getPreviewSize(); | // Path: app/src/main/java/com/demo/amazing/util/BitmapUtil.java
// public class BitmapUtil {
//
// public static Bitmap rotateBitmap(Context context, Bitmap bitmap, int degree) {
// Bitmap dest = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//
// Canvas canvas = new Canvas(dest);
// Matrix matrix = new Matrix();
// matrix.setRotate(degree, bitmap.getWidth() / 2, bitmap.getWidth() / 2);
// //matrix.setRotate(degree);
// Paint paint = new Paint();
// canvas.drawBitmap(bitmap, matrix, paint);
// paint.setAntiAlias(true);
// paint.setTextSize(28);
// paint.setColor(context.getResources().getColor(R.color.colorAccent));
// canvas.drawText("Image from", bitmap.getWidth() / 2, bitmap.getHeight() / 2, paint);
// return dest;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/CameraActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import com.demo.amazing.R;
import com.demo.amazing.util.BitmapUtil;
import com.demo.amazing.util.LogUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
release();
}
private void release() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
release();
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
try {
Camera.Size previewSize = camera.getParameters().getPreviewSize(); | LogUtil.e("preview size=" + previewSize.width + " : " + previewSize.height); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/CameraActivity.java | // Path: app/src/main/java/com/demo/amazing/util/BitmapUtil.java
// public class BitmapUtil {
//
// public static Bitmap rotateBitmap(Context context, Bitmap bitmap, int degree) {
// Bitmap dest = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//
// Canvas canvas = new Canvas(dest);
// Matrix matrix = new Matrix();
// matrix.setRotate(degree, bitmap.getWidth() / 2, bitmap.getWidth() / 2);
// //matrix.setRotate(degree);
// Paint paint = new Paint();
// canvas.drawBitmap(bitmap, matrix, paint);
// paint.setAntiAlias(true);
// paint.setTextSize(28);
// paint.setColor(context.getResources().getColor(R.color.colorAccent));
// canvas.drawText("Image from", bitmap.getWidth() / 2, bitmap.getHeight() / 2, paint);
// return dest;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import com.demo.amazing.R;
import com.demo.amazing.util.BitmapUtil;
import com.demo.amazing.util.LogUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; |
private void release() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
release();
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
try {
Camera.Size previewSize = camera.getParameters().getPreviewSize();
LogUtil.e("preview size=" + previewSize.width + " : " + previewSize.height);
YuvImage image = new YuvImage(data, ImageFormat.NV21, previewSize.width, previewSize.height, null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 80, stream);
Bitmap bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
stream.close(); | // Path: app/src/main/java/com/demo/amazing/util/BitmapUtil.java
// public class BitmapUtil {
//
// public static Bitmap rotateBitmap(Context context, Bitmap bitmap, int degree) {
// Bitmap dest = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//
// Canvas canvas = new Canvas(dest);
// Matrix matrix = new Matrix();
// matrix.setRotate(degree, bitmap.getWidth() / 2, bitmap.getWidth() / 2);
// //matrix.setRotate(degree);
// Paint paint = new Paint();
// canvas.drawBitmap(bitmap, matrix, paint);
// paint.setAntiAlias(true);
// paint.setTextSize(28);
// paint.setColor(context.getResources().getColor(R.color.colorAccent));
// canvas.drawText("Image from", bitmap.getWidth() / 2, bitmap.getHeight() / 2, paint);
// return dest;
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/CameraActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import com.demo.amazing.R;
import com.demo.amazing.util.BitmapUtil;
import com.demo.amazing.util.LogUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
private void release() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
release();
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
try {
Camera.Size previewSize = camera.getParameters().getPreviewSize();
LogUtil.e("preview size=" + previewSize.width + " : " + previewSize.height);
YuvImage image = new YuvImage(data, ImageFormat.NV21, previewSize.width, previewSize.height, null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 80, stream);
Bitmap bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
stream.close(); | bitmap = BitmapUtil.rotateBitmap(this, bitmap, 270); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/activity/MoveActivity.java | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.Scroller;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil; | switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getRawX();
downY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
curX = event.getRawX();
curY = event.getRawY();
onLayout();
downX = curX;
downY = curY;
break;
case MotionEvent.ACTION_UP:
onUp();
break;
}
return true;
}
});
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
viewWidth = layout.getWidth();
viewHeight = layout.getHeight();
}
});
}
private void onUp() {
final int offsetX; | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/activity/MoveActivity.java
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.Scroller;
import com.demo.amazing.R;
import com.demo.amazing.util.LogUtil;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getRawX();
downY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
curX = event.getRawX();
curY = event.getRawY();
onLayout();
downX = curX;
downY = curY;
break;
case MotionEvent.ACTION_UP:
onUp();
break;
}
return true;
}
});
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
viewWidth = layout.getWidth();
viewHeight = layout.getHeight();
}
});
}
private void onUp() {
final int offsetX; | LogUtil.e("layout left=" + layout.getLeft() + " x=" + layout.getX()); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/widget/MyRender.java | // Path: app/src/main/java/com/demo/amazing/bean/Square.java
// public class Square {
// private FloatBuffer vertexBuffer;
// private ShortBuffer drawListBuffer;
//
// // number of coordinates per vertex in this array
// static final int COORDS_PER_VERTEX = 3;
// static float squareCoords[] = {-0.5f, 0.5f, 0.0f, // top left
// -0.5f, -0.5f, 0.0f, // bottom left
// 0.5f, -0.5f, 0.0f, // bottom right
// 0.5f, 0.5f, 0.0f}; // top right
//
// private short drawOrder[] = {0, 1, 2, 0, 2, 3}; // order to draw vertices
//
// public Square() {
// // initialize vertex byte buffer for shape coordinates
// ByteBuffer bb = ByteBuffer.allocateDirect(
// // (# of coordinate values * 4 bytes per float)
// squareCoords.length * 4);
// bb.order(ByteOrder.nativeOrder());
// vertexBuffer = bb.asFloatBuffer();
// vertexBuffer.put(squareCoords);
// vertexBuffer.position(0);
//
// // initialize byte buffer for the draw list
// ByteBuffer dlb = ByteBuffer.allocateDirect(
// // (# of coordinate values * 2 bytes per short)
// drawOrder.length * 2);
// dlb.order(ByteOrder.nativeOrder());
// drawListBuffer = dlb.asShortBuffer();
// drawListBuffer.put(drawOrder);
// drawListBuffer.position(0);
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/bean/Triangle.java
// public class Triangle {
//
// private FloatBuffer vertexBuffer;
//
// static final int COORDS_PER_VERTEX = 3;
//
// private final String vertexShaderCode =
// "uniform mat4 uMVPMatrix;" +
// "attribute vec4 vPosition; " +
// "void main(){" + "" +
// " gl_Position = " +
// "uMVPMatrix * vPosition;" + "}";
//
// private final String fragmentShaderCode = "precision mediump float; " + "uniform vec4 vColor; " + "void main(){"
// + " gl_FragColor = vColor;" + "}";
//
// static float triangleCoords[] = { // in counterclockwise order:
// 0.0f, 0.622008459f, 0.0f, // top
// -0.5f, -0.311004243f, 0.0f, // bottom left
// 0.5f, -0.311004243f, 0.0f // bottom right
// };
//
// private final int program;
//
// private int positionHandle;
//
// private int colorHandle;
//
// private int mVPHandle;
//
// private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
//
// private final int vertexStride = COORDS_PER_VERTEX * 4;
//
// // Set color with red, green, blue and alpha (opacity) values
// float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 1.0f};
// //float color[] = {0.0f, 1.0f, 0.0f, 1.0f};
// public Triangle() {
// ByteBuffer byteBuffer = ByteBuffer.allocateDirect(triangleCoords.length * 4);
//
// byteBuffer.order(ByteOrder.nativeOrder());
//
// vertexBuffer = byteBuffer.asFloatBuffer();
//
// vertexBuffer.put(triangleCoords);
// vertexBuffer.position(0);
//
// int vertexShader = MyRender.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
//
// int fragmentShader = MyRender.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
//
// program = GLES20.glCreateProgram();
//
// GLES20.glAttachShader(program, vertexShader);
//
// GLES20.glAttachShader(program, fragmentShader);
//
// GLES20.glLinkProgram(program);
// }
//
// public void draw(float[] mVPMatrix) {
//
// GLES20.glUseProgram(program);
//
// positionHandle = GLES20.glGetAttribLocation(program, "vPosition");
//
//
// GLES20.glEnableVertexAttribArray(positionHandle);
//
// GLES20.glVertexAttribPointer(positionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride,
// vertexBuffer);
//
// colorHandle = GLES20.glGetUniformLocation(program, "vColor");
//
// GLES20.glUniform4fv(colorHandle, 1, color, 0);
//
// mVPHandle = GLES20.glGetUniformLocation(program, "uMVPMatrix");
//
// GLES20.glUniformMatrix4fv(mVPHandle, 1, false, mVPMatrix, 0);
//
// GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
//
// GLES20.glDisableVertexAttribArray(positionHandle);
//
//
// }
//
// }
| import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import com.demo.amazing.bean.Square;
import com.demo.amazing.bean.Triangle;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10; | package com.demo.amazing.widget;
/**
* Created by hzsunyj on 17/5/2.
*/
public class MyRender implements GLSurfaceView.Renderer {
private Triangle triangle;
| // Path: app/src/main/java/com/demo/amazing/bean/Square.java
// public class Square {
// private FloatBuffer vertexBuffer;
// private ShortBuffer drawListBuffer;
//
// // number of coordinates per vertex in this array
// static final int COORDS_PER_VERTEX = 3;
// static float squareCoords[] = {-0.5f, 0.5f, 0.0f, // top left
// -0.5f, -0.5f, 0.0f, // bottom left
// 0.5f, -0.5f, 0.0f, // bottom right
// 0.5f, 0.5f, 0.0f}; // top right
//
// private short drawOrder[] = {0, 1, 2, 0, 2, 3}; // order to draw vertices
//
// public Square() {
// // initialize vertex byte buffer for shape coordinates
// ByteBuffer bb = ByteBuffer.allocateDirect(
// // (# of coordinate values * 4 bytes per float)
// squareCoords.length * 4);
// bb.order(ByteOrder.nativeOrder());
// vertexBuffer = bb.asFloatBuffer();
// vertexBuffer.put(squareCoords);
// vertexBuffer.position(0);
//
// // initialize byte buffer for the draw list
// ByteBuffer dlb = ByteBuffer.allocateDirect(
// // (# of coordinate values * 2 bytes per short)
// drawOrder.length * 2);
// dlb.order(ByteOrder.nativeOrder());
// drawListBuffer = dlb.asShortBuffer();
// drawListBuffer.put(drawOrder);
// drawListBuffer.position(0);
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/bean/Triangle.java
// public class Triangle {
//
// private FloatBuffer vertexBuffer;
//
// static final int COORDS_PER_VERTEX = 3;
//
// private final String vertexShaderCode =
// "uniform mat4 uMVPMatrix;" +
// "attribute vec4 vPosition; " +
// "void main(){" + "" +
// " gl_Position = " +
// "uMVPMatrix * vPosition;" + "}";
//
// private final String fragmentShaderCode = "precision mediump float; " + "uniform vec4 vColor; " + "void main(){"
// + " gl_FragColor = vColor;" + "}";
//
// static float triangleCoords[] = { // in counterclockwise order:
// 0.0f, 0.622008459f, 0.0f, // top
// -0.5f, -0.311004243f, 0.0f, // bottom left
// 0.5f, -0.311004243f, 0.0f // bottom right
// };
//
// private final int program;
//
// private int positionHandle;
//
// private int colorHandle;
//
// private int mVPHandle;
//
// private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
//
// private final int vertexStride = COORDS_PER_VERTEX * 4;
//
// // Set color with red, green, blue and alpha (opacity) values
// float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 1.0f};
// //float color[] = {0.0f, 1.0f, 0.0f, 1.0f};
// public Triangle() {
// ByteBuffer byteBuffer = ByteBuffer.allocateDirect(triangleCoords.length * 4);
//
// byteBuffer.order(ByteOrder.nativeOrder());
//
// vertexBuffer = byteBuffer.asFloatBuffer();
//
// vertexBuffer.put(triangleCoords);
// vertexBuffer.position(0);
//
// int vertexShader = MyRender.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
//
// int fragmentShader = MyRender.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
//
// program = GLES20.glCreateProgram();
//
// GLES20.glAttachShader(program, vertexShader);
//
// GLES20.glAttachShader(program, fragmentShader);
//
// GLES20.glLinkProgram(program);
// }
//
// public void draw(float[] mVPMatrix) {
//
// GLES20.glUseProgram(program);
//
// positionHandle = GLES20.glGetAttribLocation(program, "vPosition");
//
//
// GLES20.glEnableVertexAttribArray(positionHandle);
//
// GLES20.glVertexAttribPointer(positionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride,
// vertexBuffer);
//
// colorHandle = GLES20.glGetUniformLocation(program, "vColor");
//
// GLES20.glUniform4fv(colorHandle, 1, color, 0);
//
// mVPHandle = GLES20.glGetUniformLocation(program, "uMVPMatrix");
//
// GLES20.glUniformMatrix4fv(mVPHandle, 1, false, mVPMatrix, 0);
//
// GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
//
// GLES20.glDisableVertexAttribArray(positionHandle);
//
//
// }
//
// }
// Path: app/src/main/java/com/demo/amazing/widget/MyRender.java
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import com.demo.amazing.bean.Square;
import com.demo.amazing.bean.Triangle;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
package com.demo.amazing.widget;
/**
* Created by hzsunyj on 17/5/2.
*/
public class MyRender implements GLSurfaceView.Renderer {
private Triangle triangle;
| private Square square; |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/app/AmazingApplication.java | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.app.Application;
import com.demo.amazing.util.LogUtil; | package com.demo.amazing.app;
/**
* Created by hzsunyj on 2018/5/4.
*/
public class AmazingApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level); | // Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/app/AmazingApplication.java
import android.app.Application;
import com.demo.amazing.util.LogUtil;
package com.demo.amazing.app;
/**
* Created by hzsunyj on 2018/5/4.
*/
public class AmazingApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level); | LogUtil.d("Application", "onTrimMemory=" + level); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/observer/Observable.java | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
| import com.demo.amazing.net.action.Action;
import java.util.ArrayList; | package com.demo.amazing.net.observer;
/**
* Created by hzsunyj on 2017/8/30.
*/
public class Observable implements Observer {
private final ArrayList<Observer> observers;
public Observable() {
observers = new ArrayList<>();
}
public synchronized void registerObserver(Observer o) {
if (o == null)
return;
if (!observers.contains(o)) {
observers.add(o);
}
}
public synchronized void unrigisterObserver(Observer o) {
observers.remove(o);
}
public void onAction() {
onAction(null);
}
@Override | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
// Path: app/src/main/java/com/demo/amazing/net/observer/Observable.java
import com.demo.amazing.net.action.Action;
import java.util.ArrayList;
package com.demo.amazing.net.observer;
/**
* Created by hzsunyj on 2017/8/30.
*/
public class Observable implements Observer {
private final ArrayList<Observer> observers;
public Observable() {
observers = new ArrayList<>();
}
public synchronized void registerObserver(Observer o) {
if (o == null)
return;
if (!observers.contains(o)) {
observers.add(o);
}
}
public synchronized void unrigisterObserver(Observer o) {
observers.remove(o);
}
public void onAction() {
onAction(null);
}
@Override | public void onAction(Action action) { |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/server/Server.java | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.support.annotation.NonNull;
import com.demo.amazing.net.action.Action;
import com.demo.amazing.util.LogUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.ByteString; | package com.demo.amazing.net.server;
/**
* Created by hzsunyj on 2017/8/30.
*/
public class Server {
MockWebServer mockWebServer;
private String wsUrl;
public Server() {
new Thread(new Runnable() {
@Override
public void run() {
start();
}
}).start();
}
public void getServerUrl() {
String hostName = mockWebServer.getHostName();
int port = mockWebServer.getPort();
StringBuilder sb = new StringBuilder();
sb.append("ws://").append(hostName).append(":").append(port);
wsUrl = sb.toString();
}
private void start() {
mockWebServer = new MockWebServer();
mockWebServer.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response); | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/net/server/Server.java
import android.support.annotation.NonNull;
import com.demo.amazing.net.action.Action;
import com.demo.amazing.util.LogUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.ByteString;
package com.demo.amazing.net.server;
/**
* Created by hzsunyj on 2017/8/30.
*/
public class Server {
MockWebServer mockWebServer;
private String wsUrl;
public Server() {
new Thread(new Runnable() {
@Override
public void run() {
start();
}
}).start();
}
public void getServerUrl() {
String hostName = mockWebServer.getHostName();
int port = mockWebServer.getPort();
StringBuilder sb = new StringBuilder();
sb.append("ws://").append(hostName).append(":").append(port);
wsUrl = sb.toString();
}
private void start() {
mockWebServer = new MockWebServer();
mockWebServer.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response); | LogUtil.e("server onOpen"); |
FreeSunny/Amazing | app/src/main/java/com/demo/amazing/net/server/Server.java | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
| import android.support.annotation.NonNull;
import com.demo.amazing.net.action.Action;
import com.demo.amazing.util.LogUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.ByteString; |
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
LogUtil.e("server onClosed: code=" + code + " reason=" + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
LogUtil.e("server onFailure: t=" + t.getMessage());
}
}));
getServerUrl();
}
AtomicInteger increment = new AtomicInteger(0);
@NonNull
private String getText(String text) { | // Path: app/src/main/java/com/demo/amazing/net/action/Action.java
// public class Action {
//
// public static final int UNKNOWN_ACTION = -1;
//
// public static final int LINK_ACTION = 1;
//
// public static final int FAIL_ACTION = 2;
//
// public static final int VOTE_ACTION = 3;
//
// public static final int DESC_ACTION = 4;
//
// public int action;// 动作类型
//
// public String desc;
//
// public Action(int action) {
// this.action = action;
// }
//
// public Action(int action, String desc) {
// this.action = action;
// this.desc = desc;
// }
//
// public static Action builder() {
// return new Action(UNKNOWN_ACTION, null);
// }
// }
//
// Path: app/src/main/java/com/demo/amazing/util/LogUtil.java
// public class LogUtil {
//
// public static void e(String msg) {
// Log.e("free", msg);
// }
//
// public static void d(String tag, String msg) {
// Log.e("free", msg);
// }
// }
// Path: app/src/main/java/com/demo/amazing/net/server/Server.java
import android.support.annotation.NonNull;
import com.demo.amazing.net.action.Action;
import com.demo.amazing.util.LogUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.ByteString;
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
LogUtil.e("server onClosed: code=" + code + " reason=" + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
super.onFailure(webSocket, t, response);
LogUtil.e("server onFailure: t=" + t.getMessage());
}
}));
getServerUrl();
}
AtomicInteger increment = new AtomicInteger(0);
@NonNull
private String getText(String text) { | int action = Action.UNKNOWN_ACTION; |
philipperemy/Leboncoin | src/run/DeleteAdMailCleaner.java | // Path: src/mail/MailManager.java
// public class MailManager {
//
// public synchronized static boolean doAction(MessageProcess f) {
// return doActionGmail(f, 0);
// }
//
// static int MAX_ATTEMPS = 10;
//
// public synchronized static boolean doActionGmail(MessageProcess f,
// int attempts) {
// try {
// Properties props = System.getProperties();
// props.setProperty("mail.smtp.host", "smtp.gmail.com");
// props.setProperty("mail.smtp.socketFactory.port", "465");
// props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props, null);
// Store store = session.getStore("imaps");
// store.connect("smtp.gmail.com", DefaultUserConf.EMAIL,
// DefaultUserConf.PASSWORD);
//
// Folder inbox = store.getFolder("Inbox");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionGmail(f, attempts++);
// }
// }
// return false;
// }
//
// public synchronized static boolean doActionAEI(MessageProcess f,
// int attempts) {
// try {
// Properties props = new Properties();
// props.put("mail.smtp.host", "ssl0.ovh.net");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.socketFactory.class",
// "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props,
// new javax.mail.Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(
// "philippe.remy%junior-aei.com", "phremy");
// }
// });
//
// Store store = session.getStore("imap");
// store.connect("ssl0.ovh.net", "philippe.remy%junior-aei.com",
// "phremy");
//
// // Get folder
// Folder inbox = store.getFolder("INBOX");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionAEI(f, attempts++);
// }
// }
//
// return false;
// }
//
// }
//
// Path: src/mail/processing/CleanDeletingAdEmail.java
// public class CleanDeletingAdEmail implements MessageProcess
// {
// @Override
// public void treatMessage(Message message) throws Exception
// {
// String sender = InternetAddress.toString(message.getFrom());
// String subject = message.getSubject();
// if (sender.contains("leboncoin.fr") && subject.contains("Suppression de votre annonce"))
// {
// Logger.traceINFO("Received : " + subject);
// Logger.traceINFO("Cleaning this email");
// message.setFlag(Flag.SEEN, true);
// }
// }
//
// }
| import mail.MailManager;
import mail.processing.CleanDeletingAdEmail;
| package run;
public class DeleteAdMailCleaner implements LeboncoinRunner
{
@Override
public void run()
{
| // Path: src/mail/MailManager.java
// public class MailManager {
//
// public synchronized static boolean doAction(MessageProcess f) {
// return doActionGmail(f, 0);
// }
//
// static int MAX_ATTEMPS = 10;
//
// public synchronized static boolean doActionGmail(MessageProcess f,
// int attempts) {
// try {
// Properties props = System.getProperties();
// props.setProperty("mail.smtp.host", "smtp.gmail.com");
// props.setProperty("mail.smtp.socketFactory.port", "465");
// props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props, null);
// Store store = session.getStore("imaps");
// store.connect("smtp.gmail.com", DefaultUserConf.EMAIL,
// DefaultUserConf.PASSWORD);
//
// Folder inbox = store.getFolder("Inbox");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionGmail(f, attempts++);
// }
// }
// return false;
// }
//
// public synchronized static boolean doActionAEI(MessageProcess f,
// int attempts) {
// try {
// Properties props = new Properties();
// props.put("mail.smtp.host", "ssl0.ovh.net");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.socketFactory.class",
// "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props,
// new javax.mail.Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(
// "philippe.remy%junior-aei.com", "phremy");
// }
// });
//
// Store store = session.getStore("imap");
// store.connect("ssl0.ovh.net", "philippe.remy%junior-aei.com",
// "phremy");
//
// // Get folder
// Folder inbox = store.getFolder("INBOX");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionAEI(f, attempts++);
// }
// }
//
// return false;
// }
//
// }
//
// Path: src/mail/processing/CleanDeletingAdEmail.java
// public class CleanDeletingAdEmail implements MessageProcess
// {
// @Override
// public void treatMessage(Message message) throws Exception
// {
// String sender = InternetAddress.toString(message.getFrom());
// String subject = message.getSubject();
// if (sender.contains("leboncoin.fr") && subject.contains("Suppression de votre annonce"))
// {
// Logger.traceINFO("Received : " + subject);
// Logger.traceINFO("Cleaning this email");
// message.setFlag(Flag.SEEN, true);
// }
// }
//
// }
// Path: src/run/DeleteAdMailCleaner.java
import mail.MailManager;
import mail.processing.CleanDeletingAdEmail;
package run;
public class DeleteAdMailCleaner implements LeboncoinRunner
{
@Override
public void run()
{
| MailManager.doAction(new CleanDeletingAdEmail());
|
philipperemy/Leboncoin | src/run/DeleteAdMailCleaner.java | // Path: src/mail/MailManager.java
// public class MailManager {
//
// public synchronized static boolean doAction(MessageProcess f) {
// return doActionGmail(f, 0);
// }
//
// static int MAX_ATTEMPS = 10;
//
// public synchronized static boolean doActionGmail(MessageProcess f,
// int attempts) {
// try {
// Properties props = System.getProperties();
// props.setProperty("mail.smtp.host", "smtp.gmail.com");
// props.setProperty("mail.smtp.socketFactory.port", "465");
// props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props, null);
// Store store = session.getStore("imaps");
// store.connect("smtp.gmail.com", DefaultUserConf.EMAIL,
// DefaultUserConf.PASSWORD);
//
// Folder inbox = store.getFolder("Inbox");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionGmail(f, attempts++);
// }
// }
// return false;
// }
//
// public synchronized static boolean doActionAEI(MessageProcess f,
// int attempts) {
// try {
// Properties props = new Properties();
// props.put("mail.smtp.host", "ssl0.ovh.net");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.socketFactory.class",
// "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props,
// new javax.mail.Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(
// "philippe.remy%junior-aei.com", "phremy");
// }
// });
//
// Store store = session.getStore("imap");
// store.connect("ssl0.ovh.net", "philippe.remy%junior-aei.com",
// "phremy");
//
// // Get folder
// Folder inbox = store.getFolder("INBOX");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionAEI(f, attempts++);
// }
// }
//
// return false;
// }
//
// }
//
// Path: src/mail/processing/CleanDeletingAdEmail.java
// public class CleanDeletingAdEmail implements MessageProcess
// {
// @Override
// public void treatMessage(Message message) throws Exception
// {
// String sender = InternetAddress.toString(message.getFrom());
// String subject = message.getSubject();
// if (sender.contains("leboncoin.fr") && subject.contains("Suppression de votre annonce"))
// {
// Logger.traceINFO("Received : " + subject);
// Logger.traceINFO("Cleaning this email");
// message.setFlag(Flag.SEEN, true);
// }
// }
//
// }
| import mail.MailManager;
import mail.processing.CleanDeletingAdEmail;
| package run;
public class DeleteAdMailCleaner implements LeboncoinRunner
{
@Override
public void run()
{
| // Path: src/mail/MailManager.java
// public class MailManager {
//
// public synchronized static boolean doAction(MessageProcess f) {
// return doActionGmail(f, 0);
// }
//
// static int MAX_ATTEMPS = 10;
//
// public synchronized static boolean doActionGmail(MessageProcess f,
// int attempts) {
// try {
// Properties props = System.getProperties();
// props.setProperty("mail.smtp.host", "smtp.gmail.com");
// props.setProperty("mail.smtp.socketFactory.port", "465");
// props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.setProperty("mail.smtp.auth", "true");
// props.setProperty("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props, null);
// Store store = session.getStore("imaps");
// store.connect("smtp.gmail.com", DefaultUserConf.EMAIL,
// DefaultUserConf.PASSWORD);
//
// Folder inbox = store.getFolder("Inbox");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionGmail(f, attempts++);
// }
// }
// return false;
// }
//
// public synchronized static boolean doActionAEI(MessageProcess f,
// int attempts) {
// try {
// Properties props = new Properties();
// props.put("mail.smtp.host", "ssl0.ovh.net");
// props.put("mail.smtp.socketFactory.port", "465");
// props.put("mail.smtp.socketFactory.class",
// "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.port", "465");
//
// Session session = Session.getDefaultInstance(props,
// new javax.mail.Authenticator() {
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(
// "philippe.remy%junior-aei.com", "phremy");
// }
// });
//
// Store store = session.getStore("imap");
// store.connect("ssl0.ovh.net", "philippe.remy%junior-aei.com",
// "phremy");
//
// // Get folder
// Folder inbox = store.getFolder("INBOX");
// inbox.open(Folder.READ_WRITE);
//
// // Get directory
// Flags seen = new Flags(Flags.Flag.SEEN);
// FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
// Message messages[] = inbox.search(unseenFlagTerm);
//
// for (int i = 0; i < messages.length; i++) {
// f.treatMessage(messages[i]);
// }
//
// // Close connection
// inbox.close(true);
// store.close();
//
// return true;
// } catch (Exception e) {
// Logger.traceERROR(e);
// Logger.traceERROR("Attempts : " + attempts + " / " + MAX_ATTEMPS);
// if (attempts > MAX_ATTEMPS) {
// return false;
// } else {
// doActionAEI(f, attempts++);
// }
// }
//
// return false;
// }
//
// }
//
// Path: src/mail/processing/CleanDeletingAdEmail.java
// public class CleanDeletingAdEmail implements MessageProcess
// {
// @Override
// public void treatMessage(Message message) throws Exception
// {
// String sender = InternetAddress.toString(message.getFrom());
// String subject = message.getSubject();
// if (sender.contains("leboncoin.fr") && subject.contains("Suppression de votre annonce"))
// {
// Logger.traceINFO("Received : " + subject);
// Logger.traceINFO("Cleaning this email");
// message.setFlag(Flag.SEEN, true);
// }
// }
//
// }
// Path: src/run/DeleteAdMailCleaner.java
import mail.MailManager;
import mail.processing.CleanDeletingAdEmail;
package run;
public class DeleteAdMailCleaner implements LeboncoinRunner
{
@Override
public void run()
{
| MailManager.doAction(new CleanDeletingAdEmail());
|
philipperemy/Leboncoin | src/utils/Utils.java | // Path: src/log/Logger.java
// public class Logger
// {
// private static final String infoKey = "INFO";
// private static final String errorKey = "ERROR";
//
// private static final Printer out = new Printer();
//
// public static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//
// private static String getCallingClass()
// {
// final Throwable t = new Throwable();
// final StackTraceElement methodCaller = t.getStackTrace()[3];
// String filename = methodCaller.getFileName();
// return filename.substring(0, filename.lastIndexOf('.'));
// }
//
// private static String baseLogMessage(String key, String msg)
// {
// return sdf.format(new Date()) + " [" + key + "] [" + getCallingClass() + "] " + msg;
// }
//
// public static void traceINFO(String msg)
// {
// out.println(baseLogMessage(infoKey, msg));
// }
//
// public static void traceINFO_NoNewLine(String msg)
// {
// out.print(baseLogMessage(infoKey, msg));
// }
//
// public static void traceINFO_NoBaseLine(String msg)
// {
// out.println(msg);
// }
//
// public static void traceERROR(String msg)
// {
// out.println(baseLogMessage(errorKey, msg));
// }
//
// public static void traceINFO(int level, long[] array)
// {
// StringBuilder sBuilder = new StringBuilder();
// sBuilder.append(level + " : ");
// for (int i = 0; i < array.length; i++)
// {
// if (i == array.length - 1)
// {
//
// sBuilder.append(array[i]);
// }
// else
// {
// sBuilder.append(array[i] + ", ");
// }
// }
// traceINFO(sBuilder.toString());
// }
//
// public static void traceINFO(String... msgs)
// {
// StringBuilder sBuilder = new StringBuilder();
// for (int i = 0; i < msgs.length; i++)
// {
// if (i == msgs.length - 1)
// {
//
// sBuilder.append(msgs[i]);
// }
// else
// {
// sBuilder.append(msgs[i] + ", ");
// }
// }
// traceINFO(sBuilder.toString());
// }
//
// public static void traceERROR(Exception e)
// {
// if (e != null)
// {
// out.println(baseLogMessage(errorKey, e.getMessage()));
// e.printStackTrace(System.out);
// }
// }
//
// public static void endLogging()
// {
// out.close();
// }
// }
| import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import log.Logger;
| package utils;
public class Utils
{
public static void sleep(int sec)
{
try
{
Thread.sleep(sec * 1000);
}
catch (InterruptedException e)
{
| // Path: src/log/Logger.java
// public class Logger
// {
// private static final String infoKey = "INFO";
// private static final String errorKey = "ERROR";
//
// private static final Printer out = new Printer();
//
// public static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//
// private static String getCallingClass()
// {
// final Throwable t = new Throwable();
// final StackTraceElement methodCaller = t.getStackTrace()[3];
// String filename = methodCaller.getFileName();
// return filename.substring(0, filename.lastIndexOf('.'));
// }
//
// private static String baseLogMessage(String key, String msg)
// {
// return sdf.format(new Date()) + " [" + key + "] [" + getCallingClass() + "] " + msg;
// }
//
// public static void traceINFO(String msg)
// {
// out.println(baseLogMessage(infoKey, msg));
// }
//
// public static void traceINFO_NoNewLine(String msg)
// {
// out.print(baseLogMessage(infoKey, msg));
// }
//
// public static void traceINFO_NoBaseLine(String msg)
// {
// out.println(msg);
// }
//
// public static void traceERROR(String msg)
// {
// out.println(baseLogMessage(errorKey, msg));
// }
//
// public static void traceINFO(int level, long[] array)
// {
// StringBuilder sBuilder = new StringBuilder();
// sBuilder.append(level + " : ");
// for (int i = 0; i < array.length; i++)
// {
// if (i == array.length - 1)
// {
//
// sBuilder.append(array[i]);
// }
// else
// {
// sBuilder.append(array[i] + ", ");
// }
// }
// traceINFO(sBuilder.toString());
// }
//
// public static void traceINFO(String... msgs)
// {
// StringBuilder sBuilder = new StringBuilder();
// for (int i = 0; i < msgs.length; i++)
// {
// if (i == msgs.length - 1)
// {
//
// sBuilder.append(msgs[i]);
// }
// else
// {
// sBuilder.append(msgs[i] + ", ");
// }
// }
// traceINFO(sBuilder.toString());
// }
//
// public static void traceERROR(Exception e)
// {
// if (e != null)
// {
// out.println(baseLogMessage(errorKey, e.getMessage()));
// e.printStackTrace(System.out);
// }
// }
//
// public static void endLogging()
// {
// out.close();
// }
// }
// Path: src/utils/Utils.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import log.Logger;
package utils;
public class Utils
{
public static void sleep(int sec)
{
try
{
Thread.sleep(sec * 1000);
}
catch (InterruptedException e)
{
| Logger.traceERROR(e);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.