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 |
|---|---|---|---|---|---|---|
AdamBien/headlands | headlands/src/main/java/com/airhacks/headlands/notifications/boundary/WebSocketFirehose.java | // Path: headlands/src/main/java/com/airhacks/headlands/notifications/entity/CacheChangedEvent.java
// public class CacheChangedEvent {
//
// private EventType type;
// private String cacheName;
// private JsonArrayBuilder payload;
//
// public CacheChangedEvent(String cacheName, EventType type) {
// this.type = type;
// this.cacheName = cacheName;
// this.payload = Json.createArrayBuilder();
// }
//
// public void consume(CacheEntryEvent<? extends String, ? extends String> event) {
// String key = event.getKey();
// String value = event.getValue();
// String oldValue = event.getOldValue();
// JsonObjectBuilder builder = Json.createObjectBuilder().add("newValue", value);
// if (oldValue != null) {
// builder.add("oldValue", oldValue);
// }
// JsonObject diff = builder.build();
//
// JsonObject changeSet = Json.createObjectBuilder().
// add("cacheName", cacheName).
// add("eventType", type.name()).
// add("key", key).
// add(key, diff).
// build();
// payload.add(changeSet);
// }
//
// public JsonArray getPayload() {
// return payload.build();
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// }
| import com.airhacks.headlands.notifications.entity.CacheChangedEvent;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;
import javax.enterprise.event.Observes;
import javax.json.JsonArray;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint; | package com.airhacks.headlands.notifications.boundary;
/**
*
* @author airhacks.com
*/
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@ServerEndpoint(value = "/firehose/{cache-name}", encoders = JsonArrayEncoder.class)
public class WebSocketFirehose {
CopyOnWriteArrayList<Session> sessions;
@PostConstruct
public void init() {
this.sessions = new CopyOnWriteArrayList<>();
}
@OnOpen
public void onConnect(Session session, @PathParam("cache-name") String cacheName) {
System.out.println("uri: " + session.getRequestURI().toString());
this.sessions.add(session);
}
@OnClose
public void onClose(Session session) {
this.sessions.remove(session);
}
| // Path: headlands/src/main/java/com/airhacks/headlands/notifications/entity/CacheChangedEvent.java
// public class CacheChangedEvent {
//
// private EventType type;
// private String cacheName;
// private JsonArrayBuilder payload;
//
// public CacheChangedEvent(String cacheName, EventType type) {
// this.type = type;
// this.cacheName = cacheName;
// this.payload = Json.createArrayBuilder();
// }
//
// public void consume(CacheEntryEvent<? extends String, ? extends String> event) {
// String key = event.getKey();
// String value = event.getValue();
// String oldValue = event.getOldValue();
// JsonObjectBuilder builder = Json.createObjectBuilder().add("newValue", value);
// if (oldValue != null) {
// builder.add("oldValue", oldValue);
// }
// JsonObject diff = builder.build();
//
// JsonObject changeSet = Json.createObjectBuilder().
// add("cacheName", cacheName).
// add("eventType", type.name()).
// add("key", key).
// add(key, diff).
// build();
// payload.add(changeSet);
// }
//
// public JsonArray getPayload() {
// return payload.build();
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// }
// Path: headlands/src/main/java/com/airhacks/headlands/notifications/boundary/WebSocketFirehose.java
import com.airhacks.headlands.notifications.entity.CacheChangedEvent;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;
import javax.enterprise.event.Observes;
import javax.json.JsonArray;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
package com.airhacks.headlands.notifications.boundary;
/**
*
* @author airhacks.com
*/
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@ServerEndpoint(value = "/firehose/{cache-name}", encoders = JsonArrayEncoder.class)
public class WebSocketFirehose {
CopyOnWriteArrayList<Session> sessions;
@PostConstruct
public void init() {
this.sessions = new CopyOnWriteArrayList<>();
}
@OnOpen
public void onConnect(Session session, @PathParam("cache-name") String cacheName) {
System.out.println("uri: " + session.getRequestURI().toString());
this.sessions.add(session);
}
@OnClose
public void onClose(Session session) {
this.sessions.remove(session);
}
| public void onChange(@Observes CacheChangedEvent event) { |
AdamBien/headlands | headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesPresenter.java | // Path: headlands-ui/src/main/java/com/airhacks/headlands/CacheAccessor.java
// public class CacheAccessor {
//
// private ObjectProperty<Cache<String, String>> currentCache;
// private CachingProvider cachingProvider;
// private CacheManager cacheManager;
//
// private SimpleBooleanProperty cacheStarted;
//
// private ExecutorService executor;
//
// @PostConstruct
// public void initialize() {
// System.setProperty("hazelcast.jcache.provider.type", "server");
// this.currentCache = new SimpleObjectProperty<>();
// this.cacheStarted = new SimpleBooleanProperty();
// this.executor = Executors.newCachedThreadPool();
// }
//
// public void store(String keyString, String valueString) {
// getCurrentCache().put(keyString, valueString);
// }
//
// public List<String> getCacheNames() {
// List<String> caches = new ArrayList<>();
// Iterable<String> names = this.cacheManager.getCacheNames();
// names.forEach(caches::add);
// return caches;
// }
//
// public void start() {
// this.executor.submit(() -> {
// this.cachingProvider = Caching.getCachingProvider();
// this.cacheManager = cachingProvider.getCacheManager();
// runLater(() -> this.cacheStarted.set(true));
// }
// );
// }
//
// public BooleanProperty isStarted() {
// return cacheStarted;
// }
//
// public void stop() {
// this.executor.submit(() -> {
// getCurrentCache().close();
// this.cacheManager.close();
// this.cachingProvider.close();
// runLater(() -> this.cacheStarted.set(false));
//
// });
//
// }
//
// public void createCache(String cacheName) {
// MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
//
// configuration.setStoreByValue(false).
// setTypes(String.class, String.class).
// setManagementEnabled(true).
// setStoreByValue(true);
//
// this.currentCache.set(cacheManager.
// createCache(cacheName, configuration));
//
// }
//
// public String getValue(String key) {
// return getCurrentCache().get(key);
// }
//
// public List<Cache.Entry<String, String>> getAllEntries() {
// List<Cache.Entry<String, String>> entries = new ArrayList<>();
// for (Cache.Entry<String, String> entry : getCurrentCache()) {
// entries.add(entry);
// }
// return entries;
// }
//
// public void remove(String key) {
// getCurrentCache().remove(key);
// }
//
// public void selectCache(String cacheName) {
// this.currentCache.set(this.cacheManager.getCache(cacheName, String.class, String.class));
// }
//
// Cache<String, String> getCurrentCache() {
// return this.currentCache.get();
// }
//
// public ObjectProperty<Cache<String, String>> currentCacheProperty() {
// return this.currentCache;
// }
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/HazelcastDiscoverer.java
// public class HazelcastDiscoverer {
//
// public List<String> getMapNames() {
// Set<HazelcastInstance> allHazelcastInstances = Hazelcast.getAllHazelcastInstances();
// return allHazelcastInstances.stream().map(i -> i.getDistributedObjects()).
// map(this::convert).flatMap(list -> list.stream()).collect(Collectors.toList());
// }
//
// List<String> convert(Collection<DistributedObject> distributedObjects) {
// return distributedObjects.stream().map(this::extractCacheName).
// flatMap(list -> list.stream()).
// collect(Collectors.toList());
// }
//
// List<String> extractCacheName(DistributedObject distributedObject) {
// CacheDistributedObject cdo = (CacheDistributedObject) distributedObject;
// return cdo.getService().getCacheConfigs().
// stream().map(c -> c.getName()).
// collect(Collectors.toList());
//
// }
//
// }
| import com.airhacks.headlands.CacheAccessor;
import com.airhacks.headlands.HazelcastDiscoverer;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.BooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javax.inject.Inject; | package com.airhacks.headlands.caches;
/**
*
* @author airhacks.com
*/
public class CachesPresenter implements Initializable {
@FXML
ComboBox<String> caches;
@Inject | // Path: headlands-ui/src/main/java/com/airhacks/headlands/CacheAccessor.java
// public class CacheAccessor {
//
// private ObjectProperty<Cache<String, String>> currentCache;
// private CachingProvider cachingProvider;
// private CacheManager cacheManager;
//
// private SimpleBooleanProperty cacheStarted;
//
// private ExecutorService executor;
//
// @PostConstruct
// public void initialize() {
// System.setProperty("hazelcast.jcache.provider.type", "server");
// this.currentCache = new SimpleObjectProperty<>();
// this.cacheStarted = new SimpleBooleanProperty();
// this.executor = Executors.newCachedThreadPool();
// }
//
// public void store(String keyString, String valueString) {
// getCurrentCache().put(keyString, valueString);
// }
//
// public List<String> getCacheNames() {
// List<String> caches = new ArrayList<>();
// Iterable<String> names = this.cacheManager.getCacheNames();
// names.forEach(caches::add);
// return caches;
// }
//
// public void start() {
// this.executor.submit(() -> {
// this.cachingProvider = Caching.getCachingProvider();
// this.cacheManager = cachingProvider.getCacheManager();
// runLater(() -> this.cacheStarted.set(true));
// }
// );
// }
//
// public BooleanProperty isStarted() {
// return cacheStarted;
// }
//
// public void stop() {
// this.executor.submit(() -> {
// getCurrentCache().close();
// this.cacheManager.close();
// this.cachingProvider.close();
// runLater(() -> this.cacheStarted.set(false));
//
// });
//
// }
//
// public void createCache(String cacheName) {
// MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
//
// configuration.setStoreByValue(false).
// setTypes(String.class, String.class).
// setManagementEnabled(true).
// setStoreByValue(true);
//
// this.currentCache.set(cacheManager.
// createCache(cacheName, configuration));
//
// }
//
// public String getValue(String key) {
// return getCurrentCache().get(key);
// }
//
// public List<Cache.Entry<String, String>> getAllEntries() {
// List<Cache.Entry<String, String>> entries = new ArrayList<>();
// for (Cache.Entry<String, String> entry : getCurrentCache()) {
// entries.add(entry);
// }
// return entries;
// }
//
// public void remove(String key) {
// getCurrentCache().remove(key);
// }
//
// public void selectCache(String cacheName) {
// this.currentCache.set(this.cacheManager.getCache(cacheName, String.class, String.class));
// }
//
// Cache<String, String> getCurrentCache() {
// return this.currentCache.get();
// }
//
// public ObjectProperty<Cache<String, String>> currentCacheProperty() {
// return this.currentCache;
// }
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/HazelcastDiscoverer.java
// public class HazelcastDiscoverer {
//
// public List<String> getMapNames() {
// Set<HazelcastInstance> allHazelcastInstances = Hazelcast.getAllHazelcastInstances();
// return allHazelcastInstances.stream().map(i -> i.getDistributedObjects()).
// map(this::convert).flatMap(list -> list.stream()).collect(Collectors.toList());
// }
//
// List<String> convert(Collection<DistributedObject> distributedObjects) {
// return distributedObjects.stream().map(this::extractCacheName).
// flatMap(list -> list.stream()).
// collect(Collectors.toList());
// }
//
// List<String> extractCacheName(DistributedObject distributedObject) {
// CacheDistributedObject cdo = (CacheDistributedObject) distributedObject;
// return cdo.getService().getCacheConfigs().
// stream().map(c -> c.getName()).
// collect(Collectors.toList());
//
// }
//
// }
// Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesPresenter.java
import com.airhacks.headlands.CacheAccessor;
import com.airhacks.headlands.HazelcastDiscoverer;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.BooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javax.inject.Inject;
package com.airhacks.headlands.caches;
/**
*
* @author airhacks.com
*/
public class CachesPresenter implements Initializable {
@FXML
ComboBox<String> caches;
@Inject | CacheAccessor accessor; |
AdamBien/headlands | headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesPresenter.java | // Path: headlands-ui/src/main/java/com/airhacks/headlands/CacheAccessor.java
// public class CacheAccessor {
//
// private ObjectProperty<Cache<String, String>> currentCache;
// private CachingProvider cachingProvider;
// private CacheManager cacheManager;
//
// private SimpleBooleanProperty cacheStarted;
//
// private ExecutorService executor;
//
// @PostConstruct
// public void initialize() {
// System.setProperty("hazelcast.jcache.provider.type", "server");
// this.currentCache = new SimpleObjectProperty<>();
// this.cacheStarted = new SimpleBooleanProperty();
// this.executor = Executors.newCachedThreadPool();
// }
//
// public void store(String keyString, String valueString) {
// getCurrentCache().put(keyString, valueString);
// }
//
// public List<String> getCacheNames() {
// List<String> caches = new ArrayList<>();
// Iterable<String> names = this.cacheManager.getCacheNames();
// names.forEach(caches::add);
// return caches;
// }
//
// public void start() {
// this.executor.submit(() -> {
// this.cachingProvider = Caching.getCachingProvider();
// this.cacheManager = cachingProvider.getCacheManager();
// runLater(() -> this.cacheStarted.set(true));
// }
// );
// }
//
// public BooleanProperty isStarted() {
// return cacheStarted;
// }
//
// public void stop() {
// this.executor.submit(() -> {
// getCurrentCache().close();
// this.cacheManager.close();
// this.cachingProvider.close();
// runLater(() -> this.cacheStarted.set(false));
//
// });
//
// }
//
// public void createCache(String cacheName) {
// MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
//
// configuration.setStoreByValue(false).
// setTypes(String.class, String.class).
// setManagementEnabled(true).
// setStoreByValue(true);
//
// this.currentCache.set(cacheManager.
// createCache(cacheName, configuration));
//
// }
//
// public String getValue(String key) {
// return getCurrentCache().get(key);
// }
//
// public List<Cache.Entry<String, String>> getAllEntries() {
// List<Cache.Entry<String, String>> entries = new ArrayList<>();
// for (Cache.Entry<String, String> entry : getCurrentCache()) {
// entries.add(entry);
// }
// return entries;
// }
//
// public void remove(String key) {
// getCurrentCache().remove(key);
// }
//
// public void selectCache(String cacheName) {
// this.currentCache.set(this.cacheManager.getCache(cacheName, String.class, String.class));
// }
//
// Cache<String, String> getCurrentCache() {
// return this.currentCache.get();
// }
//
// public ObjectProperty<Cache<String, String>> currentCacheProperty() {
// return this.currentCache;
// }
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/HazelcastDiscoverer.java
// public class HazelcastDiscoverer {
//
// public List<String> getMapNames() {
// Set<HazelcastInstance> allHazelcastInstances = Hazelcast.getAllHazelcastInstances();
// return allHazelcastInstances.stream().map(i -> i.getDistributedObjects()).
// map(this::convert).flatMap(list -> list.stream()).collect(Collectors.toList());
// }
//
// List<String> convert(Collection<DistributedObject> distributedObjects) {
// return distributedObjects.stream().map(this::extractCacheName).
// flatMap(list -> list.stream()).
// collect(Collectors.toList());
// }
//
// List<String> extractCacheName(DistributedObject distributedObject) {
// CacheDistributedObject cdo = (CacheDistributedObject) distributedObject;
// return cdo.getService().getCacheConfigs().
// stream().map(c -> c.getName()).
// collect(Collectors.toList());
//
// }
//
// }
| import com.airhacks.headlands.CacheAccessor;
import com.airhacks.headlands.HazelcastDiscoverer;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.BooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javax.inject.Inject; | package com.airhacks.headlands.caches;
/**
*
* @author airhacks.com
*/
public class CachesPresenter implements Initializable {
@FXML
ComboBox<String> caches;
@Inject
CacheAccessor accessor;
@FXML
Button startButton;
@FXML
Button stopButton;
@FXML
Button createCacheButton;
@FXML
TextField cacheNameField;
@Inject | // Path: headlands-ui/src/main/java/com/airhacks/headlands/CacheAccessor.java
// public class CacheAccessor {
//
// private ObjectProperty<Cache<String, String>> currentCache;
// private CachingProvider cachingProvider;
// private CacheManager cacheManager;
//
// private SimpleBooleanProperty cacheStarted;
//
// private ExecutorService executor;
//
// @PostConstruct
// public void initialize() {
// System.setProperty("hazelcast.jcache.provider.type", "server");
// this.currentCache = new SimpleObjectProperty<>();
// this.cacheStarted = new SimpleBooleanProperty();
// this.executor = Executors.newCachedThreadPool();
// }
//
// public void store(String keyString, String valueString) {
// getCurrentCache().put(keyString, valueString);
// }
//
// public List<String> getCacheNames() {
// List<String> caches = new ArrayList<>();
// Iterable<String> names = this.cacheManager.getCacheNames();
// names.forEach(caches::add);
// return caches;
// }
//
// public void start() {
// this.executor.submit(() -> {
// this.cachingProvider = Caching.getCachingProvider();
// this.cacheManager = cachingProvider.getCacheManager();
// runLater(() -> this.cacheStarted.set(true));
// }
// );
// }
//
// public BooleanProperty isStarted() {
// return cacheStarted;
// }
//
// public void stop() {
// this.executor.submit(() -> {
// getCurrentCache().close();
// this.cacheManager.close();
// this.cachingProvider.close();
// runLater(() -> this.cacheStarted.set(false));
//
// });
//
// }
//
// public void createCache(String cacheName) {
// MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
//
// configuration.setStoreByValue(false).
// setTypes(String.class, String.class).
// setManagementEnabled(true).
// setStoreByValue(true);
//
// this.currentCache.set(cacheManager.
// createCache(cacheName, configuration));
//
// }
//
// public String getValue(String key) {
// return getCurrentCache().get(key);
// }
//
// public List<Cache.Entry<String, String>> getAllEntries() {
// List<Cache.Entry<String, String>> entries = new ArrayList<>();
// for (Cache.Entry<String, String> entry : getCurrentCache()) {
// entries.add(entry);
// }
// return entries;
// }
//
// public void remove(String key) {
// getCurrentCache().remove(key);
// }
//
// public void selectCache(String cacheName) {
// this.currentCache.set(this.cacheManager.getCache(cacheName, String.class, String.class));
// }
//
// Cache<String, String> getCurrentCache() {
// return this.currentCache.get();
// }
//
// public ObjectProperty<Cache<String, String>> currentCacheProperty() {
// return this.currentCache;
// }
//
// }
//
// Path: headlands-ui/src/main/java/com/airhacks/headlands/HazelcastDiscoverer.java
// public class HazelcastDiscoverer {
//
// public List<String> getMapNames() {
// Set<HazelcastInstance> allHazelcastInstances = Hazelcast.getAllHazelcastInstances();
// return allHazelcastInstances.stream().map(i -> i.getDistributedObjects()).
// map(this::convert).flatMap(list -> list.stream()).collect(Collectors.toList());
// }
//
// List<String> convert(Collection<DistributedObject> distributedObjects) {
// return distributedObjects.stream().map(this::extractCacheName).
// flatMap(list -> list.stream()).
// collect(Collectors.toList());
// }
//
// List<String> extractCacheName(DistributedObject distributedObject) {
// CacheDistributedObject cdo = (CacheDistributedObject) distributedObject;
// return cdo.getService().getCacheConfigs().
// stream().map(c -> c.getName()).
// collect(Collectors.toList());
//
// }
//
// }
// Path: headlands-ui/src/main/java/com/airhacks/headlands/caches/CachesPresenter.java
import com.airhacks.headlands.CacheAccessor;
import com.airhacks.headlands.HazelcastDiscoverer;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.BooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javax.inject.Inject;
package com.airhacks.headlands.caches;
/**
*
* @author airhacks.com
*/
public class CachesPresenter implements Initializable {
@FXML
ComboBox<String> caches;
@Inject
CacheAccessor accessor;
@FXML
Button startButton;
@FXML
Button stopButton;
@FXML
Button createCacheButton;
@FXML
TextField cacheNameField;
@Inject | HazelcastDiscoverer discoverer; |
AdamBien/headlands | headlands/src/main/java/com/airhacks/headlands/notifications/control/CacheEntryChangedListener.java | // Path: headlands/src/main/java/com/airhacks/headlands/notifications/entity/CacheChangedEvent.java
// public class CacheChangedEvent {
//
// private EventType type;
// private String cacheName;
// private JsonArrayBuilder payload;
//
// public CacheChangedEvent(String cacheName, EventType type) {
// this.type = type;
// this.cacheName = cacheName;
// this.payload = Json.createArrayBuilder();
// }
//
// public void consume(CacheEntryEvent<? extends String, ? extends String> event) {
// String key = event.getKey();
// String value = event.getValue();
// String oldValue = event.getOldValue();
// JsonObjectBuilder builder = Json.createObjectBuilder().add("newValue", value);
// if (oldValue != null) {
// builder.add("oldValue", oldValue);
// }
// JsonObject diff = builder.build();
//
// JsonObject changeSet = Json.createObjectBuilder().
// add("cacheName", cacheName).
// add("eventType", type.name()).
// add("key", key).
// add(key, diff).
// build();
// payload.add(changeSet);
// }
//
// public JsonArray getPayload() {
// return payload.build();
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// }
| import com.airhacks.headlands.notifications.entity.CacheChangedEvent;
import java.io.Serializable;
import java.util.function.Consumer;
import javax.cache.event.CacheEntryCreatedListener;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryListenerException;
import javax.cache.event.CacheEntryRemovedListener;
import javax.cache.event.CacheEntryUpdatedListener;
import javax.cache.event.EventType; | package com.airhacks.headlands.notifications.control;
/**
*
* @author airhacks.com
*/
public class CacheEntryChangedListener implements CacheEntryCreatedListener<String, String>,
CacheEntryUpdatedListener<String, String>,
CacheEntryRemovedListener<String, String>,
Serializable {
| // Path: headlands/src/main/java/com/airhacks/headlands/notifications/entity/CacheChangedEvent.java
// public class CacheChangedEvent {
//
// private EventType type;
// private String cacheName;
// private JsonArrayBuilder payload;
//
// public CacheChangedEvent(String cacheName, EventType type) {
// this.type = type;
// this.cacheName = cacheName;
// this.payload = Json.createArrayBuilder();
// }
//
// public void consume(CacheEntryEvent<? extends String, ? extends String> event) {
// String key = event.getKey();
// String value = event.getValue();
// String oldValue = event.getOldValue();
// JsonObjectBuilder builder = Json.createObjectBuilder().add("newValue", value);
// if (oldValue != null) {
// builder.add("oldValue", oldValue);
// }
// JsonObject diff = builder.build();
//
// JsonObject changeSet = Json.createObjectBuilder().
// add("cacheName", cacheName).
// add("eventType", type.name()).
// add("key", key).
// add(key, diff).
// build();
// payload.add(changeSet);
// }
//
// public JsonArray getPayload() {
// return payload.build();
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// }
// Path: headlands/src/main/java/com/airhacks/headlands/notifications/control/CacheEntryChangedListener.java
import com.airhacks.headlands.notifications.entity.CacheChangedEvent;
import java.io.Serializable;
import java.util.function.Consumer;
import javax.cache.event.CacheEntryCreatedListener;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryListenerException;
import javax.cache.event.CacheEntryRemovedListener;
import javax.cache.event.CacheEntryUpdatedListener;
import javax.cache.event.EventType;
package com.airhacks.headlands.notifications.control;
/**
*
* @author airhacks.com
*/
public class CacheEntryChangedListener implements CacheEntryCreatedListener<String, String>,
CacheEntryUpdatedListener<String, String>,
CacheEntryRemovedListener<String, String>,
Serializable {
| private final transient Consumer<CacheChangedEvent> sink; |
AdamBien/headlands | headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesPresenter.java | // Path: headlands-ui/src/main/java/com/airhacks/headlands/CacheAccessor.java
// public class CacheAccessor {
//
// private ObjectProperty<Cache<String, String>> currentCache;
// private CachingProvider cachingProvider;
// private CacheManager cacheManager;
//
// private SimpleBooleanProperty cacheStarted;
//
// private ExecutorService executor;
//
// @PostConstruct
// public void initialize() {
// System.setProperty("hazelcast.jcache.provider.type", "server");
// this.currentCache = new SimpleObjectProperty<>();
// this.cacheStarted = new SimpleBooleanProperty();
// this.executor = Executors.newCachedThreadPool();
// }
//
// public void store(String keyString, String valueString) {
// getCurrentCache().put(keyString, valueString);
// }
//
// public List<String> getCacheNames() {
// List<String> caches = new ArrayList<>();
// Iterable<String> names = this.cacheManager.getCacheNames();
// names.forEach(caches::add);
// return caches;
// }
//
// public void start() {
// this.executor.submit(() -> {
// this.cachingProvider = Caching.getCachingProvider();
// this.cacheManager = cachingProvider.getCacheManager();
// runLater(() -> this.cacheStarted.set(true));
// }
// );
// }
//
// public BooleanProperty isStarted() {
// return cacheStarted;
// }
//
// public void stop() {
// this.executor.submit(() -> {
// getCurrentCache().close();
// this.cacheManager.close();
// this.cachingProvider.close();
// runLater(() -> this.cacheStarted.set(false));
//
// });
//
// }
//
// public void createCache(String cacheName) {
// MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
//
// configuration.setStoreByValue(false).
// setTypes(String.class, String.class).
// setManagementEnabled(true).
// setStoreByValue(true);
//
// this.currentCache.set(cacheManager.
// createCache(cacheName, configuration));
//
// }
//
// public String getValue(String key) {
// return getCurrentCache().get(key);
// }
//
// public List<Cache.Entry<String, String>> getAllEntries() {
// List<Cache.Entry<String, String>> entries = new ArrayList<>();
// for (Cache.Entry<String, String> entry : getCurrentCache()) {
// entries.add(entry);
// }
// return entries;
// }
//
// public void remove(String key) {
// getCurrentCache().remove(key);
// }
//
// public void selectCache(String cacheName) {
// this.currentCache.set(this.cacheManager.getCache(cacheName, String.class, String.class));
// }
//
// Cache<String, String> getCurrentCache() {
// return this.currentCache.get();
// }
//
// public ObjectProperty<Cache<String, String>> currentCacheProperty() {
// return this.currentCache;
// }
//
// }
| import com.airhacks.headlands.CacheAccessor;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Pair;
import javax.cache.Cache;
import javax.inject.Inject; | package com.airhacks.headlands.entries;
/**
*
* @author airhacks.com
*/
public class EntriesPresenter implements Initializable {
@Inject | // Path: headlands-ui/src/main/java/com/airhacks/headlands/CacheAccessor.java
// public class CacheAccessor {
//
// private ObjectProperty<Cache<String, String>> currentCache;
// private CachingProvider cachingProvider;
// private CacheManager cacheManager;
//
// private SimpleBooleanProperty cacheStarted;
//
// private ExecutorService executor;
//
// @PostConstruct
// public void initialize() {
// System.setProperty("hazelcast.jcache.provider.type", "server");
// this.currentCache = new SimpleObjectProperty<>();
// this.cacheStarted = new SimpleBooleanProperty();
// this.executor = Executors.newCachedThreadPool();
// }
//
// public void store(String keyString, String valueString) {
// getCurrentCache().put(keyString, valueString);
// }
//
// public List<String> getCacheNames() {
// List<String> caches = new ArrayList<>();
// Iterable<String> names = this.cacheManager.getCacheNames();
// names.forEach(caches::add);
// return caches;
// }
//
// public void start() {
// this.executor.submit(() -> {
// this.cachingProvider = Caching.getCachingProvider();
// this.cacheManager = cachingProvider.getCacheManager();
// runLater(() -> this.cacheStarted.set(true));
// }
// );
// }
//
// public BooleanProperty isStarted() {
// return cacheStarted;
// }
//
// public void stop() {
// this.executor.submit(() -> {
// getCurrentCache().close();
// this.cacheManager.close();
// this.cachingProvider.close();
// runLater(() -> this.cacheStarted.set(false));
//
// });
//
// }
//
// public void createCache(String cacheName) {
// MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
//
// configuration.setStoreByValue(false).
// setTypes(String.class, String.class).
// setManagementEnabled(true).
// setStoreByValue(true);
//
// this.currentCache.set(cacheManager.
// createCache(cacheName, configuration));
//
// }
//
// public String getValue(String key) {
// return getCurrentCache().get(key);
// }
//
// public List<Cache.Entry<String, String>> getAllEntries() {
// List<Cache.Entry<String, String>> entries = new ArrayList<>();
// for (Cache.Entry<String, String> entry : getCurrentCache()) {
// entries.add(entry);
// }
// return entries;
// }
//
// public void remove(String key) {
// getCurrentCache().remove(key);
// }
//
// public void selectCache(String cacheName) {
// this.currentCache.set(this.cacheManager.getCache(cacheName, String.class, String.class));
// }
//
// Cache<String, String> getCurrentCache() {
// return this.currentCache.get();
// }
//
// public ObjectProperty<Cache<String, String>> currentCacheProperty() {
// return this.currentCache;
// }
//
// }
// Path: headlands-ui/src/main/java/com/airhacks/headlands/entries/EntriesPresenter.java
import com.airhacks.headlands.CacheAccessor;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Pair;
import javax.cache.Cache;
import javax.inject.Inject;
package com.airhacks.headlands.entries;
/**
*
* @author airhacks.com
*/
public class EntriesPresenter implements Initializable {
@Inject | CacheAccessor cs; |
AdamBien/headlands | headlands/src/main/java/com/airhacks/headlands/cache/control/ConfigurationProvider.java | // Path: headlands/src/main/java/com/airhacks/headlands/cache/entity/CacheConfiguration.java
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class CacheConfiguration {
//
// private boolean storeByValue;
// private boolean managementEnabled;
// private boolean statisticsEnabled;
// private boolean readThrough;
// private boolean writeThrough;
// private long expiryForAccess;
// private long expiryForCreation;
// private long expiryForUpdate;
//
// public CacheConfiguration() {
// this.storeByValue = false;
// this.managementEnabled = true;
// this.statisticsEnabled = true;
// this.readThrough = true;
// this.writeThrough = true;
// this.expiryForAccess = Duration.ofMinutes(5).toMillis();
// }
//
// public CacheConfiguration(long expiryForAccess, long expiryForCreation,
// long expiryForUpdate, boolean storeByValue,
// boolean managementEnabled, boolean statisticsEnabled,
// boolean readThrough, boolean writeThrough) {
// this.expiryForAccess = expiryForAccess;
// this.expiryForCreation = expiryForCreation;
// this.expiryForUpdate = expiryForUpdate;
// this.storeByValue = storeByValue;
// this.managementEnabled = managementEnabled;
// this.statisticsEnabled = statisticsEnabled;
// this.readThrough = readThrough;
// this.writeThrough = writeThrough;
// }
//
// public boolean isStoreByValue() {
// return storeByValue;
// }
//
// public boolean isManagementEnabled() {
// return managementEnabled;
// }
//
// public boolean isStatisticsEnabled() {
// return statisticsEnabled;
// }
//
// public boolean isReadThrough() {
// return readThrough;
// }
//
// public boolean isWriteThrough() {
// return writeThrough;
// }
//
// public long getExpiryForAccess() {
// return expiryForAccess;
// }
//
// public long getExpiryForCreation() {
// return expiryForCreation;
// }
//
// public long getExpiryForUpdate() {
// return expiryForUpdate;
// }
//
// public long getExpiryForAccessInSeconds() {
// return Duration.of(this.expiryForAccess, ChronoUnit.MILLIS).
// getSeconds();
// }
//
// }
| import com.airhacks.headlands.cache.entity.CacheConfiguration;
import java.util.concurrent.TimeUnit;
import javax.cache.Cache;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.Factory;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ExpiryPolicy;
import javax.inject.Inject; | package com.airhacks.headlands.cache.control;
/**
*
* @author airhacks.com
*/
public class ConfigurationProvider {
@Inject
Initializer initializer;
| // Path: headlands/src/main/java/com/airhacks/headlands/cache/entity/CacheConfiguration.java
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class CacheConfiguration {
//
// private boolean storeByValue;
// private boolean managementEnabled;
// private boolean statisticsEnabled;
// private boolean readThrough;
// private boolean writeThrough;
// private long expiryForAccess;
// private long expiryForCreation;
// private long expiryForUpdate;
//
// public CacheConfiguration() {
// this.storeByValue = false;
// this.managementEnabled = true;
// this.statisticsEnabled = true;
// this.readThrough = true;
// this.writeThrough = true;
// this.expiryForAccess = Duration.ofMinutes(5).toMillis();
// }
//
// public CacheConfiguration(long expiryForAccess, long expiryForCreation,
// long expiryForUpdate, boolean storeByValue,
// boolean managementEnabled, boolean statisticsEnabled,
// boolean readThrough, boolean writeThrough) {
// this.expiryForAccess = expiryForAccess;
// this.expiryForCreation = expiryForCreation;
// this.expiryForUpdate = expiryForUpdate;
// this.storeByValue = storeByValue;
// this.managementEnabled = managementEnabled;
// this.statisticsEnabled = statisticsEnabled;
// this.readThrough = readThrough;
// this.writeThrough = writeThrough;
// }
//
// public boolean isStoreByValue() {
// return storeByValue;
// }
//
// public boolean isManagementEnabled() {
// return managementEnabled;
// }
//
// public boolean isStatisticsEnabled() {
// return statisticsEnabled;
// }
//
// public boolean isReadThrough() {
// return readThrough;
// }
//
// public boolean isWriteThrough() {
// return writeThrough;
// }
//
// public long getExpiryForAccess() {
// return expiryForAccess;
// }
//
// public long getExpiryForCreation() {
// return expiryForCreation;
// }
//
// public long getExpiryForUpdate() {
// return expiryForUpdate;
// }
//
// public long getExpiryForAccessInSeconds() {
// return Duration.of(this.expiryForAccess, ChronoUnit.MILLIS).
// getSeconds();
// }
//
// }
// Path: headlands/src/main/java/com/airhacks/headlands/cache/control/ConfigurationProvider.java
import com.airhacks.headlands.cache.entity.CacheConfiguration;
import java.util.concurrent.TimeUnit;
import javax.cache.Cache;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.Factory;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ExpiryPolicy;
import javax.inject.Inject;
package com.airhacks.headlands.cache.control;
/**
*
* @author airhacks.com
*/
public class ConfigurationProvider {
@Inject
Initializer initializer;
| public CacheConfiguration getConfiguration(String cacheName) { |
AdamBien/headlands | headlands/src/test/java/com/airhacks/headlands/engine/control/NashornEngineTest.java | // Path: headlands/src/main/java/com/airhacks/headlands/processors/control/CacheProcessor.java
// public interface CacheProcessor {
//
// Map<String, String> process(Cache<String, String> cache, Map<String, String> empty);
//
// }
| import com.airhacks.headlands.processors.control.CacheProcessor;
import javax.cache.processor.EntryProcessor;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test; | package com.airhacks.headlands.engine.control;
/**
*
* @author airhacks.com
*/
public class NashornEngineTest {
private NashornEngine cut;
@Before
public void init() {
this.cut = new NashornEngine();
this.cut.initializeEngine();
}
@Test
public void createProcessorFromEmptyScript() { | // Path: headlands/src/main/java/com/airhacks/headlands/processors/control/CacheProcessor.java
// public interface CacheProcessor {
//
// Map<String, String> process(Cache<String, String> cache, Map<String, String> empty);
//
// }
// Path: headlands/src/test/java/com/airhacks/headlands/engine/control/NashornEngineTest.java
import com.airhacks.headlands.processors.control.CacheProcessor;
import javax.cache.processor.EntryProcessor;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
package com.airhacks.headlands.engine.control;
/**
*
* @author airhacks.com
*/
public class NashornEngineTest {
private NashornEngine cut;
@Before
public void init() {
this.cut = new NashornEngine();
this.cut.initializeEngine();
}
@Test
public void createProcessorFromEmptyScript() { | CacheProcessor invalid = this.cut.evalScript("", CacheProcessor.class); |
zhihu/Matisse | matisse/src/main/java/com/zhihu/matisse/internal/utils/MediaStoreCompat.java | // Path: matisse/src/main/java/com/zhihu/matisse/internal/entity/CaptureStrategy.java
// public class CaptureStrategy {
//
// public final boolean isPublic;
// public final String authority;
// public final String directory;
//
// public CaptureStrategy(boolean isPublic, String authority) {
// this(isPublic, authority, null);
// }
//
// public CaptureStrategy(boolean isPublic, String authority, String directory) {
// this.isPublic = isPublic;
// this.authority = authority;
// this.directory = directory;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale; | /*
* Copyright 2017 Zhihu 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 com.zhihu.matisse.internal.utils;
public class MediaStoreCompat {
private final WeakReference<Activity> mContext;
private final WeakReference<Fragment> mFragment; | // Path: matisse/src/main/java/com/zhihu/matisse/internal/entity/CaptureStrategy.java
// public class CaptureStrategy {
//
// public final boolean isPublic;
// public final String authority;
// public final String directory;
//
// public CaptureStrategy(boolean isPublic, String authority) {
// this(isPublic, authority, null);
// }
//
// public CaptureStrategy(boolean isPublic, String authority, String directory) {
// this.isPublic = isPublic;
// this.authority = authority;
// this.directory = directory;
// }
// }
// Path: matisse/src/main/java/com/zhihu/matisse/internal/utils/MediaStoreCompat.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/*
* Copyright 2017 Zhihu 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 com.zhihu.matisse.internal.utils;
public class MediaStoreCompat {
private final WeakReference<Activity> mContext;
private final WeakReference<Fragment> mFragment; | private CaptureStrategy mCaptureStrategy; |
zhihu/Matisse | matisse/src/main/java/com/zhihu/matisse/internal/entity/IncapableCause.java | // Path: matisse/src/main/java/com/zhihu/matisse/internal/ui/widget/IncapableDialog.java
// public class IncapableDialog extends DialogFragment {
//
// public static final String EXTRA_TITLE = "extra_title";
// public static final String EXTRA_MESSAGE = "extra_message";
//
// public static IncapableDialog newInstance(String title, String message) {
// IncapableDialog dialog = new IncapableDialog();
// Bundle args = new Bundle();
// args.putString(EXTRA_TITLE, title);
// args.putString(EXTRA_MESSAGE, message);
// dialog.setArguments(args);
// return dialog;
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// String title = getArguments().getString(EXTRA_TITLE);
// String message = getArguments().getString(EXTRA_MESSAGE);
//
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// if (!TextUtils.isEmpty(title)) {
// builder.setTitle(title);
// }
// if (!TextUtils.isEmpty(message)) {
// builder.setMessage(message);
// }
// builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
//
// return builder.create();
// }
// }
| import android.content.Context;
import androidx.annotation.IntDef;
import androidx.fragment.app.FragmentActivity;
import android.widget.Toast;
import com.zhihu.matisse.internal.ui.widget.IncapableDialog;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.SOURCE; |
public IncapableCause(String message) {
mMessage = message;
}
public IncapableCause(String title, String message) {
mTitle = title;
mMessage = message;
}
public IncapableCause(@Form int form, String message) {
mForm = form;
mMessage = message;
}
public IncapableCause(@Form int form, String title, String message) {
mForm = form;
mTitle = title;
mMessage = message;
}
public static void handleCause(Context context, IncapableCause cause) {
if (cause == null)
return;
switch (cause.mForm) {
case NONE:
// do nothing.
break;
case DIALOG: | // Path: matisse/src/main/java/com/zhihu/matisse/internal/ui/widget/IncapableDialog.java
// public class IncapableDialog extends DialogFragment {
//
// public static final String EXTRA_TITLE = "extra_title";
// public static final String EXTRA_MESSAGE = "extra_message";
//
// public static IncapableDialog newInstance(String title, String message) {
// IncapableDialog dialog = new IncapableDialog();
// Bundle args = new Bundle();
// args.putString(EXTRA_TITLE, title);
// args.putString(EXTRA_MESSAGE, message);
// dialog.setArguments(args);
// return dialog;
// }
//
// @NonNull
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// String title = getArguments().getString(EXTRA_TITLE);
// String message = getArguments().getString(EXTRA_MESSAGE);
//
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// if (!TextUtils.isEmpty(title)) {
// builder.setTitle(title);
// }
// if (!TextUtils.isEmpty(message)) {
// builder.setMessage(message);
// }
// builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
//
// return builder.create();
// }
// }
// Path: matisse/src/main/java/com/zhihu/matisse/internal/entity/IncapableCause.java
import android.content.Context;
import androidx.annotation.IntDef;
import androidx.fragment.app.FragmentActivity;
import android.widget.Toast;
import com.zhihu.matisse.internal.ui.widget.IncapableDialog;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.SOURCE;
public IncapableCause(String message) {
mMessage = message;
}
public IncapableCause(String title, String message) {
mTitle = title;
mMessage = message;
}
public IncapableCause(@Form int form, String message) {
mForm = form;
mMessage = message;
}
public IncapableCause(@Form int form, String title, String message) {
mForm = form;
mTitle = title;
mMessage = message;
}
public static void handleCause(Context context, IncapableCause cause) {
if (cause == null)
return;
switch (cause.mForm) {
case NONE:
// do nothing.
break;
case DIALOG: | IncapableDialog incapableDialog = IncapableDialog.newInstance(cause.mTitle, cause.mMessage); |
zhihu/Matisse | matisse/src/main/java/com/zhihu/matisse/internal/entity/Item.java | // Path: matisse/src/main/java/com/zhihu/matisse/MimeType.java
// @SuppressWarnings("unused")
// public enum MimeType {
//
// // ============== images ==============
// JPEG("image/jpeg", arraySetOf(
// "jpg",
// "jpeg"
// )),
// PNG("image/png", arraySetOf(
// "png"
// )),
// GIF("image/gif", arraySetOf(
// "gif"
// )),
// BMP("image/x-ms-bmp", arraySetOf(
// "bmp"
// )),
// WEBP("image/webp", arraySetOf(
// "webp"
// )),
//
// // ============== videos ==============
// MPEG("video/mpeg", arraySetOf(
// "mpeg",
// "mpg"
// )),
// MP4("video/mp4", arraySetOf(
// "mp4",
// "m4v"
// )),
// QUICKTIME("video/quicktime", arraySetOf(
// "mov"
// )),
// THREEGPP("video/3gpp", arraySetOf(
// "3gp",
// "3gpp"
// )),
// THREEGPP2("video/3gpp2", arraySetOf(
// "3g2",
// "3gpp2"
// )),
// MKV("video/x-matroska", arraySetOf(
// "mkv"
// )),
// WEBM("video/webm", arraySetOf(
// "webm"
// )),
// TS("video/mp2ts", arraySetOf(
// "ts"
// )),
// AVI("video/avi", arraySetOf(
// "avi"
// ));
//
// private final String mMimeTypeName;
// private final Set<String> mExtensions;
//
// MimeType(String mimeTypeName, Set<String> extensions) {
// mMimeTypeName = mimeTypeName;
// mExtensions = extensions;
// }
//
// public static Set<MimeType> ofAll() {
// return EnumSet.allOf(MimeType.class);
// }
//
// public static Set<MimeType> of(MimeType type, MimeType... rest) {
// return EnumSet.of(type, rest);
// }
//
// public static Set<MimeType> ofImage() {
// return EnumSet.of(JPEG, PNG, GIF, BMP, WEBP);
// }
//
// public static Set<MimeType> ofImage(boolean onlyGif) {
// return EnumSet.of(GIF);
// }
//
// public static Set<MimeType> ofGif() {
// return ofImage(true);
// }
//
// public static Set<MimeType> ofVideo() {
// return EnumSet.of(MPEG, MP4, QUICKTIME, THREEGPP, THREEGPP2, MKV, WEBM, TS, AVI);
// }
//
// public static boolean isImage(String mimeType) {
// if (mimeType == null) return false;
// return mimeType.startsWith("image");
// }
//
// public static boolean isVideo(String mimeType) {
// if (mimeType == null) return false;
// return mimeType.startsWith("video");
// }
//
// public static boolean isGif(String mimeType) {
// if (mimeType == null) return false;
// return mimeType.equals(MimeType.GIF.toString());
// }
//
// private static Set<String> arraySetOf(String... suffixes) {
// return new ArraySet<>(Arrays.asList(suffixes));
// }
//
// @Override
// public String toString() {
// return mMimeTypeName;
// }
//
// public boolean checkType(ContentResolver resolver, Uri uri) {
// MimeTypeMap map = MimeTypeMap.getSingleton();
// if (uri == null) {
// return false;
// }
// String type = map.getExtensionFromMimeType(resolver.getType(uri));
// String path = null;
// // lazy load the path and prevent resolve for multiple times
// boolean pathParsed = false;
// for (String extension : mExtensions) {
// if (extension.equals(type)) {
// return true;
// }
// if (!pathParsed) {
// // we only resolve the path for one time
// path = PhotoMetadataUtils.getPath(resolver, uri);
// if (!TextUtils.isEmpty(path)) {
// path = path.toLowerCase(Locale.US);
// }
// pathParsed = true;
// }
// if (path != null && path.endsWith(extension)) {
// return true;
// }
// }
// return false;
// }
// }
| import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import androidx.annotation.Nullable;
import com.zhihu.matisse.MimeType; | public static Item valueOf(Cursor cursor) {
return new Item(cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE)),
cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns.SIZE)),
cursor.getLong(cursor.getColumnIndex("duration")));
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(mimeType);
dest.writeParcelable(uri, 0);
dest.writeLong(size);
dest.writeLong(duration);
}
public Uri getContentUri() {
return uri;
}
public boolean isCapture() {
return id == ITEM_ID_CAPTURE;
}
public boolean isImage() { | // Path: matisse/src/main/java/com/zhihu/matisse/MimeType.java
// @SuppressWarnings("unused")
// public enum MimeType {
//
// // ============== images ==============
// JPEG("image/jpeg", arraySetOf(
// "jpg",
// "jpeg"
// )),
// PNG("image/png", arraySetOf(
// "png"
// )),
// GIF("image/gif", arraySetOf(
// "gif"
// )),
// BMP("image/x-ms-bmp", arraySetOf(
// "bmp"
// )),
// WEBP("image/webp", arraySetOf(
// "webp"
// )),
//
// // ============== videos ==============
// MPEG("video/mpeg", arraySetOf(
// "mpeg",
// "mpg"
// )),
// MP4("video/mp4", arraySetOf(
// "mp4",
// "m4v"
// )),
// QUICKTIME("video/quicktime", arraySetOf(
// "mov"
// )),
// THREEGPP("video/3gpp", arraySetOf(
// "3gp",
// "3gpp"
// )),
// THREEGPP2("video/3gpp2", arraySetOf(
// "3g2",
// "3gpp2"
// )),
// MKV("video/x-matroska", arraySetOf(
// "mkv"
// )),
// WEBM("video/webm", arraySetOf(
// "webm"
// )),
// TS("video/mp2ts", arraySetOf(
// "ts"
// )),
// AVI("video/avi", arraySetOf(
// "avi"
// ));
//
// private final String mMimeTypeName;
// private final Set<String> mExtensions;
//
// MimeType(String mimeTypeName, Set<String> extensions) {
// mMimeTypeName = mimeTypeName;
// mExtensions = extensions;
// }
//
// public static Set<MimeType> ofAll() {
// return EnumSet.allOf(MimeType.class);
// }
//
// public static Set<MimeType> of(MimeType type, MimeType... rest) {
// return EnumSet.of(type, rest);
// }
//
// public static Set<MimeType> ofImage() {
// return EnumSet.of(JPEG, PNG, GIF, BMP, WEBP);
// }
//
// public static Set<MimeType> ofImage(boolean onlyGif) {
// return EnumSet.of(GIF);
// }
//
// public static Set<MimeType> ofGif() {
// return ofImage(true);
// }
//
// public static Set<MimeType> ofVideo() {
// return EnumSet.of(MPEG, MP4, QUICKTIME, THREEGPP, THREEGPP2, MKV, WEBM, TS, AVI);
// }
//
// public static boolean isImage(String mimeType) {
// if (mimeType == null) return false;
// return mimeType.startsWith("image");
// }
//
// public static boolean isVideo(String mimeType) {
// if (mimeType == null) return false;
// return mimeType.startsWith("video");
// }
//
// public static boolean isGif(String mimeType) {
// if (mimeType == null) return false;
// return mimeType.equals(MimeType.GIF.toString());
// }
//
// private static Set<String> arraySetOf(String... suffixes) {
// return new ArraySet<>(Arrays.asList(suffixes));
// }
//
// @Override
// public String toString() {
// return mMimeTypeName;
// }
//
// public boolean checkType(ContentResolver resolver, Uri uri) {
// MimeTypeMap map = MimeTypeMap.getSingleton();
// if (uri == null) {
// return false;
// }
// String type = map.getExtensionFromMimeType(resolver.getType(uri));
// String path = null;
// // lazy load the path and prevent resolve for multiple times
// boolean pathParsed = false;
// for (String extension : mExtensions) {
// if (extension.equals(type)) {
// return true;
// }
// if (!pathParsed) {
// // we only resolve the path for one time
// path = PhotoMetadataUtils.getPath(resolver, uri);
// if (!TextUtils.isEmpty(path)) {
// path = path.toLowerCase(Locale.US);
// }
// pathParsed = true;
// }
// if (path != null && path.endsWith(extension)) {
// return true;
// }
// }
// return false;
// }
// }
// Path: matisse/src/main/java/com/zhihu/matisse/internal/entity/Item.java
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import androidx.annotation.Nullable;
import com.zhihu.matisse.MimeType;
public static Item valueOf(Cursor cursor) {
return new Item(cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE)),
cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns.SIZE)),
cursor.getLong(cursor.getColumnIndex("duration")));
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(mimeType);
dest.writeParcelable(uri, 0);
dest.writeLong(size);
dest.writeLong(duration);
}
public Uri getContentUri() {
return uri;
}
public boolean isCapture() {
return id == ITEM_ID_CAPTURE;
}
public boolean isImage() { | return MimeType.isImage(mimeType); |
zhihu/Matisse | matisse/src/main/java/com/zhihu/matisse/internal/ui/widget/AlbumsSpinner.java | // Path: matisse/src/main/java/com/zhihu/matisse/internal/entity/Album.java
// public class Album implements Parcelable {
// public static final Creator<Album> CREATOR = new Creator<Album>() {
// @Nullable
// @Override
// public Album createFromParcel(Parcel source) {
// return new Album(source);
// }
//
// @Override
// public Album[] newArray(int size) {
// return new Album[size];
// }
// };
// public static final String ALBUM_ID_ALL = String.valueOf(-1);
// public static final String ALBUM_NAME_ALL = "All";
//
// private final String mId;
// private final Uri mCoverUri;
// private final String mDisplayName;
// private long mCount;
//
// public Album(String id, Uri coverUri, String albumName, long count) {
// mId = id;
// mCoverUri = coverUri;
// mDisplayName = albumName;
// mCount = count;
// }
//
// private Album(Parcel source) {
// mId = source.readString();
// mCoverUri = source.readParcelable(Uri.class.getClassLoader());
// mDisplayName = source.readString();
// mCount = source.readLong();
// }
//
// /**
// * Constructs a new {@link Album} entity from the {@link Cursor}.
// * This method is not responsible for managing cursor resource, such as close, iterate, and so on.
// */
// public static Album valueOf(Cursor cursor) {
// String clumn = cursor.getString(cursor.getColumnIndex(AlbumLoader.COLUMN_URI));
// return new Album(
// cursor.getString(cursor.getColumnIndex("bucket_id")),
// Uri.parse(clumn != null ? clumn : ""),
// cursor.getString(cursor.getColumnIndex("bucket_display_name")),
// cursor.getLong(cursor.getColumnIndex(AlbumLoader.COLUMN_COUNT)));
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mId);
// dest.writeParcelable(mCoverUri, 0);
// dest.writeString(mDisplayName);
// dest.writeLong(mCount);
// }
//
// public String getId() {
// return mId;
// }
//
// public Uri getCoverUri() {
// return mCoverUri;
// }
//
// public long getCount() {
// return mCount;
// }
//
// public void addCaptureCount() {
// mCount++;
// }
//
// public String getDisplayName(Context context) {
// if (isAll()) {
// return context.getString(R.string.album_name_all);
// }
// return mDisplayName;
// }
//
// public boolean isAll() {
// return ALBUM_ID_ALL.equals(mId);
// }
//
// public boolean isEmpty() {
// return mCount == 0;
// }
//
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.ListPopupWindow;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.zhihu.matisse.R;
import com.zhihu.matisse.internal.entity.Album;
import com.zhihu.matisse.internal.utils.Platform; | float density = context.getResources().getDisplayMetrics().density;
mListPopupWindow.setContentWidth((int) (216 * density));
mListPopupWindow.setHorizontalOffset((int) (16 * density));
mListPopupWindow.setVerticalOffset((int) (-48 * density));
mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlbumsSpinner.this.onItemSelected(parent.getContext(), position);
if (mOnItemSelectedListener != null) {
mOnItemSelectedListener.onItemSelected(parent, view, position, id);
}
}
});
}
public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
mOnItemSelectedListener = listener;
}
public void setSelection(Context context, int position) {
mListPopupWindow.setSelection(position);
onItemSelected(context, position);
}
private void onItemSelected(Context context, int position) {
mListPopupWindow.dismiss();
Cursor cursor = mAdapter.getCursor();
cursor.moveToPosition(position); | // Path: matisse/src/main/java/com/zhihu/matisse/internal/entity/Album.java
// public class Album implements Parcelable {
// public static final Creator<Album> CREATOR = new Creator<Album>() {
// @Nullable
// @Override
// public Album createFromParcel(Parcel source) {
// return new Album(source);
// }
//
// @Override
// public Album[] newArray(int size) {
// return new Album[size];
// }
// };
// public static final String ALBUM_ID_ALL = String.valueOf(-1);
// public static final String ALBUM_NAME_ALL = "All";
//
// private final String mId;
// private final Uri mCoverUri;
// private final String mDisplayName;
// private long mCount;
//
// public Album(String id, Uri coverUri, String albumName, long count) {
// mId = id;
// mCoverUri = coverUri;
// mDisplayName = albumName;
// mCount = count;
// }
//
// private Album(Parcel source) {
// mId = source.readString();
// mCoverUri = source.readParcelable(Uri.class.getClassLoader());
// mDisplayName = source.readString();
// mCount = source.readLong();
// }
//
// /**
// * Constructs a new {@link Album} entity from the {@link Cursor}.
// * This method is not responsible for managing cursor resource, such as close, iterate, and so on.
// */
// public static Album valueOf(Cursor cursor) {
// String clumn = cursor.getString(cursor.getColumnIndex(AlbumLoader.COLUMN_URI));
// return new Album(
// cursor.getString(cursor.getColumnIndex("bucket_id")),
// Uri.parse(clumn != null ? clumn : ""),
// cursor.getString(cursor.getColumnIndex("bucket_display_name")),
// cursor.getLong(cursor.getColumnIndex(AlbumLoader.COLUMN_COUNT)));
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mId);
// dest.writeParcelable(mCoverUri, 0);
// dest.writeString(mDisplayName);
// dest.writeLong(mCount);
// }
//
// public String getId() {
// return mId;
// }
//
// public Uri getCoverUri() {
// return mCoverUri;
// }
//
// public long getCount() {
// return mCount;
// }
//
// public void addCaptureCount() {
// mCount++;
// }
//
// public String getDisplayName(Context context) {
// if (isAll()) {
// return context.getString(R.string.album_name_all);
// }
// return mDisplayName;
// }
//
// public boolean isAll() {
// return ALBUM_ID_ALL.equals(mId);
// }
//
// public boolean isEmpty() {
// return mCount == 0;
// }
//
// }
// Path: matisse/src/main/java/com/zhihu/matisse/internal/ui/widget/AlbumsSpinner.java
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.ListPopupWindow;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.zhihu.matisse.R;
import com.zhihu.matisse.internal.entity.Album;
import com.zhihu.matisse.internal.utils.Platform;
float density = context.getResources().getDisplayMetrics().density;
mListPopupWindow.setContentWidth((int) (216 * density));
mListPopupWindow.setHorizontalOffset((int) (16 * density));
mListPopupWindow.setVerticalOffset((int) (-48 * density));
mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlbumsSpinner.this.onItemSelected(parent.getContext(), position);
if (mOnItemSelectedListener != null) {
mOnItemSelectedListener.onItemSelected(parent, view, position, id);
}
}
});
}
public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
mOnItemSelectedListener = listener;
}
public void setSelection(Context context, int position) {
mListPopupWindow.setSelection(position);
onItemSelected(context, position);
}
private void onItemSelected(Context context, int position) {
mListPopupWindow.dismiss();
Cursor cursor = mAdapter.getCursor();
cursor.moveToPosition(position); | Album album = Album.valueOf(cursor); |
HackGSU/mobile-android | app/src/main/java/com/hackgsu/fall2016/android/views/AboutRecyclerView.java | // Path: app/src/main/java/com/hackgsu/fall2016/android/DataStore.java
// public class DataStore {
// private static ArrayList<AboutPerson> aboutPeople;
// private static ArrayList<Announcement> announcements = new ArrayList<>();
// private static String openingCeremoniesRoomNumber;
// private static ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();
//
// static {
// aboutPeople = new ArrayList<>();
//
// aboutPeople.add(new AboutPerson("Alex Mitchell", "iOS Developer", "https://goo.gl/cHty7J", R.drawable.alex_pic));
// aboutPeople.add(new AboutPerson("Viraj Shah", "iOS Developer", "https://goo.gl/v5YZaL", R.drawable.viraj_pic));
// aboutPeople.add(new AboutPerson("Harsha Goli", "iOS Developer", "https://goo.gl/UCVv11", R.drawable.harsha_pic));
// aboutPeople.add(new AboutPerson("Dylan Welch", "iOS Developer", "https://goo.gl/8RDDyo", R.drawable.dylan_pic));
// aboutPeople.add(new AboutPerson("Josh King", "Android Developer", "https://goo.gl/Izv7vk", R.drawable.josh_pic));
// aboutPeople.add(new AboutPerson("Pranathi Venigandla", "Android Developer", "https://goo.gl/S8KP2A", R.drawable.pranathi_pic));
// aboutPeople.add(new AboutPerson("Solomon Arnett", "Web Developer", "https://goo.gl/QbIimx", R.drawable.solo_pic));
// aboutPeople.add(new AboutPerson("Sri Rajasekaran", "Web Developer", "https://goo.gl/7GZoGB", R.drawable.sri_pic));
// aboutPeople.add(new AboutPerson("Abhinav Reddy", "Web Developer", "https://goo.gl/PSCYbR", R.drawable.abhinav_pic));
// }
//
// public static ArrayList<AboutPerson> getAboutPeople () {
// return aboutPeople;
// }
//
// public static ArrayList<Announcement> getAnnouncements (boolean onlyReturnBookmarkedAnnouncements) {
// if (!onlyReturnBookmarkedAnnouncements) { return getAnnouncements(); }
//
// ArrayList<Announcement> filteredAnnouncements = new ArrayList<>();
// for (Announcement announcement : getAnnouncements()) { if (announcement.isBookmarkedByMe()) { filteredAnnouncements.add(announcement); } }
// Collections.sort(filteredAnnouncements);
// return filteredAnnouncements;
// }
//
// public static ArrayList<Announcement> getAnnouncements () {
// return announcements;
// }
//
// public static String getOpeningCeremoniesRoomNumber () {
// return openingCeremoniesRoomNumber;
// }
//
// public static ArrayList<ScheduleEvent> getScheduleEvents () {
// return scheduleEvents;
// }
//
// public static void setAnnouncements (Context context, ArrayList<Announcement> announcements) {
// Collections.sort(announcements);
// AnnouncementController.setIsBookmarkedByMeBasedOnPrefs(context, announcements);
// AnnouncementController.setIsLikedByMeBasedOnPrefs(context, announcements);
// DataStore.announcements = announcements;
// }
//
// public static void setOpeningCeremoniesRoomNumber (String openingCeremoniesRoomNumber) {
// DataStore.openingCeremoniesRoomNumber = openingCeremoniesRoomNumber;
// }
//
// public static void setScheduleEvents (ArrayList<ScheduleEvent> scheduleEvents) {
// DataStore.scheduleEvents = scheduleEvents;
// }
// }
//
// Path: app/src/main/java/com/hackgsu/fall2016/android/model/AboutPerson.java
// public class AboutPerson {
// private final String name;
// private final String role;
// private final String linkedInUrl;
// private
// @DrawableRes
// int picture;
//
// public AboutPerson(String name, String role, String linkedInUrl, int picture) {
// this.name = name;
// this.role = role;
// this.linkedInUrl = linkedInUrl;
// this.picture = picture;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRole() {
// return role;
// }
//
// public String getLinkedInUrl() {
// return linkedInUrl;
// }
//
// public int getPicture() { return picture; }
// }
| import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.hackgsu.fall2016.android.DataStore;
import com.hackgsu.fall2016.android.R;
import com.hackgsu.fall2016.android.model.AboutPerson; | package com.hackgsu.fall2016.android.views;
public class AboutRecyclerView extends ThemedEmptyStateRecyclerView {
private AboutAdapter adapter;
private GridLayoutManager layoutManager;
public AboutRecyclerView(Context context) {
super(context);
init(null, 0);
}
public AboutRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public AboutRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
public class AboutAdapter extends Adapter<AboutViewHolder> {
@Override
public AboutViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View cardView = View.inflate(getContext(), R.layout.about_person_card, null);
return new AboutViewHolder(cardView);
}
@Override
public void onBindViewHolder(AboutViewHolder holder, int position) { | // Path: app/src/main/java/com/hackgsu/fall2016/android/DataStore.java
// public class DataStore {
// private static ArrayList<AboutPerson> aboutPeople;
// private static ArrayList<Announcement> announcements = new ArrayList<>();
// private static String openingCeremoniesRoomNumber;
// private static ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();
//
// static {
// aboutPeople = new ArrayList<>();
//
// aboutPeople.add(new AboutPerson("Alex Mitchell", "iOS Developer", "https://goo.gl/cHty7J", R.drawable.alex_pic));
// aboutPeople.add(new AboutPerson("Viraj Shah", "iOS Developer", "https://goo.gl/v5YZaL", R.drawable.viraj_pic));
// aboutPeople.add(new AboutPerson("Harsha Goli", "iOS Developer", "https://goo.gl/UCVv11", R.drawable.harsha_pic));
// aboutPeople.add(new AboutPerson("Dylan Welch", "iOS Developer", "https://goo.gl/8RDDyo", R.drawable.dylan_pic));
// aboutPeople.add(new AboutPerson("Josh King", "Android Developer", "https://goo.gl/Izv7vk", R.drawable.josh_pic));
// aboutPeople.add(new AboutPerson("Pranathi Venigandla", "Android Developer", "https://goo.gl/S8KP2A", R.drawable.pranathi_pic));
// aboutPeople.add(new AboutPerson("Solomon Arnett", "Web Developer", "https://goo.gl/QbIimx", R.drawable.solo_pic));
// aboutPeople.add(new AboutPerson("Sri Rajasekaran", "Web Developer", "https://goo.gl/7GZoGB", R.drawable.sri_pic));
// aboutPeople.add(new AboutPerson("Abhinav Reddy", "Web Developer", "https://goo.gl/PSCYbR", R.drawable.abhinav_pic));
// }
//
// public static ArrayList<AboutPerson> getAboutPeople () {
// return aboutPeople;
// }
//
// public static ArrayList<Announcement> getAnnouncements (boolean onlyReturnBookmarkedAnnouncements) {
// if (!onlyReturnBookmarkedAnnouncements) { return getAnnouncements(); }
//
// ArrayList<Announcement> filteredAnnouncements = new ArrayList<>();
// for (Announcement announcement : getAnnouncements()) { if (announcement.isBookmarkedByMe()) { filteredAnnouncements.add(announcement); } }
// Collections.sort(filteredAnnouncements);
// return filteredAnnouncements;
// }
//
// public static ArrayList<Announcement> getAnnouncements () {
// return announcements;
// }
//
// public static String getOpeningCeremoniesRoomNumber () {
// return openingCeremoniesRoomNumber;
// }
//
// public static ArrayList<ScheduleEvent> getScheduleEvents () {
// return scheduleEvents;
// }
//
// public static void setAnnouncements (Context context, ArrayList<Announcement> announcements) {
// Collections.sort(announcements);
// AnnouncementController.setIsBookmarkedByMeBasedOnPrefs(context, announcements);
// AnnouncementController.setIsLikedByMeBasedOnPrefs(context, announcements);
// DataStore.announcements = announcements;
// }
//
// public static void setOpeningCeremoniesRoomNumber (String openingCeremoniesRoomNumber) {
// DataStore.openingCeremoniesRoomNumber = openingCeremoniesRoomNumber;
// }
//
// public static void setScheduleEvents (ArrayList<ScheduleEvent> scheduleEvents) {
// DataStore.scheduleEvents = scheduleEvents;
// }
// }
//
// Path: app/src/main/java/com/hackgsu/fall2016/android/model/AboutPerson.java
// public class AboutPerson {
// private final String name;
// private final String role;
// private final String linkedInUrl;
// private
// @DrawableRes
// int picture;
//
// public AboutPerson(String name, String role, String linkedInUrl, int picture) {
// this.name = name;
// this.role = role;
// this.linkedInUrl = linkedInUrl;
// this.picture = picture;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRole() {
// return role;
// }
//
// public String getLinkedInUrl() {
// return linkedInUrl;
// }
//
// public int getPicture() { return picture; }
// }
// Path: app/src/main/java/com/hackgsu/fall2016/android/views/AboutRecyclerView.java
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.hackgsu.fall2016.android.DataStore;
import com.hackgsu.fall2016.android.R;
import com.hackgsu.fall2016.android.model.AboutPerson;
package com.hackgsu.fall2016.android.views;
public class AboutRecyclerView extends ThemedEmptyStateRecyclerView {
private AboutAdapter adapter;
private GridLayoutManager layoutManager;
public AboutRecyclerView(Context context) {
super(context);
init(null, 0);
}
public AboutRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public AboutRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
public class AboutAdapter extends Adapter<AboutViewHolder> {
@Override
public AboutViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View cardView = View.inflate(getContext(), R.layout.about_person_card, null);
return new AboutViewHolder(cardView);
}
@Override
public void onBindViewHolder(AboutViewHolder holder, int position) { | holder.loadPerson(DataStore.getAboutPeople().get(position)); |
HackGSU/mobile-android | app/src/main/java/com/hackgsu/fall2016/android/views/AboutRecyclerView.java | // Path: app/src/main/java/com/hackgsu/fall2016/android/DataStore.java
// public class DataStore {
// private static ArrayList<AboutPerson> aboutPeople;
// private static ArrayList<Announcement> announcements = new ArrayList<>();
// private static String openingCeremoniesRoomNumber;
// private static ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();
//
// static {
// aboutPeople = new ArrayList<>();
//
// aboutPeople.add(new AboutPerson("Alex Mitchell", "iOS Developer", "https://goo.gl/cHty7J", R.drawable.alex_pic));
// aboutPeople.add(new AboutPerson("Viraj Shah", "iOS Developer", "https://goo.gl/v5YZaL", R.drawable.viraj_pic));
// aboutPeople.add(new AboutPerson("Harsha Goli", "iOS Developer", "https://goo.gl/UCVv11", R.drawable.harsha_pic));
// aboutPeople.add(new AboutPerson("Dylan Welch", "iOS Developer", "https://goo.gl/8RDDyo", R.drawable.dylan_pic));
// aboutPeople.add(new AboutPerson("Josh King", "Android Developer", "https://goo.gl/Izv7vk", R.drawable.josh_pic));
// aboutPeople.add(new AboutPerson("Pranathi Venigandla", "Android Developer", "https://goo.gl/S8KP2A", R.drawable.pranathi_pic));
// aboutPeople.add(new AboutPerson("Solomon Arnett", "Web Developer", "https://goo.gl/QbIimx", R.drawable.solo_pic));
// aboutPeople.add(new AboutPerson("Sri Rajasekaran", "Web Developer", "https://goo.gl/7GZoGB", R.drawable.sri_pic));
// aboutPeople.add(new AboutPerson("Abhinav Reddy", "Web Developer", "https://goo.gl/PSCYbR", R.drawable.abhinav_pic));
// }
//
// public static ArrayList<AboutPerson> getAboutPeople () {
// return aboutPeople;
// }
//
// public static ArrayList<Announcement> getAnnouncements (boolean onlyReturnBookmarkedAnnouncements) {
// if (!onlyReturnBookmarkedAnnouncements) { return getAnnouncements(); }
//
// ArrayList<Announcement> filteredAnnouncements = new ArrayList<>();
// for (Announcement announcement : getAnnouncements()) { if (announcement.isBookmarkedByMe()) { filteredAnnouncements.add(announcement); } }
// Collections.sort(filteredAnnouncements);
// return filteredAnnouncements;
// }
//
// public static ArrayList<Announcement> getAnnouncements () {
// return announcements;
// }
//
// public static String getOpeningCeremoniesRoomNumber () {
// return openingCeremoniesRoomNumber;
// }
//
// public static ArrayList<ScheduleEvent> getScheduleEvents () {
// return scheduleEvents;
// }
//
// public static void setAnnouncements (Context context, ArrayList<Announcement> announcements) {
// Collections.sort(announcements);
// AnnouncementController.setIsBookmarkedByMeBasedOnPrefs(context, announcements);
// AnnouncementController.setIsLikedByMeBasedOnPrefs(context, announcements);
// DataStore.announcements = announcements;
// }
//
// public static void setOpeningCeremoniesRoomNumber (String openingCeremoniesRoomNumber) {
// DataStore.openingCeremoniesRoomNumber = openingCeremoniesRoomNumber;
// }
//
// public static void setScheduleEvents (ArrayList<ScheduleEvent> scheduleEvents) {
// DataStore.scheduleEvents = scheduleEvents;
// }
// }
//
// Path: app/src/main/java/com/hackgsu/fall2016/android/model/AboutPerson.java
// public class AboutPerson {
// private final String name;
// private final String role;
// private final String linkedInUrl;
// private
// @DrawableRes
// int picture;
//
// public AboutPerson(String name, String role, String linkedInUrl, int picture) {
// this.name = name;
// this.role = role;
// this.linkedInUrl = linkedInUrl;
// this.picture = picture;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRole() {
// return role;
// }
//
// public String getLinkedInUrl() {
// return linkedInUrl;
// }
//
// public int getPicture() { return picture; }
// }
| import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.hackgsu.fall2016.android.DataStore;
import com.hackgsu.fall2016.android.R;
import com.hackgsu.fall2016.android.model.AboutPerson; | View cardView = View.inflate(getContext(), R.layout.about_person_card, null);
return new AboutViewHolder(cardView);
}
@Override
public void onBindViewHolder(AboutViewHolder holder, int position) {
holder.loadPerson(DataStore.getAboutPeople().get(position));
}
@Override
public int getItemCount() {
return DataStore.getAboutPeople().size();
}
}
public class AboutViewHolder extends ViewHolder {
private final ImageView personImage;
private final TextView personName;
private final TextView personRole;
AboutViewHolder(View cardView) {
super(cardView);
personImage = (ImageView) cardView.findViewById(R.id.person_image);
personName = (TextView) cardView.findViewById(R.id.person_name);
personRole = (TextView) cardView.findViewById(R.id.person_role);
}
| // Path: app/src/main/java/com/hackgsu/fall2016/android/DataStore.java
// public class DataStore {
// private static ArrayList<AboutPerson> aboutPeople;
// private static ArrayList<Announcement> announcements = new ArrayList<>();
// private static String openingCeremoniesRoomNumber;
// private static ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();
//
// static {
// aboutPeople = new ArrayList<>();
//
// aboutPeople.add(new AboutPerson("Alex Mitchell", "iOS Developer", "https://goo.gl/cHty7J", R.drawable.alex_pic));
// aboutPeople.add(new AboutPerson("Viraj Shah", "iOS Developer", "https://goo.gl/v5YZaL", R.drawable.viraj_pic));
// aboutPeople.add(new AboutPerson("Harsha Goli", "iOS Developer", "https://goo.gl/UCVv11", R.drawable.harsha_pic));
// aboutPeople.add(new AboutPerson("Dylan Welch", "iOS Developer", "https://goo.gl/8RDDyo", R.drawable.dylan_pic));
// aboutPeople.add(new AboutPerson("Josh King", "Android Developer", "https://goo.gl/Izv7vk", R.drawable.josh_pic));
// aboutPeople.add(new AboutPerson("Pranathi Venigandla", "Android Developer", "https://goo.gl/S8KP2A", R.drawable.pranathi_pic));
// aboutPeople.add(new AboutPerson("Solomon Arnett", "Web Developer", "https://goo.gl/QbIimx", R.drawable.solo_pic));
// aboutPeople.add(new AboutPerson("Sri Rajasekaran", "Web Developer", "https://goo.gl/7GZoGB", R.drawable.sri_pic));
// aboutPeople.add(new AboutPerson("Abhinav Reddy", "Web Developer", "https://goo.gl/PSCYbR", R.drawable.abhinav_pic));
// }
//
// public static ArrayList<AboutPerson> getAboutPeople () {
// return aboutPeople;
// }
//
// public static ArrayList<Announcement> getAnnouncements (boolean onlyReturnBookmarkedAnnouncements) {
// if (!onlyReturnBookmarkedAnnouncements) { return getAnnouncements(); }
//
// ArrayList<Announcement> filteredAnnouncements = new ArrayList<>();
// for (Announcement announcement : getAnnouncements()) { if (announcement.isBookmarkedByMe()) { filteredAnnouncements.add(announcement); } }
// Collections.sort(filteredAnnouncements);
// return filteredAnnouncements;
// }
//
// public static ArrayList<Announcement> getAnnouncements () {
// return announcements;
// }
//
// public static String getOpeningCeremoniesRoomNumber () {
// return openingCeremoniesRoomNumber;
// }
//
// public static ArrayList<ScheduleEvent> getScheduleEvents () {
// return scheduleEvents;
// }
//
// public static void setAnnouncements (Context context, ArrayList<Announcement> announcements) {
// Collections.sort(announcements);
// AnnouncementController.setIsBookmarkedByMeBasedOnPrefs(context, announcements);
// AnnouncementController.setIsLikedByMeBasedOnPrefs(context, announcements);
// DataStore.announcements = announcements;
// }
//
// public static void setOpeningCeremoniesRoomNumber (String openingCeremoniesRoomNumber) {
// DataStore.openingCeremoniesRoomNumber = openingCeremoniesRoomNumber;
// }
//
// public static void setScheduleEvents (ArrayList<ScheduleEvent> scheduleEvents) {
// DataStore.scheduleEvents = scheduleEvents;
// }
// }
//
// Path: app/src/main/java/com/hackgsu/fall2016/android/model/AboutPerson.java
// public class AboutPerson {
// private final String name;
// private final String role;
// private final String linkedInUrl;
// private
// @DrawableRes
// int picture;
//
// public AboutPerson(String name, String role, String linkedInUrl, int picture) {
// this.name = name;
// this.role = role;
// this.linkedInUrl = linkedInUrl;
// this.picture = picture;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRole() {
// return role;
// }
//
// public String getLinkedInUrl() {
// return linkedInUrl;
// }
//
// public int getPicture() { return picture; }
// }
// Path: app/src/main/java/com/hackgsu/fall2016/android/views/AboutRecyclerView.java
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.hackgsu.fall2016.android.DataStore;
import com.hackgsu.fall2016.android.R;
import com.hackgsu.fall2016.android.model.AboutPerson;
View cardView = View.inflate(getContext(), R.layout.about_person_card, null);
return new AboutViewHolder(cardView);
}
@Override
public void onBindViewHolder(AboutViewHolder holder, int position) {
holder.loadPerson(DataStore.getAboutPeople().get(position));
}
@Override
public int getItemCount() {
return DataStore.getAboutPeople().size();
}
}
public class AboutViewHolder extends ViewHolder {
private final ImageView personImage;
private final TextView personName;
private final TextView personRole;
AboutViewHolder(View cardView) {
super(cardView);
personImage = (ImageView) cardView.findViewById(R.id.person_image);
personName = (TextView) cardView.findViewById(R.id.person_name);
personRole = (TextView) cardView.findViewById(R.id.person_role);
}
| public void loadPerson(AboutPerson aboutPerson) { |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseActivity.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map; | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStop() {
super.onStop();
}
protected ActionBar initActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowHomeEnabled(true);
return actionBar;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
final Intent startIntent = new Intent(this, StartActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
protected void registerScreen(String event) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseActivity.java
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStop() {
super.onStop();
}
protected ActionBar initActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowHomeEnabled(true);
return actionBar;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
final Intent startIntent = new Intent(this, StartActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
protected void registerScreen(String event) { | Analytics.getInstance(this).registerScreen(event); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/SitesStore.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/LocationUtils.java
// public class LocationUtils {
//
// private static final String TAG = "LocationUtils";
// /**
// * Simple formatting of an {@link Address}.
// * @param address the address
// * @return formatted address.
// */
// public static String getAddressLine(Address address) {
// StringBuilder sb = new StringBuilder();
// if (address.getAddressLine(0) != null) {
// sb.append(address.getAddressLine(0));
// }
// if (address.getAddressLine(1) != null) {
// sb.append(" ").append(address.getAddressLine(1));
// }
// return sb.toString();
// }
//
// /**
// * Converts a string representation to {@link android.location.Location}.
// * @param locationData the location (latitude,longitude)
// * @return android location.
// */
// public static Location parseLocation(String locationData) {
// String[] longAndLat = locationData.split(",");
// //Defualt to the world center, The Royal Palace
// float latitude = 59.3270053f;
// float longitude = 18.0723166f;
// try {
// latitude = Float.parseFloat(longAndLat[0]);
// longitude = Float.parseFloat(longAndLat[1]);
// } catch (NumberFormatException nfe) {
// Log.e(TAG, nfe.toString());
// } catch (ArrayIndexOutOfBoundsException aioobe) {
// Log.e(TAG, aioobe.toString());
// }
//
// Location location = new Location("sthlmtraveling");
// location.setLatitude(latitude);
// location.setLongitude(longitude);
//
// return location;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
| import android.content.Context;
import android.location.Location;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.markupartist.sthlmtraveling.utils.LocationUtils;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2; | package com.markupartist.sthlmtraveling.provider.site;
public class SitesStore {
private static Pattern SITE_NAME_PATTERN = Pattern.compile("([\\w\\s0-9-& ]+)");
private static SitesStore sInstance;
private SitesStore() {
}
public static SitesStore getInstance() {
if (sInstance == null) {
sInstance = new SitesStore();
}
return sInstance;
}
public ArrayList<Site> getSite(final Context context, final String name) throws IOException {
return getSiteV2(context, name);
}
public ArrayList<Site> getSiteV2(final Context context, final String name) throws IOException {
return getSiteV2(context, name, true);
}
public ArrayList<Site> getSiteV2(final Context context, final String name, final boolean onlyStations) throws IOException {
if (TextUtils.isEmpty(name)) {
return new ArrayList<>();
}
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/LocationUtils.java
// public class LocationUtils {
//
// private static final String TAG = "LocationUtils";
// /**
// * Simple formatting of an {@link Address}.
// * @param address the address
// * @return formatted address.
// */
// public static String getAddressLine(Address address) {
// StringBuilder sb = new StringBuilder();
// if (address.getAddressLine(0) != null) {
// sb.append(address.getAddressLine(0));
// }
// if (address.getAddressLine(1) != null) {
// sb.append(" ").append(address.getAddressLine(1));
// }
// return sb.toString();
// }
//
// /**
// * Converts a string representation to {@link android.location.Location}.
// * @param locationData the location (latitude,longitude)
// * @return android location.
// */
// public static Location parseLocation(String locationData) {
// String[] longAndLat = locationData.split(",");
// //Defualt to the world center, The Royal Palace
// float latitude = 59.3270053f;
// float longitude = 18.0723166f;
// try {
// latitude = Float.parseFloat(longAndLat[0]);
// longitude = Float.parseFloat(longAndLat[1]);
// } catch (NumberFormatException nfe) {
// Log.e(TAG, nfe.toString());
// } catch (ArrayIndexOutOfBoundsException aioobe) {
// Log.e(TAG, aioobe.toString());
// }
//
// Location location = new Location("sthlmtraveling");
// location.setLatitude(latitude);
// location.setLongitude(longitude);
//
// return location;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/SitesStore.java
import android.content.Context;
import android.location.Location;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.markupartist.sthlmtraveling.utils.LocationUtils;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2;
package com.markupartist.sthlmtraveling.provider.site;
public class SitesStore {
private static Pattern SITE_NAME_PATTERN = Pattern.compile("([\\w\\s0-9-& ]+)");
private static SitesStore sInstance;
private SitesStore() {
}
public static SitesStore getInstance() {
if (sInstance == null) {
sInstance = new SitesStore();
}
return sInstance;
}
public ArrayList<Site> getSite(final Context context, final String name) throws IOException {
return getSiteV2(context, name);
}
public ArrayList<Site> getSiteV2(final Context context, final String name) throws IOException {
return getSiteV2(context, name, true);
}
public ArrayList<Site> getSiteV2(final Context context, final String name, final boolean onlyStations) throws IOException {
if (TextUtils.isEmpty(name)) {
return new ArrayList<>();
}
| HttpHelper httpHelper = HttpHelper.getInstance(context); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/SitesStore.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/LocationUtils.java
// public class LocationUtils {
//
// private static final String TAG = "LocationUtils";
// /**
// * Simple formatting of an {@link Address}.
// * @param address the address
// * @return formatted address.
// */
// public static String getAddressLine(Address address) {
// StringBuilder sb = new StringBuilder();
// if (address.getAddressLine(0) != null) {
// sb.append(address.getAddressLine(0));
// }
// if (address.getAddressLine(1) != null) {
// sb.append(" ").append(address.getAddressLine(1));
// }
// return sb.toString();
// }
//
// /**
// * Converts a string representation to {@link android.location.Location}.
// * @param locationData the location (latitude,longitude)
// * @return android location.
// */
// public static Location parseLocation(String locationData) {
// String[] longAndLat = locationData.split(",");
// //Defualt to the world center, The Royal Palace
// float latitude = 59.3270053f;
// float longitude = 18.0723166f;
// try {
// latitude = Float.parseFloat(longAndLat[0]);
// longitude = Float.parseFloat(longAndLat[1]);
// } catch (NumberFormatException nfe) {
// Log.e(TAG, nfe.toString());
// } catch (ArrayIndexOutOfBoundsException aioobe) {
// Log.e(TAG, aioobe.toString());
// }
//
// Location location = new Location("sthlmtraveling");
// location.setLatitude(latitude);
// location.setLongitude(longitude);
//
// return location;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
| import android.content.Context;
import android.location.Location;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.markupartist.sthlmtraveling.utils.LocationUtils;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2; | package com.markupartist.sthlmtraveling.provider.site;
public class SitesStore {
private static Pattern SITE_NAME_PATTERN = Pattern.compile("([\\w\\s0-9-& ]+)");
private static SitesStore sInstance;
private SitesStore() {
}
public static SitesStore getInstance() {
if (sInstance == null) {
sInstance = new SitesStore();
}
return sInstance;
}
public ArrayList<Site> getSite(final Context context, final String name) throws IOException {
return getSiteV2(context, name);
}
public ArrayList<Site> getSiteV2(final Context context, final String name) throws IOException {
return getSiteV2(context, name, true);
}
public ArrayList<Site> getSiteV2(final Context context, final String name, final boolean onlyStations) throws IOException {
if (TextUtils.isEmpty(name)) {
return new ArrayList<>();
}
HttpHelper httpHelper = HttpHelper.getInstance(context);
String onlyStationsParam = onlyStations ? "true" : "false"; | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/LocationUtils.java
// public class LocationUtils {
//
// private static final String TAG = "LocationUtils";
// /**
// * Simple formatting of an {@link Address}.
// * @param address the address
// * @return formatted address.
// */
// public static String getAddressLine(Address address) {
// StringBuilder sb = new StringBuilder();
// if (address.getAddressLine(0) != null) {
// sb.append(address.getAddressLine(0));
// }
// if (address.getAddressLine(1) != null) {
// sb.append(" ").append(address.getAddressLine(1));
// }
// return sb.toString();
// }
//
// /**
// * Converts a string representation to {@link android.location.Location}.
// * @param locationData the location (latitude,longitude)
// * @return android location.
// */
// public static Location parseLocation(String locationData) {
// String[] longAndLat = locationData.split(",");
// //Defualt to the world center, The Royal Palace
// float latitude = 59.3270053f;
// float longitude = 18.0723166f;
// try {
// latitude = Float.parseFloat(longAndLat[0]);
// longitude = Float.parseFloat(longAndLat[1]);
// } catch (NumberFormatException nfe) {
// Log.e(TAG, nfe.toString());
// } catch (ArrayIndexOutOfBoundsException aioobe) {
// Log.e(TAG, aioobe.toString());
// }
//
// Location location = new Location("sthlmtraveling");
// location.setLatitude(latitude);
// location.setLongitude(longitude);
//
// return location;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/SitesStore.java
import android.content.Context;
import android.location.Location;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.markupartist.sthlmtraveling.utils.LocationUtils;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2;
package com.markupartist.sthlmtraveling.provider.site;
public class SitesStore {
private static Pattern SITE_NAME_PATTERN = Pattern.compile("([\\w\\s0-9-& ]+)");
private static SitesStore sInstance;
private SitesStore() {
}
public static SitesStore getInstance() {
if (sInstance == null) {
sInstance = new SitesStore();
}
return sInstance;
}
public ArrayList<Site> getSite(final Context context, final String name) throws IOException {
return getSiteV2(context, name);
}
public ArrayList<Site> getSiteV2(final Context context, final String name) throws IOException {
return getSiteV2(context, name, true);
}
public ArrayList<Site> getSiteV2(final Context context, final String name, final boolean onlyStations) throws IOException {
if (TextUtils.isEmpty(name)) {
return new ArrayList<>();
}
HttpHelper httpHelper = HttpHelper.getInstance(context);
String onlyStationsParam = onlyStations ? "true" : "false"; | String url = apiEndpoint2() + "v1/site/" |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/SitesStore.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/LocationUtils.java
// public class LocationUtils {
//
// private static final String TAG = "LocationUtils";
// /**
// * Simple formatting of an {@link Address}.
// * @param address the address
// * @return formatted address.
// */
// public static String getAddressLine(Address address) {
// StringBuilder sb = new StringBuilder();
// if (address.getAddressLine(0) != null) {
// sb.append(address.getAddressLine(0));
// }
// if (address.getAddressLine(1) != null) {
// sb.append(" ").append(address.getAddressLine(1));
// }
// return sb.toString();
// }
//
// /**
// * Converts a string representation to {@link android.location.Location}.
// * @param locationData the location (latitude,longitude)
// * @return android location.
// */
// public static Location parseLocation(String locationData) {
// String[] longAndLat = locationData.split(",");
// //Defualt to the world center, The Royal Palace
// float latitude = 59.3270053f;
// float longitude = 18.0723166f;
// try {
// latitude = Float.parseFloat(longAndLat[0]);
// longitude = Float.parseFloat(longAndLat[1]);
// } catch (NumberFormatException nfe) {
// Log.e(TAG, nfe.toString());
// } catch (ArrayIndexOutOfBoundsException aioobe) {
// Log.e(TAG, aioobe.toString());
// }
//
// Location location = new Location("sthlmtraveling");
// location.setLatitude(latitude);
// location.setLongitude(longitude);
//
// return location;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
| import android.content.Context;
import android.location.Location;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.markupartist.sthlmtraveling.utils.LocationUtils;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2; |
HttpHelper httpHelper = HttpHelper.getInstance(context);
Response response = httpHelper.getClient().newCall(
httpHelper.createRequest(endpoint)).execute();
if (!response.isSuccessful()) {
Log.w("SiteStore", "Expected 200, got " + response.code());
throw new IOException("A remote server error occurred when getting sites.");
}
String rawContent = response.body().string();
ArrayList<Site> stopPoints = new ArrayList<Site>();
try {
JSONObject jsonSites = new JSONObject(rawContent);
if (jsonSites.has("sites")) {
JSONArray jsonSitesArray = jsonSites.getJSONArray("sites");
for (int i = 0; i < jsonSitesArray.length(); i++) {
try {
JSONObject jsonStop = jsonSitesArray.getJSONObject(i);
Site site = new Site();
Pair<String, String> nameAndLocality =
nameAsNameAndLocality(jsonStop.getString("name"));
site.setName(nameAndLocality.first);
site.setLocality(nameAndLocality.second);
site.setId(jsonStop.getInt("site_id"));
site.setSource(Site.SOURCE_STHLM_TRAVELING);
site.setType(Site.TYPE_TRANSIT_STOP);
String locationData = jsonStop.optString("location");
if(locationData != null) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/LocationUtils.java
// public class LocationUtils {
//
// private static final String TAG = "LocationUtils";
// /**
// * Simple formatting of an {@link Address}.
// * @param address the address
// * @return formatted address.
// */
// public static String getAddressLine(Address address) {
// StringBuilder sb = new StringBuilder();
// if (address.getAddressLine(0) != null) {
// sb.append(address.getAddressLine(0));
// }
// if (address.getAddressLine(1) != null) {
// sb.append(" ").append(address.getAddressLine(1));
// }
// return sb.toString();
// }
//
// /**
// * Converts a string representation to {@link android.location.Location}.
// * @param locationData the location (latitude,longitude)
// * @return android location.
// */
// public static Location parseLocation(String locationData) {
// String[] longAndLat = locationData.split(",");
// //Defualt to the world center, The Royal Palace
// float latitude = 59.3270053f;
// float longitude = 18.0723166f;
// try {
// latitude = Float.parseFloat(longAndLat[0]);
// longitude = Float.parseFloat(longAndLat[1]);
// } catch (NumberFormatException nfe) {
// Log.e(TAG, nfe.toString());
// } catch (ArrayIndexOutOfBoundsException aioobe) {
// Log.e(TAG, aioobe.toString());
// }
//
// Location location = new Location("sthlmtraveling");
// location.setLatitude(latitude);
// location.setLongitude(longitude);
//
// return location;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/SitesStore.java
import android.content.Context;
import android.location.Location;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.markupartist.sthlmtraveling.utils.LocationUtils;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2;
HttpHelper httpHelper = HttpHelper.getInstance(context);
Response response = httpHelper.getClient().newCall(
httpHelper.createRequest(endpoint)).execute();
if (!response.isSuccessful()) {
Log.w("SiteStore", "Expected 200, got " + response.code());
throw new IOException("A remote server error occurred when getting sites.");
}
String rawContent = response.body().string();
ArrayList<Site> stopPoints = new ArrayList<Site>();
try {
JSONObject jsonSites = new JSONObject(rawContent);
if (jsonSites.has("sites")) {
JSONArray jsonSitesArray = jsonSites.getJSONArray("sites");
for (int i = 0; i < jsonSitesArray.length(); i++) {
try {
JSONObject jsonStop = jsonSitesArray.getJSONObject(i);
Site site = new Site();
Pair<String, String> nameAndLocality =
nameAsNameAndLocality(jsonStop.getString("name"));
site.setName(nameAndLocality.first);
site.setLocality(nameAndLocality.second);
site.setId(jsonStop.getInt("site_id"));
site.setSource(Site.SOURCE_STHLM_TRAVELING);
site.setType(Site.TYPE_TRANSIT_STOP);
String locationData = jsonStop.optString("location");
if(locationData != null) { | site.setLocation(LocationUtils.parseLocation(locationData)); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/AdProxy.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.crashlytics.android.Crashlytics;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.R; |
public void onDestroy() {
if (mAdView == null) {
return;
}
mAdView.destroy();
}
public void onPause() {
if (mAdView == null) {
return;
}
mAdView.pause();
}
public void onResume() {
if (mAdView == null) {
return;
}
mAdView.resume();
}
public void load() {
userConsentForm.showIfConsentIsUnknown();
AdRequest.Builder builder = new AdRequest.Builder();
if (BuildConfig.DEBUG) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/AdProxy.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.crashlytics.android.Crashlytics;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.R;
public void onDestroy() {
if (mAdView == null) {
return;
}
mAdView.destroy();
}
public void onPause() {
if (mAdView == null) {
return;
}
mAdView.pause();
}
public void onResume() {
if (mAdView == null) {
return;
}
mAdView.resume();
}
public void load() {
userConsentForm.showIfConsentIsUnknown();
AdRequest.Builder builder = new AdRequest.Builder();
if (BuildConfig.DEBUG) { | String[] testDevices = AppConfig.ADMOB_TEST_DEVICES; |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseListFragment.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
| import android.content.Intent;
import androidx.fragment.app.ListFragment;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map; | package com.markupartist.sthlmtraveling;
public class BaseListFragment extends ListFragment {
protected void registerScreen(String event) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseListFragment.java
import android.content.Intent;
import androidx.fragment.app.ListFragment;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map;
package com.markupartist.sthlmtraveling;
public class BaseListFragment extends ListFragment {
protected void registerScreen(String event) { | Analytics.getInstance(getActivity()).registerScreen(event); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/Site.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/models/Place.java
// public class Place implements Parcelable {
// private final String id;
// private final String name;
// private final String type;
// private final double lat;
// private final double lon;
// private final int stopIndex;
// @Nullable
// private final String track;
// @Nullable
// private final List<Entrance> entrances;
//
// public Place(String id, String name, String type, double lat, double lon,
// int stopIndex, @Nullable String track, @Nullable List<Entrance> entrances) {
// this.id = id;
// this.name = name;
// this.type = type;
// this.lat = lat;
// this.lon = lon;
// this.stopIndex = stopIndex;
// this.track = track;
// this.entrances = entrances;
// }
//
// protected Place(Parcel in) {
// id = in.readString();
// name = in.readString();
// type = in.readString();
// lat = in.readDouble();
// lon = in.readDouble();
// stopIndex = in.readInt();
// track = in.readString();
// entrances = in.createTypedArrayList(Entrance.CREATOR);
// }
//
// public static final Creator<Place> CREATOR = new Creator<Place>() {
// @Override
// public Place createFromParcel(Parcel in) {
// return new Place(in);
// }
//
// @Override
// public Place[] newArray(int size) {
// return new Place[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(id);
// dest.writeString(name);
// dest.writeString(type);
// dest.writeDouble(lat);
// dest.writeDouble(lon);
// dest.writeInt(stopIndex);
// dest.writeString(track);
// dest.writeTypedList(entrances);
// }
//
// public String getId() {
// return id;
// }
//
// public double getLat() {
// return lat;
// }
//
// public double getLon() {
// return lon;
// }
//
// public String getName() {
// return name;
// }
//
// public String getType() {
// return type;
// }
//
// public boolean isMyLocation() {
// return name != null && name.equals(Site.TYPE_MY_LOCATION);
// }
//
// public boolean hasLocation() {
// // Sorry Null Island.
// return lat != 0 && lon != 0;
// }
//
// public int getStopIndex() {
// return stopIndex;
// }
//
// public boolean hasEntrances() {
// return entrances != null && !entrances.isEmpty();
// }
//
// public List<Entrance> getEntrances() {
// return entrances;
// }
//
// @Nullable
// public String getTrack() {
// return track;
// }
//
// public boolean looksEquals(Place other) {
// if (id != null && other.getId() != null) {
// return id.equals(other.getId());
// } else if (stopIndex == other.getStopIndex()) {
// return true;
// } else if (name != null && other.getName() != null) {
// return name.equals(other.getName());
// }
// return false;
// }
// }
| import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.models.Place;
import org.json.JSONException;
import org.json.JSONObject; |
public boolean hasLocation() {
return mLocation != null;
}
public void setLocation(double lat, double lng) {
mLocation = new Location("sthlmtraveling");
mLocation.setLatitude(lat);
mLocation.setLongitude(lng);
}
public void setLocation(int lat, int lng) {
if (lat == 0 || lng == 0) {
return;
}
mLocation = new Location("sthlmtraveling");
mLocation.setLatitude(lat / 1E6);
mLocation.setLongitude(lng / 1E6);
}
public String toDump() {
return "Site [mId=" + mId
+ ", mName=" + mName
+ ", mType=" + mType
+ ", mLocation=" + mLocation
+ ", mSource=" + mSource
+ ", mLocality=" + mLocality
+ "]";
}
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/models/Place.java
// public class Place implements Parcelable {
// private final String id;
// private final String name;
// private final String type;
// private final double lat;
// private final double lon;
// private final int stopIndex;
// @Nullable
// private final String track;
// @Nullable
// private final List<Entrance> entrances;
//
// public Place(String id, String name, String type, double lat, double lon,
// int stopIndex, @Nullable String track, @Nullable List<Entrance> entrances) {
// this.id = id;
// this.name = name;
// this.type = type;
// this.lat = lat;
// this.lon = lon;
// this.stopIndex = stopIndex;
// this.track = track;
// this.entrances = entrances;
// }
//
// protected Place(Parcel in) {
// id = in.readString();
// name = in.readString();
// type = in.readString();
// lat = in.readDouble();
// lon = in.readDouble();
// stopIndex = in.readInt();
// track = in.readString();
// entrances = in.createTypedArrayList(Entrance.CREATOR);
// }
//
// public static final Creator<Place> CREATOR = new Creator<Place>() {
// @Override
// public Place createFromParcel(Parcel in) {
// return new Place(in);
// }
//
// @Override
// public Place[] newArray(int size) {
// return new Place[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(id);
// dest.writeString(name);
// dest.writeString(type);
// dest.writeDouble(lat);
// dest.writeDouble(lon);
// dest.writeInt(stopIndex);
// dest.writeString(track);
// dest.writeTypedList(entrances);
// }
//
// public String getId() {
// return id;
// }
//
// public double getLat() {
// return lat;
// }
//
// public double getLon() {
// return lon;
// }
//
// public String getName() {
// return name;
// }
//
// public String getType() {
// return type;
// }
//
// public boolean isMyLocation() {
// return name != null && name.equals(Site.TYPE_MY_LOCATION);
// }
//
// public boolean hasLocation() {
// // Sorry Null Island.
// return lat != 0 && lon != 0;
// }
//
// public int getStopIndex() {
// return stopIndex;
// }
//
// public boolean hasEntrances() {
// return entrances != null && !entrances.isEmpty();
// }
//
// public List<Entrance> getEntrances() {
// return entrances;
// }
//
// @Nullable
// public String getTrack() {
// return track;
// }
//
// public boolean looksEquals(Place other) {
// if (id != null && other.getId() != null) {
// return id.equals(other.getId());
// } else if (stopIndex == other.getStopIndex()) {
// return true;
// } else if (name != null && other.getName() != null) {
// return name.equals(other.getName());
// }
// return false;
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/site/Site.java
import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.core.util.Pair;
import android.text.TextUtils;
import android.util.Log;
import com.markupartist.sthlmtraveling.data.models.Place;
import org.json.JSONException;
import org.json.JSONObject;
public boolean hasLocation() {
return mLocation != null;
}
public void setLocation(double lat, double lng) {
mLocation = new Location("sthlmtraveling");
mLocation.setLatitude(lat);
mLocation.setLongitude(lng);
}
public void setLocation(int lat, int lng) {
if (lat == 0 || lng == 0) {
return;
}
mLocation = new Location("sthlmtraveling");
mLocation.setLatitude(lat / 1E6);
mLocation.setLongitude(lng / 1E6);
}
public String toDump() {
return "Site [mId=" + mId
+ ", mName=" + mName
+ ", mType=" + mType
+ ", mLocation=" + mLocation
+ ", mSource=" + mSource
+ ", mLocality=" + mLocality
+ "]";
}
| public Place asPlace() { |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public class ApiConf {
// public static String KEY = AppConfig.STHLM_TRAVELING_API_KEY;
//
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
//
// public static String get(String s) {
// return s;
// }
//
// }
| import android.content.Context;
import android.util.Log;
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.provider.ApiConf;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit; | /*
* Copyright (C) 2009-2014 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.data.misc;
public class HttpHelper {
static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static HttpHelper sInstance;
OkHttpClient mClient;
private HttpHelper(final Context context) {
mClient = new OkHttpClient();
mClient.setConnectTimeout(15, TimeUnit.SECONDS);
mClient.setReadTimeout(15, TimeUnit.SECONDS);
installHttpCache(context);
}
public static HttpHelper getInstance(final Context context) {
if (sInstance == null) {
sInstance = new HttpHelper(context);
}
return sInstance;
}
/**
* Install an HTTP cache in the application cache directory.
*/
private void installHttpCache(final Context context) {
// Install an HTTP cache in the application cache directory.
try {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(context.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
mClient.setCache(cache);
} catch (Throwable e) {
Log.e("HttpHelper", "Unable to install disk cache.");
}
}
public Request createRequest(final String endpoint) throws IOException {
return new Request.Builder()
.get()
.url(endpoint) | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public class ApiConf {
// public static String KEY = AppConfig.STHLM_TRAVELING_API_KEY;
//
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
//
// public static String get(String s) {
// return s;
// }
//
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
import android.content.Context;
import android.util.Log;
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.provider.ApiConf;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/*
* Copyright (C) 2009-2014 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.data.misc;
public class HttpHelper {
static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static HttpHelper sInstance;
OkHttpClient mClient;
private HttpHelper(final Context context) {
mClient = new OkHttpClient();
mClient.setConnectTimeout(15, TimeUnit.SECONDS);
mClient.setReadTimeout(15, TimeUnit.SECONDS);
installHttpCache(context);
}
public static HttpHelper getInstance(final Context context) {
if (sInstance == null) {
sInstance = new HttpHelper(context);
}
return sInstance;
}
/**
* Install an HTTP cache in the application cache directory.
*/
private void installHttpCache(final Context context) {
// Install an HTTP cache in the application cache directory.
try {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(context.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
mClient.setCache(cache);
} catch (Throwable e) {
Log.e("HttpHelper", "Unable to install disk cache.");
}
}
public Request createRequest(final String endpoint) throws IOException {
return new Request.Builder()
.get()
.url(endpoint) | .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY)) |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public class ApiConf {
// public static String KEY = AppConfig.STHLM_TRAVELING_API_KEY;
//
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
//
// public static String get(String s) {
// return s;
// }
//
// }
| import android.content.Context;
import android.util.Log;
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.provider.ApiConf;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit; | installHttpCache(context);
}
public static HttpHelper getInstance(final Context context) {
if (sInstance == null) {
sInstance = new HttpHelper(context);
}
return sInstance;
}
/**
* Install an HTTP cache in the application cache directory.
*/
private void installHttpCache(final Context context) {
// Install an HTTP cache in the application cache directory.
try {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(context.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
mClient.setCache(cache);
} catch (Throwable e) {
Log.e("HttpHelper", "Unable to install disk cache.");
}
}
public Request createRequest(final String endpoint) throws IOException {
return new Request.Builder()
.get()
.url(endpoint)
.addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY)) | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public class ApiConf {
// public static String KEY = AppConfig.STHLM_TRAVELING_API_KEY;
//
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
//
// public static String get(String s) {
// return s;
// }
//
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
import android.content.Context;
import android.util.Log;
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.provider.ApiConf;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
installHttpCache(context);
}
public static HttpHelper getInstance(final Context context) {
if (sInstance == null) {
sInstance = new HttpHelper(context);
}
return sInstance;
}
/**
* Install an HTTP cache in the application cache directory.
*/
private void installHttpCache(final Context context) {
// Install an HTTP cache in the application cache directory.
try {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(context.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
mClient.setCache(cache);
} catch (Throwable e) {
Log.e("HttpHelper", "Unable to install disk cache.");
}
}
public Request createRequest(final String endpoint) throws IOException {
return new Request.Builder()
.get()
.url(endpoint)
.addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY)) | .header("User-Agent", AppConfig.USER_AGENT) |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/PlacesProvider.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/PlacesProvider.java
// public static final class Places implements BaseColumns {
// private Places() {
// }
//
// public static final Uri CONTENT_URI = Uri.parse("content://"
// + PlacesProvider.AUTHORITY + "/places");
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.sthlmtraveling.places";
//
// public static final String PLACE_ID = "_id";
//
// public static final String SITE_ID = "site_id";
//
// public static final String NAME = "name";
//
// public static final String PREFERRED_TRANSPORT_MODE = "preferred_transport_mode";
//
// public static final String STARRED = "starred";
//
// public static final String POSITION = "position";
// }
| import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.provider.PlacesProvider.Place.Places;
import java.util.HashMap; | package com.markupartist.sthlmtraveling.provider;
public class PlacesProvider extends ContentProvider {
private static final String TAG = "PlacesProvider";
private static final String DATABASE_NAME = "places.db";
private static final int DATABASE_VERSION = 1;
private static final String PLACES_TABLE_NAME = "places";
public static final String AUTHORITY = BuildConfig.BASE_PROVIDER_AUTHORITY + ".placesprovider";
private static final UriMatcher sUriMatcher;
private static final int PLACES = 1;
private static HashMap<String, String> sPlacesProjectionMap;
private DatabaseHelper dbHelper;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(AUTHORITY, PLACES_TABLE_NAME, PLACES);
sPlacesProjectionMap = new HashMap<String, String>(); | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/PlacesProvider.java
// public static final class Places implements BaseColumns {
// private Places() {
// }
//
// public static final Uri CONTENT_URI = Uri.parse("content://"
// + PlacesProvider.AUTHORITY + "/places");
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.sthlmtraveling.places";
//
// public static final String PLACE_ID = "_id";
//
// public static final String SITE_ID = "site_id";
//
// public static final String NAME = "name";
//
// public static final String PREFERRED_TRANSPORT_MODE = "preferred_transport_mode";
//
// public static final String STARRED = "starred";
//
// public static final String POSITION = "position";
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/PlacesProvider.java
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.provider.PlacesProvider.Place.Places;
import java.util.HashMap;
package com.markupartist.sthlmtraveling.provider;
public class PlacesProvider extends ContentProvider {
private static final String TAG = "PlacesProvider";
private static final String DATABASE_NAME = "places.db";
private static final int DATABASE_VERSION = 1;
private static final String PLACES_TABLE_NAME = "places";
public static final String AUTHORITY = BuildConfig.BASE_PROVIDER_AUTHORITY + ".placesprovider";
private static final UriMatcher sUriMatcher;
private static final int PLACES = 1;
private static HashMap<String, String> sPlacesProjectionMap;
private DatabaseHelper dbHelper;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(AUTHORITY, PLACES_TABLE_NAME, PLACES);
sPlacesProjectionMap = new HashMap<String, String>(); | sPlacesProjectionMap.put(Places.PLACE_ID, Places.PLACE_ID); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/deviation/DeviationStore.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
| import android.content.Context;
import android.text.format.Time;
import android.util.Log;
import android.util.TimeFormatException;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2; |
Time created = new Time();
created.parse(jsonDeviation.getString("created"));
Deviation deviation = new Deviation();
deviation.setCreated(created);
deviation.setDetails(stripNewLinesAtTheEnd(jsonDeviation.getString("description")));
deviation.setHeader(jsonDeviation.getString("header"));
//deviation.setLink(jsonDeviation.getString("link"));
//deviation.setMessageVersion(jsonDeviation.getInt("messageVersion"));
deviation.setReference(jsonDeviation.getLong("reference"));
deviation.setScope(jsonDeviation.getString("scope"));
deviation.setScopeElements(jsonDeviation.getString("scope_elements"));
//deviation.setSortOrder(jsonDeviation.getInt("sortOrder"));
deviations.add(deviation);
} catch (TimeFormatException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return deviations;
}
private String retrieveDeviations(final Context context) throws IOException { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/deviation/DeviationStore.java
import android.content.Context;
import android.text.format.Time;
import android.util.Log;
import android.util.TimeFormatException;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2;
Time created = new Time();
created.parse(jsonDeviation.getString("created"));
Deviation deviation = new Deviation();
deviation.setCreated(created);
deviation.setDetails(stripNewLinesAtTheEnd(jsonDeviation.getString("description")));
deviation.setHeader(jsonDeviation.getString("header"));
//deviation.setLink(jsonDeviation.getString("link"));
//deviation.setMessageVersion(jsonDeviation.getInt("messageVersion"));
deviation.setReference(jsonDeviation.getLong("reference"));
deviation.setScope(jsonDeviation.getString("scope"));
deviation.setScopeElements(jsonDeviation.getString("scope_elements"));
//deviation.setSortOrder(jsonDeviation.getInt("sortOrder"));
deviations.add(deviation);
} catch (TimeFormatException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return deviations;
}
private String retrieveDeviations(final Context context) throws IOException { | final String endpoint = apiEndpoint2() + "v1/deviation/"; |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/deviation/DeviationStore.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
| import android.content.Context;
import android.text.format.Time;
import android.util.Log;
import android.util.TimeFormatException;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2; | created.parse(jsonDeviation.getString("created"));
Deviation deviation = new Deviation();
deviation.setCreated(created);
deviation.setDetails(stripNewLinesAtTheEnd(jsonDeviation.getString("description")));
deviation.setHeader(jsonDeviation.getString("header"));
//deviation.setLink(jsonDeviation.getString("link"));
//deviation.setMessageVersion(jsonDeviation.getInt("messageVersion"));
deviation.setReference(jsonDeviation.getLong("reference"));
deviation.setScope(jsonDeviation.getString("scope"));
deviation.setScopeElements(jsonDeviation.getString("scope_elements"));
//deviation.setSortOrder(jsonDeviation.getInt("sortOrder"));
deviations.add(deviation);
} catch (TimeFormatException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return deviations;
}
private String retrieveDeviations(final Context context) throws IOException {
final String endpoint = apiEndpoint2() + "v1/deviation/";
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/HttpHelper.java
// public class HttpHelper {
// static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static HttpHelper sInstance;
// OkHttpClient mClient;
//
// private HttpHelper(final Context context) {
// mClient = new OkHttpClient();
// mClient.setConnectTimeout(15, TimeUnit.SECONDS);
// mClient.setReadTimeout(15, TimeUnit.SECONDS);
// installHttpCache(context);
// }
//
// public static HttpHelper getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new HttpHelper(context);
// }
// return sInstance;
// }
//
// /**
// * Install an HTTP cache in the application cache directory.
// */
// private void installHttpCache(final Context context) {
// // Install an HTTP cache in the application cache directory.
// try {
// // Install an HTTP cache in the application cache directory.
// File cacheDir = new File(context.getCacheDir(), "http");
// Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
// mClient.setCache(cache);
// } catch (Throwable e) {
// Log.e("HttpHelper", "Unable to install disk cache.");
// }
// }
//
// public Request createRequest(final String endpoint) throws IOException {
// return new Request.Builder()
// .get()
// .url(endpoint)
// .addHeader("X-STHLMTraveling-API-Key", ApiConf.get(ApiConf.KEY))
// .header("User-Agent", AppConfig.USER_AGENT)
// .build();
// }
//
// public OkHttpClient getClient() {
// return mClient;
// }
//
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/ApiConf.java
// public static String apiEndpoint2() {
// return AppConfig.STHLM_TRAVELING_API_ENDPOINT;
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/deviation/DeviationStore.java
import android.content.Context;
import android.text.format.Time;
import android.util.Log;
import android.util.TimeFormatException;
import com.markupartist.sthlmtraveling.data.misc.HttpHelper;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.markupartist.sthlmtraveling.provider.ApiConf.apiEndpoint2;
created.parse(jsonDeviation.getString("created"));
Deviation deviation = new Deviation();
deviation.setCreated(created);
deviation.setDetails(stripNewLinesAtTheEnd(jsonDeviation.getString("description")));
deviation.setHeader(jsonDeviation.getString("header"));
//deviation.setLink(jsonDeviation.getString("link"));
//deviation.setMessageVersion(jsonDeviation.getInt("messageVersion"));
deviation.setReference(jsonDeviation.getLong("reference"));
deviation.setScope(jsonDeviation.getString("scope"));
deviation.setScopeElements(jsonDeviation.getString("scope_elements"));
//deviation.setSortOrder(jsonDeviation.getInt("sortOrder"));
deviations.add(deviation);
} catch (TimeFormatException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return deviations;
}
private String retrieveDeviations(final Context context) throws IOException {
final String endpoint = apiEndpoint2() + "v1/deviation/";
| HttpHelper httpHelper = HttpHelper.getInstance(context); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/receivers/OnBootReceiver.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/service/DeviationService.java
// public class DeviationService extends WakefulIntentService {
// private static String TAG = "DeviationService";
// private static String LINE_PATTERN = "[A-Za-zåäöÅÄÖ ]?([\\d]+)[ A-Z]?";
// private static Pattern sLinePattern = Pattern.compile(LINE_PATTERN);
// private NotificationManager mNotificationManager;
// //private Intent mInvokeIntent;
// private DeviationNotificationDbAdapter mDb;
//
// public DeviationService() {
// super("DeviationService");
// }
//
// @Override
// protected void doWakefulWork(Intent intent) {
// mNotificationManager =
// (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// //mInvokeIntent = new Intent(this, DeviationsActivity.class);
//
// mDb = new DeviationNotificationDbAdapter(getApplicationContext());
// mDb.open();
//
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(this);
// String filterString = sharedPreferences.getString("notification_deviations_lines_csv", "");
// ArrayList<Integer> triggerFor = DeviationStore.extractLineNumbers(filterString, null);
//
// DeviationStore deviationStore = new DeviationStore();
//
// try {
// ArrayList<Deviation> deviations = deviationStore.getDeviations(this);
// deviations = DeviationStore.filterByLineNumbers(deviations, triggerFor);
//
// for (Deviation deviation : deviations) {
// if (!mDb.containsReference(deviation.getReference(),
// deviation.getMessageVersion())) {
// mDb.create(deviation.getReference(), deviation.getMessageVersion());
// Log.d(TAG, "Notification triggered for " + deviation.getReference());
// showNotification(deviation);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// mDb.close();
// }
//
// /**
// * Show a notification while this service is running.
// */
// private void showNotification(Deviation deviation) {
// // The PendingIntent to launch our activity if the user selects this notification
// Intent i = new Intent(this, DeviationsActivity.class);
// i.setAction(DeviationsActivity.DEVIATION_FILTER_ACTION);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
//
// Notification notification = new NotificationCompat.Builder(this)
// .setSmallIcon(android.R.drawable.stat_notify_error)
// .setTicker(deviation.getDetails())
// .setWhen(System.currentTimeMillis())
// .setContentIntent(contentIntent)
// .setContentTitle(getText(R.string.deviations_label))
// .setContentText(getText(R.string.new_deviations))
// .build();
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// // Send the notification.
// mNotificationManager.notify(R.string.deviations_label, notification);
// }
//
// public static void startAsRepeating(Context context) {
// stopService(context);
// }
//
// public static void startService(Context context) {
// stopService(context);
// }
//
// public static void stopService(Context context) {
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(context);
// AlarmManager mgr =
// (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Intent i = new Intent(context, OnAlarmReceiver.class);
// PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
// mgr.cancel(pi);
// sharedPreferences.edit().putBoolean("notification_deviations_enabled", false).apply();
// Log.d(TAG, "Deviation service stopped");
// }
// }
| import com.markupartist.sthlmtraveling.service.DeviationService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log; | package com.markupartist.sthlmtraveling.receivers;
public class OnBootReceiver extends BroadcastReceiver {
//private static final int PERIOD = 300000; // 5 minutes
private static final int PERIOD = 300000; // 5 minutes
private static final String TAG = "OnBootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnBootReceiver");
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/service/DeviationService.java
// public class DeviationService extends WakefulIntentService {
// private static String TAG = "DeviationService";
// private static String LINE_PATTERN = "[A-Za-zåäöÅÄÖ ]?([\\d]+)[ A-Z]?";
// private static Pattern sLinePattern = Pattern.compile(LINE_PATTERN);
// private NotificationManager mNotificationManager;
// //private Intent mInvokeIntent;
// private DeviationNotificationDbAdapter mDb;
//
// public DeviationService() {
// super("DeviationService");
// }
//
// @Override
// protected void doWakefulWork(Intent intent) {
// mNotificationManager =
// (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// //mInvokeIntent = new Intent(this, DeviationsActivity.class);
//
// mDb = new DeviationNotificationDbAdapter(getApplicationContext());
// mDb.open();
//
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(this);
// String filterString = sharedPreferences.getString("notification_deviations_lines_csv", "");
// ArrayList<Integer> triggerFor = DeviationStore.extractLineNumbers(filterString, null);
//
// DeviationStore deviationStore = new DeviationStore();
//
// try {
// ArrayList<Deviation> deviations = deviationStore.getDeviations(this);
// deviations = DeviationStore.filterByLineNumbers(deviations, triggerFor);
//
// for (Deviation deviation : deviations) {
// if (!mDb.containsReference(deviation.getReference(),
// deviation.getMessageVersion())) {
// mDb.create(deviation.getReference(), deviation.getMessageVersion());
// Log.d(TAG, "Notification triggered for " + deviation.getReference());
// showNotification(deviation);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// mDb.close();
// }
//
// /**
// * Show a notification while this service is running.
// */
// private void showNotification(Deviation deviation) {
// // The PendingIntent to launch our activity if the user selects this notification
// Intent i = new Intent(this, DeviationsActivity.class);
// i.setAction(DeviationsActivity.DEVIATION_FILTER_ACTION);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
//
// Notification notification = new NotificationCompat.Builder(this)
// .setSmallIcon(android.R.drawable.stat_notify_error)
// .setTicker(deviation.getDetails())
// .setWhen(System.currentTimeMillis())
// .setContentIntent(contentIntent)
// .setContentTitle(getText(R.string.deviations_label))
// .setContentText(getText(R.string.new_deviations))
// .build();
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// // Send the notification.
// mNotificationManager.notify(R.string.deviations_label, notification);
// }
//
// public static void startAsRepeating(Context context) {
// stopService(context);
// }
//
// public static void startService(Context context) {
// stopService(context);
// }
//
// public static void stopService(Context context) {
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(context);
// AlarmManager mgr =
// (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Intent i = new Intent(context, OnAlarmReceiver.class);
// PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
// mgr.cancel(pi);
// sharedPreferences.edit().putBoolean("notification_deviations_enabled", false).apply();
// Log.d(TAG, "Deviation service stopped");
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/receivers/OnBootReceiver.java
import com.markupartist.sthlmtraveling.service.DeviationService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
package com.markupartist.sthlmtraveling.receivers;
public class OnBootReceiver extends BroadcastReceiver {
//private static final int PERIOD = 300000; // 5 minutes
private static final int PERIOD = 300000; // 5 minutes
private static final String TAG = "OnBootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnBootReceiver");
| DeviationService.startAsRepeating(context); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/api/PlaceQuery.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/models/Place.java
// public class Place implements Parcelable {
// private final String id;
// private final String name;
// private final String type;
// private final double lat;
// private final double lon;
// private final int stopIndex;
// @Nullable
// private final String track;
// @Nullable
// private final List<Entrance> entrances;
//
// public Place(String id, String name, String type, double lat, double lon,
// int stopIndex, @Nullable String track, @Nullable List<Entrance> entrances) {
// this.id = id;
// this.name = name;
// this.type = type;
// this.lat = lat;
// this.lon = lon;
// this.stopIndex = stopIndex;
// this.track = track;
// this.entrances = entrances;
// }
//
// protected Place(Parcel in) {
// id = in.readString();
// name = in.readString();
// type = in.readString();
// lat = in.readDouble();
// lon = in.readDouble();
// stopIndex = in.readInt();
// track = in.readString();
// entrances = in.createTypedArrayList(Entrance.CREATOR);
// }
//
// public static final Creator<Place> CREATOR = new Creator<Place>() {
// @Override
// public Place createFromParcel(Parcel in) {
// return new Place(in);
// }
//
// @Override
// public Place[] newArray(int size) {
// return new Place[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(id);
// dest.writeString(name);
// dest.writeString(type);
// dest.writeDouble(lat);
// dest.writeDouble(lon);
// dest.writeInt(stopIndex);
// dest.writeString(track);
// dest.writeTypedList(entrances);
// }
//
// public String getId() {
// return id;
// }
//
// public double getLat() {
// return lat;
// }
//
// public double getLon() {
// return lon;
// }
//
// public String getName() {
// return name;
// }
//
// public String getType() {
// return type;
// }
//
// public boolean isMyLocation() {
// return name != null && name.equals(Site.TYPE_MY_LOCATION);
// }
//
// public boolean hasLocation() {
// // Sorry Null Island.
// return lat != 0 && lon != 0;
// }
//
// public int getStopIndex() {
// return stopIndex;
// }
//
// public boolean hasEntrances() {
// return entrances != null && !entrances.isEmpty();
// }
//
// public List<Entrance> getEntrances() {
// return entrances;
// }
//
// @Nullable
// public String getTrack() {
// return track;
// }
//
// public boolean looksEquals(Place other) {
// if (id != null && other.getId() != null) {
// return id.equals(other.getId());
// } else if (stopIndex == other.getStopIndex()) {
// return true;
// } else if (name != null && other.getName() != null) {
// return name.equals(other.getName());
// }
// return false;
// }
// }
| import android.location.Location;
import android.text.TextUtils;
import com.markupartist.sthlmtraveling.data.models.Place;
import java.util.Locale; | }
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
public String getName() {
return name;
}
public String toString() {
if (id != null) {
if (this.lat != 0D && this.lon != 0D) {
return String.format(Locale.US, "%s,%s:%s:%s", lat, lon, id, name);
}
return String.format(Locale.US, "%s:%s", id, name);
}
return String.format(Locale.US, "%s,%s:%s", lat, lon, name);
}
public static final class Builder {
private String id;
private String name;
private double lon;
private double lat;
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/models/Place.java
// public class Place implements Parcelable {
// private final String id;
// private final String name;
// private final String type;
// private final double lat;
// private final double lon;
// private final int stopIndex;
// @Nullable
// private final String track;
// @Nullable
// private final List<Entrance> entrances;
//
// public Place(String id, String name, String type, double lat, double lon,
// int stopIndex, @Nullable String track, @Nullable List<Entrance> entrances) {
// this.id = id;
// this.name = name;
// this.type = type;
// this.lat = lat;
// this.lon = lon;
// this.stopIndex = stopIndex;
// this.track = track;
// this.entrances = entrances;
// }
//
// protected Place(Parcel in) {
// id = in.readString();
// name = in.readString();
// type = in.readString();
// lat = in.readDouble();
// lon = in.readDouble();
// stopIndex = in.readInt();
// track = in.readString();
// entrances = in.createTypedArrayList(Entrance.CREATOR);
// }
//
// public static final Creator<Place> CREATOR = new Creator<Place>() {
// @Override
// public Place createFromParcel(Parcel in) {
// return new Place(in);
// }
//
// @Override
// public Place[] newArray(int size) {
// return new Place[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(id);
// dest.writeString(name);
// dest.writeString(type);
// dest.writeDouble(lat);
// dest.writeDouble(lon);
// dest.writeInt(stopIndex);
// dest.writeString(track);
// dest.writeTypedList(entrances);
// }
//
// public String getId() {
// return id;
// }
//
// public double getLat() {
// return lat;
// }
//
// public double getLon() {
// return lon;
// }
//
// public String getName() {
// return name;
// }
//
// public String getType() {
// return type;
// }
//
// public boolean isMyLocation() {
// return name != null && name.equals(Site.TYPE_MY_LOCATION);
// }
//
// public boolean hasLocation() {
// // Sorry Null Island.
// return lat != 0 && lon != 0;
// }
//
// public int getStopIndex() {
// return stopIndex;
// }
//
// public boolean hasEntrances() {
// return entrances != null && !entrances.isEmpty();
// }
//
// public List<Entrance> getEntrances() {
// return entrances;
// }
//
// @Nullable
// public String getTrack() {
// return track;
// }
//
// public boolean looksEquals(Place other) {
// if (id != null && other.getId() != null) {
// return id.equals(other.getId());
// } else if (stopIndex == other.getStopIndex()) {
// return true;
// } else if (name != null && other.getName() != null) {
// return name.equals(other.getName());
// }
// return false;
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/api/PlaceQuery.java
import android.location.Location;
import android.text.TextUtils;
import com.markupartist.sthlmtraveling.data.models.Place;
import java.util.Locale;
}
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
public String getName() {
return name;
}
public String toString() {
if (id != null) {
if (this.lat != 0D && this.lon != 0D) {
return String.format(Locale.US, "%s,%s:%s:%s", lat, lon, id, name);
}
return String.format(Locale.US, "%s:%s", id, name);
}
return String.format(Locale.US, "%s,%s:%s", lat, lon, name);
}
public static final class Builder {
private String id;
private String name;
private double lon;
private double lat;
| public Builder place(Place place) { |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/receivers/OnAlarmReceiver.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/service/DeviationService.java
// public class DeviationService extends WakefulIntentService {
// private static String TAG = "DeviationService";
// private static String LINE_PATTERN = "[A-Za-zåäöÅÄÖ ]?([\\d]+)[ A-Z]?";
// private static Pattern sLinePattern = Pattern.compile(LINE_PATTERN);
// private NotificationManager mNotificationManager;
// //private Intent mInvokeIntent;
// private DeviationNotificationDbAdapter mDb;
//
// public DeviationService() {
// super("DeviationService");
// }
//
// @Override
// protected void doWakefulWork(Intent intent) {
// mNotificationManager =
// (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// //mInvokeIntent = new Intent(this, DeviationsActivity.class);
//
// mDb = new DeviationNotificationDbAdapter(getApplicationContext());
// mDb.open();
//
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(this);
// String filterString = sharedPreferences.getString("notification_deviations_lines_csv", "");
// ArrayList<Integer> triggerFor = DeviationStore.extractLineNumbers(filterString, null);
//
// DeviationStore deviationStore = new DeviationStore();
//
// try {
// ArrayList<Deviation> deviations = deviationStore.getDeviations(this);
// deviations = DeviationStore.filterByLineNumbers(deviations, triggerFor);
//
// for (Deviation deviation : deviations) {
// if (!mDb.containsReference(deviation.getReference(),
// deviation.getMessageVersion())) {
// mDb.create(deviation.getReference(), deviation.getMessageVersion());
// Log.d(TAG, "Notification triggered for " + deviation.getReference());
// showNotification(deviation);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// mDb.close();
// }
//
// /**
// * Show a notification while this service is running.
// */
// private void showNotification(Deviation deviation) {
// // The PendingIntent to launch our activity if the user selects this notification
// Intent i = new Intent(this, DeviationsActivity.class);
// i.setAction(DeviationsActivity.DEVIATION_FILTER_ACTION);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
//
// Notification notification = new NotificationCompat.Builder(this)
// .setSmallIcon(android.R.drawable.stat_notify_error)
// .setTicker(deviation.getDetails())
// .setWhen(System.currentTimeMillis())
// .setContentIntent(contentIntent)
// .setContentTitle(getText(R.string.deviations_label))
// .setContentText(getText(R.string.new_deviations))
// .build();
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// // Send the notification.
// mNotificationManager.notify(R.string.deviations_label, notification);
// }
//
// public static void startAsRepeating(Context context) {
// stopService(context);
// }
//
// public static void startService(Context context) {
// stopService(context);
// }
//
// public static void stopService(Context context) {
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(context);
// AlarmManager mgr =
// (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Intent i = new Intent(context, OnAlarmReceiver.class);
// PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
// mgr.cancel(pi);
// sharedPreferences.edit().putBoolean("notification_deviations_enabled", false).apply();
// Log.d(TAG, "Deviation service stopped");
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/service/WakefulIntentService.java
// abstract public class WakefulIntentService extends IntentService {
// private static String TAG = "WakefulIntentService";
// public static final String LOCK_NAME =
// "com.markupartist.sthlmtraveling.service.WakefulIntentService.Static";
// private static PowerManager.WakeLock lockStatic = null;
//
// public WakefulIntentService(String name) {
// super(name);
// }
//
// synchronized private static PowerManager.WakeLock getLock(Context context) {
// if (lockStatic == null) {
// PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//
// lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME);
// lockStatic.setReferenceCounted(true);
// }
//
// return (lockStatic);
// }
//
// abstract void doWakefulWork(Intent intent);
//
// public static void acquireStaticLock(Context context) {
// Log.d(TAG, "About acquire static lock");
// getLock(context).acquire();
// }
//
// @Override
// final protected void onHandleIntent(Intent intent) {
// try {
// doWakefulWork(intent);
// } finally {
// PowerManager.WakeLock lock = getLock(getApplicationContext());
// if (lock.isHeld()) {
// try {
// lock.release();
// } catch (Exception e) {
// Log.e(TAG, "Exception when releasing wakelock");
// }
// }
// }
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.markupartist.sthlmtraveling.service.DeviationService;
import com.markupartist.sthlmtraveling.service.WakefulIntentService; | package com.markupartist.sthlmtraveling.receivers;
public class OnAlarmReceiver extends BroadcastReceiver {
private static final String TAG = "OnAlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "recieved alarm");
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/service/DeviationService.java
// public class DeviationService extends WakefulIntentService {
// private static String TAG = "DeviationService";
// private static String LINE_PATTERN = "[A-Za-zåäöÅÄÖ ]?([\\d]+)[ A-Z]?";
// private static Pattern sLinePattern = Pattern.compile(LINE_PATTERN);
// private NotificationManager mNotificationManager;
// //private Intent mInvokeIntent;
// private DeviationNotificationDbAdapter mDb;
//
// public DeviationService() {
// super("DeviationService");
// }
//
// @Override
// protected void doWakefulWork(Intent intent) {
// mNotificationManager =
// (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// //mInvokeIntent = new Intent(this, DeviationsActivity.class);
//
// mDb = new DeviationNotificationDbAdapter(getApplicationContext());
// mDb.open();
//
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(this);
// String filterString = sharedPreferences.getString("notification_deviations_lines_csv", "");
// ArrayList<Integer> triggerFor = DeviationStore.extractLineNumbers(filterString, null);
//
// DeviationStore deviationStore = new DeviationStore();
//
// try {
// ArrayList<Deviation> deviations = deviationStore.getDeviations(this);
// deviations = DeviationStore.filterByLineNumbers(deviations, triggerFor);
//
// for (Deviation deviation : deviations) {
// if (!mDb.containsReference(deviation.getReference(),
// deviation.getMessageVersion())) {
// mDb.create(deviation.getReference(), deviation.getMessageVersion());
// Log.d(TAG, "Notification triggered for " + deviation.getReference());
// showNotification(deviation);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// mDb.close();
// }
//
// /**
// * Show a notification while this service is running.
// */
// private void showNotification(Deviation deviation) {
// // The PendingIntent to launch our activity if the user selects this notification
// Intent i = new Intent(this, DeviationsActivity.class);
// i.setAction(DeviationsActivity.DEVIATION_FILTER_ACTION);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
//
// Notification notification = new NotificationCompat.Builder(this)
// .setSmallIcon(android.R.drawable.stat_notify_error)
// .setTicker(deviation.getDetails())
// .setWhen(System.currentTimeMillis())
// .setContentIntent(contentIntent)
// .setContentTitle(getText(R.string.deviations_label))
// .setContentText(getText(R.string.new_deviations))
// .build();
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// // Send the notification.
// mNotificationManager.notify(R.string.deviations_label, notification);
// }
//
// public static void startAsRepeating(Context context) {
// stopService(context);
// }
//
// public static void startService(Context context) {
// stopService(context);
// }
//
// public static void stopService(Context context) {
// SharedPreferences sharedPreferences =
// PreferenceManager.getDefaultSharedPreferences(context);
// AlarmManager mgr =
// (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Intent i = new Intent(context, OnAlarmReceiver.class);
// PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
// mgr.cancel(pi);
// sharedPreferences.edit().putBoolean("notification_deviations_enabled", false).apply();
// Log.d(TAG, "Deviation service stopped");
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/service/WakefulIntentService.java
// abstract public class WakefulIntentService extends IntentService {
// private static String TAG = "WakefulIntentService";
// public static final String LOCK_NAME =
// "com.markupartist.sthlmtraveling.service.WakefulIntentService.Static";
// private static PowerManager.WakeLock lockStatic = null;
//
// public WakefulIntentService(String name) {
// super(name);
// }
//
// synchronized private static PowerManager.WakeLock getLock(Context context) {
// if (lockStatic == null) {
// PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//
// lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME);
// lockStatic.setReferenceCounted(true);
// }
//
// return (lockStatic);
// }
//
// abstract void doWakefulWork(Intent intent);
//
// public static void acquireStaticLock(Context context) {
// Log.d(TAG, "About acquire static lock");
// getLock(context).acquire();
// }
//
// @Override
// final protected void onHandleIntent(Intent intent) {
// try {
// doWakefulWork(intent);
// } finally {
// PowerManager.WakeLock lock = getLock(getApplicationContext());
// if (lock.isHeld()) {
// try {
// lock.release();
// } catch (Exception e) {
// Log.e(TAG, "Exception when releasing wakelock");
// }
// }
// }
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/receivers/OnAlarmReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.markupartist.sthlmtraveling.service.DeviationService;
import com.markupartist.sthlmtraveling.service.WakefulIntentService;
package com.markupartist.sthlmtraveling.receivers;
public class OnAlarmReceiver extends BroadcastReceiver {
private static final String TAG = "OnAlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "recieved alarm");
| DeviationService.startService(context); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseFragment.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
| import android.content.Intent;
import androidx.fragment.app.Fragment;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map; | package com.markupartist.sthlmtraveling;
public class BaseFragment extends Fragment {
protected void registerScreen(String event) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseFragment.java
import android.content.Intent;
import androidx.fragment.app.Fragment;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map;
package com.markupartist.sthlmtraveling;
public class BaseFragment extends Fragment {
protected void registerScreen(String event) { | Analytics.getInstance(getActivity()).registerScreen(event); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/DeviationDetailActivity.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/deviation/Deviation.java
// public class Deviation implements Parcelable {
// private Long mReference;
// private int mMessageVersion;
// private String mLink;
// private String mMobileLink;
// private Time mCreated;
// private boolean mIsMainNews;
// private int mSortOrder;
// private String mHeader;
// private String mDetails;
// private String mScope;
// private String mScopeElements;
//
// public Deviation(Parcel parcel) {
// mReference = parcel.readLong();
// mMessageVersion = parcel.readInt();
// mLink = parcel.readString();
// mMobileLink = parcel.readString();
// mCreated = new Time();
// mCreated.parse3339(parcel.readString());
// mIsMainNews = (Boolean) parcel.readValue(null);
// mSortOrder = parcel.readInt();
// mHeader = parcel.readString();
// mDetails = parcel.readString();
// mScope = parcel.readString();
// mScopeElements = parcel.readString();
// }
//
// public Deviation() {
// }
//
// public void setReference(Long reference) {
// this.mReference = reference;
// }
// public Long getReference() {
// return mReference;
// }
// public void setMessageVersion(int messageVersion) {
// this.mMessageVersion = messageVersion;
// }
// public int getMessageVersion() {
// return mMessageVersion;
// }
// public void setMobileLink(String mobileLink) {
// this.mMobileLink = mobileLink;
// }
// public String getMobileLink() {
// return mMobileLink;
// }
// public void setCreated(Time created) {
// this.mCreated = created;
// }
// public Time getCreated() {
// return mCreated;
// }
// public void setMainNews(boolean isMainNews) {
// this.mIsMainNews = isMainNews;
// }
// public boolean isMainNews() {
// return mIsMainNews;
// }
// public void setSortOrder(int sortOrder) {
// this.mSortOrder = sortOrder;
// }
// public int getSortOrder() {
// return mSortOrder;
// }
// public void setLink(String mLink) {
// this.mLink = mLink;
// }
// public String getLink() {
// return mLink;
// }
// public void setHeader(String header) {
// this.mHeader = header;
// }
// public String getHeader() {
// return mHeader;
// }
// public void setDetails(String details) {
// this.mDetails = details;
// }
// public String getDetails() {
// return mDetails;
// }
// public void setScope(String scope) {
// this.mScope = scope;
// }
// public String getScope() {
// return mScope;
// }
// public void setScopeElements(String scopeElements) {
// this.mScopeElements = scopeElements;
// }
// public String getScopeElements() {
// return mScopeElements;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeLong(mReference);
// parcel.writeInt(mMessageVersion);
// parcel.writeString(mLink);
// parcel.writeString(mMobileLink);
// parcel.writeString(mCreated.format3339(false));
// parcel.writeValue(mIsMainNews);
// parcel.writeInt(mSortOrder);
// parcel.writeString(mHeader);
// parcel.writeString(mDetails);
// parcel.writeString(mScope);
// parcel.writeString(mScopeElements);
// }
//
// public static final Creator<Deviation> CREATOR = new Creator<Deviation>() {
// public Deviation createFromParcel(Parcel parcel) {
// return new Deviation(parcel);
// }
//
// public Deviation[] newArray(int size) {
// return new Deviation[size];
// }
// };
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "Deviation [mCreated=" + mCreated + ", mDetails=" + mDetails
// + ", mHeader=" + mHeader + ", mIsMainNews=" + mIsMainNews
// + ", mLink=" + mLink + ", mMessageVersion=" + mMessageVersion
// + ", mMobileLink=" + mMobileLink + ", mReference=" + mReference
// + ", mScope=" + mScope + ", mSortOrder=" + mSortOrder
// + ", sScopeElements=" + mScopeElements + "]";
// }
// }
| import android.app.NotificationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.markupartist.sthlmtraveling.provider.deviation.Deviation; | mNotificationManager.cancelAll();
finish();
return;
}
try {
String header = uri.getQueryParameter("header");
String details = uri.getQueryParameter("details");
String scope = uri.getQueryParameter("scope");
String reference = uri.getQueryParameter("reference");
Time created = new Time();
created.parse3339(uri.getQueryParameter("created"));
int notificationId = Integer.parseInt(uri.getQueryParameter("notificationId"));
TextView headerView = (TextView) findViewById(R.id.deviation_header);
headerView.setText(header);
TextView detailsView = (TextView) findViewById(R.id.deviation_details);
detailsView.setText(details);
TextView createdView = (TextView) findViewById(R.id.deviation_created);
createdView.setText(created.format("%F %R"));
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(notificationId);
} catch (Exception e) {
Crashlytics.log("URI: " + uri.toString());
Crashlytics.logException(e);
}
}
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/deviation/Deviation.java
// public class Deviation implements Parcelable {
// private Long mReference;
// private int mMessageVersion;
// private String mLink;
// private String mMobileLink;
// private Time mCreated;
// private boolean mIsMainNews;
// private int mSortOrder;
// private String mHeader;
// private String mDetails;
// private String mScope;
// private String mScopeElements;
//
// public Deviation(Parcel parcel) {
// mReference = parcel.readLong();
// mMessageVersion = parcel.readInt();
// mLink = parcel.readString();
// mMobileLink = parcel.readString();
// mCreated = new Time();
// mCreated.parse3339(parcel.readString());
// mIsMainNews = (Boolean) parcel.readValue(null);
// mSortOrder = parcel.readInt();
// mHeader = parcel.readString();
// mDetails = parcel.readString();
// mScope = parcel.readString();
// mScopeElements = parcel.readString();
// }
//
// public Deviation() {
// }
//
// public void setReference(Long reference) {
// this.mReference = reference;
// }
// public Long getReference() {
// return mReference;
// }
// public void setMessageVersion(int messageVersion) {
// this.mMessageVersion = messageVersion;
// }
// public int getMessageVersion() {
// return mMessageVersion;
// }
// public void setMobileLink(String mobileLink) {
// this.mMobileLink = mobileLink;
// }
// public String getMobileLink() {
// return mMobileLink;
// }
// public void setCreated(Time created) {
// this.mCreated = created;
// }
// public Time getCreated() {
// return mCreated;
// }
// public void setMainNews(boolean isMainNews) {
// this.mIsMainNews = isMainNews;
// }
// public boolean isMainNews() {
// return mIsMainNews;
// }
// public void setSortOrder(int sortOrder) {
// this.mSortOrder = sortOrder;
// }
// public int getSortOrder() {
// return mSortOrder;
// }
// public void setLink(String mLink) {
// this.mLink = mLink;
// }
// public String getLink() {
// return mLink;
// }
// public void setHeader(String header) {
// this.mHeader = header;
// }
// public String getHeader() {
// return mHeader;
// }
// public void setDetails(String details) {
// this.mDetails = details;
// }
// public String getDetails() {
// return mDetails;
// }
// public void setScope(String scope) {
// this.mScope = scope;
// }
// public String getScope() {
// return mScope;
// }
// public void setScopeElements(String scopeElements) {
// this.mScopeElements = scopeElements;
// }
// public String getScopeElements() {
// return mScopeElements;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeLong(mReference);
// parcel.writeInt(mMessageVersion);
// parcel.writeString(mLink);
// parcel.writeString(mMobileLink);
// parcel.writeString(mCreated.format3339(false));
// parcel.writeValue(mIsMainNews);
// parcel.writeInt(mSortOrder);
// parcel.writeString(mHeader);
// parcel.writeString(mDetails);
// parcel.writeString(mScope);
// parcel.writeString(mScopeElements);
// }
//
// public static final Creator<Deviation> CREATOR = new Creator<Deviation>() {
// public Deviation createFromParcel(Parcel parcel) {
// return new Deviation(parcel);
// }
//
// public Deviation[] newArray(int size) {
// return new Deviation[size];
// }
// };
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "Deviation [mCreated=" + mCreated + ", mDetails=" + mDetails
// + ", mHeader=" + mHeader + ", mIsMainNews=" + mIsMainNews
// + ", mLink=" + mLink + ", mMessageVersion=" + mMessageVersion
// + ", mMobileLink=" + mMobileLink + ", mReference=" + mReference
// + ", mScope=" + mScope + ", mSortOrder=" + mSortOrder
// + ", sScopeElements=" + mScopeElements + "]";
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/DeviationDetailActivity.java
import android.app.NotificationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.markupartist.sthlmtraveling.provider.deviation.Deviation;
mNotificationManager.cancelAll();
finish();
return;
}
try {
String header = uri.getQueryParameter("header");
String details = uri.getQueryParameter("details");
String scope = uri.getQueryParameter("scope");
String reference = uri.getQueryParameter("reference");
Time created = new Time();
created.parse3339(uri.getQueryParameter("created"));
int notificationId = Integer.parseInt(uri.getQueryParameter("notificationId"));
TextView headerView = (TextView) findViewById(R.id.deviation_header);
headerView.setText(header);
TextView detailsView = (TextView) findViewById(R.id.deviation_details);
detailsView.setText(details);
TextView createdView = (TextView) findViewById(R.id.deviation_created);
createdView.setText(created.format("%F %R"));
NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(notificationId);
} catch (Exception e) {
Crashlytics.log("URI: " + uri.toString());
Crashlytics.logException(e);
}
}
| public static Uri getUri(Deviation deviation, int notificationId) { |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseListFragmentActivity.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map; | package com.markupartist.sthlmtraveling;
public class BaseListFragmentActivity extends AppCompatActivity implements OnItemClickListener {
private ListView mListView;
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStop() {
super.onStop();
}
protected void registerScreen(String event) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/utils/Analytics.java
// public class Analytics {
//
// private static String ACTION_CLICK = "Click";
//
// private static Analytics sInstance;
// private final Context mContext;
//
// public Analytics(final Context context) {
// mContext = context;
// }
//
// public static Analytics getInstance(final Context context) {
// if (sInstance == null) {
// sInstance = new Analytics(context);
// }
// return sInstance;
// }
//
// public void registerScreen(final String screenName) {
// // Noop
// }
//
// public void event(final String category, final String action) {
// event(category, action, null);
// }
//
// public void event(final String category, final String action, final String label) {
// // Noop
// }
//
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/BaseListFragmentActivity.java
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.markupartist.sthlmtraveling.utils.Analytics;
import java.util.Map;
package com.markupartist.sthlmtraveling;
public class BaseListFragmentActivity extends AppCompatActivity implements OnItemClickListener {
private ListView mListView;
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStop() {
super.onStop();
}
protected void registerScreen(String event) { | Analytics.getInstance(this).registerScreen(event); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/JourneysProvider.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/JourneysProvider.java
// public static final class Journeys implements BaseColumns {
// public static final Uri CONTENT_URI =
// Uri.parse("content://" + JourneysProvider.AUTHORITY + "/journeys");
// public static final String CONTENT_TYPE =
// "vnd.android.cursor.dir/vnd.sthlmtraveling.journeys";
//
// public static final int JOURNEY_ID_PATH_POSITION = 1;
//
// /**
// * The default number of journeys to be saved in history.
// * </p>
// * Total number of journeys is history size + starred journeys.
// */
// public static final int DEFAULT_HISTORY_SIZE = 5;
//
// public static final String ID = "_id";
//
// /**
// * The name, example "Take me home" or "To work".
// */
// public static final String NAME = "name";
//
// /**
// * The position in a list.
// */
// public static final String POSITION = "position";
//
// /**
// * If the journey is starred.
// */
// public static final String STARRED = "starred";
//
// /**
// * When the entry was created.
// */
// public static final String CREATED_AT = "created_at";
//
// /**
// * When the entry was updated.
// */
// public static final String UPDATED_AT = "updated_at";
//
// /**
// * The journey data as json.
// */
// public static final String JOURNEY_DATA = "journey_data";
//
// /**
// * The default sort order.
// */
// public static final String DEFAULT_SORT_ORDER =
// "position DESC, updated_at DESC, created_at DESC";
//
// /**
// * The history sort order, this also includes a limit.
// */
// public static final String HISTORY_SORT_ORDER =
// "updated_at DESC, created_at DESC LIMIT " + DEFAULT_HISTORY_SIZE;
//
//
// private Journeys() {
// }
// }
| import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.provider.JourneysProvider.Journey.Journeys;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale; | /*
* Copyright (C) 2011 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.provider;
public class JourneysProvider extends ContentProvider {
private static final String TAG = "JourneysProvider";
private static final String DATABASE_NAME = "journeys.db";
private static final int DATABASE_VERSION = 2;
private static final String JOURNEYS_TABLE_NAME = "journeys";
public static final String AUTHORITY = BuildConfig.BASE_PROVIDER_AUTHORITY + ".journeysprovider";
/**
* A UriMatcher instance
*/
private static final UriMatcher sUriMatcher;
/**
* The incoming URI matches the Journeys URI pattern.
*/
private static final int JOURNEYS = 1;
/**
* The incoming URI matches the Journey ID URI pattern
*/
private static final int JOURNEY_ID = 2;
/**
* A projection map used to select columns from the database.
*/
private static HashMap<String, String> sJourneysProjectionMap;
private DatabaseHelper dbHelper;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(AUTHORITY, "journeys", JOURNEYS);
sUriMatcher.addURI(AUTHORITY, "journeys/#", JOURNEY_ID);
sJourneysProjectionMap = new HashMap<String, String>(); | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/JourneysProvider.java
// public static final class Journeys implements BaseColumns {
// public static final Uri CONTENT_URI =
// Uri.parse("content://" + JourneysProvider.AUTHORITY + "/journeys");
// public static final String CONTENT_TYPE =
// "vnd.android.cursor.dir/vnd.sthlmtraveling.journeys";
//
// public static final int JOURNEY_ID_PATH_POSITION = 1;
//
// /**
// * The default number of journeys to be saved in history.
// * </p>
// * Total number of journeys is history size + starred journeys.
// */
// public static final int DEFAULT_HISTORY_SIZE = 5;
//
// public static final String ID = "_id";
//
// /**
// * The name, example "Take me home" or "To work".
// */
// public static final String NAME = "name";
//
// /**
// * The position in a list.
// */
// public static final String POSITION = "position";
//
// /**
// * If the journey is starred.
// */
// public static final String STARRED = "starred";
//
// /**
// * When the entry was created.
// */
// public static final String CREATED_AT = "created_at";
//
// /**
// * When the entry was updated.
// */
// public static final String UPDATED_AT = "updated_at";
//
// /**
// * The journey data as json.
// */
// public static final String JOURNEY_DATA = "journey_data";
//
// /**
// * The default sort order.
// */
// public static final String DEFAULT_SORT_ORDER =
// "position DESC, updated_at DESC, created_at DESC";
//
// /**
// * The history sort order, this also includes a limit.
// */
// public static final String HISTORY_SORT_ORDER =
// "updated_at DESC, created_at DESC LIMIT " + DEFAULT_HISTORY_SIZE;
//
//
// private Journeys() {
// }
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/provider/JourneysProvider.java
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.provider.JourneysProvider.Journey.Journeys;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
/*
* Copyright (C) 2011 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.provider;
public class JourneysProvider extends ContentProvider {
private static final String TAG = "JourneysProvider";
private static final String DATABASE_NAME = "journeys.db";
private static final int DATABASE_VERSION = 2;
private static final String JOURNEYS_TABLE_NAME = "journeys";
public static final String AUTHORITY = BuildConfig.BASE_PROVIDER_AUTHORITY + ".journeysprovider";
/**
* A UriMatcher instance
*/
private static final UriMatcher sUriMatcher;
/**
* The incoming URI matches the Journeys URI pattern.
*/
private static final int JOURNEYS = 1;
/**
* The incoming URI matches the Journey ID URI pattern
*/
private static final int JOURNEY_ID = 2;
/**
* A projection map used to select columns from the database.
*/
private static HashMap<String, String> sJourneysProjectionMap;
private DatabaseHelper dbHelper;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(AUTHORITY, "journeys", JOURNEYS);
sUriMatcher.addURI(AUTHORITY, "journeys/#", JOURNEY_ID);
sJourneysProjectionMap = new HashMap<String, String>(); | sJourneysProjectionMap.put(Journeys.ID, Journeys.ID); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/ApiServiceProvider.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/api/ApiService.java
// public interface ApiService {
// @GET("/v1/planner/")
// void getPlan(
// @Query("from") PlaceQuery from,
// @Query("to") PlaceQuery to,
// @Query("mode") String mode,
// @Query("alternative") boolean alternative,
// @Query("via") PlaceQuery via,
// @Query("arriveBy") boolean arriveBy,
// @Query("time") String time,
// @Query("travelMode") TravelModeQuery travelMode,
// @Query("dir") String dir,
// @Query("paginateRef") String paginateRef,
// Callback<Plan> callback);
//
// @GET("/v1/planner/intermediate/")
// void getIntermediateStops(
// @Query("reference") List<String> reference,
// Callback<IntermediateResponse> callback);
//
// @GET("/v1/semistatic/site/near/")
// void getNearbyStops(
// @Query("latitude") double latitude,
// @Query("longitude") double longitude,
// Callback<NearbyStopsResponse> callback);
// }
| import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.data.api.ApiService;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter; | /*
* Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.data.misc;
/**
*
*/
public class ApiServiceProvider {
public static RestAdapter getRestAdapter(OkHttpClient client) {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) { | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/api/ApiService.java
// public interface ApiService {
// @GET("/v1/planner/")
// void getPlan(
// @Query("from") PlaceQuery from,
// @Query("to") PlaceQuery to,
// @Query("mode") String mode,
// @Query("alternative") boolean alternative,
// @Query("via") PlaceQuery via,
// @Query("arriveBy") boolean arriveBy,
// @Query("time") String time,
// @Query("travelMode") TravelModeQuery travelMode,
// @Query("dir") String dir,
// @Query("paginateRef") String paginateRef,
// Callback<Plan> callback);
//
// @GET("/v1/planner/intermediate/")
// void getIntermediateStops(
// @Query("reference") List<String> reference,
// Callback<IntermediateResponse> callback);
//
// @GET("/v1/semistatic/site/near/")
// void getNearbyStops(
// @Query("latitude") double latitude,
// @Query("longitude") double longitude,
// Callback<NearbyStopsResponse> callback);
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/ApiServiceProvider.java
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.data.api.ApiService;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;
/*
* Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.data.misc;
/**
*
*/
public class ApiServiceProvider {
public static RestAdapter getRestAdapter(OkHttpClient client) {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) { | request.addHeader("User-Agent", AppConfig.USER_AGENT); |
johannilsson/sthlmtraveling | sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/ApiServiceProvider.java | // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/api/ApiService.java
// public interface ApiService {
// @GET("/v1/planner/")
// void getPlan(
// @Query("from") PlaceQuery from,
// @Query("to") PlaceQuery to,
// @Query("mode") String mode,
// @Query("alternative") boolean alternative,
// @Query("via") PlaceQuery via,
// @Query("arriveBy") boolean arriveBy,
// @Query("time") String time,
// @Query("travelMode") TravelModeQuery travelMode,
// @Query("dir") String dir,
// @Query("paginateRef") String paginateRef,
// Callback<Plan> callback);
//
// @GET("/v1/planner/intermediate/")
// void getIntermediateStops(
// @Query("reference") List<String> reference,
// Callback<IntermediateResponse> callback);
//
// @GET("/v1/semistatic/site/near/")
// void getNearbyStops(
// @Query("latitude") double latitude,
// @Query("longitude") double longitude,
// Callback<NearbyStopsResponse> callback);
// }
| import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.data.api.ApiService;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter; | /*
* Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.data.misc;
/**
*
*/
public class ApiServiceProvider {
public static RestAdapter getRestAdapter(OkHttpClient client) {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("User-Agent", AppConfig.USER_AGENT);
request.addHeader("X-STHLMTraveling-API-Key", AppConfig.STHLM_TRAVELING_API_KEY);
}
};
return new RestAdapter.Builder()
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
.setEndpoint(AppConfig.STHLM_TRAVELING_API_ENDPOINT)
.setConverter(new GsonConverter(GsonProvider.provideGson()))
.setRequestInterceptor(requestInterceptor)
.setClient(new OkClient(client))
.build();
}
| // Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/AppConfig.java
// public class AppConfig {
// public static final String ANALYTICS_PROPERTY_KEY = BuildConfig.APP_ANALYTICS_PROPERTY_KEY;
// public static final String APP_VERSION = BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + ")";
// public static final String WIDESPACE_SID = BuildConfig.DEBUG ? BuildConfig.APP_WIDESPACE_DEBUG_SID : BuildConfig.APP_WIDESPACE_SID;
// public static final String STHLM_TRAVELING_API_KEY = BuildConfig.APP_STHLMTRAVELING_API_KEY;
// public static final String USER_AGENT = "STHLMTraveling-Android/" + BuildConfig.VERSION_NAME;
// public static final String STHLM_TRAVELING_API_ENDPOINT = "http://api.sthlmtraveling.se/";
// public static final String ADMOB_ROUTE_DETAILS_AD_UNIT_ID = BuildConfig.ADMOB_ROUTE_DETAILS_AD_UNIT_ID;
// public static final String[] ADMOB_TEST_DEVICES = TextUtils.split(BuildConfig.ADMOB_TEST_DEVICES, ",");
//
// public static boolean shouldServeAds() {
// return BuildConfig.APP_IS_ADS_ENABLED;
// }
// }
//
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/api/ApiService.java
// public interface ApiService {
// @GET("/v1/planner/")
// void getPlan(
// @Query("from") PlaceQuery from,
// @Query("to") PlaceQuery to,
// @Query("mode") String mode,
// @Query("alternative") boolean alternative,
// @Query("via") PlaceQuery via,
// @Query("arriveBy") boolean arriveBy,
// @Query("time") String time,
// @Query("travelMode") TravelModeQuery travelMode,
// @Query("dir") String dir,
// @Query("paginateRef") String paginateRef,
// Callback<Plan> callback);
//
// @GET("/v1/planner/intermediate/")
// void getIntermediateStops(
// @Query("reference") List<String> reference,
// Callback<IntermediateResponse> callback);
//
// @GET("/v1/semistatic/site/near/")
// void getNearbyStops(
// @Query("latitude") double latitude,
// @Query("longitude") double longitude,
// Callback<NearbyStopsResponse> callback);
// }
// Path: sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/data/misc/ApiServiceProvider.java
import com.markupartist.sthlmtraveling.AppConfig;
import com.markupartist.sthlmtraveling.BuildConfig;
import com.markupartist.sthlmtraveling.data.api.ApiService;
import com.squareup.okhttp.OkHttpClient;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;
/*
* Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.com>
*
* 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.markupartist.sthlmtraveling.data.misc;
/**
*
*/
public class ApiServiceProvider {
public static RestAdapter getRestAdapter(OkHttpClient client) {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("User-Agent", AppConfig.USER_AGENT);
request.addHeader("X-STHLMTraveling-API-Key", AppConfig.STHLM_TRAVELING_API_KEY);
}
};
return new RestAdapter.Builder()
.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
.setEndpoint(AppConfig.STHLM_TRAVELING_API_ENDPOINT)
.setConverter(new GsonConverter(GsonProvider.provideGson()))
.setRequestInterceptor(requestInterceptor)
.setClient(new OkClient(client))
.build();
}
| public static ApiService getApiService(OkHttpClient okHttpClient) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_SESSION_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_SESSION_INFO.java
// public class CK_SESSION_INFO {
//
// public static final long CKF_RW_SESSION = 0x00000002;
// public static final long CKF_SERIAL_SESSION = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SESSION_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public long slotID;
// public long state;
// public long flags;
// public long ulDeviceError;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotID=0x%08x\n state=0x%08x{%s}\n flags=0x%08x{%s}\n deviceError=%d\n)",
// slotID, state, CKS.L2S(state), flags, f2s(flags), ulDeviceError);
// }
// }
| import org.pkcs11.jacknji11.CK_SESSION_INFO;
import jnr.ffi.Struct; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_SESSION_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_SESSION_INFO extends Struct {
public long slotID;
public long state;
public long flags;
public long ulDeviceError;
public JFFI_CK_SESSION_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_SESSION_INFO.java
// public class CK_SESSION_INFO {
//
// public static final long CKF_RW_SESSION = 0x00000002;
// public static final long CKF_SERIAL_SESSION = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SESSION_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public long slotID;
// public long state;
// public long flags;
// public long ulDeviceError;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotID=0x%08x\n state=0x%08x{%s}\n flags=0x%08x{%s}\n deviceError=%d\n)",
// slotID, state, CKS.L2S(state), flags, f2s(flags), ulDeviceError);
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_SESSION_INFO.java
import org.pkcs11.jacknji11.CK_SESSION_INFO;
import jnr.ffi.Struct;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_SESSION_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_SESSION_INFO extends Struct {
public long slotID;
public long state;
public long flags;
public long ulDeviceError;
public JFFI_CK_SESSION_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| public JFFI_CK_SESSION_INFO readFrom(CK_SESSION_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_MECHANISM_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_MECHANISM_INFO.java
// public class CK_MECHANISM_INFO {
// public static final long CKF_HW = 0x00000001;
// public static final long CKF_ENCRYPT = 0x00000100;
// public static final long CKF_DECRYPT = 0x00000200;
// public static final long CKF_DIGEST = 0x00000400;
// public static final long CKF_SIGN = 0x00000800;
// public static final long CKF_SIGN_RECOVER = 0x00001000;
// public static final long CKF_VERIFY = 0x00002000;
// public static final long CKF_VERIFY_RECOVER = 0x00004000;
// public static final long CKF_GENERATE = 0x00008000;
// public static final long CKF_GENERATE_KEY_PAIR = 0x00010000;
// public static final long CKF_WRAP = 0x00020000;
// public static final long CKF_UNWRAP = 0x00040000;
// public static final long CKF_DERIVE = 0x00080000;
// public static final long CKF_EC_F_P = 0x00100000;
// public static final long CKF_EC_F_2M = 0x00200000;
// public static final long CKF_EC_ECPARAMETERS = 0x00400000;
// public static final long CKF_EC_NAMEDCURVE = 0x00800000;
// public static final long CKF_EC_UNCOMPRESS = 0x01000000;
// public static final long CKF_EC_COMPRESS = 0x02000000;
// public static final long CKF_EXTENSION = 0x80000000;
//
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_MECHANISM_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
//
// public long ulMinKeySize;
// public long ulMaxKeySize;
// public long flags;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n minKeySize=%d\n maxKeySize=%d\n flags=0x%08x{%s}\n)",
// ulMinKeySize, ulMaxKeySize, flags, f2s(flags));
//
// }
// }
| import org.pkcs11.jacknji11.CK_MECHANISM_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_MECHANSIM_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_MECHANISM_INFO extends Structure {
public NativeLong ulMinKeySize;
public NativeLong ulMaxKeySize;
public NativeLong flags;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("ulMinKeySize", "ulMaxKeySize", "flags");
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_MECHANISM_INFO.java
// public class CK_MECHANISM_INFO {
// public static final long CKF_HW = 0x00000001;
// public static final long CKF_ENCRYPT = 0x00000100;
// public static final long CKF_DECRYPT = 0x00000200;
// public static final long CKF_DIGEST = 0x00000400;
// public static final long CKF_SIGN = 0x00000800;
// public static final long CKF_SIGN_RECOVER = 0x00001000;
// public static final long CKF_VERIFY = 0x00002000;
// public static final long CKF_VERIFY_RECOVER = 0x00004000;
// public static final long CKF_GENERATE = 0x00008000;
// public static final long CKF_GENERATE_KEY_PAIR = 0x00010000;
// public static final long CKF_WRAP = 0x00020000;
// public static final long CKF_UNWRAP = 0x00040000;
// public static final long CKF_DERIVE = 0x00080000;
// public static final long CKF_EC_F_P = 0x00100000;
// public static final long CKF_EC_F_2M = 0x00200000;
// public static final long CKF_EC_ECPARAMETERS = 0x00400000;
// public static final long CKF_EC_NAMEDCURVE = 0x00800000;
// public static final long CKF_EC_UNCOMPRESS = 0x01000000;
// public static final long CKF_EC_COMPRESS = 0x02000000;
// public static final long CKF_EXTENSION = 0x80000000;
//
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_MECHANISM_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
//
// public long ulMinKeySize;
// public long ulMaxKeySize;
// public long flags;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n minKeySize=%d\n maxKeySize=%d\n flags=0x%08x{%s}\n)",
// ulMinKeySize, ulMaxKeySize, flags, f2s(flags));
//
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_MECHANISM_INFO.java
import org.pkcs11.jacknji11.CK_MECHANISM_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_MECHANSIM_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_MECHANISM_INFO extends Structure {
public NativeLong ulMinKeySize;
public NativeLong ulMaxKeySize;
public NativeLong flags;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("ulMinKeySize", "ulMaxKeySize", "flags");
}
| public JNA_CK_MECHANISM_INFO readFrom(CK_MECHANISM_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_VERSION.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_VERSION.java
// public class CK_VERSION {
// public byte major;
// public byte minor;
// }
| import org.pkcs11.jacknji11.CK_VERSION;
import jnr.ffi.Struct; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_VERSION. It hardly seems worthwhile
* wrapping 2 bytes, but we have.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_VERSION extends Struct {
public byte major;
public byte minor;
public JFFI_CK_VERSION() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_VERSION.java
// public class CK_VERSION {
// public byte major;
// public byte minor;
// }
// Path: src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_VERSION.java
import org.pkcs11.jacknji11.CK_VERSION;
import jnr.ffi.Struct;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_VERSION. It hardly seems worthwhile
* wrapping 2 bytes, but we have.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_VERSION extends Struct {
public byte major;
public byte minor;
public JFFI_CK_VERSION() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| public JFFI_CK_VERSION readFrom(CK_VERSION version) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_SLOT_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_SLOT_INFO.java
// public class CK_SLOT_INFO {
//
// public static final long CKF_TOKEN_PRESENT = 0x00000001;
// public static final long CKF_REMOVABLE_DEVICE = 0x00000002;
// public static final long CKF_HW_SLOT = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SLOT_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public byte[] slotDescription = new byte[64];
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public CK_VERSION hardwareVersion = new CK_VERSION();
// public CK_VERSION firmwareVersion = new CK_VERSION();
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotDescription=%s\n manufacturerID=%s\n flags=0x%08x{%s}\n hardwareVersion=%d.%d\n firmwareVersion=%d.%d\n)",
// Buf.escstr(slotDescription), Buf.escstr(manufacturerID), flags, f2s(flags),
// hardwareVersion.major & 0xff, hardwareVersion.minor & 0xff,
// firmwareVersion.major & 0xff, firmwareVersion.minor & 0xff);
// }
// }
| import org.pkcs11.jacknji11.CK_SLOT_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_SLOT_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_SLOT_INFO extends Structure {
public byte[] slotDescription;
public byte[] manufacturerID;
public NativeLong flags;
public JNA_CK_VERSION hardwareVersion;
public JNA_CK_VERSION firmwareVersion;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("slotDescription", "manufacturerID", "flags", "hardwareVersion", "firmwareVersion");
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_SLOT_INFO.java
// public class CK_SLOT_INFO {
//
// public static final long CKF_TOKEN_PRESENT = 0x00000001;
// public static final long CKF_REMOVABLE_DEVICE = 0x00000002;
// public static final long CKF_HW_SLOT = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SLOT_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public byte[] slotDescription = new byte[64];
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public CK_VERSION hardwareVersion = new CK_VERSION();
// public CK_VERSION firmwareVersion = new CK_VERSION();
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotDescription=%s\n manufacturerID=%s\n flags=0x%08x{%s}\n hardwareVersion=%d.%d\n firmwareVersion=%d.%d\n)",
// Buf.escstr(slotDescription), Buf.escstr(manufacturerID), flags, f2s(flags),
// hardwareVersion.major & 0xff, hardwareVersion.minor & 0xff,
// firmwareVersion.major & 0xff, firmwareVersion.minor & 0xff);
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_SLOT_INFO.java
import org.pkcs11.jacknji11.CK_SLOT_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_SLOT_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_SLOT_INFO extends Structure {
public byte[] slotDescription;
public byte[] manufacturerID;
public NativeLong flags;
public JNA_CK_VERSION hardwareVersion;
public JNA_CK_VERSION firmwareVersion;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("slotDescription", "manufacturerID", "flags", "hardwareVersion", "firmwareVersion");
}
| public JNA_CK_SLOT_INFO readFrom(CK_SLOT_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_INFO.java
// public class CK_INFO {
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public CK_VERSION cryptokiVersion = new CK_VERSION();
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public byte[] libraryDescription = new byte[32];
// public CK_VERSION libraryVersion = new CK_VERSION();
//
// /** @return string */
// public String toString() {
// return String.format("(\n version=%d.%d\n manufacturerID=%s\n flags=0x%08x{%s}\n libraryDescription=%s\n libraryVersion=%d.%d\n)",
// cryptokiVersion.major & 0xff, cryptokiVersion.minor & 0xff, Buf.escstr(manufacturerID),
// flags, f2s(flags), Buf.escstr(libraryDescription),
// libraryVersion.major & 0xff, libraryVersion.minor & 0xff);
//
// }
// }
| import org.pkcs11.jacknji11.CK_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_INFO struct. It sets align type to {@link Structure#ALIGN_NONE}
* since the ULONGS (NativeLongs) don't line up on a 4 byte boundary. You wouldn't care to know
* how painful that learning experience was.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_INFO extends Structure {
public JNA_CK_VERSION cryptokiVersion;
public byte[] manufacturerID;
public NativeLong flags;
public byte[] libraryDescription;
public JNA_CK_VERSION libraryVersion;
/**
* Default constructor.
* need to set alignment to none since 'flags' is not
* correctly aligned to a 4 byte boundary
*/
public JNA_CK_INFO() {
setAlignType(ALIGN_NONE);
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("cryptokiVersion", "manufacturerID", "flags", "libraryDescription", "libraryVersion");
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_INFO.java
// public class CK_INFO {
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public CK_VERSION cryptokiVersion = new CK_VERSION();
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public byte[] libraryDescription = new byte[32];
// public CK_VERSION libraryVersion = new CK_VERSION();
//
// /** @return string */
// public String toString() {
// return String.format("(\n version=%d.%d\n manufacturerID=%s\n flags=0x%08x{%s}\n libraryDescription=%s\n libraryVersion=%d.%d\n)",
// cryptokiVersion.major & 0xff, cryptokiVersion.minor & 0xff, Buf.escstr(manufacturerID),
// flags, f2s(flags), Buf.escstr(libraryDescription),
// libraryVersion.major & 0xff, libraryVersion.minor & 0xff);
//
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_INFO.java
import org.pkcs11.jacknji11.CK_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_INFO struct. It sets align type to {@link Structure#ALIGN_NONE}
* since the ULONGS (NativeLongs) don't line up on a 4 byte boundary. You wouldn't care to know
* how painful that learning experience was.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_INFO extends Structure {
public JNA_CK_VERSION cryptokiVersion;
public byte[] manufacturerID;
public NativeLong flags;
public byte[] libraryDescription;
public JNA_CK_VERSION libraryVersion;
/**
* Default constructor.
* need to set alignment to none since 'flags' is not
* correctly aligned to a 4 byte boundary
*/
public JNA_CK_INFO() {
setAlignType(ALIGN_NONE);
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("cryptokiVersion", "manufacturerID", "flags", "libraryDescription", "libraryVersion");
}
| public JNA_CK_INFO readFrom(CK_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_VERSION.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_VERSION.java
// public class CK_VERSION {
// public byte major;
// public byte minor;
// }
| import java.util.Arrays;
import java.util.List;
import com.sun.jna.Structure;
import org.pkcs11.jacknji11.CK_VERSION; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_VERSION. It hardly seems worthwhile
* wrapping 2 bytes, but we have.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_VERSION extends Structure {
public byte major;
public byte minor;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("major", "minor");
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_VERSION.java
// public class CK_VERSION {
// public byte major;
// public byte minor;
// }
// Path: src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_VERSION.java
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Structure;
import org.pkcs11.jacknji11.CK_VERSION;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_VERSION. It hardly seems worthwhile
* wrapping 2 bytes, but we have.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_VERSION extends Structure {
public byte major;
public byte minor;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("major", "minor");
}
| public JNA_CK_VERSION readFrom(CK_VERSION version) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_INFO.java
// public class CK_INFO {
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public CK_VERSION cryptokiVersion = new CK_VERSION();
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public byte[] libraryDescription = new byte[32];
// public CK_VERSION libraryVersion = new CK_VERSION();
//
// /** @return string */
// public String toString() {
// return String.format("(\n version=%d.%d\n manufacturerID=%s\n flags=0x%08x{%s}\n libraryDescription=%s\n libraryVersion=%d.%d\n)",
// cryptokiVersion.major & 0xff, cryptokiVersion.minor & 0xff, Buf.escstr(manufacturerID),
// flags, f2s(flags), Buf.escstr(libraryDescription),
// libraryVersion.major & 0xff, libraryVersion.minor & 0xff);
//
// }
// }
| import org.pkcs11.jacknji11.CK_INFO;
import jnr.ffi.Struct; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_INFO extends Struct {
public JFFI_CK_VERSION cryptokiVersion;
public byte[] manufacturerID;
public long flags;
public byte[] libraryDescription;
public JFFI_CK_VERSION libraryVersion;
/**
* Default constructor.
* need to set alignment to none since 'flags' is not
* correctly aligned to a 4 byte boundary
*/
public JFFI_CK_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
// setAlignType();
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_INFO.java
// public class CK_INFO {
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public CK_VERSION cryptokiVersion = new CK_VERSION();
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public byte[] libraryDescription = new byte[32];
// public CK_VERSION libraryVersion = new CK_VERSION();
//
// /** @return string */
// public String toString() {
// return String.format("(\n version=%d.%d\n manufacturerID=%s\n flags=0x%08x{%s}\n libraryDescription=%s\n libraryVersion=%d.%d\n)",
// cryptokiVersion.major & 0xff, cryptokiVersion.minor & 0xff, Buf.escstr(manufacturerID),
// flags, f2s(flags), Buf.escstr(libraryDescription),
// libraryVersion.major & 0xff, libraryVersion.minor & 0xff);
//
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_INFO.java
import org.pkcs11.jacknji11.CK_INFO;
import jnr.ffi.Struct;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_INFO extends Struct {
public JFFI_CK_VERSION cryptokiVersion;
public byte[] manufacturerID;
public long flags;
public byte[] libraryDescription;
public JFFI_CK_VERSION libraryVersion;
/**
* Default constructor.
* need to set alignment to none since 'flags' is not
* correctly aligned to a 4 byte boundary
*/
public JFFI_CK_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
// setAlignType();
}
| public JFFI_CK_INFO readFrom(CK_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_MECHANISM_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_MECHANISM_INFO.java
// public class CK_MECHANISM_INFO {
// public static final long CKF_HW = 0x00000001;
// public static final long CKF_ENCRYPT = 0x00000100;
// public static final long CKF_DECRYPT = 0x00000200;
// public static final long CKF_DIGEST = 0x00000400;
// public static final long CKF_SIGN = 0x00000800;
// public static final long CKF_SIGN_RECOVER = 0x00001000;
// public static final long CKF_VERIFY = 0x00002000;
// public static final long CKF_VERIFY_RECOVER = 0x00004000;
// public static final long CKF_GENERATE = 0x00008000;
// public static final long CKF_GENERATE_KEY_PAIR = 0x00010000;
// public static final long CKF_WRAP = 0x00020000;
// public static final long CKF_UNWRAP = 0x00040000;
// public static final long CKF_DERIVE = 0x00080000;
// public static final long CKF_EC_F_P = 0x00100000;
// public static final long CKF_EC_F_2M = 0x00200000;
// public static final long CKF_EC_ECPARAMETERS = 0x00400000;
// public static final long CKF_EC_NAMEDCURVE = 0x00800000;
// public static final long CKF_EC_UNCOMPRESS = 0x01000000;
// public static final long CKF_EC_COMPRESS = 0x02000000;
// public static final long CKF_EXTENSION = 0x80000000;
//
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_MECHANISM_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
//
// public long ulMinKeySize;
// public long ulMaxKeySize;
// public long flags;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n minKeySize=%d\n maxKeySize=%d\n flags=0x%08x{%s}\n)",
// ulMinKeySize, ulMaxKeySize, flags, f2s(flags));
//
// }
// }
| import org.pkcs11.jacknji11.CK_MECHANISM_INFO;
import jnr.ffi.Struct; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_MECHANSIM_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_MECHANISM_INFO extends Struct {
public long ulMinKeySize;
public long ulMaxKeySize;
public long flags;
public JFFI_CK_MECHANISM_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_MECHANISM_INFO.java
// public class CK_MECHANISM_INFO {
// public static final long CKF_HW = 0x00000001;
// public static final long CKF_ENCRYPT = 0x00000100;
// public static final long CKF_DECRYPT = 0x00000200;
// public static final long CKF_DIGEST = 0x00000400;
// public static final long CKF_SIGN = 0x00000800;
// public static final long CKF_SIGN_RECOVER = 0x00001000;
// public static final long CKF_VERIFY = 0x00002000;
// public static final long CKF_VERIFY_RECOVER = 0x00004000;
// public static final long CKF_GENERATE = 0x00008000;
// public static final long CKF_GENERATE_KEY_PAIR = 0x00010000;
// public static final long CKF_WRAP = 0x00020000;
// public static final long CKF_UNWRAP = 0x00040000;
// public static final long CKF_DERIVE = 0x00080000;
// public static final long CKF_EC_F_P = 0x00100000;
// public static final long CKF_EC_F_2M = 0x00200000;
// public static final long CKF_EC_ECPARAMETERS = 0x00400000;
// public static final long CKF_EC_NAMEDCURVE = 0x00800000;
// public static final long CKF_EC_UNCOMPRESS = 0x01000000;
// public static final long CKF_EC_COMPRESS = 0x02000000;
// public static final long CKF_EXTENSION = 0x80000000;
//
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_MECHANISM_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
//
// public long ulMinKeySize;
// public long ulMaxKeySize;
// public long flags;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n minKeySize=%d\n maxKeySize=%d\n flags=0x%08x{%s}\n)",
// ulMinKeySize, ulMaxKeySize, flags, f2s(flags));
//
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_MECHANISM_INFO.java
import org.pkcs11.jacknji11.CK_MECHANISM_INFO;
import jnr.ffi.Struct;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_MECHANSIM_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_MECHANISM_INFO extends Struct {
public long ulMinKeySize;
public long ulMaxKeySize;
public long flags;
public JFFI_CK_MECHANISM_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| public JFFI_CK_MECHANISM_INFO readFrom(CK_MECHANISM_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_SESSION_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_SESSION_INFO.java
// public class CK_SESSION_INFO {
//
// public static final long CKF_RW_SESSION = 0x00000002;
// public static final long CKF_SERIAL_SESSION = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SESSION_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public long slotID;
// public long state;
// public long flags;
// public long ulDeviceError;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotID=0x%08x\n state=0x%08x{%s}\n flags=0x%08x{%s}\n deviceError=%d\n)",
// slotID, state, CKS.L2S(state), flags, f2s(flags), ulDeviceError);
// }
// }
| import org.pkcs11.jacknji11.CK_SESSION_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_SESSION_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_SESSION_INFO extends Structure {
public NativeLong slotID;
public NativeLong state;
public NativeLong flags;
public NativeLong ulDeviceError;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("slotID", "state", "flags", "ulDeviceError");
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_SESSION_INFO.java
// public class CK_SESSION_INFO {
//
// public static final long CKF_RW_SESSION = 0x00000002;
// public static final long CKF_SERIAL_SESSION = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SESSION_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String I2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public long slotID;
// public long state;
// public long flags;
// public long ulDeviceError;
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotID=0x%08x\n state=0x%08x{%s}\n flags=0x%08x{%s}\n deviceError=%d\n)",
// slotID, state, CKS.L2S(state), flags, f2s(flags), ulDeviceError);
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jna/JNA_CK_SESSION_INFO.java
import org.pkcs11.jacknji11.CK_SESSION_INFO;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.NativeLong;
import com.sun.jna.Structure;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jna;
/**
* JNA wrapper for PKCS#11 CK_SESSION_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JNA_CK_SESSION_INFO extends Structure {
public NativeLong slotID;
public NativeLong state;
public NativeLong flags;
public NativeLong ulDeviceError;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("slotID", "state", "flags", "ulDeviceError");
}
| public JNA_CK_SESSION_INFO readFrom(CK_SESSION_INFO info) { |
joelhockey/jacknji11 | src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_SLOT_INFO.java | // Path: src/main/java/org/pkcs11/jacknji11/CK_SLOT_INFO.java
// public class CK_SLOT_INFO {
//
// public static final long CKF_TOKEN_PRESENT = 0x00000001;
// public static final long CKF_REMOVABLE_DEVICE = 0x00000002;
// public static final long CKF_HW_SLOT = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SLOT_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public byte[] slotDescription = new byte[64];
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public CK_VERSION hardwareVersion = new CK_VERSION();
// public CK_VERSION firmwareVersion = new CK_VERSION();
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotDescription=%s\n manufacturerID=%s\n flags=0x%08x{%s}\n hardwareVersion=%d.%d\n firmwareVersion=%d.%d\n)",
// Buf.escstr(slotDescription), Buf.escstr(manufacturerID), flags, f2s(flags),
// hardwareVersion.major & 0xff, hardwareVersion.minor & 0xff,
// firmwareVersion.major & 0xff, firmwareVersion.minor & 0xff);
// }
// }
| import org.pkcs11.jacknji11.CK_SLOT_INFO;
import jnr.ffi.Struct; | /*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_SLOT_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_SLOT_INFO extends Struct {
public byte[] slotDescription;
public byte[] manufacturerID;
public long flags;
public JFFI_CK_VERSION hardwareVersion;
public JFFI_CK_VERSION firmwareVersion;
public JFFI_CK_SLOT_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| // Path: src/main/java/org/pkcs11/jacknji11/CK_SLOT_INFO.java
// public class CK_SLOT_INFO {
//
// public static final long CKF_TOKEN_PRESENT = 0x00000001;
// public static final long CKF_REMOVABLE_DEVICE = 0x00000002;
// public static final long CKF_HW_SLOT = 0x00000004;
//
// /** Maps from long value to String description (variable name). */
// private static final Map<Long, String> L2S = C.createL2SMap(CK_SLOT_INFO.class);
// /**
// * Convert long constant value to name.
// * @param ckf value
// * @return name
// */
// public static final String L2S(long ckf) { return C.l2s(L2S, "CKF", ckf); }
// /**
// * Convert flags to string.
// * @param flags flags
// * @return string format
// */
// public static String f2s(long flags) { return C.f2s(L2S, flags); }
//
// public byte[] slotDescription = new byte[64];
// public byte[] manufacturerID = new byte[32];
// public long flags;
// public CK_VERSION hardwareVersion = new CK_VERSION();
// public CK_VERSION firmwareVersion = new CK_VERSION();
//
// /** @return True, if the provided flag is set */
// public boolean isFlagSet(long CKF_FLAG) {
// return (flags & CKF_FLAG) != 0L;
// }
//
// /** @return string */
// public String toString() {
// return String.format("(\n slotDescription=%s\n manufacturerID=%s\n flags=0x%08x{%s}\n hardwareVersion=%d.%d\n firmwareVersion=%d.%d\n)",
// Buf.escstr(slotDescription), Buf.escstr(manufacturerID), flags, f2s(flags),
// hardwareVersion.major & 0xff, hardwareVersion.minor & 0xff,
// firmwareVersion.major & 0xff, firmwareVersion.minor & 0xff);
// }
// }
// Path: src/main/java/org/pkcs11/jacknji11/jffi/JFFI_CK_SLOT_INFO.java
import org.pkcs11.jacknji11.CK_SLOT_INFO;
import jnr.ffi.Struct;
/*
* Copyright 2010-2011 Joel Hockey (joel.hockey@gmail.com). All rights reserved.
* 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 org.pkcs11.jacknji11.jffi;
/**
* JFFI wrapper for PKCS#11 CK_SLOT_INFO struct.
* @author Joel Hockey (joel.hockey@gmail.com)
*/
public class JFFI_CK_SLOT_INFO extends Struct {
public byte[] slotDescription;
public byte[] manufacturerID;
public long flags;
public JFFI_CK_VERSION hardwareVersion;
public JFFI_CK_VERSION firmwareVersion;
public JFFI_CK_SLOT_INFO() {
super(jnr.ffi.Runtime.getSystemRuntime());
}
| public JFFI_CK_SLOT_INFO readFrom(CK_SLOT_INFO info) { |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatcherFactoryGenerator.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingException.java
// public class ProcessingException extends RuntimeException {
//
// public ProcessingException(String message, String simpleName, JavaFileObject.Kind kind, Exception cause) {
// super(String.format("%s: %s (%s)", message, simpleName, kind), cause);
// }
//
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public final class ProcessingPredicates {
//
// /**
// * Walks through parent chain and if any contains
// * {@link DoNotGenerateMatcher} annotation, skips this element
// *
// * @return predicate to help filter fields for matcher generation
// */
// public static Predicate<Element> shouldGenerateMatcher() {
// return element -> ElementParentsIterable.stream(element)
// .noneMatch(next -> nonNull(next.getAnnotation(DoNotGenerateMatcher.class)));
// }
//
// /**
// * Syntax sugar for {@link #hasParentPackageElement()}
// */
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
//
// /**
// * To help filter nested classes
// */
// public static Predicate<Element> hasParentPackageElement() {
// return entry -> entry.getEnclosingElement() instanceof PackageElement;
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatchersGenProperties.java
// static MatchersGenProperties props() {
// return PropertyLoader.newInstance().populate(MatchersGenProperties.class);
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
| import com.squareup.javapoet.JavaFile;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingException;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.groupingBy;
import static ru.yandex.qatools.processors.matcher.gen.MatchersGenProperties.props;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
import static ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates.isEntryWithParentPackageElement; | package ru.yandex.qatools.processors.matcher.gen;
/**
* @author lanwen (Merkushev Kirill)
*/
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MatcherFactoryGenerator extends AbstractProcessor {
private static final Logger LOGGER = Logger.getLogger(MatcherFactoryGenerator.class.toString());
@Override
public Set<String> getSupportedAnnotationTypes() { | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingException.java
// public class ProcessingException extends RuntimeException {
//
// public ProcessingException(String message, String simpleName, JavaFileObject.Kind kind, Exception cause) {
// super(String.format("%s: %s (%s)", message, simpleName, kind), cause);
// }
//
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public final class ProcessingPredicates {
//
// /**
// * Walks through parent chain and if any contains
// * {@link DoNotGenerateMatcher} annotation, skips this element
// *
// * @return predicate to help filter fields for matcher generation
// */
// public static Predicate<Element> shouldGenerateMatcher() {
// return element -> ElementParentsIterable.stream(element)
// .noneMatch(next -> nonNull(next.getAnnotation(DoNotGenerateMatcher.class)));
// }
//
// /**
// * Syntax sugar for {@link #hasParentPackageElement()}
// */
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
//
// /**
// * To help filter nested classes
// */
// public static Predicate<Element> hasParentPackageElement() {
// return entry -> entry.getEnclosingElement() instanceof PackageElement;
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatchersGenProperties.java
// static MatchersGenProperties props() {
// return PropertyLoader.newInstance().populate(MatchersGenProperties.class);
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatcherFactoryGenerator.java
import com.squareup.javapoet.JavaFile;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingException;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.groupingBy;
import static ru.yandex.qatools.processors.matcher.gen.MatchersGenProperties.props;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
import static ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates.isEntryWithParentPackageElement;
package ru.yandex.qatools.processors.matcher.gen;
/**
* @author lanwen (Merkushev Kirill)
*/
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MatcherFactoryGenerator extends AbstractProcessor {
private static final Logger LOGGER = Logger.getLogger(MatcherFactoryGenerator.class.toString());
@Override
public Set<String> getSupportedAnnotationTypes() { | return new HashSet<>(props().annotationsToProcess()); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatcherFactoryGenerator.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingException.java
// public class ProcessingException extends RuntimeException {
//
// public ProcessingException(String message, String simpleName, JavaFileObject.Kind kind, Exception cause) {
// super(String.format("%s: %s (%s)", message, simpleName, kind), cause);
// }
//
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public final class ProcessingPredicates {
//
// /**
// * Walks through parent chain and if any contains
// * {@link DoNotGenerateMatcher} annotation, skips this element
// *
// * @return predicate to help filter fields for matcher generation
// */
// public static Predicate<Element> shouldGenerateMatcher() {
// return element -> ElementParentsIterable.stream(element)
// .noneMatch(next -> nonNull(next.getAnnotation(DoNotGenerateMatcher.class)));
// }
//
// /**
// * Syntax sugar for {@link #hasParentPackageElement()}
// */
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
//
// /**
// * To help filter nested classes
// */
// public static Predicate<Element> hasParentPackageElement() {
// return entry -> entry.getEnclosingElement() instanceof PackageElement;
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatchersGenProperties.java
// static MatchersGenProperties props() {
// return PropertyLoader.newInstance().populate(MatchersGenProperties.class);
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
| import com.squareup.javapoet.JavaFile;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingException;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.groupingBy;
import static ru.yandex.qatools.processors.matcher.gen.MatchersGenProperties.props;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
import static ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates.isEntryWithParentPackageElement; |
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
if (roundEnv.processingOver()) {
return false;
}
if (annotations.isEmpty()) {
LOGGER.info("No any annotation found...");
return false;
}
List<Element> fields = new LinkedList<>();
for (TypeElement annotation : annotations) {
LOGGER.info(format("Work with %s...", annotation.getQualifiedName()));
roundEnv.getElementsAnnotatedWith(annotation)
.stream()
.flatMap(MatcherFactoryGenerator::asFields)
.filter(ProcessingPredicates.shouldGenerateMatcher())
.forEach(fields::add);
}
| // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingException.java
// public class ProcessingException extends RuntimeException {
//
// public ProcessingException(String message, String simpleName, JavaFileObject.Kind kind, Exception cause) {
// super(String.format("%s: %s (%s)", message, simpleName, kind), cause);
// }
//
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public final class ProcessingPredicates {
//
// /**
// * Walks through parent chain and if any contains
// * {@link DoNotGenerateMatcher} annotation, skips this element
// *
// * @return predicate to help filter fields for matcher generation
// */
// public static Predicate<Element> shouldGenerateMatcher() {
// return element -> ElementParentsIterable.stream(element)
// .noneMatch(next -> nonNull(next.getAnnotation(DoNotGenerateMatcher.class)));
// }
//
// /**
// * Syntax sugar for {@link #hasParentPackageElement()}
// */
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
//
// /**
// * To help filter nested classes
// */
// public static Predicate<Element> hasParentPackageElement() {
// return entry -> entry.getEnclosingElement() instanceof PackageElement;
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatchersGenProperties.java
// static MatchersGenProperties props() {
// return PropertyLoader.newInstance().populate(MatchersGenProperties.class);
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
// public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() {
// return entry -> hasParentPackageElement().test(entry.getClassElement());
// }
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/MatcherFactoryGenerator.java
import com.squareup.javapoet.JavaFile;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingException;
import ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.groupingBy;
import static ru.yandex.qatools.processors.matcher.gen.MatchersGenProperties.props;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
import static ru.yandex.qatools.processors.matcher.gen.processing.ProcessingPredicates.isEntryWithParentPackageElement;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
if (roundEnv.processingOver()) {
return false;
}
if (annotations.isEmpty()) {
LOGGER.info("No any annotation found...");
return false;
}
List<Element> fields = new LinkedList<>();
for (TypeElement annotation : annotations) {
LOGGER.info(format("Work with %s...", annotation.getQualifiedName()));
roundEnv.getElementsAnnotatedWith(annotation)
.stream()
.flatMap(MatcherFactoryGenerator::asFields)
.filter(ProcessingPredicates.shouldGenerateMatcher())
.forEach(fields::add);
}
| Map<Element, ClassSpecDescription> classes = groupedClasses(fields); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods; | package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception { | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception { | LinkedList<Element> fields = findFields(WithSomeFields.class); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods; | package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception {
LinkedList<Element> fields = findFields(WithSomeFields.class);
| // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception {
LinkedList<Element> fields = findFields(WithSomeFields.class);
| ClassSpecDescription apply = collectingMethods().finisher().apply(fields); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods; | package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception {
LinkedList<Element> fields = findFields(WithSomeFields.class);
| // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception {
LinkedList<Element> fields = findFields(WithSomeFields.class);
| ClassSpecDescription apply = collectingMethods().finisher().apply(fields); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods; | package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception {
LinkedList<Element> fields = findFields(WithSomeFields.class);
ClassSpecDescription apply = collectingMethods().finisher().apply(fields);
assertThat(apply.getClassElement().getSimpleName().toString(), equalTo(WithSomeFields.class.getSimpleName()));
assertThat(apply.getSpec().methodSpecs, hasSize(fields.size() + 1));
assertThat(
apply.getSpec().methodSpecs.stream().map(methodSpec -> methodSpec.name).collect(toList()),
hasItems("withValue", "withBytes", "withStr", "withInteger", "withLower")
);
}
@Test
public void shouldThrowException_ifNoGetterPresent() throws Exception {
thrown.expect(NoSuchElementException.class); | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithSomeFields.java
// public class WithSomeFields {
// int value;
// byte[] bytes;
// String str;
// Integer integer;
// String lower;
//
// int getValue() {
// return value;
// }
//
// byte[] getBytes() {
// return bytes;
// }
//
// String getStr() {
// return str;
// }
//
// Integer getInteger() {
// return integer;
// }
//
// String getLOWER() {
// return lower;
// }
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/WithoutGetter.java
// public class WithoutGetter {
// private String prop;
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollector.java
// public static MethodsCollector collectingMethods() {
// return new MethodsCollector();
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithSomeFields;
import ru.yandex.qatools.processors.matcher.gen.testclasses.WithoutGetter;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollector.collectingMethods;
package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public class MethodsCollectorTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldCollectFields() throws Exception {
LinkedList<Element> fields = findFields(WithSomeFields.class);
ClassSpecDescription apply = collectingMethods().finisher().apply(fields);
assertThat(apply.getClassElement().getSimpleName().toString(), equalTo(WithSomeFields.class.getSimpleName()));
assertThat(apply.getSpec().methodSpecs, hasSize(fields.size() + 1));
assertThat(
apply.getSpec().methodSpecs.stream().map(methodSpec -> methodSpec.name).collect(toList()),
hasItems("withValue", "withBytes", "withStr", "withInteger", "withLower")
);
}
@Test
public void shouldThrowException_ifNoGetterPresent() throws Exception {
thrown.expect(NoSuchElementException.class); | thrown.expectMessage(allOf(containsString("WithoutGetter"), containsString("prop"))); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterableTest.java | // Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/Outer.java
// public class Outer {
// public static class Nested {
// public static class TwiceNested {
// private int field;
// }
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
// public static Predicate<Element> ofKind(ElementKind kind) {
// return elem -> elem.getKind() == kind;
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.qatools.processors.matcher.gen.testclasses.Outer;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable.stream;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollectorTest.ofKind; | package ru.yandex.qatools.processors.matcher.gen.elements;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ElementParentsIterableTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Test
public void shouldGetParents() throws Exception {
TypeElement twiceNested = compilation.getElements() | // Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/Outer.java
// public class Outer {
// public static class Nested {
// public static class TwiceNested {
// private int field;
// }
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
// public static Predicate<Element> ofKind(ElementKind kind) {
// return elem -> elem.getKind() == kind;
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterableTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.qatools.processors.matcher.gen.testclasses.Outer;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable.stream;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollectorTest.ofKind;
package ru.yandex.qatools.processors.matcher.gen.elements;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ElementParentsIterableTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Test
public void shouldGetParents() throws Exception {
TypeElement twiceNested = compilation.getElements() | .getTypeElement(Outer.Nested.TwiceNested.class.getCanonicalName()); |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterableTest.java | // Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/Outer.java
// public class Outer {
// public static class Nested {
// public static class TwiceNested {
// private int field;
// }
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
// public static Predicate<Element> ofKind(ElementKind kind) {
// return elem -> elem.getKind() == kind;
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.qatools.processors.matcher.gen.testclasses.Outer;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable.stream;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollectorTest.ofKind; | package ru.yandex.qatools.processors.matcher.gen.elements;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ElementParentsIterableTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Test
public void shouldGetParents() throws Exception {
TypeElement twiceNested = compilation.getElements()
.getTypeElement(Outer.Nested.TwiceNested.class.getCanonicalName());
List<? extends Element> members = compilation.getElements().getAllMembers(twiceNested);
| // Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/Outer.java
// public class Outer {
// public static class Nested {
// public static class TwiceNested {
// private int field;
// }
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
// public static Predicate<Element> ofKind(ElementKind kind) {
// return elem -> elem.getKind() == kind;
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterableTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.qatools.processors.matcher.gen.testclasses.Outer;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable.stream;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollectorTest.ofKind;
package ru.yandex.qatools.processors.matcher.gen.elements;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ElementParentsIterableTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Test
public void shouldGetParents() throws Exception {
TypeElement twiceNested = compilation.getElements()
.getTypeElement(Outer.Nested.TwiceNested.class.getCanonicalName());
List<? extends Element> members = compilation.getElements().getAllMembers(twiceNested);
| Element field = members.stream().filter(ofKind(ElementKind.FIELD)).findFirst() |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterableTest.java | // Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/Outer.java
// public class Outer {
// public static class Nested {
// public static class TwiceNested {
// private int field;
// }
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
// public static Predicate<Element> ofKind(ElementKind kind) {
// return elem -> elem.getKind() == kind;
// }
| import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.qatools.processors.matcher.gen.testclasses.Outer;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable.stream;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollectorTest.ofKind; | package ru.yandex.qatools.processors.matcher.gen.elements;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ElementParentsIterableTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Test
public void shouldGetParents() throws Exception {
TypeElement twiceNested = compilation.getElements()
.getTypeElement(Outer.Nested.TwiceNested.class.getCanonicalName());
List<? extends Element> members = compilation.getElements().getAllMembers(twiceNested);
| // Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/testclasses/Outer.java
// public class Outer {
// public static class Nested {
// public static class TwiceNested {
// private int field;
// }
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
//
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/processing/MethodsCollectorTest.java
// public static Predicate<Element> ofKind(ElementKind kind) {
// return elem -> elem.getKind() == kind;
// }
// Path: feature-matcher-generator/src/test/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterableTest.java
import com.google.testing.compile.CompilationRule;
import org.junit.Rule;
import org.junit.Test;
import ru.yandex.qatools.processors.matcher.gen.testclasses.Outer;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable.stream;
import static ru.yandex.qatools.processors.matcher.gen.processing.MethodsCollectorTest.ofKind;
package ru.yandex.qatools.processors.matcher.gen.elements;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ElementParentsIterableTest {
@Rule
public CompilationRule compilation = new CompilationRule();
@Test
public void shouldGetParents() throws Exception {
TypeElement twiceNested = compilation.getElements()
.getTypeElement(Outer.Nested.TwiceNested.class.getCanonicalName());
List<? extends Element> members = compilation.getElements().getAllMembers(twiceNested);
| Element field = members.stream().filter(ofKind(ElementKind.FIELD)).findFirst() |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public class ElementParentsIterable implements Iterable<Element> {
// private final Element start;
//
// public ElementParentsIterable(Element start) {
// this.start = Objects.requireNonNull(start, "element can't be null");
// }
//
// @Override
// public Iterator<Element> iterator() {
// return new Iterator<Element>() {
// private Element current = start;
//
// @Override
// public boolean hasNext() {
// return nonNull(current.getEnclosingElement());
// }
//
// @Override
// public Element next() {
// Element next = current;
// current = current.getEnclosingElement();
// return next;
// }
// };
// }
//
// /**
// * Creates stream with parent chain
// *
// * @param element element to start with (will be included to chain)
// * @return stream with elements from current with his parents until package (inclusive)
// */
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
// }
| import ru.yandex.qatools.processors.matcher.gen.annotations.DoNotGenerateMatcher;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import java.util.function.Predicate;
import static java.util.Objects.nonNull; | package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public final class ProcessingPredicates {
/**
* Walks through parent chain and if any contains
* {@link DoNotGenerateMatcher} annotation, skips this element
*
* @return predicate to help filter fields for matcher generation
*/
public static Predicate<Element> shouldGenerateMatcher() { | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public class ElementParentsIterable implements Iterable<Element> {
// private final Element start;
//
// public ElementParentsIterable(Element start) {
// this.start = Objects.requireNonNull(start, "element can't be null");
// }
//
// @Override
// public Iterator<Element> iterator() {
// return new Iterator<Element>() {
// private Element current = start;
//
// @Override
// public boolean hasNext() {
// return nonNull(current.getEnclosingElement());
// }
//
// @Override
// public Element next() {
// Element next = current;
// current = current.getEnclosingElement();
// return next;
// }
// };
// }
//
// /**
// * Creates stream with parent chain
// *
// * @param element element to start with (will be included to chain)
// * @return stream with elements from current with his parents until package (inclusive)
// */
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
// }
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
import ru.yandex.qatools.processors.matcher.gen.annotations.DoNotGenerateMatcher;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import java.util.function.Predicate;
import static java.util.Objects.nonNull;
package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public final class ProcessingPredicates {
/**
* Walks through parent chain and if any contains
* {@link DoNotGenerateMatcher} annotation, skips this element
*
* @return predicate to help filter fields for matcher generation
*/
public static Predicate<Element> shouldGenerateMatcher() { | return element -> ElementParentsIterable.stream(element) |
yandex-qatools/hamcrest-pojo-matcher-generator | feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public class ElementParentsIterable implements Iterable<Element> {
// private final Element start;
//
// public ElementParentsIterable(Element start) {
// this.start = Objects.requireNonNull(start, "element can't be null");
// }
//
// @Override
// public Iterator<Element> iterator() {
// return new Iterator<Element>() {
// private Element current = start;
//
// @Override
// public boolean hasNext() {
// return nonNull(current.getEnclosingElement());
// }
//
// @Override
// public Element next() {
// Element next = current;
// current = current.getEnclosingElement();
// return next;
// }
// };
// }
//
// /**
// * Creates stream with parent chain
// *
// * @param element element to start with (will be included to chain)
// * @return stream with elements from current with his parents until package (inclusive)
// */
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
// }
| import ru.yandex.qatools.processors.matcher.gen.annotations.DoNotGenerateMatcher;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import java.util.function.Predicate;
import static java.util.Objects.nonNull; | package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public final class ProcessingPredicates {
/**
* Walks through parent chain and if any contains
* {@link DoNotGenerateMatcher} annotation, skips this element
*
* @return predicate to help filter fields for matcher generation
*/
public static Predicate<Element> shouldGenerateMatcher() {
return element -> ElementParentsIterable.stream(element)
.noneMatch(next -> nonNull(next.getAnnotation(DoNotGenerateMatcher.class)));
}
/**
* Syntax sugar for {@link #hasParentPackageElement()}
*/ | // Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/bean/ClassSpecDescription.java
// public class ClassSpecDescription implements Comparable<ClassSpecDescription> {
//
// private Element classElement;
// private TypeSpec spec;
//
// public ClassSpecDescription(Element classElement, TypeSpec spec) {
// this.classElement = classElement;
// this.spec = spec;
// }
//
// public Element getClassElement() {
// return classElement;
// }
//
// public TypeSpec getSpec() {
// return spec;
// }
//
// public void setSpec(TypeSpec spec) {
// this.spec = spec;
// }
//
// public JavaFile asJavaFile() {
// return JavaFile.builder(
// ((PackageElement) getClassElement().getEnclosingElement()).getQualifiedName().toString(),
// getSpec()
// ).build();
// }
//
// public void mergeWithParentFrom(Map<Element, ClassSpecDescription> classes) {
// ClassSpecDescription container = classes.computeIfAbsent(
// getClassElement().getEnclosingElement(),
// enclosing -> new ClassSpecDescription(
// getClassElement().getEnclosingElement(),
// MethodsCollector.commonClassPart(enclosing).build()
// )
// );
//
// container.setSpec(
// container.getSpec()
// .toBuilder()
// .addType(getSpec())
// .build()
// );
// }
//
// @Override
// public int compareTo(ClassSpecDescription o) {
// return Comparator.comparing(ClassSpecDescription::depthOf).compare(this, o);
// }
//
// private static long depthOf(ClassSpecDescription element) {
// return ElementParentsIterable.stream(element.getClassElement())
// .filter(hasParentPackageElement().negate())
// .count();
// }
// }
//
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/elements/ElementParentsIterable.java
// public class ElementParentsIterable implements Iterable<Element> {
// private final Element start;
//
// public ElementParentsIterable(Element start) {
// this.start = Objects.requireNonNull(start, "element can't be null");
// }
//
// @Override
// public Iterator<Element> iterator() {
// return new Iterator<Element>() {
// private Element current = start;
//
// @Override
// public boolean hasNext() {
// return nonNull(current.getEnclosingElement());
// }
//
// @Override
// public Element next() {
// Element next = current;
// current = current.getEnclosingElement();
// return next;
// }
// };
// }
//
// /**
// * Creates stream with parent chain
// *
// * @param element element to start with (will be included to chain)
// * @return stream with elements from current with his parents until package (inclusive)
// */
// public static Stream<Element> stream(Element element) {
// return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
// }
// }
// Path: feature-matcher-generator/src/main/java/ru/yandex/qatools/processors/matcher/gen/processing/ProcessingPredicates.java
import ru.yandex.qatools.processors.matcher.gen.annotations.DoNotGenerateMatcher;
import ru.yandex.qatools.processors.matcher.gen.bean.ClassSpecDescription;
import ru.yandex.qatools.processors.matcher.gen.elements.ElementParentsIterable;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import java.util.function.Predicate;
import static java.util.Objects.nonNull;
package ru.yandex.qatools.processors.matcher.gen.processing;
/**
* @author lanwen (Merkushev Kirill)
*/
public final class ProcessingPredicates {
/**
* Walks through parent chain and if any contains
* {@link DoNotGenerateMatcher} annotation, skips this element
*
* @return predicate to help filter fields for matcher generation
*/
public static Predicate<Element> shouldGenerateMatcher() {
return element -> ElementParentsIterable.stream(element)
.noneMatch(next -> nonNull(next.getAnnotation(DoNotGenerateMatcher.class)));
}
/**
* Syntax sugar for {@link #hasParentPackageElement()}
*/ | public static Predicate<ClassSpecDescription> isEntryWithParentPackageElement() { |
openwdl/wdl | versions/1.0/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WDLParserTest.java | // Path: versions/development/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WdlParserTestErrorListener.java
// public static class SyntaxError {
//
// private final Object offendingSymbol;
// private final int line;
// private final int position;
// private final String message;
//
// SyntaxError(Object offendingSymbol, int line, int position, String message) {
// this.offendingSymbol = offendingSymbol;
// this.line = line;
// this.position = position;
// this.message = message;
// }
//
// public Object getOffendingSymbol() {
// return offendingSymbol;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getPosition() {
// return position;
// }
//
// public String getMessage() {
// return message;
// }
//
// public AssertionError getAssertionError() {
// return new AssertionError(toString());
// }
//
// @Override
// public String toString() {
// return "line " + line + ":" + position + " " + message;
// }
// }
| import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.openwdl.wdl.parser.WdlParser.*;
import org.openwdl.wdl.parser.WdlParserTestErrorListener.SyntaxError;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream; | }
public static Stream<Arguments> failingWdlFiles() throws IOException {
List<Arguments> testArguments = new ArrayList<>();
File exampleDir = new File(examplesDirectory);
for (File wdlFile : exampleDir.listFiles()) {
if (wdlFile.getName().endsWith(".error")) {
String name = wdlFile.getName();
testArguments.add(Arguments.of(Files.readAllBytes(wdlFile.toPath()), name));
}
}
return testArguments.stream();
}
@ParameterizedTest
@MethodSource("failingWdlFiles")
public void testWdlFiles_shouldFailParsing(byte[] fileBytes, String fileName) {
System.out.println("Testing WDL File: " + fileName + " should fail to parse");
WdlParserTestErrorListener errorListener = new WdlParserTestErrorListener();
CodePointBuffer codePointBuffer = CodePointBuffer.withBytes(ByteBuffer.wrap(fileBytes));
CommentAggregatingTokenSource tokenSource = new CommentAggregatingTokenSource(CodePointCharStream.fromBuffer(
codePointBuffer));
WdlParser parser = new WdlParser(new CommonTokenStream(tokenSource));
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
parser.document();
Assertions.assertTrue(errorListener.hasErrors());
| // Path: versions/development/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WdlParserTestErrorListener.java
// public static class SyntaxError {
//
// private final Object offendingSymbol;
// private final int line;
// private final int position;
// private final String message;
//
// SyntaxError(Object offendingSymbol, int line, int position, String message) {
// this.offendingSymbol = offendingSymbol;
// this.line = line;
// this.position = position;
// this.message = message;
// }
//
// public Object getOffendingSymbol() {
// return offendingSymbol;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getPosition() {
// return position;
// }
//
// public String getMessage() {
// return message;
// }
//
// public AssertionError getAssertionError() {
// return new AssertionError(toString());
// }
//
// @Override
// public String toString() {
// return "line " + line + ":" + position + " " + message;
// }
// }
// Path: versions/1.0/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WDLParserTest.java
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.openwdl.wdl.parser.WdlParser.*;
import org.openwdl.wdl.parser.WdlParserTestErrorListener.SyntaxError;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
}
public static Stream<Arguments> failingWdlFiles() throws IOException {
List<Arguments> testArguments = new ArrayList<>();
File exampleDir = new File(examplesDirectory);
for (File wdlFile : exampleDir.listFiles()) {
if (wdlFile.getName().endsWith(".error")) {
String name = wdlFile.getName();
testArguments.add(Arguments.of(Files.readAllBytes(wdlFile.toPath()), name));
}
}
return testArguments.stream();
}
@ParameterizedTest
@MethodSource("failingWdlFiles")
public void testWdlFiles_shouldFailParsing(byte[] fileBytes, String fileName) {
System.out.println("Testing WDL File: " + fileName + " should fail to parse");
WdlParserTestErrorListener errorListener = new WdlParserTestErrorListener();
CodePointBuffer codePointBuffer = CodePointBuffer.withBytes(ByteBuffer.wrap(fileBytes));
CommentAggregatingTokenSource tokenSource = new CommentAggregatingTokenSource(CodePointCharStream.fromBuffer(
codePointBuffer));
WdlParser parser = new WdlParser(new CommonTokenStream(tokenSource));
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
parser.document();
Assertions.assertTrue(errorListener.hasErrors());
| List<SyntaxError> errors = errorListener.getErrors(); |
openwdl/wdl | versions/development/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WDLParserTest.java | // Path: versions/development/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WdlParserTestErrorListener.java
// public static class SyntaxError {
//
// private final Object offendingSymbol;
// private final int line;
// private final int position;
// private final String message;
//
// SyntaxError(Object offendingSymbol, int line, int position, String message) {
// this.offendingSymbol = offendingSymbol;
// this.line = line;
// this.position = position;
// this.message = message;
// }
//
// public Object getOffendingSymbol() {
// return offendingSymbol;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getPosition() {
// return position;
// }
//
// public String getMessage() {
// return message;
// }
//
// public AssertionError getAssertionError() {
// return new AssertionError(toString());
// }
//
// @Override
// public String toString() {
// return "line " + line + ":" + position + " " + message;
// }
// }
| import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.openwdl.wdl.parser.WdlParser.*;
import org.openwdl.wdl.parser.WdlParserTestErrorListener.SyntaxError;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream; | }
public static Stream<Arguments> failingWdlFiles() throws IOException {
List<Arguments> testArguments = new ArrayList<>();
File exampleDir = new File(examplesDirectory);
for (File wdlFile : exampleDir.listFiles()) {
if (wdlFile.getName().endsWith(".error")) {
String name = wdlFile.getName();
testArguments.add(Arguments.of(Files.readAllBytes(wdlFile.toPath()), name));
}
}
return testArguments.stream();
}
@ParameterizedTest
@MethodSource("failingWdlFiles")
public void testWdlFiles_shouldFailParings(byte[] fileBytes, String fileName) {
System.out.println("Testing WDL File: " + fileName + " should fail to parse");
WdlParserTestErrorListener errorListener = new WdlParserTestErrorListener();
CodePointBuffer codePointBuffer = CodePointBuffer.withBytes(ByteBuffer.wrap(fileBytes));
CommentAggregatingTokenSource tokenSource = new CommentAggregatingTokenSource(CodePointCharStream
.fromBuffer(codePointBuffer));
WdlParser parser = new WdlParser(new CommonTokenStream(tokenSource));
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
parser.document();
Assertions.assertTrue(errorListener.hasErrors());
| // Path: versions/development/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WdlParserTestErrorListener.java
// public static class SyntaxError {
//
// private final Object offendingSymbol;
// private final int line;
// private final int position;
// private final String message;
//
// SyntaxError(Object offendingSymbol, int line, int position, String message) {
// this.offendingSymbol = offendingSymbol;
// this.line = line;
// this.position = position;
// this.message = message;
// }
//
// public Object getOffendingSymbol() {
// return offendingSymbol;
// }
//
// public int getLine() {
// return line;
// }
//
// public int getPosition() {
// return position;
// }
//
// public String getMessage() {
// return message;
// }
//
// public AssertionError getAssertionError() {
// return new AssertionError(toString());
// }
//
// @Override
// public String toString() {
// return "line " + line + ":" + position + " " + message;
// }
// }
// Path: versions/development/parsers/antlr4/Java/src/test/java/org/openwdl/wdl/parser/WDLParserTest.java
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.openwdl.wdl.parser.WdlParser.*;
import org.openwdl.wdl.parser.WdlParserTestErrorListener.SyntaxError;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
}
public static Stream<Arguments> failingWdlFiles() throws IOException {
List<Arguments> testArguments = new ArrayList<>();
File exampleDir = new File(examplesDirectory);
for (File wdlFile : exampleDir.listFiles()) {
if (wdlFile.getName().endsWith(".error")) {
String name = wdlFile.getName();
testArguments.add(Arguments.of(Files.readAllBytes(wdlFile.toPath()), name));
}
}
return testArguments.stream();
}
@ParameterizedTest
@MethodSource("failingWdlFiles")
public void testWdlFiles_shouldFailParings(byte[] fileBytes, String fileName) {
System.out.println("Testing WDL File: " + fileName + " should fail to parse");
WdlParserTestErrorListener errorListener = new WdlParserTestErrorListener();
CodePointBuffer codePointBuffer = CodePointBuffer.withBytes(ByteBuffer.wrap(fileBytes));
CommentAggregatingTokenSource tokenSource = new CommentAggregatingTokenSource(CodePointCharStream
.fromBuffer(codePointBuffer));
WdlParser parser = new WdlParser(new CommonTokenStream(tokenSource));
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
parser.document();
Assertions.assertTrue(errorListener.hasErrors());
| List<SyntaxError> errors = errorListener.getErrors(); |
mangstadt/vinnie | src/test/java/com/github/mangstadt/vinnie/VObjectParametersTest.java | // Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsAndHash(Object one, Object two) {
// assertEquals(one, two);
// assertEquals(two, one);
// assertEquals(one.hashCode(), two.hashCode());
// }
//
// Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsMethodEssentials(Object object) {
// assertTrue(object.equals(object));
// assertFalse(object.equals(null));
// assertFalse(object.equals("other class"));
// }
| import static org.junit.Assert.fail;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsAndHash;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsMethodEssentials;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; | }
parameters.clear();
parameters.put("CHARSET", "illegal name");
try {
parameters.getCharset();
fail();
} catch (IllegalCharsetNameException e) {
//expected
}
parameters.clear();
parameters.put("CHARSET", "utf-8");
assertEquals("UTF-8", parameters.getCharset().name());
}
@Test
public void copy() {
VObjectParameters orig = new VObjectParameters();
orig.put("name", "value");
VObjectParameters copy = new VObjectParameters(orig);
assertEquals(orig, copy);
orig.put("name", "value2");
assertEquals(Arrays.asList("value"), copy.get("name"));
}
@Test
public void equals_and_hash() {
VObjectParameters one = new VObjectParameters(); | // Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsAndHash(Object one, Object two) {
// assertEquals(one, two);
// assertEquals(two, one);
// assertEquals(one.hashCode(), two.hashCode());
// }
//
// Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsMethodEssentials(Object object) {
// assertTrue(object.equals(object));
// assertFalse(object.equals(null));
// assertFalse(object.equals("other class"));
// }
// Path: src/test/java/com/github/mangstadt/vinnie/VObjectParametersTest.java
import static org.junit.Assert.fail;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsAndHash;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsMethodEssentials;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
}
parameters.clear();
parameters.put("CHARSET", "illegal name");
try {
parameters.getCharset();
fail();
} catch (IllegalCharsetNameException e) {
//expected
}
parameters.clear();
parameters.put("CHARSET", "utf-8");
assertEquals("UTF-8", parameters.getCharset().name());
}
@Test
public void copy() {
VObjectParameters orig = new VObjectParameters();
orig.put("name", "value");
VObjectParameters copy = new VObjectParameters(orig);
assertEquals(orig, copy);
orig.put("name", "value2");
assertEquals(Arrays.asList("value"), copy.get("name"));
}
@Test
public void equals_and_hash() {
VObjectParameters one = new VObjectParameters(); | assertEqualsMethodEssentials(one); |
mangstadt/vinnie | src/test/java/com/github/mangstadt/vinnie/VObjectParametersTest.java | // Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsAndHash(Object one, Object two) {
// assertEquals(one, two);
// assertEquals(two, one);
// assertEquals(one.hashCode(), two.hashCode());
// }
//
// Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsMethodEssentials(Object object) {
// assertTrue(object.equals(object));
// assertFalse(object.equals(null));
// assertFalse(object.equals("other class"));
// }
| import static org.junit.Assert.fail;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsAndHash;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsMethodEssentials;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; | parameters.getCharset();
fail();
} catch (IllegalCharsetNameException e) {
//expected
}
parameters.clear();
parameters.put("CHARSET", "utf-8");
assertEquals("UTF-8", parameters.getCharset().name());
}
@Test
public void copy() {
VObjectParameters orig = new VObjectParameters();
orig.put("name", "value");
VObjectParameters copy = new VObjectParameters(orig);
assertEquals(orig, copy);
orig.put("name", "value2");
assertEquals(Arrays.asList("value"), copy.get("name"));
}
@Test
public void equals_and_hash() {
VObjectParameters one = new VObjectParameters();
assertEqualsMethodEssentials(one);
one.put("name", "value");
VObjectParameters two = new VObjectParameters();
two.put("name", "value"); | // Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsAndHash(Object one, Object two) {
// assertEquals(one, two);
// assertEquals(two, one);
// assertEquals(one.hashCode(), two.hashCode());
// }
//
// Path: src/test/java/com/github/mangstadt/vinnie/TestUtils.java
// public static void assertEqualsMethodEssentials(Object object) {
// assertTrue(object.equals(object));
// assertFalse(object.equals(null));
// assertFalse(object.equals("other class"));
// }
// Path: src/test/java/com/github/mangstadt/vinnie/VObjectParametersTest.java
import static org.junit.Assert.fail;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsAndHash;
import static com.github.mangstadt.vinnie.TestUtils.assertEqualsMethodEssentials;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
parameters.getCharset();
fail();
} catch (IllegalCharsetNameException e) {
//expected
}
parameters.clear();
parameters.put("CHARSET", "utf-8");
assertEquals("UTF-8", parameters.getCharset().name());
}
@Test
public void copy() {
VObjectParameters orig = new VObjectParameters();
orig.put("name", "value");
VObjectParameters copy = new VObjectParameters(orig);
assertEquals(orig, copy);
orig.put("name", "value2");
assertEquals(Arrays.asList("value"), copy.get("name"));
}
@Test
public void equals_and_hash() {
VObjectParameters one = new VObjectParameters();
assertEqualsMethodEssentials(one);
one.put("name", "value");
VObjectParameters two = new VObjectParameters();
two.put("name", "value"); | assertEqualsAndHash(one, two); |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AnyJobRestriction.java
// public class AnyJobRestriction extends JobRestriction {
// @DataBoundConstructor
// public AnyJobRestriction() {
// }
//
// @Override
// public boolean canTake(Queue.BuildableItem item) {
// return true;
// }
//
// @Override
// public boolean canTake(Run run) {
// return true;
// }
//
// @Extension(ordinal = 1000)
// public static class DescriptorImpl extends JobRestrictionDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.restrictions_Logic_Any();
// }
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/JenkinsHelper.java
// @Restricted(NoExternalUse.class)
// public class JenkinsHelper {
//
// /**
// * Gets the {@link Jenkins} singleton.
// * @return {@link Jenkins} instance
// * @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
// */
// @Nonnull
// public static Jenkins getInstanceOrDie() throws IllegalStateException {
// final Jenkins instance = Jenkins.getInstance();
// if (instance == null) {
// throw new IllegalStateException("Jenkins has not been started, or was already shut down");
// }
// return instance;
// }
//
// }
| import hudson.model.Queue;
import hudson.model.Run;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Nonnull;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic.AnyJobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.JenkinsHelper;
import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Job;
import hudson.model.Node; | /*
* The MIT License
*
* Copyright 2013-2016 Synopsys Inc., Oleg Nenashev
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions;
/**
* The extension point, which allows to restrict job executions.
*
* @author Oleg Nenashev
*/
public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
public static final JobRestriction DEFAULT = new AnyJobRestriction();
/**
* Check if the {@link Queue} item can be taken.
* This method is being used to check if the {@link Node} can take the
* specified job. If the job cannot be taken, Jenkins will try to launch
* the job on other nodes.
* @param item An item to be checked
* @return true if the node can take the item
*/
public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
/**
* Check if the {@link Job} can be executed according to the specified {@link Run}.
* If the job cannot be executed, it will be aborted by the plugin.
* @param run A {@link Run} to be checked
* @return true if the build can be executed
*/
public abstract boolean canTake(@Nonnull Run run);
@Override
public JobRestrictionDescriptor getDescriptor() { | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AnyJobRestriction.java
// public class AnyJobRestriction extends JobRestriction {
// @DataBoundConstructor
// public AnyJobRestriction() {
// }
//
// @Override
// public boolean canTake(Queue.BuildableItem item) {
// return true;
// }
//
// @Override
// public boolean canTake(Run run) {
// return true;
// }
//
// @Extension(ordinal = 1000)
// public static class DescriptorImpl extends JobRestrictionDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.restrictions_Logic_Any();
// }
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/JenkinsHelper.java
// @Restricted(NoExternalUse.class)
// public class JenkinsHelper {
//
// /**
// * Gets the {@link Jenkins} singleton.
// * @return {@link Jenkins} instance
// * @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
// */
// @Nonnull
// public static Jenkins getInstanceOrDie() throws IllegalStateException {
// final Jenkins instance = Jenkins.getInstance();
// if (instance == null) {
// throw new IllegalStateException("Jenkins has not been started, or was already shut down");
// }
// return instance;
// }
//
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
import hudson.model.Queue;
import hudson.model.Run;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Nonnull;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic.AnyJobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.JenkinsHelper;
import hudson.DescriptorExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Describable;
import hudson.model.Job;
import hudson.model.Node;
/*
* The MIT License
*
* Copyright 2013-2016 Synopsys Inc., Oleg Nenashev
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions;
/**
* The extension point, which allows to restrict job executions.
*
* @author Oleg Nenashev
*/
public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
public static final JobRestriction DEFAULT = new AnyJobRestriction();
/**
* Check if the {@link Queue} item can be taken.
* This method is being used to check if the {@link Node} can take the
* specified job. If the job cannot be taken, Jenkins will try to launch
* the job on other nodes.
* @param item An item to be checked
* @return true if the node can take the item
*/
public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
/**
* Check if the {@link Job} can be executed according to the specified {@link Run}.
* If the job cannot be executed, it will be aborted by the plugin.
* @param run A {@link Run} to be checked
* @return true if the build can be executed
*/
public abstract boolean canTake(@Nonnull Run run);
@Override
public JobRestrictionDescriptor getDescriptor() { | return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass()); |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/StartedByUserRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/UserSelector.java
// public class UserSelector implements Describable<UserSelector>, Serializable {
//
// /**ID of the user*/
// @CheckForNull String selectedUserId;
//
// @DataBoundConstructor
// public UserSelector(@CheckForNull String selectedUserId) {
// this.selectedUserId = hudson.Util.fixEmptyAndTrim(selectedUserId);
// }
//
// @CheckForNull
// public String getSelectedUserId() {
// return selectedUserId;
// }
//
// @Override
// public Descriptor<UserSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserSelector) {
// UserSelector cmp = (UserSelector)obj;
// return selectedUserId != null ? selectedUserId.equals(cmp.selectedUserId) : cmp.selectedUserId == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedUserId != null ? selectedUserId.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<UserSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// @Restricted(NoExternalUse.class) // Stapler only
// public FormValidation doCheckSelectedUserId(@QueryParameter String selectedUserId) {
// selectedUserId = Util.fixEmptyAndTrim(selectedUserId);
// if (selectedUserId == null) {
// return FormValidation.error("Field is empty");
// }
//
// User user = User.getById(selectedUserId, false);
// if (user == null) {
// return FormValidation.warning("User " + selectedUserId + " is not registered in Jenkins");
// }
//
// return FormValidation.ok();
// }
// }
// }
| import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.UserSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import java.util.HashSet; | /*
* The MIT License
*
* Copyright 2014-2016 Oleg Nenashev
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.job;
/**
* Handles restrictions from User causes.
* @author Oleg Nenashev
* @since 0.4
*/
// TODO: it's a real issue, needs some love
@SuppressFBWarnings(value = "SE_NO_SERIALVERSIONID",
justification = "XStream does actually need serialization, the code needs refactoring in 1.0")
public class StartedByUserRestriction extends AbstractUserCauseRestriction {
| // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/UserSelector.java
// public class UserSelector implements Describable<UserSelector>, Serializable {
//
// /**ID of the user*/
// @CheckForNull String selectedUserId;
//
// @DataBoundConstructor
// public UserSelector(@CheckForNull String selectedUserId) {
// this.selectedUserId = hudson.Util.fixEmptyAndTrim(selectedUserId);
// }
//
// @CheckForNull
// public String getSelectedUserId() {
// return selectedUserId;
// }
//
// @Override
// public Descriptor<UserSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserSelector) {
// UserSelector cmp = (UserSelector)obj;
// return selectedUserId != null ? selectedUserId.equals(cmp.selectedUserId) : cmp.selectedUserId == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedUserId != null ? selectedUserId.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<UserSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// @Restricted(NoExternalUse.class) // Stapler only
// public FormValidation doCheckSelectedUserId(@QueryParameter String selectedUserId) {
// selectedUserId = Util.fixEmptyAndTrim(selectedUserId);
// if (selectedUserId == null) {
// return FormValidation.error("Field is empty");
// }
//
// User user = User.getById(selectedUserId, false);
// if (user == null) {
// return FormValidation.warning("User " + selectedUserId + " is not registered in Jenkins");
// }
//
// return FormValidation.ok();
// }
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/StartedByUserRestriction.java
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.UserSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import java.util.HashSet;
/*
* The MIT License
*
* Copyright 2014-2016 Oleg Nenashev
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.job;
/**
* Handles restrictions from User causes.
* @author Oleg Nenashev
* @since 0.4
*/
// TODO: it's a real issue, needs some love
@SuppressFBWarnings(value = "SE_NO_SERIALVERSIONID",
justification = "XStream does actually need serialization, the code needs refactoring in 1.0")
public class StartedByUserRestriction extends AbstractUserCauseRestriction {
| private final List<UserSelector> usersList; |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/StartedByUserRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/UserSelector.java
// public class UserSelector implements Describable<UserSelector>, Serializable {
//
// /**ID of the user*/
// @CheckForNull String selectedUserId;
//
// @DataBoundConstructor
// public UserSelector(@CheckForNull String selectedUserId) {
// this.selectedUserId = hudson.Util.fixEmptyAndTrim(selectedUserId);
// }
//
// @CheckForNull
// public String getSelectedUserId() {
// return selectedUserId;
// }
//
// @Override
// public Descriptor<UserSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserSelector) {
// UserSelector cmp = (UserSelector)obj;
// return selectedUserId != null ? selectedUserId.equals(cmp.selectedUserId) : cmp.selectedUserId == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedUserId != null ? selectedUserId.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<UserSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// @Restricted(NoExternalUse.class) // Stapler only
// public FormValidation doCheckSelectedUserId(@QueryParameter String selectedUserId) {
// selectedUserId = Util.fixEmptyAndTrim(selectedUserId);
// if (selectedUserId == null) {
// return FormValidation.error("Field is empty");
// }
//
// User user = User.getById(selectedUserId, false);
// if (user == null) {
// return FormValidation.warning("User " + selectedUserId + " is not registered in Jenkins");
// }
//
// return FormValidation.ok();
// }
// }
// }
| import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.UserSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import java.util.HashSet; | return usersList;
}
public @Deprecated boolean isAcceptAutomaticRuns() {
return acceptAutomaticRuns;
}
public boolean isAcceptAnonymousUsers() {
return acceptAnonymousUsers;
}
private synchronized @Nonnull Set<String> getAcceptedUsers() {
if (acceptedUsers == null) {
final List<UserSelector> selectors = getUsersList();
acceptedUsers = new HashSet<String>(selectors.size());
for (UserSelector selector : selectors) {
acceptedUsers.add(selector.getSelectedUserId()); // merge equal entries
}
}
return acceptedUsers;
}
@Override
protected boolean acceptsUser(@CheckForNull String userId) {
return userId == null
? acceptAnonymousUsers
: getAcceptedUsers().contains(userId);
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/UserSelector.java
// public class UserSelector implements Describable<UserSelector>, Serializable {
//
// /**ID of the user*/
// @CheckForNull String selectedUserId;
//
// @DataBoundConstructor
// public UserSelector(@CheckForNull String selectedUserId) {
// this.selectedUserId = hudson.Util.fixEmptyAndTrim(selectedUserId);
// }
//
// @CheckForNull
// public String getSelectedUserId() {
// return selectedUserId;
// }
//
// @Override
// public Descriptor<UserSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserSelector) {
// UserSelector cmp = (UserSelector)obj;
// return selectedUserId != null ? selectedUserId.equals(cmp.selectedUserId) : cmp.selectedUserId == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedUserId != null ? selectedUserId.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<UserSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// @Restricted(NoExternalUse.class) // Stapler only
// public FormValidation doCheckSelectedUserId(@QueryParameter String selectedUserId) {
// selectedUserId = Util.fixEmptyAndTrim(selectedUserId);
// if (selectedUserId == null) {
// return FormValidation.error("Field is empty");
// }
//
// User user = User.getById(selectedUserId, false);
// if (user == null) {
// return FormValidation.warning("User " + selectedUserId + " is not registered in Jenkins");
// }
//
// return FormValidation.ok();
// }
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/StartedByUserRestriction.java
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.UserSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import java.util.HashSet;
return usersList;
}
public @Deprecated boolean isAcceptAutomaticRuns() {
return acceptAutomaticRuns;
}
public boolean isAcceptAnonymousUsers() {
return acceptAnonymousUsers;
}
private synchronized @Nonnull Set<String> getAcceptedUsers() {
if (acceptedUsers == null) {
final List<UserSelector> selectors = getUsersList();
acceptedUsers = new HashSet<String>(selectors.size());
for (UserSelector selector : selectors) {
acceptedUsers.add(selector.getSelectedUserId()); // merge equal entries
}
}
return acceptedUsers;
}
@Override
protected boolean acceptsUser(@CheckForNull String userId) {
return userId == null
? acceptAnonymousUsers
: getAcceptedUsers().contains(userId);
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/OrJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* OR condition, which takes two parameters
* @author Oleg Nenashev
* @see MultipleOrJobRestriction
*/
public class OrJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public OrJobRestriction(JobRestriction first, JobRestriction second) { | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/OrJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* OR condition, which takes two parameters
* @author Oleg Nenashev
* @see MultipleOrJobRestriction
*/
public class OrJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public OrJobRestriction(JobRestriction first, JobRestriction second) { | this.first = first != null ? first : DEFAULT; |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/OrJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* OR condition, which takes two parameters
* @author Oleg Nenashev
* @see MultipleOrJobRestriction
*/
public class OrJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public OrJobRestriction(JobRestriction first, JobRestriction second) {
this.first = first != null ? first : DEFAULT;
this.second = second != null ? second : DEFAULT;
}
public JobRestriction getFirst() {
return first;
}
public JobRestriction getSecond() {
return second;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return first.canTake(item) || second.canTake(item);
}
@Override
public boolean canTake(Run run) {
return first.canTake(run) && second.canTake(run);
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/OrJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* OR condition, which takes two parameters
* @author Oleg Nenashev
* @see MultipleOrJobRestriction
*/
public class OrJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public OrJobRestriction(JobRestriction first, JobRestriction second) {
this.first = first != null ? first : DEFAULT;
this.second = second != null ? second : DEFAULT;
}
public JobRestriction getFirst() {
return first;
}
public JobRestriction getSecond() {
return second;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return first.canTake(item) || second.canTake(item);
}
@Override
public boolean canTake(Run run) {
return first.canTake(run) && second.canTake(run);
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/io/jenkins/plugins/jobrestrictions/restrictions/job/JobClassNameRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/util/ClassSelector.java
// public class ClassSelector implements Describable<ClassSelector>, Serializable {
//
// /**ID of the user*/
// final @CheckForNull String selectedClass;
//
// @DataBoundConstructor
// public ClassSelector(@CheckForNull String selectedClass) {
// this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
// }
//
// @CheckForNull
// public String getSelectedClass() {
// return selectedClass;
// }
//
// @Override
// public Descriptor<ClassSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ClassSelector) {
// ClassSelector cmp = (ClassSelector)obj;
// return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<ClassSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
// String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
// if (_selectedClass == null) {
// return FormValidation.error("Field is empty");
// }
//
// try {
// Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(_selectedClass);
// } catch (Exception ex) {
// return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
// }
//
// return FormValidation.ok();
// }
// }
// }
| import hudson.model.Queue;
import hudson.model.Run;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension; | }
@Nonnull
public List<ClassSelector> getJobClasses() {
return jobClasses;
}
@Nonnull
private synchronized Set<String> getAcceptedJobClasses() {
if (acceptedClassesHash == null) {
final List<ClassSelector> selectors = getJobClasses();
acceptedClassesHash = new HashSet<String>(selectors.size());
for (ClassSelector selector : selectors) {
acceptedClassesHash.add(selector.getSelectedClass()); // merge equal entries
}
}
return acceptedClassesHash;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return getAcceptedJobClasses().contains(item.task.getClass().getName());
}
@Override
public boolean canTake(Run run) {
return getAcceptedJobClasses().contains(run.getParent().getClass().getName());
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/util/ClassSelector.java
// public class ClassSelector implements Describable<ClassSelector>, Serializable {
//
// /**ID of the user*/
// final @CheckForNull String selectedClass;
//
// @DataBoundConstructor
// public ClassSelector(@CheckForNull String selectedClass) {
// this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
// }
//
// @CheckForNull
// public String getSelectedClass() {
// return selectedClass;
// }
//
// @Override
// public Descriptor<ClassSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ClassSelector) {
// ClassSelector cmp = (ClassSelector)obj;
// return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<ClassSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
// String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
// if (_selectedClass == null) {
// return FormValidation.error("Field is empty");
// }
//
// try {
// Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(_selectedClass);
// } catch (Exception ex) {
// return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
// }
//
// return FormValidation.ok();
// }
// }
// }
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/restrictions/job/JobClassNameRestriction.java
import hudson.model.Queue;
import hudson.model.Run;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
}
@Nonnull
public List<ClassSelector> getJobClasses() {
return jobClasses;
}
@Nonnull
private synchronized Set<String> getAcceptedJobClasses() {
if (acceptedClassesHash == null) {
final List<ClassSelector> selectors = getJobClasses();
acceptedClassesHash = new HashSet<String>(selectors.size());
for (ClassSelector selector : selectors) {
acceptedClassesHash.add(selector.getSelectedClass()); // merge equal entries
}
}
return acceptedClassesHash;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return getAcceptedJobClasses().contains(item.task.getClass().getName());
}
@Override
public boolean canTake(Run run) {
return getAcceptedJobClasses().contains(run.getParent().getClass().getName());
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/NotJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Logic inversion condition.
* @author Oleg Nenashev
*/
public class NotJobRestriction extends JobRestriction {
JobRestriction restriction;
@DataBoundConstructor
public NotJobRestriction(JobRestriction restriction) { | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/NotJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Logic inversion condition.
* @author Oleg Nenashev
*/
public class NotJobRestriction extends JobRestriction {
JobRestriction restriction;
@DataBoundConstructor
public NotJobRestriction(JobRestriction restriction) { | this.restriction = restriction != null ? restriction : DEFAULT; |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/NotJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Logic inversion condition.
* @author Oleg Nenashev
*/
public class NotJobRestriction extends JobRestriction {
JobRestriction restriction;
@DataBoundConstructor
public NotJobRestriction(JobRestriction restriction) {
this.restriction = restriction != null ? restriction : DEFAULT;
}
public JobRestriction getRestriction() {
return restriction;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return !restriction.canTake(item);
}
@Override
public boolean canTake(Run run) {
return !restriction.canTake(run);
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/NotJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Logic inversion condition.
* @author Oleg Nenashev
*/
public class NotJobRestriction extends JobRestriction {
JobRestriction restriction;
@DataBoundConstructor
public NotJobRestriction(JobRestriction restriction) {
this.restriction = restriction != null ? restriction : DEFAULT;
}
public JobRestriction getRestriction() {
return restriction;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return !restriction.canTake(item);
}
@Override
public boolean canTake(Run run) {
return !restriction.canTake(run);
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/test/java/io/jenkins/plugins/jobrestrictions/restrictions/job/JobClassNameRestrictionTest.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/nodes/JobRestrictionProperty.java
// public class JobRestrictionProperty extends NodeProperty<Node> {
//
// /**Restriction according to buildable item requirements*/
// JobRestriction jobRestriction;
//
// @DataBoundConstructor
// public JobRestrictionProperty(JobRestriction jobRestriction) {
// this.jobRestriction = jobRestriction;
// }
//
// @Override
// public CauseOfBlockage canTake(Queue.BuildableItem item) {
// if (jobRestriction != null) {
// if (!jobRestriction.canTake(item)) {
// return JobRestrictionBlockageCause.DEFAULT;
// }
// }
//
// // Can take
// return null;
// }
//
// public JobRestriction getJobRestriction() {
// return jobRestriction;
// }
//
// @Extension
// public static class DescriptorImpl extends NodePropertyDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.nodes_JobRestrictionProperty_DisplayName();
// }
// }
// }
//
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/util/ClassSelector.java
// public class ClassSelector implements Describable<ClassSelector>, Serializable {
//
// /**ID of the user*/
// final @CheckForNull String selectedClass;
//
// @DataBoundConstructor
// public ClassSelector(@CheckForNull String selectedClass) {
// this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
// }
//
// @CheckForNull
// public String getSelectedClass() {
// return selectedClass;
// }
//
// @Override
// public Descriptor<ClassSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ClassSelector) {
// ClassSelector cmp = (ClassSelector)obj;
// return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<ClassSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
// String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
// if (_selectedClass == null) {
// return FormValidation.error("Field is empty");
// }
//
// try {
// Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(_selectedClass);
// } catch (Exception ex) {
// return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
// }
//
// return FormValidation.ok();
// }
// }
// }
| import java.util.Calendar;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import hudson.matrix.MatrixProject;
import hudson.model.Action;
import hudson.model.Queue;
import hudson.model.FreeStyleProject;
import java.util.Arrays; | /*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* 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 io.jenkins.plugins.jobrestrictions.restrictions.job;
/**
* Tests of {@link JobClassNameRestriction}.
* @author Oleg Nenashev
*/
@Issue("JENKINS-38644")
public class JobClassNameRestrictionTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void shouldRestrictJobClass() throws Exception {
JobClassNameRestriction jobClassNameRestriction = new JobClassNameRestriction( | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/nodes/JobRestrictionProperty.java
// public class JobRestrictionProperty extends NodeProperty<Node> {
//
// /**Restriction according to buildable item requirements*/
// JobRestriction jobRestriction;
//
// @DataBoundConstructor
// public JobRestrictionProperty(JobRestriction jobRestriction) {
// this.jobRestriction = jobRestriction;
// }
//
// @Override
// public CauseOfBlockage canTake(Queue.BuildableItem item) {
// if (jobRestriction != null) {
// if (!jobRestriction.canTake(item)) {
// return JobRestrictionBlockageCause.DEFAULT;
// }
// }
//
// // Can take
// return null;
// }
//
// public JobRestriction getJobRestriction() {
// return jobRestriction;
// }
//
// @Extension
// public static class DescriptorImpl extends NodePropertyDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.nodes_JobRestrictionProperty_DisplayName();
// }
// }
// }
//
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/util/ClassSelector.java
// public class ClassSelector implements Describable<ClassSelector>, Serializable {
//
// /**ID of the user*/
// final @CheckForNull String selectedClass;
//
// @DataBoundConstructor
// public ClassSelector(@CheckForNull String selectedClass) {
// this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
// }
//
// @CheckForNull
// public String getSelectedClass() {
// return selectedClass;
// }
//
// @Override
// public Descriptor<ClassSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ClassSelector) {
// ClassSelector cmp = (ClassSelector)obj;
// return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<ClassSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
// String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
// if (_selectedClass == null) {
// return FormValidation.error("Field is empty");
// }
//
// try {
// Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(_selectedClass);
// } catch (Exception ex) {
// return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
// }
//
// return FormValidation.ok();
// }
// }
// }
// Path: src/test/java/io/jenkins/plugins/jobrestrictions/restrictions/job/JobClassNameRestrictionTest.java
import java.util.Calendar;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import hudson.matrix.MatrixProject;
import hudson.model.Action;
import hudson.model.Queue;
import hudson.model.FreeStyleProject;
import java.util.Arrays;
/*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* 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 io.jenkins.plugins.jobrestrictions.restrictions.job;
/**
* Tests of {@link JobClassNameRestriction}.
* @author Oleg Nenashev
*/
@Issue("JENKINS-38644")
public class JobClassNameRestrictionTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void shouldRestrictJobClass() throws Exception {
JobClassNameRestriction jobClassNameRestriction = new JobClassNameRestriction( | Arrays.asList(new ClassSelector(FreeStyleProject.class.getName()))); |
jenkinsci/job-restrictions-plugin | src/test/java/io/jenkins/plugins/jobrestrictions/restrictions/job/JobClassNameRestrictionTest.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/nodes/JobRestrictionProperty.java
// public class JobRestrictionProperty extends NodeProperty<Node> {
//
// /**Restriction according to buildable item requirements*/
// JobRestriction jobRestriction;
//
// @DataBoundConstructor
// public JobRestrictionProperty(JobRestriction jobRestriction) {
// this.jobRestriction = jobRestriction;
// }
//
// @Override
// public CauseOfBlockage canTake(Queue.BuildableItem item) {
// if (jobRestriction != null) {
// if (!jobRestriction.canTake(item)) {
// return JobRestrictionBlockageCause.DEFAULT;
// }
// }
//
// // Can take
// return null;
// }
//
// public JobRestriction getJobRestriction() {
// return jobRestriction;
// }
//
// @Extension
// public static class DescriptorImpl extends NodePropertyDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.nodes_JobRestrictionProperty_DisplayName();
// }
// }
// }
//
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/util/ClassSelector.java
// public class ClassSelector implements Describable<ClassSelector>, Serializable {
//
// /**ID of the user*/
// final @CheckForNull String selectedClass;
//
// @DataBoundConstructor
// public ClassSelector(@CheckForNull String selectedClass) {
// this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
// }
//
// @CheckForNull
// public String getSelectedClass() {
// return selectedClass;
// }
//
// @Override
// public Descriptor<ClassSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ClassSelector) {
// ClassSelector cmp = (ClassSelector)obj;
// return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<ClassSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
// String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
// if (_selectedClass == null) {
// return FormValidation.error("Field is empty");
// }
//
// try {
// Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(_selectedClass);
// } catch (Exception ex) {
// return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
// }
//
// return FormValidation.ok();
// }
// }
// }
| import java.util.Calendar;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import hudson.matrix.MatrixProject;
import hudson.model.Action;
import hudson.model.Queue;
import hudson.model.FreeStyleProject;
import java.util.Arrays; | /*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* 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 io.jenkins.plugins.jobrestrictions.restrictions.job;
/**
* Tests of {@link JobClassNameRestriction}.
* @author Oleg Nenashev
*/
@Issue("JENKINS-38644")
public class JobClassNameRestrictionTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void shouldRestrictJobClass() throws Exception {
JobClassNameRestriction jobClassNameRestriction = new JobClassNameRestriction(
Arrays.asList(new ClassSelector(FreeStyleProject.class.getName()))); | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/nodes/JobRestrictionProperty.java
// public class JobRestrictionProperty extends NodeProperty<Node> {
//
// /**Restriction according to buildable item requirements*/
// JobRestriction jobRestriction;
//
// @DataBoundConstructor
// public JobRestrictionProperty(JobRestriction jobRestriction) {
// this.jobRestriction = jobRestriction;
// }
//
// @Override
// public CauseOfBlockage canTake(Queue.BuildableItem item) {
// if (jobRestriction != null) {
// if (!jobRestriction.canTake(item)) {
// return JobRestrictionBlockageCause.DEFAULT;
// }
// }
//
// // Can take
// return null;
// }
//
// public JobRestriction getJobRestriction() {
// return jobRestriction;
// }
//
// @Extension
// public static class DescriptorImpl extends NodePropertyDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.nodes_JobRestrictionProperty_DisplayName();
// }
// }
// }
//
// Path: src/main/java/io/jenkins/plugins/jobrestrictions/util/ClassSelector.java
// public class ClassSelector implements Describable<ClassSelector>, Serializable {
//
// /**ID of the user*/
// final @CheckForNull String selectedClass;
//
// @DataBoundConstructor
// public ClassSelector(@CheckForNull String selectedClass) {
// this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
// }
//
// @CheckForNull
// public String getSelectedClass() {
// return selectedClass;
// }
//
// @Override
// public Descriptor<ClassSelector> getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ClassSelector) {
// ClassSelector cmp = (ClassSelector)obj;
// return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
// return hash;
// }
//
// @Extension
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
// public static class DescriptorImpl extends Descriptor<ClassSelector> {
//
// @Override
// public String getDisplayName() {
// return "N/A";
// }
//
// public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
// String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
// if (_selectedClass == null) {
// return FormValidation.error("Field is empty");
// }
//
// try {
// Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(_selectedClass);
// } catch (Exception ex) {
// return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
// }
//
// return FormValidation.ok();
// }
// }
// }
// Path: src/test/java/io/jenkins/plugins/jobrestrictions/restrictions/job/JobClassNameRestrictionTest.java
import java.util.Calendar;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import hudson.matrix.MatrixProject;
import hudson.model.Action;
import hudson.model.Queue;
import hudson.model.FreeStyleProject;
import java.util.Arrays;
/*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* 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 io.jenkins.plugins.jobrestrictions.restrictions.job;
/**
* Tests of {@link JobClassNameRestriction}.
* @author Oleg Nenashev
*/
@Issue("JENKINS-38644")
public class JobClassNameRestrictionTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void shouldRestrictJobClass() throws Exception {
JobClassNameRestriction jobClassNameRestriction = new JobClassNameRestriction(
Arrays.asList(new ClassSelector(FreeStyleProject.class.getName()))); | JobRestrictionProperty prop = new JobRestrictionProperty(jobClassNameRestriction); |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AnyJobRestriction.java
// public class AnyJobRestriction extends JobRestriction {
// @DataBoundConstructor
// public AnyJobRestriction() {
// }
//
// @Override
// public boolean canTake(Queue.BuildableItem item) {
// return true;
// }
//
// @Override
// public boolean canTake(Run run) {
// return true;
// }
//
// @Extension(ordinal = 1000)
// public static class DescriptorImpl extends JobRestrictionDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.restrictions_Logic_Any();
// }
// }
// }
| import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic.AnyJobRestriction;
import hudson.model.Descriptor; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions;
/**
* Descriptor class for {@link JobRestriction}s.
* @author Oleg Nenashev
*/
public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
public JobRestrictionDescriptor getDefaultSettingsProvider() { | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AnyJobRestriction.java
// public class AnyJobRestriction extends JobRestriction {
// @DataBoundConstructor
// public AnyJobRestriction() {
// }
//
// @Override
// public boolean canTake(Queue.BuildableItem item) {
// return true;
// }
//
// @Override
// public boolean canTake(Run run) {
// return true;
// }
//
// @Extension(ordinal = 1000)
// public static class DescriptorImpl extends JobRestrictionDescriptor {
// @Override
// public String getDisplayName() {
// return Messages.restrictions_Logic_Any();
// }
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic.AnyJobRestriction;
import hudson.model.Descriptor;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions;
/**
* Descriptor class for {@link JobRestriction}s.
* @author Oleg Nenashev
*/
public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
public JobRestrictionDescriptor getDefaultSettingsProvider() { | return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class); |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AnyJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import org.kohsuke.stapler.DataBoundConstructor; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Takes any job.
* @author Oleg Nenashev
*/
public class AnyJobRestriction extends JobRestriction {
@DataBoundConstructor
public AnyJobRestriction() {
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return true;
}
@Override
public boolean canTake(Run run) {
return true;
}
@Extension(ordinal = 1000) | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AnyJobRestriction.java
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import org.kohsuke.stapler.DataBoundConstructor;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Takes any job.
* @author Oleg Nenashev
*/
public class AnyJobRestriction extends JobRestriction {
@DataBoundConstructor
public AnyJobRestriction() {
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return true;
}
@Override
public boolean canTake(Run run) {
return true;
}
@Extension(ordinal = 1000) | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/MultipleOrJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import java.util.ArrayList; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Implements "Or" condition with multiple entries.
* @author Oleg Nenashev
* @since 0.2
*/
public class MultipleOrJobRestriction extends JobRestriction {
private final ArrayList<JobRestriction> restrictions;
@DataBoundConstructor
public MultipleOrJobRestriction(ArrayList<JobRestriction> restrictions) {
this.restrictions = restrictions != null ? restrictions : new ArrayList<JobRestriction>();
}
public ArrayList<JobRestriction> getRestrictions() {
return restrictions;
}
@Override
public boolean canTake(Run run) {
for (JobRestriction restriction : restrictions) {
if (restriction.canTake(run)) {
return true;
}
}
return false;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
for (JobRestriction restriction : restrictions) {
if (restriction.canTake(item)) {
return true;
}
}
return false;
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/MultipleOrJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import java.util.ArrayList;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Implements "Or" condition with multiple entries.
* @author Oleg Nenashev
* @since 0.2
*/
public class MultipleOrJobRestriction extends JobRestriction {
private final ArrayList<JobRestriction> restrictions;
@DataBoundConstructor
public MultipleOrJobRestriction(ArrayList<JobRestriction> restrictions) {
this.restrictions = restrictions != null ? restrictions : new ArrayList<JobRestriction>();
}
public ArrayList<JobRestriction> getRestrictions() {
return restrictions;
}
@Override
public boolean canTake(Run run) {
for (JobRestriction restriction : restrictions) {
if (restriction.canTake(run)) {
return true;
}
}
return false;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
for (JobRestriction restriction : restrictions) {
if (restriction.canTake(item)) {
return true;
}
}
return false;
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/RegexNameRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/QueueHelper.java
// @Restricted(NoExternalUse.class)
// public class QueueHelper {
//
// //TODO: Optimize by StringBuilder
// /**
// * Generates job-style project name for the buildable item
// * @deprecated Just a hack, will be removed in the future versions
// * @param item Item, for which the name should be retrieved
// * @return String in the {@link Job#getFullName()} format (a/b/c/d)
// */
// @Deprecated
// public static String getFullName(@Nonnull Queue.BuildableItem item) {
// Queue.Task current = item.task;
// String res = getItemName(current);
//
// // this is only executed if we didn't call Item.getFullName() in getItemName
// while (!(current instanceof Item)) {
// Queue.Task parent = current.getOwnerTask();
// if (parent == current || parent == null) {
// break;
// }
// res = getItemName(parent) + "/" + res;
// current = parent;
// }
// return res;
// }
//
// private static String getItemName(Queue.Task task) {
// if (task instanceof Item) {
// Item stub = (Item)task;
// return stub.getFullName();
// } else {
// return task.getName();
// }
// }
// }
| import hudson.util.FormValidation;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.QueueHelper;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.job;
/**
* Restricts the jobs execution by applying regular expressions to their names.
* @author Oleg Nenashev
*/
public class RegexNameRestriction extends JobRestriction {
String regexExpression;
boolean checkShortName;
@DataBoundConstructor
public RegexNameRestriction(String regexExpression, boolean checkShortName) {
this.regexExpression = regexExpression;
this.checkShortName = checkShortName;
}
public String getRegexExpression() {
return regexExpression;
}
public boolean isCheckShortName() {
return checkShortName;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
//FIXME: switch to the "getFullName" in the future | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/QueueHelper.java
// @Restricted(NoExternalUse.class)
// public class QueueHelper {
//
// //TODO: Optimize by StringBuilder
// /**
// * Generates job-style project name for the buildable item
// * @deprecated Just a hack, will be removed in the future versions
// * @param item Item, for which the name should be retrieved
// * @return String in the {@link Job#getFullName()} format (a/b/c/d)
// */
// @Deprecated
// public static String getFullName(@Nonnull Queue.BuildableItem item) {
// Queue.Task current = item.task;
// String res = getItemName(current);
//
// // this is only executed if we didn't call Item.getFullName() in getItemName
// while (!(current instanceof Item)) {
// Queue.Task parent = current.getOwnerTask();
// if (parent == current || parent == null) {
// break;
// }
// res = getItemName(parent) + "/" + res;
// current = parent;
// }
// return res;
// }
//
// private static String getItemName(Queue.Task task) {
// if (task instanceof Item) {
// Item stub = (Item)task;
// return stub.getFullName();
// } else {
// return task.getName();
// }
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/RegexNameRestriction.java
import hudson.util.FormValidation;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.QueueHelper;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.job;
/**
* Restricts the jobs execution by applying regular expressions to their names.
* @author Oleg Nenashev
*/
public class RegexNameRestriction extends JobRestriction {
String regexExpression;
boolean checkShortName;
@DataBoundConstructor
public RegexNameRestriction(String regexExpression, boolean checkShortName) {
this.regexExpression = regexExpression;
this.checkShortName = checkShortName;
}
public String getRegexExpression() {
return regexExpression;
}
public boolean isCheckShortName() {
return checkShortName;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
//FIXME: switch to the "getFullName" in the future | return canTake(QueueHelper.getFullName(item)); |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/RegexNameRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/QueueHelper.java
// @Restricted(NoExternalUse.class)
// public class QueueHelper {
//
// //TODO: Optimize by StringBuilder
// /**
// * Generates job-style project name for the buildable item
// * @deprecated Just a hack, will be removed in the future versions
// * @param item Item, for which the name should be retrieved
// * @return String in the {@link Job#getFullName()} format (a/b/c/d)
// */
// @Deprecated
// public static String getFullName(@Nonnull Queue.BuildableItem item) {
// Queue.Task current = item.task;
// String res = getItemName(current);
//
// // this is only executed if we didn't call Item.getFullName() in getItemName
// while (!(current instanceof Item)) {
// Queue.Task parent = current.getOwnerTask();
// if (parent == current || parent == null) {
// break;
// }
// res = getItemName(parent) + "/" + res;
// current = parent;
// }
// return res;
// }
//
// private static String getItemName(Queue.Task task) {
// if (task instanceof Item) {
// Item stub = (Item)task;
// return stub.getFullName();
// } else {
// return task.getName();
// }
// }
// }
| import hudson.util.FormValidation;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.QueueHelper;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | }
public String getRegexExpression() {
return regexExpression;
}
public boolean isCheckShortName() {
return checkShortName;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
//FIXME: switch to the "getFullName" in the future
return canTake(QueueHelper.getFullName(item));
}
@Override
public boolean canTake(Run run) {
return canTake(run.getParent().getFullName());
}
public boolean canTake(String projectName) {
try {
return projectName.matches(regexExpression);
} catch (PatternSyntaxException ex) {
return true; // Ignore invalid pattern
}
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/util/QueueHelper.java
// @Restricted(NoExternalUse.class)
// public class QueueHelper {
//
// //TODO: Optimize by StringBuilder
// /**
// * Generates job-style project name for the buildable item
// * @deprecated Just a hack, will be removed in the future versions
// * @param item Item, for which the name should be retrieved
// * @return String in the {@link Job#getFullName()} format (a/b/c/d)
// */
// @Deprecated
// public static String getFullName(@Nonnull Queue.BuildableItem item) {
// Queue.Task current = item.task;
// String res = getItemName(current);
//
// // this is only executed if we didn't call Item.getFullName() in getItemName
// while (!(current instanceof Item)) {
// Queue.Task parent = current.getOwnerTask();
// if (parent == current || parent == null) {
// break;
// }
// res = getItemName(parent) + "/" + res;
// current = parent;
// }
// return res;
// }
//
// private static String getItemName(Queue.Task task) {
// if (task instanceof Item) {
// Item stub = (Item)task;
// return stub.getFullName();
// } else {
// return task.getName();
// }
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/job/RegexNameRestriction.java
import hudson.util.FormValidation;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.util.QueueHelper;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
}
public String getRegexExpression() {
return regexExpression;
}
public boolean isCheckShortName() {
return checkShortName;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
//FIXME: switch to the "getFullName" in the future
return canTake(QueueHelper.getFullName(item));
}
@Override
public boolean canTake(Run run) {
return canTake(run.getParent().getFullName());
}
public boolean canTake(String projectName) {
try {
return projectName.matches(regexExpression);
} catch (PatternSyntaxException ex) {
return true; // Ignore invalid pattern
}
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AndJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Virtual job restriction, which allows to check two restrictions at once.
* @author Oleg Nenashev
* @see MultipleAndJobRestriction
*/
public class AndJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public AndJobRestriction(JobRestriction first, JobRestriction second) { | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AndJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Virtual job restriction, which allows to check two restrictions at once.
* @author Oleg Nenashev
* @see MultipleAndJobRestriction
*/
public class AndJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public AndJobRestriction(JobRestriction first, JobRestriction second) { | this.first = first != null ? first : DEFAULT; |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AndJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Virtual job restriction, which allows to check two restrictions at once.
* @author Oleg Nenashev
* @see MultipleAndJobRestriction
*/
public class AndJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public AndJobRestriction(JobRestriction first, JobRestriction second) {
this.first = first != null ? first : DEFAULT;
this.second = second != null ? second : DEFAULT;
}
public JobRestriction getFirst() {
return first;
}
public JobRestriction getSecond() {
return second;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return first.canTake(item) && second.canTake(item);
}
@Override
public boolean canTake(Run run) {
return first.canTake(run) && second.canTake(run);
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/AndJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import static com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction.DEFAULT;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Virtual job restriction, which allows to check two restrictions at once.
* @author Oleg Nenashev
* @see MultipleAndJobRestriction
*/
public class AndJobRestriction extends JobRestriction {
JobRestriction first;
JobRestriction second;
@DataBoundConstructor
public AndJobRestriction(JobRestriction first, JobRestriction second) {
this.first = first != null ? first : DEFAULT;
this.second = second != null ? second : DEFAULT;
}
public JobRestriction getFirst() {
return first;
}
public JobRestriction getSecond() {
return second;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
return first.canTake(item) && second.canTake(item);
}
@Override
public boolean canTake(Run run) {
return first.canTake(run) && second.canTake(run);
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
jenkinsci/job-restrictions-plugin | src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/MultipleAndJobRestriction.java | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
| import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import java.util.ArrayList; | /*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Implements "And" condition with multiple entries.
* @author Oleg Nenashev
* @since 0.2
*/
public class MultipleAndJobRestriction extends JobRestriction {
private final ArrayList<JobRestriction> restrictions;
@DataBoundConstructor
public MultipleAndJobRestriction(ArrayList<JobRestriction> restrictions) {
this.restrictions = restrictions != null ? restrictions : new ArrayList<JobRestriction>();
}
public ArrayList<JobRestriction> getRestrictions() {
return restrictions;
}
@Override
public boolean canTake(Run run) {
for (JobRestriction restriction : restrictions) {
if (!restriction.canTake(run)) {
return false;
}
}
return true;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
for (JobRestriction restriction : restrictions) {
if (!restriction.canTake(item)) {
return false;
}
}
return true;
}
@Extension | // Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestriction.java
// public abstract class JobRestriction implements ExtensionPoint, Describable<JobRestriction>, Serializable {
//
// public static final JobRestriction DEFAULT = new AnyJobRestriction();
//
// /**
// * Check if the {@link Queue} item can be taken.
// * This method is being used to check if the {@link Node} can take the
// * specified job. If the job cannot be taken, Jenkins will try to launch
// * the job on other nodes.
// * @param item An item to be checked
// * @return true if the node can take the item
// */
// public abstract boolean canTake(@Nonnull Queue.BuildableItem item);
//
// /**
// * Check if the {@link Job} can be executed according to the specified {@link Run}.
// * If the job cannot be executed, it will be aborted by the plugin.
// * @param run A {@link Run} to be checked
// * @return true if the build can be executed
// */
// public abstract boolean canTake(@Nonnull Run run);
//
// @Override
// public JobRestrictionDescriptor getDescriptor() {
// return (JobRestrictionDescriptor) JenkinsHelper.getInstanceOrDie().getDescriptorOrDie(getClass());
// }
//
// /**
// * Get list of all registered {@link JobRestriction}s.
// * @return List of {@link JobRestriction}s.
// */
// public static DescriptorExtensionList<JobRestriction,JobRestrictionDescriptor> all() {
// return JenkinsHelper.getInstanceOrDie().<JobRestriction,JobRestrictionDescriptor>getDescriptorList
// (JobRestriction.class);
// }
//
// /**
// * Returns list of {@link JobRestrictionDescriptor}s.
// * @return List of available descriptors.
// * @since 0.2
// */
// public static List<JobRestrictionDescriptor> allDescriptors() {
// return all().reverseView();
// }
//
// }
//
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/JobRestrictionDescriptor.java
// public abstract class JobRestrictionDescriptor extends Descriptor<JobRestriction> {
// public JobRestrictionDescriptor getDefaultSettingsProvider() {
// return (JobRestrictionDescriptor)JobRestriction.all().find(AnyJobRestriction.class);
// }
// }
// Path: src/main/java/com/synopsys/arc/jenkinsci/plugins/jobrestrictions/restrictions/logic/MultipleAndJobRestriction.java
import org.kohsuke.stapler.DataBoundConstructor;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import java.util.ArrayList;
/*
* The MIT License
*
* Copyright 2013-2016 Oleg Nenashev, Synopsys Inc.
*
* 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 com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.logic;
/**
* Implements "And" condition with multiple entries.
* @author Oleg Nenashev
* @since 0.2
*/
public class MultipleAndJobRestriction extends JobRestriction {
private final ArrayList<JobRestriction> restrictions;
@DataBoundConstructor
public MultipleAndJobRestriction(ArrayList<JobRestriction> restrictions) {
this.restrictions = restrictions != null ? restrictions : new ArrayList<JobRestriction>();
}
public ArrayList<JobRestriction> getRestrictions() {
return restrictions;
}
@Override
public boolean canTake(Run run) {
for (JobRestriction restriction : restrictions) {
if (!restriction.canTake(run)) {
return false;
}
}
return true;
}
@Override
public boolean canTake(Queue.BuildableItem item) {
for (JobRestriction restriction : restrictions) {
if (!restriction.canTake(item)) {
return false;
}
}
return true;
}
@Extension | public static class DescriptorImpl extends JobRestrictionDescriptor { |
Mauin/RxFingerprint | rxfingerprint/src/test/java/com/mtramin/rxfingerprint/RsaEncryptionObservableTest.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.crypto.Cipher;
import io.reactivex.Observable; | /*
* Copyright 2017 Marvin Ramin.
*
* 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.mtramin.rxfingerprint;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Cipher.class)
public class RsaEncryptionObservableTest {
private static final String INPUT = "TEST";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock RsaCipherProvider cipherProvider;
Cipher cipher;
| // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/test/java/com/mtramin/rxfingerprint/RsaEncryptionObservableTest.java
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.crypto.Cipher;
import io.reactivex.Observable;
/*
* Copyright 2017 Marvin Ramin.
*
* 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.mtramin.rxfingerprint;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Cipher.class)
public class RsaEncryptionObservableTest {
private static final String INPUT = "TEST";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock RsaCipherProvider cipherProvider;
Cipher cipher;
| private Observable<FingerprintEncryptionResult> observable; |
Mauin/RxFingerprint | rxfingerprint/src/test/java/com/mtramin/rxfingerprint/RsaEncryptionObservableTest.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.crypto.Cipher;
import io.reactivex.Observable; | /*
* Copyright 2017 Marvin Ramin.
*
* 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.mtramin.rxfingerprint;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Cipher.class)
public class RsaEncryptionObservableTest {
private static final String INPUT = "TEST";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock RsaCipherProvider cipherProvider;
Cipher cipher;
private Observable<FingerprintEncryptionResult> observable;
@Before
public void setUp() throws Exception {
mockStatic(Cipher.class);
cipher = mock(Cipher.class);
RxFingerprint.disableLogging();
observable = Observable.create(new RsaEncryptionObservable(fingerprintApiWrapper, cipherProvider, INPUT.toCharArray(), new TestEncodingProvider()));
}
@Test
public void blocksEncryptionWhenFingerprintUnavailable() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(true);
observable.test()
.assertNoValues() | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/test/java/com/mtramin/rxfingerprint/RsaEncryptionObservableTest.java
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.crypto.Cipher;
import io.reactivex.Observable;
/*
* Copyright 2017 Marvin Ramin.
*
* 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.mtramin.rxfingerprint;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Cipher.class)
public class RsaEncryptionObservableTest {
private static final String INPUT = "TEST";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock RsaCipherProvider cipherProvider;
Cipher cipher;
private Observable<FingerprintEncryptionResult> observable;
@Before
public void setUp() throws Exception {
mockStatic(Cipher.class);
cipher = mock(Cipher.class);
RxFingerprint.disableLogging();
observable = Observable.create(new RsaEncryptionObservable(fingerprintApiWrapper, cipherProvider, INPUT.toCharArray(), new TestEncodingProvider()));
}
@Test
public void blocksEncryptionWhenFingerprintUnavailable() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(true);
observable.test()
.assertNoValues() | .assertError(FingerprintUnavailableException.class); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/AesDecryptionObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintDecryptionResult.java
// public class FingerprintDecryptionResult extends FingerprintAuthenticationResult {
//
// private final char[] decrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message message to be displayed to the user
// * @param decrypted decrypted data
// */
// public FingerprintDecryptionResult(FingerprintResult result, String message, char[] decrypted) {
// super(result, message);
// this.decrypted = decrypted;
// }
//
// /**
// * @return decrypted data as a String. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public String getDecrypted() {
// return new String(getDecryptedChars());
// }
//
// /**
// * @return decrypted data as a char[]. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public char[] getDecryptedChars() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access decryption result");
// }
// return decrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import com.mtramin.rxfingerprint.data.FingerprintDecryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter; | private AesDecryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
AesCipherProvider cipherProvider,
String encrypted,
EncodingProvider encodingProvider) {
super(fingerprintApiWrapper);
this.cipherProvider = cipherProvider;
encryptedString = encrypted;
this.encodingProvider = encodingProvider;
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintDecryptionResult> subscriber) {
try {
CryptoData cryptoData = CryptoData.fromString(encodingProvider, encryptedString);
Cipher cipher = cipherProvider.getCipherForDecryption(cryptoData.getIv());
return new CryptoObject(cipher);
} catch (Exception e) {
subscriber.onError(e);
return null;
}
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintDecryptionResult> emitter, AuthenticationResult result) {
try {
CryptoData cryptoData = CryptoData.fromString(encodingProvider, encryptedString);
Cipher cipher = result.getCryptoObject().getCipher();
byte[] bytes = cipher.doFinal(cryptoData.getMessage());
| // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintDecryptionResult.java
// public class FingerprintDecryptionResult extends FingerprintAuthenticationResult {
//
// private final char[] decrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message message to be displayed to the user
// * @param decrypted decrypted data
// */
// public FingerprintDecryptionResult(FingerprintResult result, String message, char[] decrypted) {
// super(result, message);
// this.decrypted = decrypted;
// }
//
// /**
// * @return decrypted data as a String. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public String getDecrypted() {
// return new String(getDecryptedChars());
// }
//
// /**
// * @return decrypted data as a char[]. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public char[] getDecryptedChars() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access decryption result");
// }
// return decrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/AesDecryptionObservable.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import com.mtramin.rxfingerprint.data.FingerprintDecryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
private AesDecryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
AesCipherProvider cipherProvider,
String encrypted,
EncodingProvider encodingProvider) {
super(fingerprintApiWrapper);
this.cipherProvider = cipherProvider;
encryptedString = encrypted;
this.encodingProvider = encodingProvider;
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintDecryptionResult> subscriber) {
try {
CryptoData cryptoData = CryptoData.fromString(encodingProvider, encryptedString);
Cipher cipher = cipherProvider.getCipherForDecryption(cryptoData.getIv());
return new CryptoObject(cipher);
} catch (Exception e) {
subscriber.onError(e);
return null;
}
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintDecryptionResult> emitter, AuthenticationResult result) {
try {
CryptoData cryptoData = CryptoData.fromString(encodingProvider, encryptedString);
Cipher cipher = result.getCryptoObject().getCipher();
byte[] bytes = cipher.doFinal(cryptoData.getMessage());
| emitter.onNext(new FingerprintDecryptionResult(FingerprintResult.AUTHENTICATED, null, ConversionUtils.toChars(bytes))); |
Mauin/RxFingerprint | rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mtramin.rxfingerprint;
/**
* Tests for the Fingerprint authentication observable
*/
@SuppressWarnings({"NewApi", "MissingPermission"})
@RunWith(MockitoJUnitRunner.class)
public class FingerprintAuthenticationTest {
private static final String ERROR_MESSAGE = "Error message";
private static final CharSequence MESSAGE_HELP = "Help message";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock FingerprintManager fingerprintManager;
@Mock CancellationSignal cancellationSignal;
| // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mtramin.rxfingerprint;
/**
* Tests for the Fingerprint authentication observable
*/
@SuppressWarnings({"NewApi", "MissingPermission"})
@RunWith(MockitoJUnitRunner.class)
public class FingerprintAuthenticationTest {
private static final String ERROR_MESSAGE = "Error message";
private static final CharSequence MESSAGE_HELP = "Help message";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock FingerprintManager fingerprintManager;
@Mock CancellationSignal cancellationSignal;
| Observable<FingerprintAuthenticationResult> observable; |
Mauin/RxFingerprint | rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.mtramin.rxfingerprint;
/**
* Tests for the Fingerprint authentication observable
*/
@SuppressWarnings({"NewApi", "MissingPermission"})
@RunWith(MockitoJUnitRunner.class)
public class FingerprintAuthenticationTest {
private static final String ERROR_MESSAGE = "Error message";
private static final CharSequence MESSAGE_HELP = "Help message";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock FingerprintManager fingerprintManager;
@Mock CancellationSignal cancellationSignal;
Observable<FingerprintAuthenticationResult> observable;
@Before
public void setUp() throws Exception {
when(fingerprintApiWrapper.createCancellationSignal()).thenReturn(cancellationSignal);
observable = Observable.create(new FingerprintAuthenticationObservable(fingerprintApiWrapper));
}
@Test
public void testFingerprintNotAvailable() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(true);
observable.test()
.assertNoValues() | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.mtramin.rxfingerprint;
/**
* Tests for the Fingerprint authentication observable
*/
@SuppressWarnings({"NewApi", "MissingPermission"})
@RunWith(MockitoJUnitRunner.class)
public class FingerprintAuthenticationTest {
private static final String ERROR_MESSAGE = "Error message";
private static final CharSequence MESSAGE_HELP = "Help message";
@Mock FingerprintApiWrapper fingerprintApiWrapper;
@Mock FingerprintManager fingerprintManager;
@Mock CancellationSignal cancellationSignal;
Observable<FingerprintAuthenticationResult> observable;
@Before
public void setUp() throws Exception {
when(fingerprintApiWrapper.createCancellationSignal()).thenReturn(cancellationSignal);
observable = Observable.create(new FingerprintAuthenticationObservable(fingerprintApiWrapper));
}
@Test
public void testFingerprintNotAvailable() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(true);
observable.test()
.assertNoValues() | .assertError(FingerprintUnavailableException.class); |
Mauin/RxFingerprint | rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | }
@Test
public void testFingerprintNotAvailable() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(true);
observable.test()
.assertNoValues()
.assertError(FingerprintUnavailableException.class);
}
@Test
public void testAuthenticationSuccessful() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(false);
when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager);
AuthenticationResult result = mock(AuthenticationResult.class);
TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();
ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
callbackCaptor.getValue().onAuthenticationSucceeded(result);
testObserver.awaitTerminalEvent();
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
FingerprintAuthenticationResult fingerprintAuthenticationResult = testObserver.values().get(0);
assertTrue("Authentication should be successful", fingerprintAuthenticationResult.isSuccess()); | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
}
@Test
public void testFingerprintNotAvailable() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(true);
observable.test()
.assertNoValues()
.assertError(FingerprintUnavailableException.class);
}
@Test
public void testAuthenticationSuccessful() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(false);
when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager);
AuthenticationResult result = mock(AuthenticationResult.class);
TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();
ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
callbackCaptor.getValue().onAuthenticationSucceeded(result);
testObserver.awaitTerminalEvent();
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
FingerprintAuthenticationResult fingerprintAuthenticationResult = testObserver.values().get(0);
assertTrue("Authentication should be successful", fingerprintAuthenticationResult.isSuccess()); | assertTrue("Result should be equal AUTHENTICATED", fingerprintAuthenticationResult.getResult().equals(FingerprintResult.AUTHENTICATED)); |
Mauin/RxFingerprint | rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | AuthenticationResult result = mock(AuthenticationResult.class);
TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();
ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
callbackCaptor.getValue().onAuthenticationSucceeded(result);
testObserver.awaitTerminalEvent();
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
FingerprintAuthenticationResult fingerprintAuthenticationResult = testObserver.values().get(0);
assertTrue("Authentication should be successful", fingerprintAuthenticationResult.isSuccess());
assertTrue("Result should be equal AUTHENTICATED", fingerprintAuthenticationResult.getResult().equals(FingerprintResult.AUTHENTICATED));
assertTrue("Should contain no message", fingerprintAuthenticationResult.getMessage() == null);
}
@Test
public void testAuthenticationError() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(false);
when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager);
TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();
ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
callbackCaptor.getValue().onAuthenticationError(0, ERROR_MESSAGE);
testObserver.awaitTerminalEvent(); | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/test/java/com/mtramin/rxfingerprint/FingerprintAuthenticationTest.java
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.CancellationSignal;
import android.os.Handler;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
AuthenticationResult result = mock(AuthenticationResult.class);
TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();
ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
callbackCaptor.getValue().onAuthenticationSucceeded(result);
testObserver.awaitTerminalEvent();
testObserver.assertNoErrors();
testObserver.assertComplete();
testObserver.assertValueCount(1);
FingerprintAuthenticationResult fingerprintAuthenticationResult = testObserver.values().get(0);
assertTrue("Authentication should be successful", fingerprintAuthenticationResult.isSuccess());
assertTrue("Result should be equal AUTHENTICATED", fingerprintAuthenticationResult.getResult().equals(FingerprintResult.AUTHENTICATED));
assertTrue("Should contain no message", fingerprintAuthenticationResult.getMessage() == null);
}
@Test
public void testAuthenticationError() throws Exception {
when(fingerprintApiWrapper.isUnavailable()).thenReturn(false);
when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager);
TestObserver<FingerprintAuthenticationResult> testObserver = observable.test();
ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class);
verify(fingerprintManager).authenticate(any(CryptoObject.class), any(CancellationSignal.class), anyInt(), callbackCaptor.capture(), any(Handler.class));
callbackCaptor.getValue().onAuthenticationError(0, ERROR_MESSAGE);
testObserver.awaitTerminalEvent(); | testObserver.assertError(FingerprintAuthenticationException.class); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/FingerprintObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import io.reactivex.Emitter;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Cancellable;
import static android.Manifest.permission.USE_FINGERPRINT;
import android.annotation.SuppressLint;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.Build;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RequiresPermission;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException; | /*
* Copyright 2015 Marvin Ramin
*
* 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.mtramin.rxfingerprint;
/**
* Base observable for Fingerprint authentication. Provides abstract methods that allow
* to alter the input and result of the authentication.
*/
@SuppressLint("NewApi") // SDK check happens in {@link FingerprintObservable#subscribe}
abstract class FingerprintObservable<T> implements ObservableOnSubscribe<T> {
private final FingerprintApiWrapper fingerprintApiWrapper;
CancellationSignal cancellationSignal;
/**
* Default constructor for fingerprint authentication
*
* @param context Context to be used for the fingerprint authentication
*/
FingerprintObservable(FingerprintApiWrapper fingerprintApiWrapper) {
this.fingerprintApiWrapper = fingerprintApiWrapper;
}
@Override
@RequiresPermission(USE_FINGERPRINT)
@RequiresApi(Build.VERSION_CODES.M)
public void subscribe(ObservableEmitter<T> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) { | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/FingerprintObservable.java
import io.reactivex.Emitter;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Cancellable;
import static android.Manifest.permission.USE_FINGERPRINT;
import android.annotation.SuppressLint;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.Build;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RequiresPermission;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
/*
* Copyright 2015 Marvin Ramin
*
* 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.mtramin.rxfingerprint;
/**
* Base observable for Fingerprint authentication. Provides abstract methods that allow
* to alter the input and result of the authentication.
*/
@SuppressLint("NewApi") // SDK check happens in {@link FingerprintObservable#subscribe}
abstract class FingerprintObservable<T> implements ObservableOnSubscribe<T> {
private final FingerprintApiWrapper fingerprintApiWrapper;
CancellationSignal cancellationSignal;
/**
* Default constructor for fingerprint authentication
*
* @param context Context to be used for the fingerprint authentication
*/
FingerprintObservable(FingerprintApiWrapper fingerprintApiWrapper) {
this.fingerprintApiWrapper = fingerprintApiWrapper;
}
@Override
@RequiresPermission(USE_FINGERPRINT)
@RequiresApi(Build.VERSION_CODES.M)
public void subscribe(ObservableEmitter<T> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) { | emitter.onError(new FingerprintUnavailableException("Fingerprint authentication is not available on this device! Ensure that the device has a Fingerprint sensor and enrolled Fingerprints by calling RxFingerprint#isAvailable(Context) first")); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/FingerprintObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import io.reactivex.Emitter;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Cancellable;
import static android.Manifest.permission.USE_FINGERPRINT;
import android.annotation.SuppressLint;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.Build;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RequiresPermission;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException; | @Override
@RequiresPermission(USE_FINGERPRINT)
@RequiresApi(Build.VERSION_CODES.M)
public void subscribe(ObservableEmitter<T> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) {
emitter.onError(new FingerprintUnavailableException("Fingerprint authentication is not available on this device! Ensure that the device has a Fingerprint sensor and enrolled Fingerprints by calling RxFingerprint#isAvailable(Context) first"));
return;
}
AuthenticationCallback callback = createAuthenticationCallback(emitter);
cancellationSignal = fingerprintApiWrapper.createCancellationSignal();
CryptoObject cryptoObject = initCryptoObject(emitter);
//noinspection MissingPermission
fingerprintApiWrapper.getFingerprintManager().authenticate(cryptoObject, cancellationSignal, 0, callback, null);
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
if (cancellationSignal != null && !cancellationSignal.isCanceled()) {
cancellationSignal.cancel();
}
}
});
}
private AuthenticationCallback createAuthenticationCallback(final ObservableEmitter<T> emitter) {
return new AuthenticationCallback() {
@Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
if (!emitter.isDisposed()) { | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationException.java
// public class FingerprintAuthenticationException extends Exception {
//
// private final String message;
//
// /**
// * Creates exception that occurs during fingerprint authentication with message
// *
// * @param errString message of exception
// */
// public FingerprintAuthenticationException(CharSequence errString) {
// message = errString.toString();
// }
//
// @Override
// public String getMessage() {
// return message;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/FingerprintObservable.java
import io.reactivex.Emitter;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Cancellable;
import static android.Manifest.permission.USE_FINGERPRINT;
import android.annotation.SuppressLint;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.os.Build;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.RequiresPermission;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationException;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
@Override
@RequiresPermission(USE_FINGERPRINT)
@RequiresApi(Build.VERSION_CODES.M)
public void subscribe(ObservableEmitter<T> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) {
emitter.onError(new FingerprintUnavailableException("Fingerprint authentication is not available on this device! Ensure that the device has a Fingerprint sensor and enrolled Fingerprints by calling RxFingerprint#isAvailable(Context) first"));
return;
}
AuthenticationCallback callback = createAuthenticationCallback(emitter);
cancellationSignal = fingerprintApiWrapper.createCancellationSignal();
CryptoObject cryptoObject = initCryptoObject(emitter);
//noinspection MissingPermission
fingerprintApiWrapper.getFingerprintManager().authenticate(cryptoObject, cancellationSignal, 0, callback, null);
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
if (cancellationSignal != null && !cancellationSignal.isCanceled()) {
cancellationSignal.cancel();
}
}
});
}
private AuthenticationCallback createAuthenticationCallback(final ObservableEmitter<T> emitter) {
return new AuthenticationCallback() {
@Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
if (!emitter.isDisposed()) { | emitter.onError(new FingerprintAuthenticationException(errString)); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/FingerprintAuthenticationObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
| import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter; | /*
* Copyright 2015 Marvin Ramin
*
* 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.mtramin.rxfingerprint;
/**
* Authenticates the user with his fingerprint.
*/
class FingerprintAuthenticationObservable extends FingerprintObservable<FingerprintAuthenticationResult> {
/**
* Creates an Observable that will enable the fingerprint scanner of the device and listen for
* the users fingerprint for authentication
*
* @param context context to use
* @return Observable {@link FingerprintAuthenticationResult}
*/
static Observable<FingerprintAuthenticationResult> create(Context context) {
return Observable.create(new FingerprintAuthenticationObservable(new FingerprintApiWrapper(context)));
}
@VisibleForTesting
FingerprintAuthenticationObservable(FingerprintApiWrapper fingerprintApiWrapper) {
super(fingerprintApiWrapper);
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintAuthenticationResult> subscriber) {
// Simple authentication does not need CryptoObject
return null;
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintAuthenticationResult> emitter, AuthenticationResult result) { | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintAuthenticationResult.java
// public class FingerprintAuthenticationResult {
// private final FingerprintResult result;
// private final String message;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message optional message to be displayed to the user
// */
// public FingerprintAuthenticationResult(FingerprintResult result, String message) {
// this.result = result;
// this.message = message;
// }
//
// /**
// * @return message that can be displayed to the user to help him guide through the
// * authentication process
// *
// * Will only return a message if {@link FingerprintAuthenticationResult#result} is of type
// * {@link FingerprintResult#HELP}. <b>Returns {@code null} otherwise!</b>
// */
// @Nullable
// public String getMessage() {
// return message;
// }
//
// /**
// * @return result of fingerprint authentication operation
// */
// public FingerprintResult getResult() {
// return result;
// }
//
// /**
// * @return {@code true} if authentication was successful
// */
// public boolean isSuccess() {
// return result == FingerprintResult.AUTHENTICATED;
// }
//
// @Override
// public String toString() {
// return "FingerprintResult {"
// + "result=" + result.name() + ", "
// + "message=" + message +
// "}";
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/FingerprintAuthenticationObservable.java
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import com.mtramin.rxfingerprint.data.FingerprintAuthenticationResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
/*
* Copyright 2015 Marvin Ramin
*
* 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.mtramin.rxfingerprint;
/**
* Authenticates the user with his fingerprint.
*/
class FingerprintAuthenticationObservable extends FingerprintObservable<FingerprintAuthenticationResult> {
/**
* Creates an Observable that will enable the fingerprint scanner of the device and listen for
* the users fingerprint for authentication
*
* @param context context to use
* @return Observable {@link FingerprintAuthenticationResult}
*/
static Observable<FingerprintAuthenticationResult> create(Context context) {
return Observable.create(new FingerprintAuthenticationObservable(new FingerprintApiWrapper(context)));
}
@VisibleForTesting
FingerprintAuthenticationObservable(FingerprintApiWrapper fingerprintApiWrapper) {
super(fingerprintApiWrapper);
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintAuthenticationResult> subscriber) {
// Simple authentication does not need CryptoObject
return null;
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintAuthenticationResult> emitter, AuthenticationResult result) { | emitter.onNext(new FingerprintAuthenticationResult(FingerprintResult.AUTHENTICATED, null)); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/RsaEncryptionObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import android.content.Context;
import android.support.annotation.VisibleForTesting;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe; | * @param toEncrypt data to encrypt @return Observable {@link FingerprintEncryptionResult}
*/
static Observable<FingerprintEncryptionResult> create(Context context, String keyName, char[] toEncrypt, boolean keyInvalidatedByBiometricEnrollment) {
if (toEncrypt == null) {
return Observable.error(new IllegalArgumentException("String to be encrypted is null. Can only encrypt valid strings"));
}
try {
return Observable.create(new RsaEncryptionObservable(new FingerprintApiWrapper(context),
new RsaCipherProvider(context, keyName, keyInvalidatedByBiometricEnrollment),
toEncrypt,
new Base64Provider()));
} catch (Exception e) {
return Observable.error(e);
}
}
@VisibleForTesting
RsaEncryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
RsaCipherProvider cipherProvider,
char[] toEncrypt,
EncodingProvider encodingProvider) {
this.fingerprintApiWrapper = fingerprintApiWrapper;
this.cipherProvider = cipherProvider;
this.toEncrypt = toEncrypt;
this.encodingProvider = encodingProvider;
}
@Override
public void subscribe(ObservableEmitter<FingerprintEncryptionResult> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) { | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/RsaEncryptionObservable.java
import android.content.Context;
import android.support.annotation.VisibleForTesting;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
* @param toEncrypt data to encrypt @return Observable {@link FingerprintEncryptionResult}
*/
static Observable<FingerprintEncryptionResult> create(Context context, String keyName, char[] toEncrypt, boolean keyInvalidatedByBiometricEnrollment) {
if (toEncrypt == null) {
return Observable.error(new IllegalArgumentException("String to be encrypted is null. Can only encrypt valid strings"));
}
try {
return Observable.create(new RsaEncryptionObservable(new FingerprintApiWrapper(context),
new RsaCipherProvider(context, keyName, keyInvalidatedByBiometricEnrollment),
toEncrypt,
new Base64Provider()));
} catch (Exception e) {
return Observable.error(e);
}
}
@VisibleForTesting
RsaEncryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
RsaCipherProvider cipherProvider,
char[] toEncrypt,
EncodingProvider encodingProvider) {
this.fingerprintApiWrapper = fingerprintApiWrapper;
this.cipherProvider = cipherProvider;
this.toEncrypt = toEncrypt;
this.encodingProvider = encodingProvider;
}
@Override
public void subscribe(ObservableEmitter<FingerprintEncryptionResult> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) { | emitter.onError(new FingerprintUnavailableException("Fingerprint authentication is not available on this device! Ensure that the device has a Fingerprint sensor and enrolled Fingerprints by calling RxFingerprint#isAvailable(Context) first")); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/RsaEncryptionObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
| import android.content.Context;
import android.support.annotation.VisibleForTesting;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe; | toEncrypt,
new Base64Provider()));
} catch (Exception e) {
return Observable.error(e);
}
}
@VisibleForTesting
RsaEncryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
RsaCipherProvider cipherProvider,
char[] toEncrypt,
EncodingProvider encodingProvider) {
this.fingerprintApiWrapper = fingerprintApiWrapper;
this.cipherProvider = cipherProvider;
this.toEncrypt = toEncrypt;
this.encodingProvider = encodingProvider;
}
@Override
public void subscribe(ObservableEmitter<FingerprintEncryptionResult> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) {
emitter.onError(new FingerprintUnavailableException("Fingerprint authentication is not available on this device! Ensure that the device has a Fingerprint sensor and enrolled Fingerprints by calling RxFingerprint#isAvailable(Context) first"));
return;
}
try {
Cipher cipher = cipherProvider.getCipherForEncryption();
byte[] encryptedBytes = cipher.doFinal(ConversionUtils.toBytes(toEncrypt));
String encryptedString = encodingProvider.encode(encryptedBytes); | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintUnavailableException.java
// public class FingerprintUnavailableException extends Exception {
//
// public FingerprintUnavailableException(String s) {
// super(s);
// }
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/RsaEncryptionObservable.java
import android.content.Context;
import android.support.annotation.VisibleForTesting;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import com.mtramin.rxfingerprint.data.FingerprintUnavailableException;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
toEncrypt,
new Base64Provider()));
} catch (Exception e) {
return Observable.error(e);
}
}
@VisibleForTesting
RsaEncryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
RsaCipherProvider cipherProvider,
char[] toEncrypt,
EncodingProvider encodingProvider) {
this.fingerprintApiWrapper = fingerprintApiWrapper;
this.cipherProvider = cipherProvider;
this.toEncrypt = toEncrypt;
this.encodingProvider = encodingProvider;
}
@Override
public void subscribe(ObservableEmitter<FingerprintEncryptionResult> emitter) throws Exception {
if (fingerprintApiWrapper.isUnavailable()) {
emitter.onError(new FingerprintUnavailableException("Fingerprint authentication is not available on this device! Ensure that the device has a Fingerprint sensor and enrolled Fingerprints by calling RxFingerprint#isAvailable(Context) first"));
return;
}
try {
Cipher cipher = cipherProvider.getCipherForEncryption();
byte[] encryptedBytes = cipher.doFinal(ConversionUtils.toBytes(toEncrypt));
String encryptedString = encodingProvider.encode(encryptedBytes); | emitter.onNext(new FingerprintEncryptionResult(FingerprintResult.AUTHENTICATED, null, encryptedString)); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/RsaDecryptionObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintDecryptionResult.java
// public class FingerprintDecryptionResult extends FingerprintAuthenticationResult {
//
// private final char[] decrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message message to be displayed to the user
// * @param decrypted decrypted data
// */
// public FingerprintDecryptionResult(FingerprintResult result, String message, char[] decrypted) {
// super(result, message);
// this.decrypted = decrypted;
// }
//
// /**
// * @return decrypted data as a String. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public String getDecrypted() {
// return new String(getDecryptedChars());
// }
//
// /**
// * @return decrypted data as a char[]. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public char[] getDecryptedChars() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access decryption result");
// }
// return decrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import com.mtramin.rxfingerprint.data.FingerprintDecryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter; | }
private RsaDecryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
RsaCipherProvider cipherProvider,
String encrypted,
EncodingProvider encodingProvider) {
super(fingerprintApiWrapper);
this.cipherProvider = cipherProvider;
encryptedString = encrypted;
this.encodingProvider = encodingProvider;
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintDecryptionResult> subscriber) {
try {
Cipher cipher = cipherProvider.getCipherForDecryption();
return new CryptoObject(cipher);
} catch (Exception e) {
subscriber.onError(e);
return null;
}
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintDecryptionResult> emitter, AuthenticationResult result) {
try {
Cipher cipher = result.getCryptoObject().getCipher();
byte[] bytes = cipher.doFinal(encodingProvider.decode(encryptedString));
| // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintDecryptionResult.java
// public class FingerprintDecryptionResult extends FingerprintAuthenticationResult {
//
// private final char[] decrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the fingerprint authentication
// * @param message message to be displayed to the user
// * @param decrypted decrypted data
// */
// public FingerprintDecryptionResult(FingerprintResult result, String message, char[] decrypted) {
// super(result, message);
// this.decrypted = decrypted;
// }
//
// /**
// * @return decrypted data as a String. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public String getDecrypted() {
// return new String(getDecryptedChars());
// }
//
// /**
// * @return decrypted data as a char[]. Can only be accessed if the result of the fingerprint
// * authentication was of type {@link FingerprintResult#AUTHENTICATED}.
// */
// public char[] getDecryptedChars() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access decryption result");
// }
// return decrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/RsaDecryptionObservable.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import com.mtramin.rxfingerprint.data.FingerprintDecryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import javax.crypto.Cipher;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
}
private RsaDecryptionObservable(FingerprintApiWrapper fingerprintApiWrapper,
RsaCipherProvider cipherProvider,
String encrypted,
EncodingProvider encodingProvider) {
super(fingerprintApiWrapper);
this.cipherProvider = cipherProvider;
encryptedString = encrypted;
this.encodingProvider = encodingProvider;
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintDecryptionResult> subscriber) {
try {
Cipher cipher = cipherProvider.getCipherForDecryption();
return new CryptoObject(cipher);
} catch (Exception e) {
subscriber.onError(e);
return null;
}
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintDecryptionResult> emitter, AuthenticationResult result) {
try {
Cipher cipher = result.getCryptoObject().getCipher();
byte[] bytes = cipher.doFinal(encodingProvider.decode(encryptedString));
| emitter.onNext(new FingerprintDecryptionResult(FingerprintResult.AUTHENTICATED, null, ConversionUtils.toChars(bytes))); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/AesEncryptionObservable.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
| import javax.crypto.spec.IvParameterSpec;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.crypto.Cipher; |
if (toEncrypt == null) {
throw new NullPointerException("String to be encrypted is null. Can only encrypt valid strings");
}
this.toEncrypt = toEncrypt;
this.encodingProvider = encodingProvider;
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintEncryptionResult> emitter) {
try {
Cipher cipher = cipherProvider.getCipherForEncryption();
return new CryptoObject(cipher);
} catch (Exception e) {
emitter.onError(e);
return null;
}
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintEncryptionResult> emitter, AuthenticationResult result) {
try {
Cipher cipher = result.getCryptoObject().getCipher();
byte[] encryptedBytes = cipher.doFinal(ConversionUtils.toBytes(toEncrypt));
byte[] ivBytes = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
String encryptedString = CryptoData.fromBytes(encodingProvider, encryptedBytes, ivBytes).toString();
CryptoData.verifyCryptoDataString(encryptedString);
| // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintEncryptionResult.java
// public class FingerprintEncryptionResult extends FingerprintAuthenticationResult {
//
// private final String encrypted;
//
// /**
// * Default constructor
// *
// * @param result result of the operation
// * @param message message to be displayed to the user
// * @param encrypted encrypted data
// */
// public FingerprintEncryptionResult(FingerprintResult result, String message, String encrypted) {
// super(result, message);
// this.encrypted = encrypted;
// }
//
// /**
// * @return encrypted data, can only be accessed if the result was of
// * type {@link FingerprintResult#AUTHENTICATED}
// */
// public String getEncrypted() {
// if (!isSuccess()) {
// throw new IllegalAccessError("Fingerprint authentication was not successful, cannot access encryption result");
// }
// return encrypted;
// }
// }
//
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/data/FingerprintResult.java
// public enum FingerprintResult {
// FAILED, HELP, AUTHENTICATED
// }
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/AesEncryptionObservable.java
import javax.crypto.spec.IvParameterSpec;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.CryptoObject;
import android.support.annotation.Nullable;
import com.mtramin.rxfingerprint.data.FingerprintEncryptionResult;
import com.mtramin.rxfingerprint.data.FingerprintResult;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.crypto.Cipher;
if (toEncrypt == null) {
throw new NullPointerException("String to be encrypted is null. Can only encrypt valid strings");
}
this.toEncrypt = toEncrypt;
this.encodingProvider = encodingProvider;
}
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintEncryptionResult> emitter) {
try {
Cipher cipher = cipherProvider.getCipherForEncryption();
return new CryptoObject(cipher);
} catch (Exception e) {
emitter.onError(e);
return null;
}
}
@Override
protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintEncryptionResult> emitter, AuthenticationResult result) {
try {
Cipher cipher = result.getCryptoObject().getCipher();
byte[] encryptedBytes = cipher.doFinal(ConversionUtils.toBytes(toEncrypt));
byte[] ivBytes = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
String encryptedString = CryptoData.fromBytes(encodingProvider, encryptedBytes, ivBytes).toString();
CryptoData.verifyCryptoDataString(encryptedString);
| emitter.onNext(new FingerprintEncryptionResult(FingerprintResult.AUTHENTICATED, null, encryptedString)); |
Mauin/RxFingerprint | rxfingerprint/src/main/java/com/mtramin/rxfingerprint/CryptoDataException.java | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/CryptoData.java
// static final String SEPARATOR = "-_-";
| import static com.mtramin.rxfingerprint.CryptoData.SEPARATOR; | /*
* Copyright 2017 Marvin Ramin.
*
* 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.mtramin.rxfingerprint;
/**
* Exception thrown when CryptoData is invalid
*/
class CryptoDataException extends Exception {
static final String ERROR_MSG = "Invalid input given for decryption operation. Make sure you provide a string that was previously encrypted by RxFingerprint. empty: %s, correct format: %s";
private CryptoDataException(String message) {
super(message);
}
static CryptoDataException fromCryptoDataString(String input) {
boolean isEmpty = input.isEmpty(); | // Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/CryptoData.java
// static final String SEPARATOR = "-_-";
// Path: rxfingerprint/src/main/java/com/mtramin/rxfingerprint/CryptoDataException.java
import static com.mtramin.rxfingerprint.CryptoData.SEPARATOR;
/*
* Copyright 2017 Marvin Ramin.
*
* 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.mtramin.rxfingerprint;
/**
* Exception thrown when CryptoData is invalid
*/
class CryptoDataException extends Exception {
static final String ERROR_MSG = "Invalid input given for decryption operation. Make sure you provide a string that was previously encrypted by RxFingerprint. empty: %s, correct format: %s";
private CryptoDataException(String message) {
super(message);
}
static CryptoDataException fromCryptoDataString(String input) {
boolean isEmpty = input.isEmpty(); | boolean containsSeparator = input.contains(SEPARATOR); |
lemberg/d8androidsdk | DrupalSDK/src/main/java/com/ls/http/base/handler/TextRequestHandler.java | // Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java
// public abstract class RequestHandler
// {
// protected final String DEFAULT_CHARSET = "utf-8";
//
// protected Object object;
//
// public abstract String stringBodyFromItem();
//
// public abstract String getBodyContentType(String defaultCharset);
//
// public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
//
// public RequestHandler()
// {
//
// }
//
// protected boolean implementsPostableInterface()
// {
// return object instanceof IPostableItem;
// }
//
// protected String getCharset(@Nullable String defaultCharset)
// {
// String charset = null;
// if(object instanceof ICharsetItem)
// {
// charset = ((ICharsetItem)object).getCharset();
// }
//
// if(charset == null)
// {
// charset = defaultCharset;;
// }
//
// if(charset == null)
// {
// charset = DEFAULT_CHARSET;
// }
// return charset;
// }
//
// public Object getObject() {
// return object;
// }
//
// public void setObject(Object object) {
// this.object = object;
// }
//
// }
| import com.ls.http.base.IPostableItem;
import com.ls.http.base.RequestHandler;
import java.io.UnsupportedEncodingException; | /*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base.handler;
class TextRequestHandler extends RequestHandler
{
@Override
public String stringBodyFromItem()
{
if(implementsPostableInterface())
{ | // Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java
// public abstract class RequestHandler
// {
// protected final String DEFAULT_CHARSET = "utf-8";
//
// protected Object object;
//
// public abstract String stringBodyFromItem();
//
// public abstract String getBodyContentType(String defaultCharset);
//
// public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
//
// public RequestHandler()
// {
//
// }
//
// protected boolean implementsPostableInterface()
// {
// return object instanceof IPostableItem;
// }
//
// protected String getCharset(@Nullable String defaultCharset)
// {
// String charset = null;
// if(object instanceof ICharsetItem)
// {
// charset = ((ICharsetItem)object).getCharset();
// }
//
// if(charset == null)
// {
// charset = defaultCharset;;
// }
//
// if(charset == null)
// {
// charset = DEFAULT_CHARSET;
// }
// return charset;
// }
//
// public Object getObject() {
// return object;
// }
//
// public void setObject(Object object) {
// this.object = object;
// }
//
// }
// Path: DrupalSDK/src/main/java/com/ls/http/base/handler/TextRequestHandler.java
import com.ls.http.base.IPostableItem;
import com.ls.http.base.RequestHandler;
import java.io.UnsupportedEncodingException;
/*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base.handler;
class TextRequestHandler extends RequestHandler
{
@Override
public String stringBodyFromItem()
{
if(implementsPostableInterface())
{ | IPostableItem item = (IPostableItem)this.object; |
lemberg/d8androidsdk | DrupalSDK/src/main/java/com/ls/http/base/handler/XMLRequestHandler.java | // Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java
// public abstract class RequestHandler
// {
// protected final String DEFAULT_CHARSET = "utf-8";
//
// protected Object object;
//
// public abstract String stringBodyFromItem();
//
// public abstract String getBodyContentType(String defaultCharset);
//
// public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
//
// public RequestHandler()
// {
//
// }
//
// protected boolean implementsPostableInterface()
// {
// return object instanceof IPostableItem;
// }
//
// protected String getCharset(@Nullable String defaultCharset)
// {
// String charset = null;
// if(object instanceof ICharsetItem)
// {
// charset = ((ICharsetItem)object).getCharset();
// }
//
// if(charset == null)
// {
// charset = defaultCharset;;
// }
//
// if(charset == null)
// {
// charset = DEFAULT_CHARSET;
// }
// return charset;
// }
//
// public Object getObject() {
// return object;
// }
//
// public void setObject(Object object) {
// this.object = object;
// }
//
// }
| import com.ls.http.base.IPostableItem;
import com.ls.http.base.RequestHandler;
import java.io.UnsupportedEncodingException; | /*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base.handler;
class XMLRequestHandler extends RequestHandler
{
@Override
public String stringBodyFromItem()
{
if(implementsPostableInterface())
{ | // Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java
// public abstract class RequestHandler
// {
// protected final String DEFAULT_CHARSET = "utf-8";
//
// protected Object object;
//
// public abstract String stringBodyFromItem();
//
// public abstract String getBodyContentType(String defaultCharset);
//
// public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
//
// public RequestHandler()
// {
//
// }
//
// protected boolean implementsPostableInterface()
// {
// return object instanceof IPostableItem;
// }
//
// protected String getCharset(@Nullable String defaultCharset)
// {
// String charset = null;
// if(object instanceof ICharsetItem)
// {
// charset = ((ICharsetItem)object).getCharset();
// }
//
// if(charset == null)
// {
// charset = defaultCharset;;
// }
//
// if(charset == null)
// {
// charset = DEFAULT_CHARSET;
// }
// return charset;
// }
//
// public Object getObject() {
// return object;
// }
//
// public void setObject(Object object) {
// this.object = object;
// }
//
// }
// Path: DrupalSDK/src/main/java/com/ls/http/base/handler/XMLRequestHandler.java
import com.ls.http.base.IPostableItem;
import com.ls.http.base.RequestHandler;
import java.io.UnsupportedEncodingException;
/*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base.handler;
class XMLRequestHandler extends RequestHandler
{
@Override
public String stringBodyFromItem()
{
if(implementsPostableInterface())
{ | IPostableItem item = (IPostableItem)this.object; |
lemberg/d8androidsdk | sample/src/main/java/com/ls/drupal8demo/adapters/CategoriesAdapter.java | // Path: sample/src/main/java/com/ls/drupal8demo/AppConstants.java
// public class AppConstants {
//
// public final static String SERVER_BASE_URL = "http://d8.uat.link/";//"http://vh015.uk.dev-ls.co.uk/";
//
// public static enum CATEGORY {
// ALL_POSTS("All Posts", null),
// INDUSTRY_NEWS("Industry News", "3"),
// OUR_POSTS("Our Posts", "4"),
// TECH_NOTES("Tech notes", "5");
//
// public final String name;
// public final String id;
//
// CATEGORY(String theName, String theId) {
// name = theName;
// this.id = theId;
// }
// }
// }
//
// Path: sample/src/main/java/com/ls/drupal8demo/CategoryFragment.java
// public class CategoryFragment extends Fragment implements OnItemClickListener {
//
// private final static String CATEGORY_ID_KEY = "category_id";
//
// private DrupalClient mClient;
//
// public static CategoryFragment newInstance(String categoryId) {
// CategoryFragment fragment = new CategoryFragment();
// Bundle args = new Bundle();
// args.putString(CATEGORY_ID_KEY, categoryId);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// String categoryId = getArguments().getString(CATEGORY_ID_KEY);
// ViewGroup result = (ViewGroup) inflater.inflate(R.layout.fragment_category, container, false);
// ListView list = (ListView) result.findViewById(R.id.listView);
// list.setOnItemClickListener(this);
//
// mClient = new DrupalClient(AppConstants.SERVER_BASE_URL, getActivity(), BaseRequest.RequestFormat.JSON,new AppLoginManager());
// View noArticlesView = result.findViewById(R.id.emptyView);
// list.setAdapter(new CategoryArticlesListAdapter(categoryId, mClient, getActivity(), noArticlesView));
// return result;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ArticlePreview article = (ArticlePreview) parent.getItemAtPosition(position);
//
// Intent intent = ArticleActivity.getExecutionIntent(getActivity(), article);
// getActivity().startActivity(intent);
// }
//
// @Override
// public void onDestroyView() {
// if (mClient != null) {
// mClient.cancelAll();
// }
// super.onDestroyView();
// }
// }
| import com.ls.drupal8demo.AppConstants;
import com.ls.drupal8demo.CategoryFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter; | /**
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.drupal8demo.adapters;
public class CategoriesAdapter extends FragmentPagerAdapter {
public CategoriesAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
| // Path: sample/src/main/java/com/ls/drupal8demo/AppConstants.java
// public class AppConstants {
//
// public final static String SERVER_BASE_URL = "http://d8.uat.link/";//"http://vh015.uk.dev-ls.co.uk/";
//
// public static enum CATEGORY {
// ALL_POSTS("All Posts", null),
// INDUSTRY_NEWS("Industry News", "3"),
// OUR_POSTS("Our Posts", "4"),
// TECH_NOTES("Tech notes", "5");
//
// public final String name;
// public final String id;
//
// CATEGORY(String theName, String theId) {
// name = theName;
// this.id = theId;
// }
// }
// }
//
// Path: sample/src/main/java/com/ls/drupal8demo/CategoryFragment.java
// public class CategoryFragment extends Fragment implements OnItemClickListener {
//
// private final static String CATEGORY_ID_KEY = "category_id";
//
// private DrupalClient mClient;
//
// public static CategoryFragment newInstance(String categoryId) {
// CategoryFragment fragment = new CategoryFragment();
// Bundle args = new Bundle();
// args.putString(CATEGORY_ID_KEY, categoryId);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// String categoryId = getArguments().getString(CATEGORY_ID_KEY);
// ViewGroup result = (ViewGroup) inflater.inflate(R.layout.fragment_category, container, false);
// ListView list = (ListView) result.findViewById(R.id.listView);
// list.setOnItemClickListener(this);
//
// mClient = new DrupalClient(AppConstants.SERVER_BASE_URL, getActivity(), BaseRequest.RequestFormat.JSON,new AppLoginManager());
// View noArticlesView = result.findViewById(R.id.emptyView);
// list.setAdapter(new CategoryArticlesListAdapter(categoryId, mClient, getActivity(), noArticlesView));
// return result;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ArticlePreview article = (ArticlePreview) parent.getItemAtPosition(position);
//
// Intent intent = ArticleActivity.getExecutionIntent(getActivity(), article);
// getActivity().startActivity(intent);
// }
//
// @Override
// public void onDestroyView() {
// if (mClient != null) {
// mClient.cancelAll();
// }
// super.onDestroyView();
// }
// }
// Path: sample/src/main/java/com/ls/drupal8demo/adapters/CategoriesAdapter.java
import com.ls.drupal8demo.AppConstants;
import com.ls.drupal8demo.CategoryFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.drupal8demo.adapters;
public class CategoriesAdapter extends FragmentPagerAdapter {
public CategoriesAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
| return CategoryFragment.newInstance(AppConstants.CATEGORY.values()[arg0].id); |
lemberg/d8androidsdk | sample/src/main/java/com/ls/drupal8demo/adapters/CategoriesAdapter.java | // Path: sample/src/main/java/com/ls/drupal8demo/AppConstants.java
// public class AppConstants {
//
// public final static String SERVER_BASE_URL = "http://d8.uat.link/";//"http://vh015.uk.dev-ls.co.uk/";
//
// public static enum CATEGORY {
// ALL_POSTS("All Posts", null),
// INDUSTRY_NEWS("Industry News", "3"),
// OUR_POSTS("Our Posts", "4"),
// TECH_NOTES("Tech notes", "5");
//
// public final String name;
// public final String id;
//
// CATEGORY(String theName, String theId) {
// name = theName;
// this.id = theId;
// }
// }
// }
//
// Path: sample/src/main/java/com/ls/drupal8demo/CategoryFragment.java
// public class CategoryFragment extends Fragment implements OnItemClickListener {
//
// private final static String CATEGORY_ID_KEY = "category_id";
//
// private DrupalClient mClient;
//
// public static CategoryFragment newInstance(String categoryId) {
// CategoryFragment fragment = new CategoryFragment();
// Bundle args = new Bundle();
// args.putString(CATEGORY_ID_KEY, categoryId);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// String categoryId = getArguments().getString(CATEGORY_ID_KEY);
// ViewGroup result = (ViewGroup) inflater.inflate(R.layout.fragment_category, container, false);
// ListView list = (ListView) result.findViewById(R.id.listView);
// list.setOnItemClickListener(this);
//
// mClient = new DrupalClient(AppConstants.SERVER_BASE_URL, getActivity(), BaseRequest.RequestFormat.JSON,new AppLoginManager());
// View noArticlesView = result.findViewById(R.id.emptyView);
// list.setAdapter(new CategoryArticlesListAdapter(categoryId, mClient, getActivity(), noArticlesView));
// return result;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ArticlePreview article = (ArticlePreview) parent.getItemAtPosition(position);
//
// Intent intent = ArticleActivity.getExecutionIntent(getActivity(), article);
// getActivity().startActivity(intent);
// }
//
// @Override
// public void onDestroyView() {
// if (mClient != null) {
// mClient.cancelAll();
// }
// super.onDestroyView();
// }
// }
| import com.ls.drupal8demo.AppConstants;
import com.ls.drupal8demo.CategoryFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter; | /**
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.drupal8demo.adapters;
public class CategoriesAdapter extends FragmentPagerAdapter {
public CategoriesAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
| // Path: sample/src/main/java/com/ls/drupal8demo/AppConstants.java
// public class AppConstants {
//
// public final static String SERVER_BASE_URL = "http://d8.uat.link/";//"http://vh015.uk.dev-ls.co.uk/";
//
// public static enum CATEGORY {
// ALL_POSTS("All Posts", null),
// INDUSTRY_NEWS("Industry News", "3"),
// OUR_POSTS("Our Posts", "4"),
// TECH_NOTES("Tech notes", "5");
//
// public final String name;
// public final String id;
//
// CATEGORY(String theName, String theId) {
// name = theName;
// this.id = theId;
// }
// }
// }
//
// Path: sample/src/main/java/com/ls/drupal8demo/CategoryFragment.java
// public class CategoryFragment extends Fragment implements OnItemClickListener {
//
// private final static String CATEGORY_ID_KEY = "category_id";
//
// private DrupalClient mClient;
//
// public static CategoryFragment newInstance(String categoryId) {
// CategoryFragment fragment = new CategoryFragment();
// Bundle args = new Bundle();
// args.putString(CATEGORY_ID_KEY, categoryId);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// String categoryId = getArguments().getString(CATEGORY_ID_KEY);
// ViewGroup result = (ViewGroup) inflater.inflate(R.layout.fragment_category, container, false);
// ListView list = (ListView) result.findViewById(R.id.listView);
// list.setOnItemClickListener(this);
//
// mClient = new DrupalClient(AppConstants.SERVER_BASE_URL, getActivity(), BaseRequest.RequestFormat.JSON,new AppLoginManager());
// View noArticlesView = result.findViewById(R.id.emptyView);
// list.setAdapter(new CategoryArticlesListAdapter(categoryId, mClient, getActivity(), noArticlesView));
// return result;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ArticlePreview article = (ArticlePreview) parent.getItemAtPosition(position);
//
// Intent intent = ArticleActivity.getExecutionIntent(getActivity(), article);
// getActivity().startActivity(intent);
// }
//
// @Override
// public void onDestroyView() {
// if (mClient != null) {
// mClient.cancelAll();
// }
// super.onDestroyView();
// }
// }
// Path: sample/src/main/java/com/ls/drupal8demo/adapters/CategoriesAdapter.java
import com.ls.drupal8demo.AppConstants;
import com.ls.drupal8demo.CategoryFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.drupal8demo.adapters;
public class CategoriesAdapter extends FragmentPagerAdapter {
public CategoriesAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
| return CategoryFragment.newInstance(AppConstants.CATEGORY.values()[arg0].id); |
lemberg/d8androidsdk | DrupalSDK/src/main/java/com/ls/drupal/AbstractDrupalArrayEntity.java | // Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseData.java
// public class ResponseData {
// protected Object data;
// protected Map<String, String> headers;
// protected int statusCode;
// protected VolleyError error;
// protected Object parsedErrorResponse;
//
//
// /**
// * @return Instance of class, specified in response or null if no such class was specified.
// */
// public Object getData() {
// return data;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public VolleyError getError() {
// return error;
// }
//
// /**
// *
// * @return parsed error response is errorResponseSpecifier was provided and error received.
// */
// public Object getParsedErrorResponse() {
// return parsedErrorResponse;
// }
//
// public void cloneTo(ResponseData target)
// {
// target.data = data;
// target.headers = headers;
// target.statusCode = statusCode;
// target.error = error;
// target.parsedErrorResponse = parsedErrorResponse;
// }
//
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.ls.http.base.ResponseData;
import android.support.annotation.NonNull;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; | public E set(int index, E object)
{
return innerItems.set(index, object);
}
/**
* Removes the object at the specified location from this list.
*
* @param index
* the index of the object to remove.
* @return the removed object.
* @throws IndexOutOfBoundsException
* - when location < 0 || location >= size()
*/
public E remove(int index)
{
return innerItems.remove(index);
}
// Replacing this with items set
@SuppressWarnings("null")
@Override
public @NonNull
Object getManagedData()
{
return this.innerItems;
}
@Override | // Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseData.java
// public class ResponseData {
// protected Object data;
// protected Map<String, String> headers;
// protected int statusCode;
// protected VolleyError error;
// protected Object parsedErrorResponse;
//
//
// /**
// * @return Instance of class, specified in response or null if no such class was specified.
// */
// public Object getData() {
// return data;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public VolleyError getError() {
// return error;
// }
//
// /**
// *
// * @return parsed error response is errorResponseSpecifier was provided and error received.
// */
// public Object getParsedErrorResponse() {
// return parsedErrorResponse;
// }
//
// public void cloneTo(ResponseData target)
// {
// target.data = data;
// target.headers = headers;
// target.statusCode = statusCode;
// target.error = error;
// target.parsedErrorResponse = parsedErrorResponse;
// }
//
// }
// Path: DrupalSDK/src/main/java/com/ls/drupal/AbstractDrupalArrayEntity.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.ls.http.base.ResponseData;
import android.support.annotation.NonNull;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public E set(int index, E object)
{
return innerItems.set(index, object);
}
/**
* Removes the object at the specified location from this list.
*
* @param index
* the index of the object to remove.
* @return the removed object.
* @throws IndexOutOfBoundsException
* - when location < 0 || location >= size()
*/
public E remove(int index)
{
return innerItems.remove(index);
}
// Replacing this with items set
@SuppressWarnings("null")
@Override
public @NonNull
Object getManagedData()
{
return this.innerItems;
}
@Override | protected void consumeObject(ResponseData entity) |
lemberg/d8androidsdk | DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java | // Path: DrupalSDK/src/main/java/com/ls/http/base/ICharsetItem.java
// public interface ICharsetItem {
//
// public final static String UTF_8 = "utf-8";
//
// /**
// * @return Charset or null if default charset gas to be used.
// */
// public String getCharset();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
| import com.ls.http.base.ICharsetItem;
import com.ls.http.base.IPostableItem;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.UnsupportedEncodingException; | /*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base;
public abstract class RequestHandler
{
protected final String DEFAULT_CHARSET = "utf-8";
protected Object object;
public abstract String stringBodyFromItem();
public abstract String getBodyContentType(String defaultCharset);
public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
public RequestHandler()
{
}
protected boolean implementsPostableInterface()
{ | // Path: DrupalSDK/src/main/java/com/ls/http/base/ICharsetItem.java
// public interface ICharsetItem {
//
// public final static String UTF_8 = "utf-8";
//
// /**
// * @return Charset or null if default charset gas to be used.
// */
// public String getCharset();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
// Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java
import com.ls.http.base.ICharsetItem;
import com.ls.http.base.IPostableItem;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.UnsupportedEncodingException;
/*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base;
public abstract class RequestHandler
{
protected final String DEFAULT_CHARSET = "utf-8";
protected Object object;
public abstract String stringBodyFromItem();
public abstract String getBodyContentType(String defaultCharset);
public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
public RequestHandler()
{
}
protected boolean implementsPostableInterface()
{ | return object instanceof IPostableItem; |
lemberg/d8androidsdk | DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java | // Path: DrupalSDK/src/main/java/com/ls/http/base/ICharsetItem.java
// public interface ICharsetItem {
//
// public final static String UTF_8 = "utf-8";
//
// /**
// * @return Charset or null if default charset gas to be used.
// */
// public String getCharset();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
| import com.ls.http.base.ICharsetItem;
import com.ls.http.base.IPostableItem;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.UnsupportedEncodingException; | /*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base;
public abstract class RequestHandler
{
protected final String DEFAULT_CHARSET = "utf-8";
protected Object object;
public abstract String stringBodyFromItem();
public abstract String getBodyContentType(String defaultCharset);
public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
public RequestHandler()
{
}
protected boolean implementsPostableInterface()
{
return object instanceof IPostableItem;
}
protected String getCharset(@Nullable String defaultCharset)
{
String charset = null; | // Path: DrupalSDK/src/main/java/com/ls/http/base/ICharsetItem.java
// public interface ICharsetItem {
//
// public final static String UTF_8 = "utf-8";
//
// /**
// * @return Charset or null if default charset gas to be used.
// */
// public String getCharset();
// }
//
// Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java
// public interface IPostableItem {
//
// public String toJsonString();
//
// public String toXMLString();
//
// public String toPlainText();
// }
// Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java
import com.ls.http.base.ICharsetItem;
import com.ls.http.base.IPostableItem;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.UnsupportedEncodingException;
/*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.http.base;
public abstract class RequestHandler
{
protected final String DEFAULT_CHARSET = "utf-8";
protected Object object;
public abstract String stringBodyFromItem();
public abstract String getBodyContentType(String defaultCharset);
public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException;
public RequestHandler()
{
}
protected boolean implementsPostableInterface()
{
return object instanceof IPostableItem;
}
protected String getCharset(@Nullable String defaultCharset)
{
String charset = null; | if(object instanceof ICharsetItem) |
lemberg/d8androidsdk | DrupalSDK/src/main/java/com/ls/drupal/AbstractDrupalEntityContainer.java | // Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseData.java
// public class ResponseData {
// protected Object data;
// protected Map<String, String> headers;
// protected int statusCode;
// protected VolleyError error;
// protected Object parsedErrorResponse;
//
//
// /**
// * @return Instance of class, specified in response or null if no such class was specified.
// */
// public Object getData() {
// return data;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public VolleyError getError() {
// return error;
// }
//
// /**
// *
// * @return parsed error response is errorResponseSpecifier was provided and error received.
// */
// public Object getParsedErrorResponse() {
// return parsedErrorResponse;
// }
//
// public void cloneTo(ResponseData target)
// {
// target.data = data;
// target.headers = headers;
// target.statusCode = statusCode;
// target.error = error;
// target.parsedErrorResponse = parsedErrorResponse;
// }
//
// }
| import com.ls.http.base.ResponseData;
import android.support.annotation.NonNull; | /*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.drupal;
/**
*
* @author lemberg
*
* @param <T> class of container content
*/
public abstract class AbstractDrupalEntityContainer<T> extends AbstractBaseDrupalEntity
{
transient private T data;
public AbstractDrupalEntityContainer(DrupalClient client,T theData)
{
super(client);
if(theData == null)
{
throw new IllegalArgumentException("Data object can't be null");
}
this.data = theData;
}
@SuppressWarnings("null")
public @NonNull T getManagedData()
{
return data;
}
@Override | // Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseData.java
// public class ResponseData {
// protected Object data;
// protected Map<String, String> headers;
// protected int statusCode;
// protected VolleyError error;
// protected Object parsedErrorResponse;
//
//
// /**
// * @return Instance of class, specified in response or null if no such class was specified.
// */
// public Object getData() {
// return data;
// }
//
// public Map<String, String> getHeaders() {
// return headers;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public VolleyError getError() {
// return error;
// }
//
// /**
// *
// * @return parsed error response is errorResponseSpecifier was provided and error received.
// */
// public Object getParsedErrorResponse() {
// return parsedErrorResponse;
// }
//
// public void cloneTo(ResponseData target)
// {
// target.data = data;
// target.headers = headers;
// target.statusCode = statusCode;
// target.error = error;
// target.parsedErrorResponse = parsedErrorResponse;
// }
//
// }
// Path: DrupalSDK/src/main/java/com/ls/drupal/AbstractDrupalEntityContainer.java
import com.ls.http.base.ResponseData;
import android.support.annotation.NonNull;
/*
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* 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 com.ls.drupal;
/**
*
* @author lemberg
*
* @param <T> class of container content
*/
public abstract class AbstractDrupalEntityContainer<T> extends AbstractBaseDrupalEntity
{
transient private T data;
public AbstractDrupalEntityContainer(DrupalClient client,T theData)
{
super(client);
if(theData == null)
{
throw new IllegalArgumentException("Data object can't be null");
}
this.data = theData;
}
@SuppressWarnings("null")
public @NonNull T getManagedData()
{
return data;
}
@Override | protected void consumeObject(ResponseData entity) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.