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
|
---|---|---|---|---|---|---|
meethai/mithai | src/test/java/edu/sjsu/mithai/data/MetadataGenerationTaskTest.java | // Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
| import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import java.io.IOException; | package edu.sjsu.mithai.data;
public class MetadataGenerationTaskTest extends BaseTest {
public MetadataGenerationTaskTest() throws IOException {}
public static void main(String[] args) {
MetadataGenerationTaskTest test = null;
try {
test = new MetadataGenerationTaskTest();
} catch (IOException e) {
e.printStackTrace();
}
try {
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void test() throws Exception {
MetadataGenerationTask task = new MetadataGenerationTask(config);
// SimpleMqttReceiver receiver = new SimpleMqttReceiver(config);
| // Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
// Path: src/test/java/edu/sjsu/mithai/data/MetadataGenerationTaskTest.java
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import java.io.IOException;
package edu.sjsu.mithai.data;
public class MetadataGenerationTaskTest extends BaseTest {
public MetadataGenerationTaskTest() throws IOException {}
public static void main(String[] args) {
MetadataGenerationTaskTest test = null;
try {
test = new MetadataGenerationTaskTest();
} catch (IOException e) {
e.printStackTrace();
}
try {
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void test() throws Exception {
MetadataGenerationTask task = new MetadataGenerationTask(config);
// SimpleMqttReceiver receiver = new SimpleMqttReceiver(config);
| TaskManager.getInstance().submitTask(task); |
meethai/mithai | src/main/java/edu/sjsu/mithai/export/http/HttpExporter.java | // Path: src/main/java/edu/sjsu/mithai/export/ExportMessage.java
// public class ExportMessage implements Serializable {
//
// //TODO in future we may need to add fields to this.
//
// protected final String message;
//
// public ExportMessage(String message) {
// this.message = message;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return "ExportMessage{" +
// "message:" + message +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/export/HttpExportMessage.java
// public class HttpExportMessage extends ExportMessage {
//
// private String uri;
//
// public HttpExportMessage(String message, String uri) {
// super(message);
// this.uri = uri;
// }
//
// public String getUri() {
// return uri;
// }
//
// @Override
// public String toString() {
// return "HttpExportMessage{" +
// "uri='" + uri + '\'' +
// "message=" + message + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/export/IExporter.java
// public interface IExporter<T> {
//
// void setup() throws Exception;
//
// void send(T message) throws IOException;
//
// void tearDown() throws IOException;
//
// }
| import edu.sjsu.mithai.export.ExportMessage;
import edu.sjsu.mithai.export.HttpExportMessage;
import edu.sjsu.mithai.export.IExporter;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException; | package edu.sjsu.mithai.export.http;
public class HttpExporter implements IExporter<ExportMessage> {
private CloseableHttpClient client;
public HttpExporter() {
}
@Override
public void setup() throws Exception {
this.client = HttpClients.createDefault();
}
@Override
public void send(ExportMessage message) throws IOException {
| // Path: src/main/java/edu/sjsu/mithai/export/ExportMessage.java
// public class ExportMessage implements Serializable {
//
// //TODO in future we may need to add fields to this.
//
// protected final String message;
//
// public ExportMessage(String message) {
// this.message = message;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return "ExportMessage{" +
// "message:" + message +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/export/HttpExportMessage.java
// public class HttpExportMessage extends ExportMessage {
//
// private String uri;
//
// public HttpExportMessage(String message, String uri) {
// super(message);
// this.uri = uri;
// }
//
// public String getUri() {
// return uri;
// }
//
// @Override
// public String toString() {
// return "HttpExportMessage{" +
// "uri='" + uri + '\'' +
// "message=" + message + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/export/IExporter.java
// public interface IExporter<T> {
//
// void setup() throws Exception;
//
// void send(T message) throws IOException;
//
// void tearDown() throws IOException;
//
// }
// Path: src/main/java/edu/sjsu/mithai/export/http/HttpExporter.java
import edu.sjsu.mithai.export.ExportMessage;
import edu.sjsu.mithai.export.HttpExportMessage;
import edu.sjsu.mithai.export.IExporter;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
package edu.sjsu.mithai.export.http;
public class HttpExporter implements IExporter<ExportMessage> {
private CloseableHttpClient client;
public HttpExporter() {
}
@Override
public void setup() throws Exception {
this.client = HttpClients.createDefault();
}
@Override
public void send(ExportMessage message) throws IOException {
| if (message instanceof HttpExportMessage) { |
meethai/mithai | src/test/java/edu/sjsu/mithai/config/ConfigurationTest.java | // Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
| import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import org.junit.Test;
import java.io.IOException; | package edu.sjsu.mithai.config;
public class ConfigurationTest extends BaseTest {
public ConfigurationTest() throws IOException {
}
@Test
public void test() {
// start monitor task | // Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
// Path: src/test/java/edu/sjsu/mithai/config/ConfigurationTest.java
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import org.junit.Test;
import java.io.IOException;
package edu.sjsu.mithai.config;
public class ConfigurationTest extends BaseTest {
public ConfigurationTest() throws IOException {
}
@Test
public void test() {
// start monitor task | TaskManager.getInstance().submitTask(new ConfigMonitorTask(config)); |
meethai/mithai | src/main/java/edu/sjsu/mithai/apps/temperature/TemperatureHandler.java | // Path: src/main/java/edu/sjsu/mithai/export/ExportMessage.java
// public class ExportMessage implements Serializable {
//
// //TODO in future we may need to add fields to this.
//
// protected final String message;
//
// public ExportMessage(String message) {
// this.message = message;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return "ExportMessage{" +
// "message:" + message +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/Ihandler.java
// public interface Ihandler {
//
// void handle(String functionName, String msg);
// }
| import com.google.gson.Gson;
import edu.sjsu.mithai.export.ExportMessage;
import edu.sjsu.mithai.spark.Store;
import edu.sjsu.mithai.util.Ihandler;
import java.util.HashMap;
import java.util.Map; | package edu.sjsu.mithai.apps.temperature;
public class TemperatureHandler implements Ihandler {
private Gson gson;
public TemperatureHandler() {
this.gson = new Gson();
}
@Override
public void handle(String functionName, String msg) {
if (functionName.equals("average")) {
System.out.println("Average is =>" + msg);
Map<String, String> data = new HashMap<>();
data.put("key","temperature.average");
data.put("value", msg);
data.put("time", String.valueOf(System.currentTimeMillis()/1_000_000));
| // Path: src/main/java/edu/sjsu/mithai/export/ExportMessage.java
// public class ExportMessage implements Serializable {
//
// //TODO in future we may need to add fields to this.
//
// protected final String message;
//
// public ExportMessage(String message) {
// this.message = message;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return "ExportMessage{" +
// "message:" + message +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/Ihandler.java
// public interface Ihandler {
//
// void handle(String functionName, String msg);
// }
// Path: src/main/java/edu/sjsu/mithai/apps/temperature/TemperatureHandler.java
import com.google.gson.Gson;
import edu.sjsu.mithai.export.ExportMessage;
import edu.sjsu.mithai.spark.Store;
import edu.sjsu.mithai.util.Ihandler;
import java.util.HashMap;
import java.util.Map;
package edu.sjsu.mithai.apps.temperature;
public class TemperatureHandler implements Ihandler {
private Gson gson;
public TemperatureHandler() {
this.gson = new Gson();
}
@Override
public void handle(String functionName, String msg) {
if (functionName.equals("average")) {
System.out.println("Average is =>" + msg);
Map<String, String> data = new HashMap<>();
data.put("key","temperature.average");
data.put("value", msg);
data.put("time", String.valueOf(System.currentTimeMillis()/1_000_000));
| ExportMessage exportMessage = new ExportMessage(gson.toJson(data)); |
meethai/mithai | src/main/scala/edu/sjsu/mithai/data/DataGenerationTask.java | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// public class MqttService {
// private static MQTTPublisher publisher;
//
// private MqttService() {
// }
//
// public static MQTTPublisher getPublisher(Configuration configuration) {
//
// if (publisher == null) {
// publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));
// }
//
// return publisher;
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java
// public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable {
//
// protected boolean stop;
//
// public StoppableExecutableTask() {
// this.stop = false;
// }
//
// @Override
// public void run() {
// do {
// execute();
// } while (!stop);
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
| import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.mqtt.MQTTPublisher;
import edu.sjsu.mithai.mqtt.MqttService;
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.StoppableExecutableTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; | package edu.sjsu.mithai.data;
public class DataGenerationTask extends StoppableExecutableTask {
private static final Logger logger = LoggerFactory.getLogger(DataGenerationTask.class);
private SensorStore sensorStore; | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// public class MqttService {
// private static MQTTPublisher publisher;
//
// private MqttService() {
// }
//
// public static MQTTPublisher getPublisher(Configuration configuration) {
//
// if (publisher == null) {
// publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));
// }
//
// return publisher;
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java
// public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable {
//
// protected boolean stop;
//
// public StoppableExecutableTask() {
// this.stop = false;
// }
//
// @Override
// public void run() {
// do {
// execute();
// } while (!stop);
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
// Path: src/main/scala/edu/sjsu/mithai/data/DataGenerationTask.java
import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.mqtt.MQTTPublisher;
import edu.sjsu.mithai.mqtt.MqttService;
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.StoppableExecutableTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
package edu.sjsu.mithai.data;
public class DataGenerationTask extends StoppableExecutableTask {
private static final Logger logger = LoggerFactory.getLogger(DataGenerationTask.class);
private SensorStore sensorStore; | private Configuration configuration; |
meethai/mithai | src/main/scala/edu/sjsu/mithai/data/DataGenerationTask.java | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// public class MqttService {
// private static MQTTPublisher publisher;
//
// private MqttService() {
// }
//
// public static MQTTPublisher getPublisher(Configuration configuration) {
//
// if (publisher == null) {
// publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));
// }
//
// return publisher;
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java
// public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable {
//
// protected boolean stop;
//
// public StoppableExecutableTask() {
// this.stop = false;
// }
//
// @Override
// public void run() {
// do {
// execute();
// } while (!stop);
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
| import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.mqtt.MQTTPublisher;
import edu.sjsu.mithai.mqtt.MqttService;
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.StoppableExecutableTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; | package edu.sjsu.mithai.data;
public class DataGenerationTask extends StoppableExecutableTask {
private static final Logger logger = LoggerFactory.getLogger(DataGenerationTask.class);
private SensorStore sensorStore;
private Configuration configuration;
private MQTTPublisher publisher;
private List<SensorData> dataList;
private SensorDataSerializationHelper avro;
public DataGenerationTask(Configuration configuration, SensorStore sensorStore) throws IOException {
this.configuration = configuration;
this.sensorStore = sensorStore; | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// public class MqttService {
// private static MQTTPublisher publisher;
//
// private MqttService() {
// }
//
// public static MQTTPublisher getPublisher(Configuration configuration) {
//
// if (publisher == null) {
// publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));
// }
//
// return publisher;
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java
// public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable {
//
// protected boolean stop;
//
// public StoppableExecutableTask() {
// this.stop = false;
// }
//
// @Override
// public void run() {
// do {
// execute();
// } while (!stop);
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
// Path: src/main/scala/edu/sjsu/mithai/data/DataGenerationTask.java
import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.mqtt.MQTTPublisher;
import edu.sjsu.mithai.mqtt.MqttService;
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.StoppableExecutableTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
package edu.sjsu.mithai.data;
public class DataGenerationTask extends StoppableExecutableTask {
private static final Logger logger = LoggerFactory.getLogger(DataGenerationTask.class);
private SensorStore sensorStore;
private Configuration configuration;
private MQTTPublisher publisher;
private List<SensorData> dataList;
private SensorDataSerializationHelper avro;
public DataGenerationTask(Configuration configuration, SensorStore sensorStore) throws IOException {
this.configuration = configuration;
this.sensorStore = sensorStore; | this.publisher = MqttService.getPublisher(configuration); |
meethai/mithai | src/main/scala/edu/sjsu/mithai/data/DataGenerationTask.java | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// public class MqttService {
// private static MQTTPublisher publisher;
//
// private MqttService() {
// }
//
// public static MQTTPublisher getPublisher(Configuration configuration) {
//
// if (publisher == null) {
// publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));
// }
//
// return publisher;
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java
// public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable {
//
// protected boolean stop;
//
// public StoppableExecutableTask() {
// this.stop = false;
// }
//
// @Override
// public void run() {
// do {
// execute();
// } while (!stop);
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
| import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.mqtt.MQTTPublisher;
import edu.sjsu.mithai.mqtt.MqttService;
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.StoppableExecutableTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; | package edu.sjsu.mithai.data;
public class DataGenerationTask extends StoppableExecutableTask {
private static final Logger logger = LoggerFactory.getLogger(DataGenerationTask.class);
private SensorStore sensorStore;
private Configuration configuration;
private MQTTPublisher publisher;
private List<SensorData> dataList;
private SensorDataSerializationHelper avro;
public DataGenerationTask(Configuration configuration, SensorStore sensorStore) throws IOException {
this.configuration = configuration;
this.sensorStore = sensorStore;
this.publisher = MqttService.getPublisher(configuration);
this.dataList = new ArrayList<>(sensorStore.getDevices().size());
avro = new SensorDataSerializationHelper();
| // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/scala/edu/sjsu/mithai/mqtt/MqttService.java
// public class MqttService {
// private static MQTTPublisher publisher;
//
// private MqttService() {
// }
//
// public static MQTTPublisher getPublisher(Configuration configuration) {
//
// if (publisher == null) {
// publisher = new MQTTPublisher(configuration.getProperty(MithaiProperties.MQTT_BROKER));
// }
//
// return publisher;
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableExecutableTask.java
// public abstract class StoppableExecutableTask implements Runnable, Executable, Stoppable {
//
// protected boolean stop;
//
// public StoppableExecutableTask() {
// this.stop = false;
// }
//
// @Override
// public void run() {
// do {
// execute();
// } while (!stop);
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
// Path: src/main/scala/edu/sjsu/mithai/data/DataGenerationTask.java
import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.mqtt.MQTTPublisher;
import edu.sjsu.mithai.mqtt.MqttService;
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.StoppableExecutableTask;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
package edu.sjsu.mithai.data;
public class DataGenerationTask extends StoppableExecutableTask {
private static final Logger logger = LoggerFactory.getLogger(DataGenerationTask.class);
private SensorStore sensorStore;
private Configuration configuration;
private MQTTPublisher publisher;
private List<SensorData> dataList;
private SensorDataSerializationHelper avro;
public DataGenerationTask(Configuration configuration, SensorStore sensorStore) throws IOException {
this.configuration = configuration;
this.sensorStore = sensorStore;
this.publisher = MqttService.getPublisher(configuration);
this.dataList = new ArrayList<>(sensorStore.getDevices().size());
avro = new SensorDataSerializationHelper();
| for (IDevice device : sensorStore.getDevices()) { |
meethai/mithai | src/main/java/edu/sjsu/mithai/export/Exporter.java | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
| import edu.sjsu.mithai.config.Configuration; | package edu.sjsu.mithai.export;
public class Exporter {
private IExporter exporter; | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
// Path: src/main/java/edu/sjsu/mithai/export/Exporter.java
import edu.sjsu.mithai.config.Configuration;
package edu.sjsu.mithai.export;
public class Exporter {
private IExporter exporter; | private Configuration configuration; |
meethai/mithai | src/main/java/edu/sjsu/mithai/apps/parkinglot/ParkingResponseHandler.java | // Path: src/main/java/edu/sjsu/mithai/export/HttpExportMessage.java
// public class HttpExportMessage extends ExportMessage {
//
// private String uri;
//
// public HttpExportMessage(String message, String uri) {
// super(message);
// this.uri = uri;
// }
//
// public String getUri() {
// return uri;
// }
//
// @Override
// public String toString() {
// return "HttpExportMessage{" +
// "uri='" + uri + '\'' +
// "message=" + message + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/Ihandler.java
// public interface Ihandler {
//
// void handle(String functionName, String msg);
// }
| import com.google.gson.Gson;
import edu.sjsu.mithai.export.HttpExportMessage;
import edu.sjsu.mithai.spark.Store;
import edu.sjsu.mithai.util.Ihandler;
import java.util.LinkedHashMap;
import java.util.Map; | package edu.sjsu.mithai.apps.parkinglot;
public class ParkingResponseHandler implements Ihandler {
private Gson gson;
private Map<String, Integer> parkingStatus;
public ParkingResponseHandler() {
this.gson = new Gson();
this.parkingStatus = new LinkedHashMap<>();
}
@Override
public void handle(String functionName, String msg) {
if (functionName.equals("ShortestPath")) {
for (String key : ParkingApplication.parkingSensorMap.keySet()) {
int status = ParkingApplication.parkingSensorMap.get(key).isParked() ? 1 : 0;
parkingStatus.put(key, status);
}
System.out.println(functionName + "=>" + msg);
| // Path: src/main/java/edu/sjsu/mithai/export/HttpExportMessage.java
// public class HttpExportMessage extends ExportMessage {
//
// private String uri;
//
// public HttpExportMessage(String message, String uri) {
// super(message);
// this.uri = uri;
// }
//
// public String getUri() {
// return uri;
// }
//
// @Override
// public String toString() {
// return "HttpExportMessage{" +
// "uri='" + uri + '\'' +
// "message=" + message + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/Ihandler.java
// public interface Ihandler {
//
// void handle(String functionName, String msg);
// }
// Path: src/main/java/edu/sjsu/mithai/apps/parkinglot/ParkingResponseHandler.java
import com.google.gson.Gson;
import edu.sjsu.mithai.export.HttpExportMessage;
import edu.sjsu.mithai.spark.Store;
import edu.sjsu.mithai.util.Ihandler;
import java.util.LinkedHashMap;
import java.util.Map;
package edu.sjsu.mithai.apps.parkinglot;
public class ParkingResponseHandler implements Ihandler {
private Gson gson;
private Map<String, Integer> parkingStatus;
public ParkingResponseHandler() {
this.gson = new Gson();
this.parkingStatus = new LinkedHashMap<>();
}
@Override
public void handle(String functionName, String msg) {
if (functionName.equals("ShortestPath")) {
for (String key : ParkingApplication.parkingSensorMap.keySet()) {
int status = ParkingApplication.parkingSensorMap.get(key).isParked() ? 1 : 0;
parkingStatus.put(key, status);
}
System.out.println(functionName + "=>" + msg);
| HttpExportMessage message = new HttpExportMessage(gson.toJson(parkingStatus), |
meethai/mithai | src/main/java/edu/sjsu/mithai/util/Client.java | // Path: src/main/java/edu/sjsu/mithai/sensors/TemperatureSensor.java
// public class TemperatureSensor extends AbstractDevice {
//
// private double min;
// private Random random;
//
// public TemperatureSensor(String id) {
// super(id);
// random = new Random();
// min = random.nextDouble() + 100;
// }
//
// @Override
// public double sense() {
// return min + random.nextDouble();
// }
//
// }
| import edu.sjsu.mithai.sensors.TemperatureSensor; | package edu.sjsu.mithai.util;
public class Client {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
TaskManager.getInstance().submitTask(new TemperatureSensorTask(i));
}
// for (int i = 0; i < 5; i++) {
// TaskManager.getInstance().submitTask(new KafkaExporterTask("KAFKA"));
// }
try {
Thread.sleep(31000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping tasks...");
try {
TaskManager.getInstance().stopAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class TemperatureSensorTask extends StoppableExecutableTask {
| // Path: src/main/java/edu/sjsu/mithai/sensors/TemperatureSensor.java
// public class TemperatureSensor extends AbstractDevice {
//
// private double min;
// private Random random;
//
// public TemperatureSensor(String id) {
// super(id);
// random = new Random();
// min = random.nextDouble() + 100;
// }
//
// @Override
// public double sense() {
// return min + random.nextDouble();
// }
//
// }
// Path: src/main/java/edu/sjsu/mithai/util/Client.java
import edu.sjsu.mithai.sensors.TemperatureSensor;
package edu.sjsu.mithai.util;
public class Client {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
TaskManager.getInstance().submitTask(new TemperatureSensorTask(i));
}
// for (int i = 0; i < 5; i++) {
// TaskManager.getInstance().submitTask(new KafkaExporterTask("KAFKA"));
// }
try {
Thread.sleep(31000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping tasks...");
try {
TaskManager.getInstance().stopAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class TemperatureSensorTask extends StoppableExecutableTask {
| TemperatureSensor sensor; |
meethai/mithai | src/test/java/edu/sjsu/mithai/data/DataGenerationTaskTest.java | // Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
| import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import java.io.IOException;
import java.util.Random; | package edu.sjsu.mithai.data;
public class DataGenerationTaskTest extends BaseTest {
public DataGenerationTaskTest() throws IOException {
}
public static void main(String[] args) {
try {
DataGenerationTaskTest test = new DataGenerationTaskTest();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void test() throws Exception {
SensorStore sensorStore = new SensorStore(); | // Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
// Path: src/test/java/edu/sjsu/mithai/data/DataGenerationTaskTest.java
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import java.io.IOException;
import java.util.Random;
package edu.sjsu.mithai.data;
public class DataGenerationTaskTest extends BaseTest {
public DataGenerationTaskTest() throws IOException {
}
public static void main(String[] args) {
try {
DataGenerationTaskTest test = new DataGenerationTaskTest();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void test() throws Exception {
SensorStore sensorStore = new SensorStore(); | sensorStore.addDevice(new IDevice() { |
meethai/mithai | src/test/java/edu/sjsu/mithai/data/DataGenerationTaskTest.java | // Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
| import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import java.io.IOException;
import java.util.Random; | package edu.sjsu.mithai.data;
public class DataGenerationTaskTest extends BaseTest {
public DataGenerationTaskTest() throws IOException {
}
public static void main(String[] args) {
try {
DataGenerationTaskTest test = new DataGenerationTaskTest();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void test() throws Exception {
SensorStore sensorStore = new SensorStore();
sensorStore.addDevice(new IDevice() {
Random random = new Random();
@Override
public double sense() {
return random.nextDouble();
}
@Override
public String getId() {
return "sensor-1";
}
@Override
public void sendData() {
}
});
DataGenerationTask task = new DataGenerationTask(config, sensorStore); | // Path: src/main/java/edu/sjsu/mithai/sensors/IDevice.java
// public interface IDevice {
//
// public double sense();
//
// public String getId();
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
// Path: src/test/java/edu/sjsu/mithai/data/DataGenerationTaskTest.java
import edu.sjsu.mithai.sensors.IDevice;
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import java.io.IOException;
import java.util.Random;
package edu.sjsu.mithai.data;
public class DataGenerationTaskTest extends BaseTest {
public DataGenerationTaskTest() throws IOException {
}
public static void main(String[] args) {
try {
DataGenerationTaskTest test = new DataGenerationTaskTest();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void test() throws Exception {
SensorStore sensorStore = new SensorStore();
sensorStore.addDevice(new IDevice() {
Random random = new Random();
@Override
public double sense() {
return random.nextDouble();
}
@Override
public String getId() {
return "sensor-1";
}
@Override
public void sendData() {
}
});
DataGenerationTask task = new DataGenerationTask(config, sensorStore); | TaskManager.getInstance().submitTask(task); |
meethai/mithai | src/main/java/edu/sjsu/mithai/export/ExporterTask.java | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java
// public abstract class StoppableRunnableTask implements Runnable, Stoppable {
//
// protected boolean stop;
//
// public StoppableRunnableTask() {
// this.stop = false;
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
| import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.util.StoppableRunnableTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; | package edu.sjsu.mithai.export;
public class ExporterTask extends StoppableRunnableTask {
private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
private static final String STOP_MESSAGE = "STOP";
| // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java
// public abstract class StoppableRunnableTask implements Runnable, Stoppable {
//
// protected boolean stop;
//
// public StoppableRunnableTask() {
// this.stop = false;
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
// Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java
import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.util.StoppableRunnableTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
package edu.sjsu.mithai.export;
public class ExporterTask extends StoppableRunnableTask {
private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
private static final String STOP_MESSAGE = "STOP";
| private Configuration configuration; |
meethai/mithai | src/main/java/edu/sjsu/mithai/export/ExporterTask.java | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java
// public abstract class StoppableRunnableTask implements Runnable, Stoppable {
//
// protected boolean stop;
//
// public StoppableRunnableTask() {
// this.stop = false;
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
| import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.util.StoppableRunnableTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; | package edu.sjsu.mithai.export;
public class ExporterTask extends StoppableRunnableTask {
private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
private static final String STOP_MESSAGE = "STOP";
private Configuration configuration;
private Exporter exporter;
private long sendInterval;
private MessageStore<ExportMessage> messageStore;
public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception {
this.configuration = configuration; | // Path: src/main/java/edu/sjsu/mithai/config/Configuration.java
// public class Configuration {
//
// protected String propertyFile;
// protected Properties properties;
//
// public Configuration(String propertyFile) throws IOException {
// this.propertyFile = propertyFile;
// this.properties = new Properties();
// properties.load(new FileReader(propertyFile));
// }
//
// public String getProperty(String key) {
// return properties.getProperty(key);
// }
//
// public void setProperty(String key, String value) {
// properties.setProperty(key, value);
// }
//
// public Properties getProperties() {
// return properties;
// }
//
// public void setProperties(Properties properties) {
// this.properties = properties;
// }
//
// public void setPropertyFile(String propertyFile) {
// this.propertyFile = propertyFile;
// }
//
// public String getPropertyFile() {
// return propertyFile;
// }
//
// public void reload() throws IOException {
// properties.clear();
// properties.load(new FileReader(propertyFile));
// System.out.println("=>" + properties);
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/config/MithaiProperties.java
// public interface MithaiProperties {
//
// // Self node properties
// String IP = "IP";
// String ID = "ID";
// String CONNECTED_DEVICE_IDS = "CONNECTED_DEVICE_IDS";
// String LOCAL_GRAPH = "LOCAL_GRAPH";
//
// // Sensor & Data generation related properties
// String NUMBER_OF_SENSORS = "NUMBER_OF_SENSORS";
// String DATA_GENERATION_INTERVAL = "DATA_GENERATION_INTERVAL";
// String META_DATA_GENERATION_INTERVAL = "META_DATA_GENERATION_INTERVAL";
// String QUIESCE_TIMEOUT = "QUIESCE_TIMEOUT";
// String RESEND_COUNT = "RESEND_COUNT";
// String STARTUP_THRESHOLD = "STARTUP_THRESHOLD";
//
// // INJECTOR PROPERTIES
// String MQTT_BROKER = "MQTT_BROKER";
// String MQTT_TOPIC = "MQTT_TOPIC";
//
// // Visualization System Properties
// String VISUALIZATION_SYSTEM_EXPORTER_URL = "VISUALIZATION_SYSTEM_EXPORTER_URL";
//
// // EXPORTER PROPERTIES
// String EXPORTER_TYPE = "EXPORTER_TYPE";
// String EXPORTER_REMOTE_URI = "EXPORTER_REMOTE_IP";
// String EXPORTER_KAFKA_TOPIC = "EXPORTER_KAFKA_TOPIC";
// String EXPORTER_TIME_INTERVAL = "EXPORTER_TIME_INTERVAL";
//
// // Graphite exporter properties
// String GRAPHITE_HOSTNAME = "GRAPHITE_HOSTNAME";
// String GRAPHITE_PORT = "GRAPHITE_PORT";
//
// //Graph Processor Tasks
// String ENTRY = "ENTRY";
// String TASK_LIST = "TASK_LIST";
// String FUNCTION_LIST = "FUNCTION_LIST";
//
// //Store Properties
// String MESSAGE_STORE_QUEUE_SIZE = "MESSAGE_STORE_QUEUE_SIZE";
// String MQTT_MESSAGE_STORE_QUEUE_SIZE = "MQTT_MESSAGE_STORE_QUEUE_SIZE";
// String SPARKCONTEXT_INTERVAL = "SPARKCONTEXT_INTERVAL";
//
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/StoppableRunnableTask.java
// public abstract class StoppableRunnableTask implements Runnable, Stoppable {
//
// protected boolean stop;
//
// public StoppableRunnableTask() {
// this.stop = false;
// }
//
// @Override
// public void stop() {
// stop = true;
// }
//
// }
// Path: src/main/java/edu/sjsu/mithai/export/ExporterTask.java
import edu.sjsu.mithai.config.Configuration;
import edu.sjsu.mithai.config.MithaiProperties;
import edu.sjsu.mithai.util.StoppableRunnableTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
package edu.sjsu.mithai.export;
public class ExporterTask extends StoppableRunnableTask {
private final Logger logger = LoggerFactory.getLogger(ExporterTask.class);
private static final String STOP_MESSAGE = "STOP";
private Configuration configuration;
private Exporter exporter;
private long sendInterval;
private MessageStore<ExportMessage> messageStore;
public ExporterTask(Configuration configuration, MessageStore<ExportMessage> messageStore) throws Exception {
this.configuration = configuration; | this.sendInterval = Long.parseLong(configuration.getProperty(MithaiProperties.EXPORTER_TIME_INTERVAL)); |
meethai/mithai | src/test/java/edu/sjsu/mithai/mqtt/MQTTDataReceiverTaskTest.java | // Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
| import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import org.junit.Test;
import java.io.IOException; | package edu.sjsu.mithai.mqtt;
/**
* Created by kaustubh on 9/21/16.
*/
public class MQTTDataReceiverTaskTest extends BaseTest {
public MQTTDataReceiverTaskTest() throws IOException {
}
public static void main(String[] args) throws IOException {
MQTTDataReceiverTaskTest mr = new MQTTDataReceiverTaskTest();
mr.test();
}
@Test
public void test() { | // Path: src/main/java/edu/sjsu/mithai/util/BaseTest.java
// public abstract class BaseTest {
//
// protected Configuration config;
//
// public BaseTest() throws IOException {
// loadConfig();
// }
//
// public abstract void test() throws Exception;
//
// public void loadConfig() throws IOException {
// config = new Configuration(getClass().getClassLoader().getResource("application.properties").getFile());
// }
//
// public void stopAfter(int seconds) {
//
// try {
// Thread.sleep(seconds * 1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// try {
// TaskManager.getInstance().stopAll();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// }
// }
//
// Path: src/main/java/edu/sjsu/mithai/util/TaskManager.java
// public class TaskManager {
// private static TaskManager ourInstance = new TaskManager();
//
// private List<Stoppable> tasks;
// private ExecutorService threadPool;
// private List<Ihandler> handlers;
//
// private TaskManager() {
// this.threadPool = Executors.newCachedThreadPool();
// this.tasks = new ArrayList<>();
// this.handlers = new ArrayList<>();
// }
//
// public static TaskManager getInstance() {
// return ourInstance;
// }
//
// public synchronized void submitTask(StoppableExecutableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void submitTask(StoppableRunnableTask task) {
// threadPool.submit(task);
// tasks.add(task);
// }
//
// public synchronized void stopAll() throws InterruptedException {
//
// for (Stoppable task : tasks) {
// System.out.println("Stopping task:" + task);
// task.stop();
// System.out.println("Task stopped..");
// }
//
// // remove all tasks
// tasks.clear();
//
// threadPool.shutdown();
// System.out.println("Stopping streaming context..");
// SparkStreamingObject.streamingContext().stop(true, false);
// System.out.println("Streaming context stopped..");
// threadPool.awaitTermination(60, TimeUnit.SECONDS);
// }
//
// public synchronized void stop(Class clazz) {
// System.out.println(tasks);
// for(Stoppable task : tasks) {
// if (clazz.isInstance(task)) {
// task.stop();
// }
// }
// }
//
// public List<Ihandler> getHandlers() {
// return handlers;
// }
//
// public void addHandler(Ihandler handler) {
// handlers.add(handler);
// }
// }
// Path: src/test/java/edu/sjsu/mithai/mqtt/MQTTDataReceiverTaskTest.java
import edu.sjsu.mithai.util.BaseTest;
import edu.sjsu.mithai.util.TaskManager;
import org.junit.Test;
import java.io.IOException;
package edu.sjsu.mithai.mqtt;
/**
* Created by kaustubh on 9/21/16.
*/
public class MQTTDataReceiverTaskTest extends BaseTest {
public MQTTDataReceiverTaskTest() throws IOException {
}
public static void main(String[] args) throws IOException {
MQTTDataReceiverTaskTest mr = new MQTTDataReceiverTaskTest();
mr.test();
}
@Test
public void test() { | TaskManager.getInstance().submitTask(new MQTTDataReceiverTask(config)); |
hortonworks-spark/spark-llap | src/test/java/com/hortonworks/spark/sql/hive/llap/TestReadSupport.java | // Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestSecureHS2Url.java
// static final String TEST_HS2_URL = "jdbc:hive2://example.com:10084";
| import org.apache.spark.sql.Row;
import org.junit.Test;
import static com.hortonworks.spark.sql.hive.llap.TestSecureHS2Url.TEST_HS2_URL;
import static org.junit.Assert.assertEquals; | package com.hortonworks.spark.sql.hive.llap;
public class TestReadSupport extends SessionTestBase {
@Test
public void testReadSupport() {
HiveWarehouseSession hive = HiveWarehouseBuilder.
session(session). | // Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestSecureHS2Url.java
// static final String TEST_HS2_URL = "jdbc:hive2://example.com:10084";
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestReadSupport.java
import org.apache.spark.sql.Row;
import org.junit.Test;
import static com.hortonworks.spark.sql.hive.llap.TestSecureHS2Url.TEST_HS2_URL;
import static org.junit.Assert.assertEquals;
package com.hortonworks.spark.sql.hive.llap;
public class TestReadSupport extends SessionTestBase {
@Test
public void testReadSupport() {
HiveWarehouseSession hive = HiveWarehouseBuilder.
session(session). | hs2url(TEST_HS2_URL). |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseDataWriterFactory.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SerializableHadoopConfiguration.java
// public class SerializableHadoopConfiguration implements Serializable {
// Configuration conf;
//
// public SerializableHadoopConfiguration(Configuration hadoopConf) {
// this.conf = hadoopConf;
//
// if (this.conf == null) {
// this.conf = new Configuration();
// }
// }
//
// public SerializableHadoopConfiguration() {
// this.conf = new Configuration();
// }
//
// public Configuration get() {
// return this.conf;
// }
//
// private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// this.conf.write(out);
// }
//
// private void readObject(java.io.ObjectInputStream in) throws IOException {
// this.conf = new Configuration();
// this.conf.readFields(in);
// }
// }
| import com.hortonworks.spark.sql.hive.llap.util.SerializableHadoopConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.types.StructType;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException; | package com.hortonworks.spark.sql.hive.llap;
public class HiveWarehouseDataWriterFactory implements DataWriterFactory<InternalRow> {
protected String jobId;
protected StructType schema;
private Path path; | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SerializableHadoopConfiguration.java
// public class SerializableHadoopConfiguration implements Serializable {
// Configuration conf;
//
// public SerializableHadoopConfiguration(Configuration hadoopConf) {
// this.conf = hadoopConf;
//
// if (this.conf == null) {
// this.conf = new Configuration();
// }
// }
//
// public SerializableHadoopConfiguration() {
// this.conf = new Configuration();
// }
//
// public Configuration get() {
// return this.conf;
// }
//
// private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// this.conf.write(out);
// }
//
// private void readObject(java.io.ObjectInputStream in) throws IOException {
// this.conf = new Configuration();
// this.conf.readFields(in);
// }
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseDataWriterFactory.java
import com.hortonworks.spark.sql.hive.llap.util.SerializableHadoopConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.types.StructType;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
package com.hortonworks.spark.sql.hive.llap;
public class HiveWarehouseDataWriterFactory implements DataWriterFactory<InternalRow> {
protected String jobId;
protected StructType schema;
private Path path; | private SerializableHadoopConfiguration conf; |
hortonworks-spark/spark-llap | src/test/java/com/hortonworks/spark/sql/hive/llap/TestWriteSupport.java | // Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockHiveWarehouseConnector.java
// public static int[] testVector = {1, 2, 3, 4, 5};
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestSecureHS2Url.java
// static final String TEST_HS2_URL = "jdbc:hive2://example.com:10084";
| import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.catalyst.InternalRow;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.hortonworks.spark.sql.hive.llap.MockHiveWarehouseConnector.testVector;
import static com.hortonworks.spark.sql.hive.llap.TestSecureHS2Url.TEST_HS2_URL;
import static org.junit.Assert.assertEquals; | package com.hortonworks.spark.sql.hive.llap;
public class TestWriteSupport extends SessionTestBase {
@Test
public void testWriteSupport() {
HiveWarehouseSession hive = HiveWarehouseBuilder.
session(session). | // Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockHiveWarehouseConnector.java
// public static int[] testVector = {1, 2, 3, 4, 5};
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestSecureHS2Url.java
// static final String TEST_HS2_URL = "jdbc:hive2://example.com:10084";
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestWriteSupport.java
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.catalyst.InternalRow;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.hortonworks.spark.sql.hive.llap.MockHiveWarehouseConnector.testVector;
import static com.hortonworks.spark.sql.hive.llap.TestSecureHS2Url.TEST_HS2_URL;
import static org.junit.Assert.assertEquals;
package com.hortonworks.spark.sql.hive.llap;
public class TestWriteSupport extends SessionTestBase {
@Test
public void testWriteSupport() {
HiveWarehouseSession hive = HiveWarehouseBuilder.
session(session). | hs2url(TEST_HS2_URL). |
hortonworks-spark/spark-llap | src/test/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseSessionHiveQlTest.java | // Path: src/test/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseBuilderTest.java
// class HiveWarehouseBuilderTest extends SessionTestBase {
//
// static final String TEST_USER = "userX";
// static final String TEST_PASSWORD = "passwordX";
// static final String TEST_DBCP2_CONF = "defaultQueryTimeout=100";
// static final Integer TEST_EXEC_RESULTS_MAX = 12345;
// static final String TEST_DEFAULT_DB = "default12345";
//
// @Test
// void testNewEntryPoint() {
// session.sessionState().conf().setConfString(HWConf.HIVESERVER2_JDBC_URL, "test");
// com.hortonworks.hwc.HiveWarehouseSession hive =
// com.hortonworks.hwc.HiveWarehouseSession.session(session)
// .userPassword(TEST_USER, TEST_PASSWORD)
// .dbcp2Conf(TEST_DBCP2_CONF)
// .maxExecResults(TEST_EXEC_RESULTS_MAX)
// .defaultDB(TEST_DEFAULT_DB).build();
// assertEquals(hive.session(), session);
// }
//
// @Test
// void testAllBuilderConfig() {
// HiveWarehouseSessionState sessionState =
// HiveWarehouseBuilder
// .session(session)
// .userPassword(TEST_USER, TEST_PASSWORD)
// .dbcp2Conf(TEST_DBCP2_CONF)
// .maxExecResults(TEST_EXEC_RESULTS_MAX)
// .defaultDB(TEST_DEFAULT_DB)
// .sessionStateForTest();
// MockHiveWarehouseSessionImpl hive = new MockHiveWarehouseSessionImpl(sessionState);
// assertEquals(hive.session(), session);
// assertEquals(HWConf.USER.getString(sessionState), TEST_USER);
// assertEquals(HWConf.PASSWORD.getString(sessionState), TEST_PASSWORD);
// assertEquals(HWConf.DBCP2_CONF.getString(sessionState), TEST_DBCP2_CONF);
// assertEquals(HWConf.MAX_EXEC_RESULTS.getInt(sessionState), TEST_EXEC_RESULTS_MAX);
// assertEquals(HWConf.DEFAULT_DB.getString(sessionState), TEST_DEFAULT_DB);
// }
//
// @Test
// void testAllConfConfig() {
// session.conf().set(HWConf.USER.qualifiedKey, TEST_USER);
// session.conf().set(HWConf.PASSWORD.qualifiedKey, TEST_PASSWORD);
// session.conf().set(HWConf.DBCP2_CONF.qualifiedKey, TEST_DBCP2_CONF);
// session.conf().set(HWConf.MAX_EXEC_RESULTS.qualifiedKey, TEST_EXEC_RESULTS_MAX);
// session.conf().set(HWConf.DEFAULT_DB.qualifiedKey, TEST_DEFAULT_DB);
// HiveWarehouseSessionState sessionState =
// HiveWarehouseBuilder
// .session(session)
// .sessionStateForTest();
// MockHiveWarehouseSessionImpl hive = new MockHiveWarehouseSessionImpl(sessionState);
// assertEquals(hive.sessionState.session, session);
// assertEquals(HWConf.USER.getString(hive.sessionState), TEST_USER);
// assertEquals(HWConf.PASSWORD.getString(hive.sessionState), TEST_PASSWORD);
// assertEquals(HWConf.DBCP2_CONF.getString(hive.sessionState), TEST_DBCP2_CONF);
// assertEquals(HWConf.MAX_EXEC_RESULTS.getInt(hive.sessionState), TEST_EXEC_RESULTS_MAX);
// assertEquals(HWConf.DEFAULT_DB.getString(hive.sessionState), TEST_DEFAULT_DB);
// }
// }
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestSecureHS2Url.java
// static final String TEST_HS2_URL = "jdbc:hive2://example.com:10084";
| import org.junit.Before;
import org.junit.Test;
import static com.hortonworks.spark.sql.hive.llap.HiveWarehouseBuilderTest.*;
import static com.hortonworks.spark.sql.hive.llap.TestSecureHS2Url.TEST_HS2_URL;
import static org.junit.Assert.assertEquals; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.hortonworks.spark.sql.hive.llap;
class HiveWarehouseSessionHiveQlTest extends SessionTestBase {
private HiveWarehouseSession hive;
private int mockExecuteResultSize;
@Before
public void setUp() {
super.setUp();
HiveWarehouseSessionState sessionState =
HiveWarehouseBuilder
.session(session)
.userPassword(TEST_USER, TEST_PASSWORD) | // Path: src/test/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseBuilderTest.java
// class HiveWarehouseBuilderTest extends SessionTestBase {
//
// static final String TEST_USER = "userX";
// static final String TEST_PASSWORD = "passwordX";
// static final String TEST_DBCP2_CONF = "defaultQueryTimeout=100";
// static final Integer TEST_EXEC_RESULTS_MAX = 12345;
// static final String TEST_DEFAULT_DB = "default12345";
//
// @Test
// void testNewEntryPoint() {
// session.sessionState().conf().setConfString(HWConf.HIVESERVER2_JDBC_URL, "test");
// com.hortonworks.hwc.HiveWarehouseSession hive =
// com.hortonworks.hwc.HiveWarehouseSession.session(session)
// .userPassword(TEST_USER, TEST_PASSWORD)
// .dbcp2Conf(TEST_DBCP2_CONF)
// .maxExecResults(TEST_EXEC_RESULTS_MAX)
// .defaultDB(TEST_DEFAULT_DB).build();
// assertEquals(hive.session(), session);
// }
//
// @Test
// void testAllBuilderConfig() {
// HiveWarehouseSessionState sessionState =
// HiveWarehouseBuilder
// .session(session)
// .userPassword(TEST_USER, TEST_PASSWORD)
// .dbcp2Conf(TEST_DBCP2_CONF)
// .maxExecResults(TEST_EXEC_RESULTS_MAX)
// .defaultDB(TEST_DEFAULT_DB)
// .sessionStateForTest();
// MockHiveWarehouseSessionImpl hive = new MockHiveWarehouseSessionImpl(sessionState);
// assertEquals(hive.session(), session);
// assertEquals(HWConf.USER.getString(sessionState), TEST_USER);
// assertEquals(HWConf.PASSWORD.getString(sessionState), TEST_PASSWORD);
// assertEquals(HWConf.DBCP2_CONF.getString(sessionState), TEST_DBCP2_CONF);
// assertEquals(HWConf.MAX_EXEC_RESULTS.getInt(sessionState), TEST_EXEC_RESULTS_MAX);
// assertEquals(HWConf.DEFAULT_DB.getString(sessionState), TEST_DEFAULT_DB);
// }
//
// @Test
// void testAllConfConfig() {
// session.conf().set(HWConf.USER.qualifiedKey, TEST_USER);
// session.conf().set(HWConf.PASSWORD.qualifiedKey, TEST_PASSWORD);
// session.conf().set(HWConf.DBCP2_CONF.qualifiedKey, TEST_DBCP2_CONF);
// session.conf().set(HWConf.MAX_EXEC_RESULTS.qualifiedKey, TEST_EXEC_RESULTS_MAX);
// session.conf().set(HWConf.DEFAULT_DB.qualifiedKey, TEST_DEFAULT_DB);
// HiveWarehouseSessionState sessionState =
// HiveWarehouseBuilder
// .session(session)
// .sessionStateForTest();
// MockHiveWarehouseSessionImpl hive = new MockHiveWarehouseSessionImpl(sessionState);
// assertEquals(hive.sessionState.session, session);
// assertEquals(HWConf.USER.getString(hive.sessionState), TEST_USER);
// assertEquals(HWConf.PASSWORD.getString(hive.sessionState), TEST_PASSWORD);
// assertEquals(HWConf.DBCP2_CONF.getString(hive.sessionState), TEST_DBCP2_CONF);
// assertEquals(HWConf.MAX_EXEC_RESULTS.getInt(hive.sessionState), TEST_EXEC_RESULTS_MAX);
// assertEquals(HWConf.DEFAULT_DB.getString(hive.sessionState), TEST_DEFAULT_DB);
// }
// }
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/TestSecureHS2Url.java
// static final String TEST_HS2_URL = "jdbc:hive2://example.com:10084";
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseSessionHiveQlTest.java
import org.junit.Before;
import org.junit.Test;
import static com.hortonworks.spark.sql.hive.llap.HiveWarehouseBuilderTest.*;
import static com.hortonworks.spark.sql.hive.llap.TestSecureHS2Url.TEST_HS2_URL;
import static org.junit.Assert.assertEquals;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.hortonworks.spark.sql.hive.llap;
class HiveWarehouseSessionHiveQlTest extends SessionTestBase {
private HiveWarehouseSession hive;
private int mockExecuteResultSize;
@Before
public void setUp() {
super.setUp();
HiveWarehouseSessionState sessionState =
HiveWarehouseBuilder
.session(session)
.userPassword(TEST_USER, TEST_PASSWORD) | .hs2url(TEST_HS2_URL) |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/hwc/HiveWarehouseSession.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseBuilder.java
// public class HiveWarehouseBuilder {
//
// HiveWarehouseSessionState sessionState = new HiveWarehouseSessionState();
//
// //Can only be instantiated through session(SparkSession session)
// private HiveWarehouseBuilder() {
// }
//
// public static HiveWarehouseBuilder session(SparkSession session) {
// HiveWarehouseBuilder builder = new HiveWarehouseBuilder();
// builder.sessionState.session = session;
// //Copy all static configuration (e.g. spark-defaults.conf)
// //with keys matching HWConf.CONF_PREFIX into
// //the SparkSQL session conf for this session
// //Otherwise these settings will not be available to
// //v2 DataSourceReader or DataSourceWriter
// //See: {@link org.apache.spark.sql.sources.v2.SessionConfigSupport}
// session.conf().getAll().foreach(new scala.runtime.AbstractFunction1<scala.Tuple2<String, String>, Object>() {
// public Object apply(Tuple2<String, String> keyValue) {
// String key = keyValue._1;
// String value = keyValue._2;
// if(key.startsWith(HiveWarehouseSession.CONF_PREFIX)) {
// session.sessionState().conf().setConfString(key, value);
// }
// return null;
// }
// });
// return builder;
// }
//
// public HiveWarehouseBuilder userPassword(String user, String password) {
// HWConf.USER.setString(sessionState, user);
// HWConf.PASSWORD.setString(sessionState, password);
// return this;
// }
//
// public HiveWarehouseBuilder hs2url(String hs2url) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL, hs2url);
// return this;
// }
//
// public HiveWarehouseBuilder principal(String principal) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL_PRINCIPAL, principal);
// return this;
// }
//
// public HiveWarehouseBuilder credentialsEnabled() {
// sessionState.session.conf().set(HIVESERVER2_CREDENTIAL_ENABLED, "true");
// return this;
// }
//
// //Hive JDBC doesn't support java.sql.Statement.setLargeMaxResults(long)
// //Need to use setMaxResults(int) instead
// public HiveWarehouseBuilder maxExecResults(int maxExecResults) {
// HWConf.MAX_EXEC_RESULTS.setInt(sessionState, maxExecResults);
// return this;
// }
//
// public HiveWarehouseBuilder dbcp2Conf(String dbcp2Conf) {
// HWConf.DBCP2_CONF.setString(sessionState, dbcp2Conf);
// return this;
// }
//
// public HiveWarehouseBuilder defaultDB(String defaultDB) {
// HWConf.DEFAULT_DB.setString(sessionState, defaultDB);
// return this;
// }
//
// //This is the only way for application to obtain a HiveWarehouseSessionImpl
// public HiveWarehouseSessionImpl build() {
// HWConf.RESOLVED_HS2_URL.setString(sessionState, HWConf.getConnectionUrl(sessionState));
// return new HiveWarehouseSessionImpl(this.sessionState);
// }
//
// // Revealed internally for test only. Exposed for Python side.
// public HiveWarehouseSessionState sessionStateForTest() {
// return this.sessionState;
// }
// }
| import com.hortonworks.spark.sql.hive.llap.HiveWarehouseBuilder;
import org.apache.spark.sql.SparkSession; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.hortonworks.hwc;
public interface HiveWarehouseSession extends com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession {
String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
String DATAFRAME_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.HiveStreamingDataSource";
String STREAM_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.streaming.HiveStreamingDataSource";
| // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseBuilder.java
// public class HiveWarehouseBuilder {
//
// HiveWarehouseSessionState sessionState = new HiveWarehouseSessionState();
//
// //Can only be instantiated through session(SparkSession session)
// private HiveWarehouseBuilder() {
// }
//
// public static HiveWarehouseBuilder session(SparkSession session) {
// HiveWarehouseBuilder builder = new HiveWarehouseBuilder();
// builder.sessionState.session = session;
// //Copy all static configuration (e.g. spark-defaults.conf)
// //with keys matching HWConf.CONF_PREFIX into
// //the SparkSQL session conf for this session
// //Otherwise these settings will not be available to
// //v2 DataSourceReader or DataSourceWriter
// //See: {@link org.apache.spark.sql.sources.v2.SessionConfigSupport}
// session.conf().getAll().foreach(new scala.runtime.AbstractFunction1<scala.Tuple2<String, String>, Object>() {
// public Object apply(Tuple2<String, String> keyValue) {
// String key = keyValue._1;
// String value = keyValue._2;
// if(key.startsWith(HiveWarehouseSession.CONF_PREFIX)) {
// session.sessionState().conf().setConfString(key, value);
// }
// return null;
// }
// });
// return builder;
// }
//
// public HiveWarehouseBuilder userPassword(String user, String password) {
// HWConf.USER.setString(sessionState, user);
// HWConf.PASSWORD.setString(sessionState, password);
// return this;
// }
//
// public HiveWarehouseBuilder hs2url(String hs2url) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL, hs2url);
// return this;
// }
//
// public HiveWarehouseBuilder principal(String principal) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL_PRINCIPAL, principal);
// return this;
// }
//
// public HiveWarehouseBuilder credentialsEnabled() {
// sessionState.session.conf().set(HIVESERVER2_CREDENTIAL_ENABLED, "true");
// return this;
// }
//
// //Hive JDBC doesn't support java.sql.Statement.setLargeMaxResults(long)
// //Need to use setMaxResults(int) instead
// public HiveWarehouseBuilder maxExecResults(int maxExecResults) {
// HWConf.MAX_EXEC_RESULTS.setInt(sessionState, maxExecResults);
// return this;
// }
//
// public HiveWarehouseBuilder dbcp2Conf(String dbcp2Conf) {
// HWConf.DBCP2_CONF.setString(sessionState, dbcp2Conf);
// return this;
// }
//
// public HiveWarehouseBuilder defaultDB(String defaultDB) {
// HWConf.DEFAULT_DB.setString(sessionState, defaultDB);
// return this;
// }
//
// //This is the only way for application to obtain a HiveWarehouseSessionImpl
// public HiveWarehouseSessionImpl build() {
// HWConf.RESOLVED_HS2_URL.setString(sessionState, HWConf.getConnectionUrl(sessionState));
// return new HiveWarehouseSessionImpl(this.sessionState);
// }
//
// // Revealed internally for test only. Exposed for Python side.
// public HiveWarehouseSessionState sessionStateForTest() {
// return this.sessionState;
// }
// }
// Path: src/main/java/com/hortonworks/hwc/HiveWarehouseSession.java
import com.hortonworks.spark.sql.hive.llap.HiveWarehouseBuilder;
import org.apache.spark.sql.SparkSession;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.hortonworks.hwc;
public interface HiveWarehouseSession extends com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession {
String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
String DATAFRAME_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.HiveStreamingDataSource";
String STREAM_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.streaming.HiveStreamingDataSource";
| static HiveWarehouseBuilder session(SparkSession session) { |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSource.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseSession.java
// public interface HiveWarehouseSession {
//
// String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
// String SPARK_DATASOURCES_PREFIX = "spark.datasource";
// String HIVE_WAREHOUSE_POSTFIX = "hive.warehouse";
// String CONF_PREFIX = SPARK_DATASOURCES_PREFIX + "." + HIVE_WAREHOUSE_POSTFIX;
//
// Dataset<Row> executeQuery(String sql);
// Dataset<Row> q(String sql);
//
// Dataset<Row> execute(String sql);
//
// boolean executeUpdate(String sql);
//
// Dataset<Row> table(String sql);
//
// SparkSession session();
//
// void setDatabase(String name);
//
// Dataset<Row> showDatabases();
//
// Dataset<Row> showTables();
//
// Dataset<Row> describeTable(String table);
//
// void createDatabase(String database, boolean ifNotExists);
//
// CreateTableBuilder createTable(String tableName);
//
// void dropDatabase(String database, boolean ifExists, boolean cascade);
//
// void dropTable(String table, boolean ifExists, boolean purge);
// }
| import java.util.Arrays;
import java.util.List;
import com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.StreamWriteSupport;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.sources.v2.SessionConfigSupport;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSource implements DataSourceV2, StreamWriteSupport, SessionConfigSupport {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSource.class);
@Override
public StreamWriter createStreamWriter(final String queryId, final StructType schema, final OutputMode mode,
final DataSourceOptions options) {
return createDataSourceWriter(queryId, schema, options);
}
private HiveStreamingDataSourceWriter createDataSourceWriter(final String id, final StructType schema,
final DataSourceOptions options) {
String dbName = null;
if(options.get("default.db").isPresent()) {
dbName = options.get("default.db").get();
} else {
dbName = options.get("database").orElse("default");
}
String tableName = options.get("table").orElse(null);
String partition = options.get("partition").orElse(null);
List<String> partitionValues = partition == null ? null : Arrays.asList(partition.split(","));
String metastoreUri = options.get("metastoreUri").orElse("thrift://localhost:9083");
String metastoreKerberosPrincipal = options.get("metastoreKrbPrincipal").orElse(null);
LOG.info("OPTIONS - database: {} table: {} partition: {} metastoreUri: {} metastoreKerberosPrincipal: {}",
dbName, tableName, partition, metastoreUri, metastoreKerberosPrincipal);
return new HiveStreamingDataSourceWriter(id, schema, dbName, tableName,
partitionValues, metastoreUri, metastoreKerberosPrincipal);
}
@Override public String keyPrefix() { | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseSession.java
// public interface HiveWarehouseSession {
//
// String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
// String SPARK_DATASOURCES_PREFIX = "spark.datasource";
// String HIVE_WAREHOUSE_POSTFIX = "hive.warehouse";
// String CONF_PREFIX = SPARK_DATASOURCES_PREFIX + "." + HIVE_WAREHOUSE_POSTFIX;
//
// Dataset<Row> executeQuery(String sql);
// Dataset<Row> q(String sql);
//
// Dataset<Row> execute(String sql);
//
// boolean executeUpdate(String sql);
//
// Dataset<Row> table(String sql);
//
// SparkSession session();
//
// void setDatabase(String name);
//
// Dataset<Row> showDatabases();
//
// Dataset<Row> showTables();
//
// Dataset<Row> describeTable(String table);
//
// void createDatabase(String database, boolean ifNotExists);
//
// CreateTableBuilder createTable(String tableName);
//
// void dropDatabase(String database, boolean ifExists, boolean cascade);
//
// void dropTable(String table, boolean ifExists, boolean purge);
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSource.java
import java.util.Arrays;
import java.util.List;
import com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.StreamWriteSupport;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.sources.v2.SessionConfigSupport;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSource implements DataSourceV2, StreamWriteSupport, SessionConfigSupport {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSource.class);
@Override
public StreamWriter createStreamWriter(final String queryId, final StructType schema, final OutputMode mode,
final DataSourceOptions options) {
return createDataSourceWriter(queryId, schema, options);
}
private HiveStreamingDataSourceWriter createDataSourceWriter(final String id, final StructType schema,
final DataSourceOptions options) {
String dbName = null;
if(options.get("default.db").isPresent()) {
dbName = options.get("default.db").get();
} else {
dbName = options.get("database").orElse("default");
}
String tableName = options.get("table").orElse(null);
String partition = options.get("partition").orElse(null);
List<String> partitionValues = partition == null ? null : Arrays.asList(partition.split(","));
String metastoreUri = options.get("metastoreUri").orElse("thrift://localhost:9083");
String metastoreKerberosPrincipal = options.get("metastoreKrbPrincipal").orElse(null);
LOG.info("OPTIONS - database: {} table: {} partition: {} metastoreUri: {} metastoreKerberosPrincipal: {}",
dbName, tableName, partition, metastoreUri, metastoreKerberosPrincipal);
return new HiveStreamingDataSourceWriter(id, schema, dbName, tableName,
partitionValues, metastoreUri, metastoreKerberosPrincipal);
}
@Override public String keyPrefix() { | return HiveWarehouseSession.HIVE_WAREHOUSE_POSTFIX; |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSourceWriter.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveStreamingDataWriterFactory.java
// public class HiveStreamingDataWriterFactory implements DataWriterFactory<InternalRow> {
//
// private String jobId;
// private StructType schema;
// private long commitIntervalRows;
// private String db;
// private String table;
// private List<String> partition;
// private String metastoreUri;
// private String metastoreKrbPrincipal;
//
// public HiveStreamingDataWriterFactory(String jobId, StructType schema, long commitIntervalRows, String db,
// String table, List<String> partition, final String metastoreUri, final String metastoreKrbPrincipal) {
// this.jobId = jobId;
// this.schema = schema;
// this.db = db;
// this.table = table;
// this.partition = partition;
// this.commitIntervalRows = commitIntervalRows;
// this.metastoreUri = metastoreUri;
// this.metastoreKrbPrincipal = metastoreKrbPrincipal;
// }
//
// @Override
// public DataWriter<InternalRow> createDataWriter(int partitionId, int attemptNumber) {
// ClassLoader restoredClassloader = Thread.currentThread().getContextClassLoader();
// ClassLoader isolatedClassloader = HiveIsolatedClassLoader.isolatedClassLoader();
// try {
// Thread.currentThread().setContextClassLoader(isolatedClassloader);
// return new HiveStreamingDataWriter(jobId, schema, commitIntervalRows, partitionId, attemptNumber, db,
// table, partition, metastoreUri, metastoreKrbPrincipal);
// } finally {
// Thread.currentThread().setContextClassLoader(restoredClassloader);
// }
// }
// }
| import java.util.List;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.SupportsWriteInternalRow;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hortonworks.spark.sql.hive.llap.HiveStreamingDataWriterFactory; | package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSourceWriter implements SupportsWriteInternalRow, StreamWriter {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSourceWriter.class);
private String jobId;
private StructType schema;
private String db;
private String table;
private List<String> partition;
private String metastoreUri;
private String metastoreKerberosPrincipal;
public HiveStreamingDataSourceWriter(String jobId, StructType schema, String db,
String table, List<String> partition, final String metastoreUri, final String metastoreKerberosPrincipal) {
this.jobId = jobId;
this.schema = schema;
this.db = db;
this.table = table;
this.partition = partition;
this.metastoreUri = metastoreUri;
this.metastoreKerberosPrincipal = metastoreKerberosPrincipal;
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() {
// for the streaming case, commit transaction happens on task commit() (atleast-once), so interval is set to -1 | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveStreamingDataWriterFactory.java
// public class HiveStreamingDataWriterFactory implements DataWriterFactory<InternalRow> {
//
// private String jobId;
// private StructType schema;
// private long commitIntervalRows;
// private String db;
// private String table;
// private List<String> partition;
// private String metastoreUri;
// private String metastoreKrbPrincipal;
//
// public HiveStreamingDataWriterFactory(String jobId, StructType schema, long commitIntervalRows, String db,
// String table, List<String> partition, final String metastoreUri, final String metastoreKrbPrincipal) {
// this.jobId = jobId;
// this.schema = schema;
// this.db = db;
// this.table = table;
// this.partition = partition;
// this.commitIntervalRows = commitIntervalRows;
// this.metastoreUri = metastoreUri;
// this.metastoreKrbPrincipal = metastoreKrbPrincipal;
// }
//
// @Override
// public DataWriter<InternalRow> createDataWriter(int partitionId, int attemptNumber) {
// ClassLoader restoredClassloader = Thread.currentThread().getContextClassLoader();
// ClassLoader isolatedClassloader = HiveIsolatedClassLoader.isolatedClassLoader();
// try {
// Thread.currentThread().setContextClassLoader(isolatedClassloader);
// return new HiveStreamingDataWriter(jobId, schema, commitIntervalRows, partitionId, attemptNumber, db,
// table, partition, metastoreUri, metastoreKrbPrincipal);
// } finally {
// Thread.currentThread().setContextClassLoader(restoredClassloader);
// }
// }
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSourceWriter.java
import java.util.List;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.SupportsWriteInternalRow;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hortonworks.spark.sql.hive.llap.HiveStreamingDataWriterFactory;
package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSourceWriter implements SupportsWriteInternalRow, StreamWriter {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSourceWriter.class);
private String jobId;
private StructType schema;
private String db;
private String table;
private List<String> partition;
private String metastoreUri;
private String metastoreKerberosPrincipal;
public HiveStreamingDataSourceWriter(String jobId, StructType schema, String db,
String table, List<String> partition, final String metastoreUri, final String metastoreKerberosPrincipal) {
this.jobId = jobId;
this.schema = schema;
this.db = db;
this.table = table;
this.partition = partition;
this.metastoreUri = metastoreUri;
this.metastoreKerberosPrincipal = metastoreKerberosPrincipal;
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() {
// for the streaming case, commit transaction happens on task commit() (atleast-once), so interval is set to -1 | return new HiveStreamingDataWriterFactory(jobId, schema, -1, db, table, partition, metastoreUri, |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/util/SchemaUtil.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/CreateTableBuilder.java
// public class CreateTableBuilder implements com.hortonworks.hwc.CreateTableBuilder {
// private HiveWarehouseSession hive;
// private String database;
// private String tableName;
// private boolean ifNotExists;
// private List<Pair<String, String>> cols = new ArrayList<>();
// private List<Pair<String, String>> parts = new ArrayList<>();
// private List<Pair<String, String>> props = new ArrayList<>();
// private String[] clusters;
// private Long buckets;
//
// public CreateTableBuilder(HiveWarehouseSession hive, String database, String tableName) {
// this.hive = hive;
// this.tableName = tableName;
// this.database = database;
// }
//
// @Override
// public CreateTableBuilder ifNotExists() {
// this.ifNotExists = true;
// return this;
// }
//
// @Override
// public CreateTableBuilder column(String name, String type) {
// cols.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder partition(String name, String type) {
// parts.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder prop(String key, String value) {
// props.add(Pair.of(key, value));
// return this;
// }
//
// @Override
// public CreateTableBuilder clusterBy(long numBuckets, String ... columns) {
// this.buckets = numBuckets;
// this.clusters = columns;
// return this;
// }
//
// @Override
// public void create() {
// hive.executeUpdate(this.toString());
// }
//
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append(createTablePrelude(database, tableName, ifNotExists));
// if(cols.size() > 0) {
// List<String> colsStrings = new ArrayList<>();
// for(Pair<String, String> col : cols) {
// colsStrings.add(col.getKey() + " " + col.getValue());
// }
// builder.append(columnSpec(join(",", colsStrings)));
// }
// if(parts.size() > 0) {
// List<String> partsStrings = new ArrayList<>();
// for(Pair<String, String> part : parts) {
// partsStrings.add(part.getKey() + " " + part.getValue());
// }
// builder.append(partitionSpec(join(",", partsStrings)));
// }
// if(clusters != null) {
// builder.append(bucketSpec(join(",", clusters), buckets));
// }
// //Currently only managed ORC tables are supported
// builder.append(" STORED AS ORC ");
// if(props.size() > 0) {
// List<String> keyValueStrings = new ArrayList<>();
// for(Pair<String, String> keyValue : props) {
// keyValueStrings.add(format("\"%s\"=\"%s\"", keyValue.getKey(), keyValue.getValue()));
// }
// builder.append(tblProperties(join(",", keyValueStrings)));
// }
// return builder.toString();
// }
// }
| import com.hortonworks.spark.sql.hive.llap.CreateTableBuilder;
import org.apache.hadoop.hive.llap.FieldDesc;
import org.apache.hadoop.hive.llap.Schema;
import org.apache.spark.sql.types.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.format; | package com.hortonworks.spark.sql.hive.llap.util;
public class SchemaUtil {
private static final String HIVE_TYPE_STRING = "HIVE_TYPE_STRING";
public static StructType convertSchema(Schema schema) {
List<FieldDesc> columns = schema.getColumns();
List<String> types = new ArrayList<>();
for(FieldDesc fieldDesc : columns) {
String name;
if(fieldDesc.getName().contains(".")) {
name = fieldDesc.getName().split("\\.")[1];
} else {
name = fieldDesc.getName();
}
types.add(format("`%s` %s", name, fieldDesc.getTypeInfo().toString()));
}
return StructType.fromDDL(String.join(", ", types));
}
public static String[] columnNames(StructType schema) {
String[] requiredColumns = new String[schema.length()];
int i = 0;
for (StructField field : schema.fields()) {
requiredColumns[i] = field.name();
i++;
}
return requiredColumns;
}
/**
*
* Builds create table query from given dataframe schema.
*
* @param schema spark dataframe schema
* @param database database name for create table query
* @param table table name for create table query
* @return a create table query string
*/
public static String buildHiveCreateTableQueryFromSparkDFSchema(StructType schema, String database, String table) { | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/CreateTableBuilder.java
// public class CreateTableBuilder implements com.hortonworks.hwc.CreateTableBuilder {
// private HiveWarehouseSession hive;
// private String database;
// private String tableName;
// private boolean ifNotExists;
// private List<Pair<String, String>> cols = new ArrayList<>();
// private List<Pair<String, String>> parts = new ArrayList<>();
// private List<Pair<String, String>> props = new ArrayList<>();
// private String[] clusters;
// private Long buckets;
//
// public CreateTableBuilder(HiveWarehouseSession hive, String database, String tableName) {
// this.hive = hive;
// this.tableName = tableName;
// this.database = database;
// }
//
// @Override
// public CreateTableBuilder ifNotExists() {
// this.ifNotExists = true;
// return this;
// }
//
// @Override
// public CreateTableBuilder column(String name, String type) {
// cols.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder partition(String name, String type) {
// parts.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder prop(String key, String value) {
// props.add(Pair.of(key, value));
// return this;
// }
//
// @Override
// public CreateTableBuilder clusterBy(long numBuckets, String ... columns) {
// this.buckets = numBuckets;
// this.clusters = columns;
// return this;
// }
//
// @Override
// public void create() {
// hive.executeUpdate(this.toString());
// }
//
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append(createTablePrelude(database, tableName, ifNotExists));
// if(cols.size() > 0) {
// List<String> colsStrings = new ArrayList<>();
// for(Pair<String, String> col : cols) {
// colsStrings.add(col.getKey() + " " + col.getValue());
// }
// builder.append(columnSpec(join(",", colsStrings)));
// }
// if(parts.size() > 0) {
// List<String> partsStrings = new ArrayList<>();
// for(Pair<String, String> part : parts) {
// partsStrings.add(part.getKey() + " " + part.getValue());
// }
// builder.append(partitionSpec(join(",", partsStrings)));
// }
// if(clusters != null) {
// builder.append(bucketSpec(join(",", clusters), buckets));
// }
// //Currently only managed ORC tables are supported
// builder.append(" STORED AS ORC ");
// if(props.size() > 0) {
// List<String> keyValueStrings = new ArrayList<>();
// for(Pair<String, String> keyValue : props) {
// keyValueStrings.add(format("\"%s\"=\"%s\"", keyValue.getKey(), keyValue.getValue()));
// }
// builder.append(tblProperties(join(",", keyValueStrings)));
// }
// return builder.toString();
// }
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SchemaUtil.java
import com.hortonworks.spark.sql.hive.llap.CreateTableBuilder;
import org.apache.hadoop.hive.llap.FieldDesc;
import org.apache.hadoop.hive.llap.Schema;
import org.apache.spark.sql.types.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.format;
package com.hortonworks.spark.sql.hive.llap.util;
public class SchemaUtil {
private static final String HIVE_TYPE_STRING = "HIVE_TYPE_STRING";
public static StructType convertSchema(Schema schema) {
List<FieldDesc> columns = schema.getColumns();
List<String> types = new ArrayList<>();
for(FieldDesc fieldDesc : columns) {
String name;
if(fieldDesc.getName().contains(".")) {
name = fieldDesc.getName().split("\\.")[1];
} else {
name = fieldDesc.getName();
}
types.add(format("`%s` %s", name, fieldDesc.getTypeInfo().toString()));
}
return StructType.fromDDL(String.join(", ", types));
}
public static String[] columnNames(StructType schema) {
String[] requiredColumns = new String[schema.length()];
int i = 0;
for (StructField field : schema.fields()) {
requiredColumns[i] = field.name();
i++;
}
return requiredColumns;
}
/**
*
* Builds create table query from given dataframe schema.
*
* @param schema spark dataframe schema
* @param database database name for create table query
* @param table table name for create table query
* @return a create table query string
*/
public static String buildHiveCreateTableQueryFromSparkDFSchema(StructType schema, String database, String table) { | CreateTableBuilder createTableBuilder = new CreateTableBuilder(null, database, table); |
hortonworks-spark/spark-llap | src/test/java/com/hortonworks/spark/sql/hive/llap/MockWriteSupport.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SerializableHadoopConfiguration.java
// public class SerializableHadoopConfiguration implements Serializable {
// Configuration conf;
//
// public SerializableHadoopConfiguration(Configuration hadoopConf) {
// this.conf = hadoopConf;
//
// if (this.conf == null) {
// this.conf = new Configuration();
// }
// }
//
// public SerializableHadoopConfiguration() {
// this.conf = new Configuration();
// }
//
// public Configuration get() {
// return this.conf;
// }
//
// private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// this.conf.write(out);
// }
//
// private void readObject(java.io.ObjectInputStream in) throws IOException {
// this.conf = new Configuration();
// this.conf.readFields(in);
// }
// }
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockHiveWarehouseConnector.java
// public static int[] testVector = {1, 2, 3, 4, 5};
| import com.hortonworks.spark.sql.hive.llap.util.SerializableHadoopConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.execution.datasources.OutputWriter;
import org.apache.spark.sql.execution.datasources.orc.OrcOutputWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.types.StructType;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.hortonworks.spark.sql.hive.llap.MockHiveWarehouseConnector.testVector;
import static org.junit.Assert.assertEquals; | package com.hortonworks.spark.sql.hive.llap;
public class MockWriteSupport {
public static class MockHiveWarehouseDataSourceWriter extends HiveWarehouseDataSourceWriter {
public MockHiveWarehouseDataSourceWriter(Map<String, String> options, String jobId, StructType schema, Path path,
Configuration conf) {
super(options, jobId, schema, path, conf);
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() { | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SerializableHadoopConfiguration.java
// public class SerializableHadoopConfiguration implements Serializable {
// Configuration conf;
//
// public SerializableHadoopConfiguration(Configuration hadoopConf) {
// this.conf = hadoopConf;
//
// if (this.conf == null) {
// this.conf = new Configuration();
// }
// }
//
// public SerializableHadoopConfiguration() {
// this.conf = new Configuration();
// }
//
// public Configuration get() {
// return this.conf;
// }
//
// private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// this.conf.write(out);
// }
//
// private void readObject(java.io.ObjectInputStream in) throws IOException {
// this.conf = new Configuration();
// this.conf.readFields(in);
// }
// }
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockHiveWarehouseConnector.java
// public static int[] testVector = {1, 2, 3, 4, 5};
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockWriteSupport.java
import com.hortonworks.spark.sql.hive.llap.util.SerializableHadoopConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.execution.datasources.OutputWriter;
import org.apache.spark.sql.execution.datasources.orc.OrcOutputWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.types.StructType;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.hortonworks.spark.sql.hive.llap.MockHiveWarehouseConnector.testVector;
import static org.junit.Assert.assertEquals;
package com.hortonworks.spark.sql.hive.llap;
public class MockWriteSupport {
public static class MockHiveWarehouseDataSourceWriter extends HiveWarehouseDataSourceWriter {
public MockHiveWarehouseDataSourceWriter(Map<String, String> options, String jobId, StructType schema, Path path,
Configuration conf) {
super(options, jobId, schema, path, conf);
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() { | return new MockHiveWarehouseDataWriterFactory(jobId, schema, path, new SerializableHadoopConfiguration(conf)); |
jenkinsci/mesos-plugin | src/main/java/org/jenkinsci/plugins/mesos/api/LaunchCommandBuilder.java | // Path: src/main/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplate.java
// public static class ContainerInfo extends AbstractDescribableImpl<ContainerInfo> {
//
// private final String type;
// private final String dockerImage;
// private final List<Volume> volumes;
// private final Network networking;
// private final boolean dockerPrivilegedMode;
// private final boolean dockerForcePullImage;
// private boolean isDind;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> portMappings;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean dockerImageCustomizable;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> parameters;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> networkInfos;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean useCustomDockerCommandShell;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient String customDockerCommandShell;
//
// @DataBoundConstructor
// public ContainerInfo(
// String type,
// String dockerImage,
// boolean isDind,
// boolean dockerPrivilegedMode,
// boolean dockerForcePullImage,
// List<Volume> volumes,
// Network networking) {
// this.type = type;
// this.dockerImage = dockerImage;
// this.dockerPrivilegedMode = dockerPrivilegedMode;
// this.dockerForcePullImage = dockerForcePullImage;
// this.volumes = volumes;
// this.isDind = isDind;
// this.networking =
// (networking != null) ? networking : ContainerInfoTaskInfoBuilder.DEFAULT_NETWORKING;
// }
//
// public boolean getIsDind() {
// return this.isDind;
// }
//
// public Network getNetworking() {
// return this.networking;
// }
//
// public String getType() {
// return type;
// }
//
// public String getDockerImage() {
// return dockerImage;
// }
//
// public boolean getDockerPrivilegedMode() {
// return dockerPrivilegedMode;
// }
//
// public boolean getDockerForcePullImage() {
// return dockerForcePullImage;
// }
//
// public List<Volume> getVolumes() {
// return volumes;
// }
//
// public List<Volume> getVolumesOrEmpty() {
// return (this.volumes != null) ? this.volumes : Collections.emptyList();
// }
//
// @Extension
// public static final class DescriptorImpl extends Descriptor<ContainerInfo> {
//
// public DescriptorImpl() {
// load();
// }
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.mesosphere.usi.core.models.PodId;
import com.mesosphere.usi.core.models.commands.LaunchPod;
import com.mesosphere.usi.core.models.constraints.AgentFilter;
import com.mesosphere.usi.core.models.constraints.AttributeStringIsFilter;
import com.mesosphere.usi.core.models.faultdomain.DomainFilter;
import com.mesosphere.usi.core.models.faultdomain.HomeRegionFilter$;
import com.mesosphere.usi.core.models.resources.ScalarRequirement;
import com.mesosphere.usi.core.models.template.FetchUri;
import com.mesosphere.usi.core.models.template.RunTemplate;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import jenkins.model.Jenkins;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.jenkinsci.plugins.mesos.MesosAgentSpecTemplate.ContainerInfo;
import scala.Option; | package org.jenkinsci.plugins.mesos.api;
/**
* A simpler factory for building {@link com.mesosphere.usi.core.models.commands.LaunchPod} for
* Jenkins agents.
*/
public class LaunchCommandBuilder {
public LaunchCommandBuilder() {}
private static final String AGENT_JAR_URI_SUFFIX = "jnlpJars/agent.jar";
// We allocate extra memory for the JVM
private static final int JVM_XMX = 32;
public static enum AgentCommandStyle {
Linux,
Windows
}
private static final String LINUX_AGENT_COMMAND_TEMPLATE =
"java -DHUDSON_HOME=jenkins -server -Xmx%dm %s -jar ${MESOS_SANDBOX-.}/agent.jar %s %s -jnlpUrl %s";
private static final String WINDOWS_AGENT_COMMAND_TEMPLATE =
"java -DHUDSON_HOME=jenkins -server -Xmx%dm %s -jar %%MESOS_SANDBOX%%/agent.jar %s %s -jnlpUrl %s";
private static final String JNLP_SECRET_FORMAT = "-secret %s";
private PodId id = null;
private ScalarRequirement cpus = null;
private ScalarRequirement memory = null;
private ScalarRequirement disk = null;
private String role = null;
private List<FetchUri> additionalFetchUris = Collections.emptyList(); | // Path: src/main/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplate.java
// public static class ContainerInfo extends AbstractDescribableImpl<ContainerInfo> {
//
// private final String type;
// private final String dockerImage;
// private final List<Volume> volumes;
// private final Network networking;
// private final boolean dockerPrivilegedMode;
// private final boolean dockerForcePullImage;
// private boolean isDind;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> portMappings;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean dockerImageCustomizable;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> parameters;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> networkInfos;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean useCustomDockerCommandShell;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient String customDockerCommandShell;
//
// @DataBoundConstructor
// public ContainerInfo(
// String type,
// String dockerImage,
// boolean isDind,
// boolean dockerPrivilegedMode,
// boolean dockerForcePullImage,
// List<Volume> volumes,
// Network networking) {
// this.type = type;
// this.dockerImage = dockerImage;
// this.dockerPrivilegedMode = dockerPrivilegedMode;
// this.dockerForcePullImage = dockerForcePullImage;
// this.volumes = volumes;
// this.isDind = isDind;
// this.networking =
// (networking != null) ? networking : ContainerInfoTaskInfoBuilder.DEFAULT_NETWORKING;
// }
//
// public boolean getIsDind() {
// return this.isDind;
// }
//
// public Network getNetworking() {
// return this.networking;
// }
//
// public String getType() {
// return type;
// }
//
// public String getDockerImage() {
// return dockerImage;
// }
//
// public boolean getDockerPrivilegedMode() {
// return dockerPrivilegedMode;
// }
//
// public boolean getDockerForcePullImage() {
// return dockerForcePullImage;
// }
//
// public List<Volume> getVolumes() {
// return volumes;
// }
//
// public List<Volume> getVolumesOrEmpty() {
// return (this.volumes != null) ? this.volumes : Collections.emptyList();
// }
//
// @Extension
// public static final class DescriptorImpl extends Descriptor<ContainerInfo> {
//
// public DescriptorImpl() {
// load();
// }
// }
// }
// Path: src/main/java/org/jenkinsci/plugins/mesos/api/LaunchCommandBuilder.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.mesosphere.usi.core.models.PodId;
import com.mesosphere.usi.core.models.commands.LaunchPod;
import com.mesosphere.usi.core.models.constraints.AgentFilter;
import com.mesosphere.usi.core.models.constraints.AttributeStringIsFilter;
import com.mesosphere.usi.core.models.faultdomain.DomainFilter;
import com.mesosphere.usi.core.models.faultdomain.HomeRegionFilter$;
import com.mesosphere.usi.core.models.resources.ScalarRequirement;
import com.mesosphere.usi.core.models.template.FetchUri;
import com.mesosphere.usi.core.models.template.RunTemplate;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import jenkins.model.Jenkins;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.jenkinsci.plugins.mesos.MesosAgentSpecTemplate.ContainerInfo;
import scala.Option;
package org.jenkinsci.plugins.mesos.api;
/**
* A simpler factory for building {@link com.mesosphere.usi.core.models.commands.LaunchPod} for
* Jenkins agents.
*/
public class LaunchCommandBuilder {
public LaunchCommandBuilder() {}
private static final String AGENT_JAR_URI_SUFFIX = "jnlpJars/agent.jar";
// We allocate extra memory for the JVM
private static final int JVM_XMX = 32;
public static enum AgentCommandStyle {
Linux,
Windows
}
private static final String LINUX_AGENT_COMMAND_TEMPLATE =
"java -DHUDSON_HOME=jenkins -server -Xmx%dm %s -jar ${MESOS_SANDBOX-.}/agent.jar %s %s -jnlpUrl %s";
private static final String WINDOWS_AGENT_COMMAND_TEMPLATE =
"java -DHUDSON_HOME=jenkins -server -Xmx%dm %s -jar %%MESOS_SANDBOX%%/agent.jar %s %s -jnlpUrl %s";
private static final String JNLP_SECRET_FORMAT = "-secret %s";
private PodId id = null;
private ScalarRequirement cpus = null;
private ScalarRequirement memory = null;
private ScalarRequirement disk = null;
private String role = null;
private List<FetchUri> additionalFetchUris = Collections.emptyList(); | private Optional<ContainerInfo> containerInfo = Optional.empty(); |
jenkinsci/mesos-plugin | src/test/java/org/jenkinsci/plugins/mesos/MesosJenkinsAgentTest.java | // Path: src/test/java/org/jenkinsci/plugins/mesos/fixture/AgentSpecMother.java
// public class AgentSpecMother {
//
// public static final MesosAgentSpecTemplate simple =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.1",
// "32",
// 1,
// 1,
// 1,
// "0",
// "",
// "",
// Collections.emptyList(),
// null,
// null,
// null);
//
// public static final MesosAgentSpecTemplate docker =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.5",
// "512",
// 3,
// 1,
// 1,
// "1",
// "",
// "",
// Collections.emptyList(),
// new ContainerInfo(
// "DOCKER",
// "jeschkies/jenkins-simple-agent:testing",
// false,
// false,
// true,
// Collections.emptyList(),
// Network.HOST),
// null,
// null);
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import com.mesosphere.usi.core.models.PodId;
import com.mesosphere.usi.core.models.PodStatus;
import com.mesosphere.usi.core.models.PodStatusUpdatedEvent;
import com.mesosphere.usi.core.models.TaskId;
import hudson.model.Descriptor;
import hudson.model.Node;
import java.io.IOException;
import java.net.URL;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.mesos.v1.Protos.TaskID;
import org.apache.mesos.v1.Protos.TaskState;
import org.apache.mesos.v1.Protos.TaskStatus;
import org.jenkinsci.plugins.mesos.fixture.AgentSpecMother;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import scala.Option; | package org.jenkinsci.plugins.mesos;
@ExtendWith(TestUtils.JenkinsParameterResolver.class)
public class MesosJenkinsAgentTest {
static ActorSystem system = ActorSystem.create("agent-test");
static ActorMaterializer materializer = ActorMaterializer.create(system);
@Test
void shortcircuitWaitUntilOnline(TestUtils.JenkinsRule j)
throws Descriptor.FormException, IOException {
// Given a Mesos Jenkins agent.
final MesosJenkinsAgent agent =
new MesosJenkinsAgent(
null,
"failed-agent", | // Path: src/test/java/org/jenkinsci/plugins/mesos/fixture/AgentSpecMother.java
// public class AgentSpecMother {
//
// public static final MesosAgentSpecTemplate simple =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.1",
// "32",
// 1,
// 1,
// 1,
// "0",
// "",
// "",
// Collections.emptyList(),
// null,
// null,
// null);
//
// public static final MesosAgentSpecTemplate docker =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.5",
// "512",
// 3,
// 1,
// 1,
// "1",
// "",
// "",
// Collections.emptyList(),
// new ContainerInfo(
// "DOCKER",
// "jeschkies/jenkins-simple-agent:testing",
// false,
// false,
// true,
// Collections.emptyList(),
// Network.HOST),
// null,
// null);
// }
// Path: src/test/java/org/jenkinsci/plugins/mesos/MesosJenkinsAgentTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import com.mesosphere.usi.core.models.PodId;
import com.mesosphere.usi.core.models.PodStatus;
import com.mesosphere.usi.core.models.PodStatusUpdatedEvent;
import com.mesosphere.usi.core.models.TaskId;
import hudson.model.Descriptor;
import hudson.model.Node;
import java.io.IOException;
import java.net.URL;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.mesos.v1.Protos.TaskID;
import org.apache.mesos.v1.Protos.TaskState;
import org.apache.mesos.v1.Protos.TaskStatus;
import org.jenkinsci.plugins.mesos.fixture.AgentSpecMother;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import scala.Option;
package org.jenkinsci.plugins.mesos;
@ExtendWith(TestUtils.JenkinsParameterResolver.class)
public class MesosJenkinsAgentTest {
static ActorSystem system = ActorSystem.create("agent-test");
static ActorMaterializer materializer = ActorMaterializer.create(system);
@Test
void shortcircuitWaitUntilOnline(TestUtils.JenkinsRule j)
throws Descriptor.FormException, IOException {
// Given a Mesos Jenkins agent.
final MesosJenkinsAgent agent =
new MesosJenkinsAgent(
null,
"failed-agent", | AgentSpecMother.simple, |
jenkinsci/mesos-plugin | src/test/java/org/jenkinsci/plugins/mesos/api/SessionTest.java | // Path: src/test/java/org/jenkinsci/plugins/mesos/TestUtils.java
// public class TestUtils {
// public static class JenkinsRule extends org.jvnet.hudson.test.JenkinsRule {
// private final ParameterContext context;
//
// JenkinsRule(ParameterContext context) {
// this.context = context;
// }
//
// @Override
// public void recipe() throws Exception {
// Optional<JenkinsRecipe> a = context.findAnnotation(JenkinsRecipe.class);
// if (!a.isPresent()) return;
// final JenkinsRecipe.Runner runner = a.get().value().newInstance();
// recipes.add(runner);
// tearDowns.add(() -> runner.tearDown(this, a.get()));
// }
// }
//
// public static class JenkinsParameterResolver implements ParameterResolver, AfterEachCallback {
// private static final String key = "jenkins-instance";
// private static final ExtensionContext.Namespace ns =
// ExtensionContext.Namespace.create(JenkinsParameterResolver.class);
//
// @Override
// public boolean supportsParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// return parameterContext.getParameter().getType().equals(JenkinsRule.class);
// }
//
// @Override
// public Object resolveParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// JenkinsRule instance =
// extensionContext
// .getStore(ns)
// .getOrComputeIfAbsent(
// key, key -> new JenkinsRule(parameterContext), JenkinsRule.class);
// try {
// instance.before();
// return instance;
// } catch (Throwable t) {
// throw new ParameterResolutionException(t.toString());
// }
// }
//
// @Override
// public void afterEach(ExtensionContext context) throws Exception {
// JenkinsRule rule = context.getStore(ns).remove(key, JenkinsRule.class);
// if (rule != null) rule.after();
// }
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/mesos/TestUtils.java
// public static class JenkinsParameterResolver implements ParameterResolver, AfterEachCallback {
// private static final String key = "jenkins-instance";
// private static final ExtensionContext.Namespace ns =
// ExtensionContext.Namespace.create(JenkinsParameterResolver.class);
//
// @Override
// public boolean supportsParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// return parameterContext.getParameter().getType().equals(JenkinsRule.class);
// }
//
// @Override
// public Object resolveParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// JenkinsRule instance =
// extensionContext
// .getStore(ns)
// .getOrComputeIfAbsent(
// key, key -> new JenkinsRule(parameterContext), JenkinsRule.class);
// try {
// instance.before();
// return instance;
// } catch (Throwable t) {
// throw new ParameterResolutionException(t.toString());
// }
// }
//
// @Override
// public void afterEach(ExtensionContext context) throws Exception {
// JenkinsRule rule = context.getStore(ns).remove(key, JenkinsRule.class);
// if (rule != null) rule.after();
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/mesos/fixture/AgentSpecMother.java
// public class AgentSpecMother {
//
// public static final MesosAgentSpecTemplate simple =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.1",
// "32",
// 1,
// 1,
// 1,
// "0",
// "",
// "",
// Collections.emptyList(),
// null,
// null,
// null);
//
// public static final MesosAgentSpecTemplate docker =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.5",
// "512",
// 3,
// 1,
// 1,
// "1",
// "",
// "",
// Collections.emptyList(),
// new ContainerInfo(
// "DOCKER",
// "jeschkies/jenkins-simple-agent:testing",
// false,
// false,
// true,
// Collections.emptyList(),
// Network.HOST),
// null,
// null);
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import akka.stream.QueueOfferResult;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.SourceQueueWithComplete;
import com.mesosphere.usi.core.models.PodId;
import com.mesosphere.usi.core.models.StateEvent;
import com.mesosphere.usi.core.models.commands.KillPod;
import com.mesosphere.usi.core.models.commands.SchedulerCommand;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.jenkinsci.plugins.mesos.TestUtils;
import org.jenkinsci.plugins.mesos.TestUtils.JenkinsParameterResolver;
import org.jenkinsci.plugins.mesos.fixture.AgentSpecMother;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.jenkinsci.plugins.mesos.api;
@ExtendWith(JenkinsParameterResolver.class)
public class SessionTest {
private static final Logger logger = LoggerFactory.getLogger(SessionTest.class);
static ActorSystem system = ActorSystem.create("mesos-scheduler-test");
static ActorMaterializer materializer = ActorMaterializer.create(system);
@Test | // Path: src/test/java/org/jenkinsci/plugins/mesos/TestUtils.java
// public class TestUtils {
// public static class JenkinsRule extends org.jvnet.hudson.test.JenkinsRule {
// private final ParameterContext context;
//
// JenkinsRule(ParameterContext context) {
// this.context = context;
// }
//
// @Override
// public void recipe() throws Exception {
// Optional<JenkinsRecipe> a = context.findAnnotation(JenkinsRecipe.class);
// if (!a.isPresent()) return;
// final JenkinsRecipe.Runner runner = a.get().value().newInstance();
// recipes.add(runner);
// tearDowns.add(() -> runner.tearDown(this, a.get()));
// }
// }
//
// public static class JenkinsParameterResolver implements ParameterResolver, AfterEachCallback {
// private static final String key = "jenkins-instance";
// private static final ExtensionContext.Namespace ns =
// ExtensionContext.Namespace.create(JenkinsParameterResolver.class);
//
// @Override
// public boolean supportsParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// return parameterContext.getParameter().getType().equals(JenkinsRule.class);
// }
//
// @Override
// public Object resolveParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// JenkinsRule instance =
// extensionContext
// .getStore(ns)
// .getOrComputeIfAbsent(
// key, key -> new JenkinsRule(parameterContext), JenkinsRule.class);
// try {
// instance.before();
// return instance;
// } catch (Throwable t) {
// throw new ParameterResolutionException(t.toString());
// }
// }
//
// @Override
// public void afterEach(ExtensionContext context) throws Exception {
// JenkinsRule rule = context.getStore(ns).remove(key, JenkinsRule.class);
// if (rule != null) rule.after();
// }
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/mesos/TestUtils.java
// public static class JenkinsParameterResolver implements ParameterResolver, AfterEachCallback {
// private static final String key = "jenkins-instance";
// private static final ExtensionContext.Namespace ns =
// ExtensionContext.Namespace.create(JenkinsParameterResolver.class);
//
// @Override
// public boolean supportsParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// return parameterContext.getParameter().getType().equals(JenkinsRule.class);
// }
//
// @Override
// public Object resolveParameter(
// ParameterContext parameterContext, ExtensionContext extensionContext)
// throws ParameterResolutionException {
// JenkinsRule instance =
// extensionContext
// .getStore(ns)
// .getOrComputeIfAbsent(
// key, key -> new JenkinsRule(parameterContext), JenkinsRule.class);
// try {
// instance.before();
// return instance;
// } catch (Throwable t) {
// throw new ParameterResolutionException(t.toString());
// }
// }
//
// @Override
// public void afterEach(ExtensionContext context) throws Exception {
// JenkinsRule rule = context.getStore(ns).remove(key, JenkinsRule.class);
// if (rule != null) rule.after();
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/mesos/fixture/AgentSpecMother.java
// public class AgentSpecMother {
//
// public static final MesosAgentSpecTemplate simple =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.1",
// "32",
// 1,
// 1,
// 1,
// "0",
// "",
// "",
// Collections.emptyList(),
// null,
// null,
// null);
//
// public static final MesosAgentSpecTemplate docker =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.5",
// "512",
// 3,
// 1,
// 1,
// "1",
// "",
// "",
// Collections.emptyList(),
// new ContainerInfo(
// "DOCKER",
// "jeschkies/jenkins-simple-agent:testing",
// false,
// false,
// true,
// Collections.emptyList(),
// Network.HOST),
// null,
// null);
// }
// Path: src/test/java/org/jenkinsci/plugins/mesos/api/SessionTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import akka.stream.QueueOfferResult;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.SourceQueueWithComplete;
import com.mesosphere.usi.core.models.PodId;
import com.mesosphere.usi.core.models.StateEvent;
import com.mesosphere.usi.core.models.commands.KillPod;
import com.mesosphere.usi.core.models.commands.SchedulerCommand;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.jenkinsci.plugins.mesos.TestUtils;
import org.jenkinsci.plugins.mesos.TestUtils.JenkinsParameterResolver;
import org.jenkinsci.plugins.mesos.fixture.AgentSpecMother;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.jenkinsci.plugins.mesos.api;
@ExtendWith(JenkinsParameterResolver.class)
public class SessionTest {
private static final Logger logger = LoggerFactory.getLogger(SessionTest.class);
static ActorSystem system = ActorSystem.create("mesos-scheduler-test");
static ActorMaterializer materializer = ActorMaterializer.create(system);
@Test | public void testLaunchOverflow(TestUtils.JenkinsRule j) throws Exception { |
jenkinsci/mesos-plugin | src/main/java/org/jenkinsci/plugins/mesos/MesosSlaveInfo.java | // Path: src/main/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplate.java
// public static class ContainerInfo extends AbstractDescribableImpl<ContainerInfo> {
//
// private final String type;
// private final String dockerImage;
// private final List<Volume> volumes;
// private final Network networking;
// private final boolean dockerPrivilegedMode;
// private final boolean dockerForcePullImage;
// private boolean isDind;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> portMappings;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean dockerImageCustomizable;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> parameters;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> networkInfos;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean useCustomDockerCommandShell;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient String customDockerCommandShell;
//
// @DataBoundConstructor
// public ContainerInfo(
// String type,
// String dockerImage,
// boolean isDind,
// boolean dockerPrivilegedMode,
// boolean dockerForcePullImage,
// List<Volume> volumes,
// Network networking) {
// this.type = type;
// this.dockerImage = dockerImage;
// this.dockerPrivilegedMode = dockerPrivilegedMode;
// this.dockerForcePullImage = dockerForcePullImage;
// this.volumes = volumes;
// this.isDind = isDind;
// this.networking =
// (networking != null) ? networking : ContainerInfoTaskInfoBuilder.DEFAULT_NETWORKING;
// }
//
// public boolean getIsDind() {
// return this.isDind;
// }
//
// public Network getNetworking() {
// return this.networking;
// }
//
// public String getType() {
// return type;
// }
//
// public String getDockerImage() {
// return dockerImage;
// }
//
// public boolean getDockerPrivilegedMode() {
// return dockerPrivilegedMode;
// }
//
// public boolean getDockerForcePullImage() {
// return dockerForcePullImage;
// }
//
// public List<Volume> getVolumes() {
// return volumes;
// }
//
// public List<Volume> getVolumesOrEmpty() {
// return (this.volumes != null) ? this.volumes : Collections.emptyList();
// }
//
// @Extension
// public static final class DescriptorImpl extends Descriptor<ContainerInfo> {
//
// public DescriptorImpl() {
// load();
// }
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Node;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.mesos.MesosAgentSpecTemplate.ContainerInfo;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.jenkinsci.plugins.mesos;
/**
* This POJO describes a Jenkins agent for Mesos on 0.x and 1.x of the plugin. It is used to migrate
* older configurations to {@link MesosAgentSpecTemplate} during deserialization. See {@link
* MesosCloud#readResolve()} for the full migration.
*/
public class MesosSlaveInfo {
private static final Logger logger = LoggerFactory.getLogger(MesosSlaveInfo.class);
private transient Node.Mode mode;
private transient String labelString;
private transient Double slaveCpus;
private transient Double diskNeeded;
private transient int slaveMem;
private transient List<URI> additionalURIs; | // Path: src/main/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplate.java
// public static class ContainerInfo extends AbstractDescribableImpl<ContainerInfo> {
//
// private final String type;
// private final String dockerImage;
// private final List<Volume> volumes;
// private final Network networking;
// private final boolean dockerPrivilegedMode;
// private final boolean dockerForcePullImage;
// private boolean isDind;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> portMappings;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean dockerImageCustomizable;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> parameters;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient List<Object> networkInfos;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient boolean useCustomDockerCommandShell;
//
// @SuppressFBWarnings("UUF_UNUSED_FIELD")
// private transient String customDockerCommandShell;
//
// @DataBoundConstructor
// public ContainerInfo(
// String type,
// String dockerImage,
// boolean isDind,
// boolean dockerPrivilegedMode,
// boolean dockerForcePullImage,
// List<Volume> volumes,
// Network networking) {
// this.type = type;
// this.dockerImage = dockerImage;
// this.dockerPrivilegedMode = dockerPrivilegedMode;
// this.dockerForcePullImage = dockerForcePullImage;
// this.volumes = volumes;
// this.isDind = isDind;
// this.networking =
// (networking != null) ? networking : ContainerInfoTaskInfoBuilder.DEFAULT_NETWORKING;
// }
//
// public boolean getIsDind() {
// return this.isDind;
// }
//
// public Network getNetworking() {
// return this.networking;
// }
//
// public String getType() {
// return type;
// }
//
// public String getDockerImage() {
// return dockerImage;
// }
//
// public boolean getDockerPrivilegedMode() {
// return dockerPrivilegedMode;
// }
//
// public boolean getDockerForcePullImage() {
// return dockerForcePullImage;
// }
//
// public List<Volume> getVolumes() {
// return volumes;
// }
//
// public List<Volume> getVolumesOrEmpty() {
// return (this.volumes != null) ? this.volumes : Collections.emptyList();
// }
//
// @Extension
// public static final class DescriptorImpl extends Descriptor<ContainerInfo> {
//
// public DescriptorImpl() {
// load();
// }
// }
// }
// Path: src/main/java/org/jenkinsci/plugins/mesos/MesosSlaveInfo.java
import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Node;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.mesos.MesosAgentSpecTemplate.ContainerInfo;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.jenkinsci.plugins.mesos;
/**
* This POJO describes a Jenkins agent for Mesos on 0.x and 1.x of the plugin. It is used to migrate
* older configurations to {@link MesosAgentSpecTemplate} during deserialization. See {@link
* MesosCloud#readResolve()} for the full migration.
*/
public class MesosSlaveInfo {
private static final Logger logger = LoggerFactory.getLogger(MesosSlaveInfo.class);
private transient Node.Mode mode;
private transient String labelString;
private transient Double slaveCpus;
private transient Double diskNeeded;
private transient int slaveMem;
private transient List<URI> additionalURIs; | private transient ContainerInfo containerInfo; |
jenkinsci/mesos-plugin | src/test/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplateDescriptorTest.java | // Path: src/main/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplate.java
// @Extension
// public static final class DescriptorImpl extends Descriptor<MesosAgentSpecTemplate> {
//
// public DescriptorImpl() {
// load();
// }
//
// /**
// * Validate that CPUs is a positive double.
// *
// * @param cpus The number of CPUs to user for agent.
// * @return Whether the supplied CPUs is valid.
// */
// public FormValidation doCheckCpus(@QueryParameter String cpus) {
// try {
// if (Double.valueOf(cpus) > 0.0) {
// return FormValidation.ok();
// } else {
// return FormValidation.error(cpus + " must be a positive floating-point-number.");
// }
// } catch (NumberFormatException e) {
// return FormValidation.error(cpus + " must be a positive floating-point-number.");
// }
// }
// }
| import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import hudson.util.FormValidation.Kind;
import org.jenkinsci.plugins.mesos.MesosAgentSpecTemplate.DescriptorImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; | package org.jenkinsci.plugins.mesos;
@ExtendWith(TestUtils.JenkinsParameterResolver.class)
public class MesosAgentSpecTemplateDescriptorTest {
@Test
public void validateCpus(TestUtils.JenkinsRule j) { | // Path: src/main/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplate.java
// @Extension
// public static final class DescriptorImpl extends Descriptor<MesosAgentSpecTemplate> {
//
// public DescriptorImpl() {
// load();
// }
//
// /**
// * Validate that CPUs is a positive double.
// *
// * @param cpus The number of CPUs to user for agent.
// * @return Whether the supplied CPUs is valid.
// */
// public FormValidation doCheckCpus(@QueryParameter String cpus) {
// try {
// if (Double.valueOf(cpus) > 0.0) {
// return FormValidation.ok();
// } else {
// return FormValidation.error(cpus + " must be a positive floating-point-number.");
// }
// } catch (NumberFormatException e) {
// return FormValidation.error(cpus + " must be a positive floating-point-number.");
// }
// }
// }
// Path: src/test/java/org/jenkinsci/plugins/mesos/MesosAgentSpecTemplateDescriptorTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import hudson.util.FormValidation.Kind;
import org.jenkinsci.plugins.mesos.MesosAgentSpecTemplate.DescriptorImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
package org.jenkinsci.plugins.mesos;
@ExtendWith(TestUtils.JenkinsParameterResolver.class)
public class MesosAgentSpecTemplateDescriptorTest {
@Test
public void validateCpus(TestUtils.JenkinsRule j) { | MesosAgentSpecTemplate.DescriptorImpl descriptor = new DescriptorImpl(); |
jenkinsci/mesos-plugin | src/test/java/org/jenkinsci/plugins/mesos/integration/MesosJenkinsAgentLifecycleTest.java | // Path: src/test/java/org/jenkinsci/plugins/mesos/fixture/AgentSpecMother.java
// public class AgentSpecMother {
//
// public static final MesosAgentSpecTemplate simple =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.1",
// "32",
// 1,
// 1,
// 1,
// "0",
// "",
// "",
// Collections.emptyList(),
// null,
// null,
// null);
//
// public static final MesosAgentSpecTemplate docker =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.5",
// "512",
// 3,
// 1,
// 1,
// "1",
// "",
// "",
// Collections.emptyList(),
// new ContainerInfo(
// "DOCKER",
// "jeschkies/jenkins-simple-agent:testing",
// false,
// false,
// true,
// Collections.emptyList(),
// Network.HOST),
// null,
// null);
// }
| import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import com.mesosphere.utils.mesos.MesosClusterExtension;
import com.mesosphere.utils.zookeeper.ZookeeperServerExtension;
import hudson.model.Slave;
import hudson.slaves.SlaveComputer;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.*;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.mesos.*;
import org.jenkinsci.plugins.mesos.fixture.AgentSpecMother;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension; | package org.jenkinsci.plugins.mesos.integration;
@ExtendWith(TestUtils.JenkinsParameterResolver.class)
@IntegrationTest
public class MesosJenkinsAgentLifecycleTest {
@RegisterExtension static ZookeeperServerExtension zkServer = new ZookeeperServerExtension();
static ActorSystem system = ActorSystem.create("mesos-scheduler-test");
static ActorMaterializer materializer = ActorMaterializer.create(system);
@RegisterExtension
static MesosClusterExtension mesosCluster =
MesosClusterExtension.builder()
.withMesosMasterUrl(String.format("zk://%s/mesos", zkServer.getConnectionUrl()))
.withLogPrefix(MesosJenkinsAgentLifecycleTest.class.getCanonicalName())
.build(system, materializer);
@Test
public void testAgentLifecycle(TestUtils.JenkinsRule j) throws Exception {
MesosCloud cloud =
new MesosCloud(
mesosCluster.getMesosUrl().toString(),
"MesosTest",
null,
"*",
System.getProperty("user.name"),
j.getURL().toString(),
Collections.emptyList());
final String name = "jenkins-lifecycle"; | // Path: src/test/java/org/jenkinsci/plugins/mesos/fixture/AgentSpecMother.java
// public class AgentSpecMother {
//
// public static final MesosAgentSpecTemplate simple =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.1",
// "32",
// 1,
// 1,
// 1,
// "0",
// "",
// "",
// Collections.emptyList(),
// null,
// null,
// null);
//
// public static final MesosAgentSpecTemplate docker =
// new MesosAgentSpecTemplate(
// "label",
// Mode.EXCLUSIVE,
// "0.5",
// "512",
// 3,
// 1,
// 1,
// "1",
// "",
// "",
// Collections.emptyList(),
// new ContainerInfo(
// "DOCKER",
// "jeschkies/jenkins-simple-agent:testing",
// false,
// false,
// true,
// Collections.emptyList(),
// Network.HOST),
// null,
// null);
// }
// Path: src/test/java/org/jenkinsci/plugins/mesos/integration/MesosJenkinsAgentLifecycleTest.java
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import com.mesosphere.utils.mesos.MesosClusterExtension;
import com.mesosphere.utils.zookeeper.ZookeeperServerExtension;
import hudson.model.Slave;
import hudson.slaves.SlaveComputer;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.*;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.mesos.*;
import org.jenkinsci.plugins.mesos.fixture.AgentSpecMother;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
package org.jenkinsci.plugins.mesos.integration;
@ExtendWith(TestUtils.JenkinsParameterResolver.class)
@IntegrationTest
public class MesosJenkinsAgentLifecycleTest {
@RegisterExtension static ZookeeperServerExtension zkServer = new ZookeeperServerExtension();
static ActorSystem system = ActorSystem.create("mesos-scheduler-test");
static ActorMaterializer materializer = ActorMaterializer.create(system);
@RegisterExtension
static MesosClusterExtension mesosCluster =
MesosClusterExtension.builder()
.withMesosMasterUrl(String.format("zk://%s/mesos", zkServer.getConnectionUrl()))
.withLogPrefix(MesosJenkinsAgentLifecycleTest.class.getCanonicalName())
.build(system, materializer);
@Test
public void testAgentLifecycle(TestUtils.JenkinsRule j) throws Exception {
MesosCloud cloud =
new MesosCloud(
mesosCluster.getMesosUrl().toString(),
"MesosTest",
null,
"*",
System.getProperty("user.name"),
j.getURL().toString(),
Collections.emptyList());
final String name = "jenkins-lifecycle"; | final MesosAgentSpecTemplate spec = AgentSpecMother.simple; |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/utils/Constants.java | // Path: app/src/main/java/com/YC2010/MyClass/model/Reminder_item.java
// public class Reminder_item {
// // variables
// String id;
// String title;
// String location;
// GregorianCalendar mClaendar;
// String type;
//
// // type:
// // "c" customized
// // "e" exams
// // "fb" facebook events
// // "d" important dates
//
// // constructor
// public Reminder_item(){
// // empty
// }
//
// // Ctor for all
// public Reminder_item(String id, String title, String location, int year, int month, int day, int hour, int minute, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day,hour,minute);
// this.type = type;
// }
//
// // ctor for no hout and minute
// public Reminder_item(String id, String title, String location, int year, int month, int day, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day);
// this.type = type;
// }
//
// //Ctor for unix time
// public Reminder_item(String id, String title, String location, long unix_time, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar();
// this.mClaendar.setTimeInMillis(unix_time);
// this.type = type;
// }
//
// public String get_id(){
// return this.id;
// }
//
// public String get_title(){
// return this.title;
// }
//
// public String get_location(){
// return this.location;
// }
//
// public long get_unix_time(){
// return this.mClaendar.getTimeInMillis();
// }
//
// public String get_type(){ return this.type;}
// }
| import com.YC2010.MyClass.model.Reminder_item;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID; | package com.YC2010.MyClass.utils;
/**
* Created by Danny on 2015/6/27.
*/
public class Constants {
public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/"; | // Path: app/src/main/java/com/YC2010/MyClass/model/Reminder_item.java
// public class Reminder_item {
// // variables
// String id;
// String title;
// String location;
// GregorianCalendar mClaendar;
// String type;
//
// // type:
// // "c" customized
// // "e" exams
// // "fb" facebook events
// // "d" important dates
//
// // constructor
// public Reminder_item(){
// // empty
// }
//
// // Ctor for all
// public Reminder_item(String id, String title, String location, int year, int month, int day, int hour, int minute, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day,hour,minute);
// this.type = type;
// }
//
// // ctor for no hout and minute
// public Reminder_item(String id, String title, String location, int year, int month, int day, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day);
// this.type = type;
// }
//
// //Ctor for unix time
// public Reminder_item(String id, String title, String location, long unix_time, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar();
// this.mClaendar.setTimeInMillis(unix_time);
// this.type = type;
// }
//
// public String get_id(){
// return this.id;
// }
//
// public String get_title(){
// return this.title;
// }
//
// public String get_location(){
// return this.location;
// }
//
// public long get_unix_time(){
// return this.mClaendar.getTimeInMillis();
// }
//
// public String get_type(){ return this.type;}
// }
// Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
import com.YC2010.MyClass.model.Reminder_item;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
package com.YC2010.MyClass.utils;
/**
* Created by Danny on 2015/6/27.
*/
public class Constants {
public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/"; | public static List<Reminder_item> holiday_2015; |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/data/ReminderDBHandler.java | // Path: app/src/main/java/com/YC2010/MyClass/model/Reminder_item.java
// public class Reminder_item {
// // variables
// String id;
// String title;
// String location;
// GregorianCalendar mClaendar;
// String type;
//
// // type:
// // "c" customized
// // "e" exams
// // "fb" facebook events
// // "d" important dates
//
// // constructor
// public Reminder_item(){
// // empty
// }
//
// // Ctor for all
// public Reminder_item(String id, String title, String location, int year, int month, int day, int hour, int minute, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day,hour,minute);
// this.type = type;
// }
//
// // ctor for no hout and minute
// public Reminder_item(String id, String title, String location, int year, int month, int day, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day);
// this.type = type;
// }
//
// //Ctor for unix time
// public Reminder_item(String id, String title, String location, long unix_time, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar();
// this.mClaendar.setTimeInMillis(unix_time);
// this.type = type;
// }
//
// public String get_id(){
// return this.id;
// }
//
// public String get_title(){
// return this.title;
// }
//
// public String get_location(){
// return this.location;
// }
//
// public long get_unix_time(){
// return this.mClaendar.getTimeInMillis();
// }
//
// public String get_type(){ return this.type;}
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.YC2010.MyClass.model.Reminder_item;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List; | package com.YC2010.MyClass.data;
/**
* Created by Jason on 2015-06-02.
*/
public class ReminderDBHandler extends SQLiteOpenHelper {
// DB Version
private static final int DATABASE_VERSION = 3;
// DB Name
private static final String DATABASE_NAME = "ReminderManager";
// Table name
private static final String TABLE_REMINDERS = "reminders";
// TABLE_REMINDERS Columns names // columnIndex
private static final String KEY_ID = "id"; // 0
private static final String KEY_TITLE = "title"; // 1
private static final String KEY_LOCATION = "location"; // 2
private static final String KEY_UNIX_TIME = "Unix_time"; // 3
private static final String KEY_TYPE = "type"; // 4
public ReminderDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("ReminderDBHandler", "onCreate");
String CREATE_TABLE = "CREATE TABLE " + TABLE_REMINDERS + "("
+ KEY_ID + " STRING PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_LOCATION + " TEXT," + KEY_UNIX_TIME + " TEXT,"
+ KEY_TYPE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDERS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new Reminder | // Path: app/src/main/java/com/YC2010/MyClass/model/Reminder_item.java
// public class Reminder_item {
// // variables
// String id;
// String title;
// String location;
// GregorianCalendar mClaendar;
// String type;
//
// // type:
// // "c" customized
// // "e" exams
// // "fb" facebook events
// // "d" important dates
//
// // constructor
// public Reminder_item(){
// // empty
// }
//
// // Ctor for all
// public Reminder_item(String id, String title, String location, int year, int month, int day, int hour, int minute, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day,hour,minute);
// this.type = type;
// }
//
// // ctor for no hout and minute
// public Reminder_item(String id, String title, String location, int year, int month, int day, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar(year,month,day);
// this.type = type;
// }
//
// //Ctor for unix time
// public Reminder_item(String id, String title, String location, long unix_time, String type){
// this.id = id;
// this.title = title;
// this.location = location;
// this.mClaendar = new GregorianCalendar();
// this.mClaendar.setTimeInMillis(unix_time);
// this.type = type;
// }
//
// public String get_id(){
// return this.id;
// }
//
// public String get_title(){
// return this.title;
// }
//
// public String get_location(){
// return this.location;
// }
//
// public long get_unix_time(){
// return this.mClaendar.getTimeInMillis();
// }
//
// public String get_type(){ return this.type;}
// }
// Path: app/src/main/java/com/YC2010/MyClass/data/ReminderDBHandler.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.YC2010.MyClass.model.Reminder_item;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
package com.YC2010.MyClass.data;
/**
* Created by Jason on 2015-06-02.
*/
public class ReminderDBHandler extends SQLiteOpenHelper {
// DB Version
private static final int DATABASE_VERSION = 3;
// DB Name
private static final String DATABASE_NAME = "ReminderManager";
// Table name
private static final String TABLE_REMINDERS = "reminders";
// TABLE_REMINDERS Columns names // columnIndex
private static final String KEY_ID = "id"; // 0
private static final String KEY_TITLE = "title"; // 1
private static final String KEY_LOCATION = "location"; // 2
private static final String KEY_UNIX_TIME = "Unix_time"; // 3
private static final String KEY_TYPE = "type"; // 4
public ReminderDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("ReminderDBHandler", "onCreate");
String CREATE_TABLE = "CREATE TABLE " + TABLE_REMINDERS + "("
+ KEY_ID + " STRING PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_LOCATION + " TEXT," + KEY_UNIX_TIME + " TEXT,"
+ KEY_TYPE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDERS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new Reminder | public void addReminder(Reminder_item reminder) { |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchExamFragment.java | // Path: app/src/main/java/com/YC2010/MyClass/ui/adapters/FinalsListAdapter.java
// public class FinalsListAdapter extends BaseAdapter {
// ArrayList<FinalObject> mArrayList;
// Context mContext;
// LayoutInflater mLayoutInflater;
//
// public FinalsListAdapter(Context context, int textViewResourceId, Bundle bundle) {
// mLayoutInflater = LayoutInflater.from(context);
// mArrayList = bundle.getParcelableArrayList(Constants.finalObjectListKey);
// mContext = context;
// Log.d("SectionListAdapter", "Course name is " + bundle.getString("courseName"));
// }
//
// @Override
// public FinalObject getItem(int i) {
// return mArrayList.get(i);
// }
//
// @Override
// public int getCount() {
// return mArrayList != null ? mArrayList.size() : 0;
// }
//
// @Override
// public long getItemId(int arg0) {
// return 0;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// //Log.d("SectionListAdapter", "enter getView");
// View v = convertView;
//
// v = mLayoutInflater.inflate(R.layout.section_item, null);
//
//
// Log.d("SectionListAdapter", "position is " + position);
//
// TextView date = (TextView) v.findViewById(R.id.section_item_capacity);
// TextView sec = (TextView) v.findViewById(R.id.section_item_lec);
// TextView loc = (TextView) v.findViewById(R.id.section_item_loc);
// TextView time = (TextView) v.findViewById(R.id.section_item_time);
//
// FinalObject finalInfo = getItem(position);
//
// sec.setText(finalInfo.getSection());
//
// if (!finalInfo.isOnline()) {
// time.setText(finalInfo.getTime());
// loc.setText(finalInfo.getLocation());
// date.setText(finalInfo.getDate());
// }
//
// return v;
// }
//
// }
| import android.app.Activity;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.YC2010.MyClass.R;
import com.YC2010.MyClass.ui.adapters.FinalsListAdapter; | package com.YC2010.MyClass.ui.fragments;
/**
* Created by Danny on 2015/12/26.
*/
public class SearchExamFragment extends Fragment {
private Activity mActivity;
private View mView;
private Bundle mFetchedResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mActivity = getActivity();
this.mFetchedResult = this.getArguments();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_search_exam, container, false);
if (mFetchedResult.getBoolean("has_finals", false)) {
TextView finals = (TextView) mView.findViewById(R.id.final_exams);
if (finals != null) {
finals.setVisibility(View.VISIBLE);
}
updateView();
}
return mView;
}
public void updateView() {
// get default divider
int[] attrs = {android.R.attr.listDivider};
TypedArray ta = mActivity.obtainStyledAttributes(attrs);
Drawable divider = ta.getDrawable(0);
ta.recycle();
LinearLayout mFinalLinearLayout = (LinearLayout) mView.findViewById(R.id.finals_list); | // Path: app/src/main/java/com/YC2010/MyClass/ui/adapters/FinalsListAdapter.java
// public class FinalsListAdapter extends BaseAdapter {
// ArrayList<FinalObject> mArrayList;
// Context mContext;
// LayoutInflater mLayoutInflater;
//
// public FinalsListAdapter(Context context, int textViewResourceId, Bundle bundle) {
// mLayoutInflater = LayoutInflater.from(context);
// mArrayList = bundle.getParcelableArrayList(Constants.finalObjectListKey);
// mContext = context;
// Log.d("SectionListAdapter", "Course name is " + bundle.getString("courseName"));
// }
//
// @Override
// public FinalObject getItem(int i) {
// return mArrayList.get(i);
// }
//
// @Override
// public int getCount() {
// return mArrayList != null ? mArrayList.size() : 0;
// }
//
// @Override
// public long getItemId(int arg0) {
// return 0;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// //Log.d("SectionListAdapter", "enter getView");
// View v = convertView;
//
// v = mLayoutInflater.inflate(R.layout.section_item, null);
//
//
// Log.d("SectionListAdapter", "position is " + position);
//
// TextView date = (TextView) v.findViewById(R.id.section_item_capacity);
// TextView sec = (TextView) v.findViewById(R.id.section_item_lec);
// TextView loc = (TextView) v.findViewById(R.id.section_item_loc);
// TextView time = (TextView) v.findViewById(R.id.section_item_time);
//
// FinalObject finalInfo = getItem(position);
//
// sec.setText(finalInfo.getSection());
//
// if (!finalInfo.isOnline()) {
// time.setText(finalInfo.getTime());
// loc.setText(finalInfo.getLocation());
// date.setText(finalInfo.getDate());
// }
//
// return v;
// }
//
// }
// Path: app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchExamFragment.java
import android.app.Activity;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.YC2010.MyClass.R;
import com.YC2010.MyClass.ui.adapters.FinalsListAdapter;
package com.YC2010.MyClass.ui.fragments;
/**
* Created by Danny on 2015/12/26.
*/
public class SearchExamFragment extends Fragment {
private Activity mActivity;
private View mView;
private Bundle mFetchedResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mActivity = getActivity();
this.mFetchedResult = this.getArguments();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_search_exam, container, false);
if (mFetchedResult.getBoolean("has_finals", false)) {
TextView finals = (TextView) mView.findViewById(R.id.final_exams);
if (finals != null) {
finals.setVisibility(View.VISIBLE);
}
updateView();
}
return mView;
}
public void updateView() {
// get default divider
int[] attrs = {android.R.attr.listDivider};
TypedArray ta = mActivity.obtainStyledAttributes(attrs);
Drawable divider = ta.getDrawable(0);
ta.recycle();
LinearLayout mFinalLinearLayout = (LinearLayout) mView.findViewById(R.id.finals_list); | FinalsListAdapter FinalsAdapter = new FinalsListAdapter(mActivity, R.layout.section_item, mFetchedResult); |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/ui/adapters/FinalsListAdapter.java | // Path: app/src/main/java/com/YC2010/MyClass/model/FinalObject.java
// public class FinalObject implements Parcelable {
// private String section;
// private String time;
// private String location;
// private String date;
// private boolean isOnline;
//
// public FinalObject() {}
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(section);
// dest.writeString(time);
// dest.writeString(location);
// dest.writeString(date);
// dest.writeByte((byte) (isOnline ? 1 : 0));
// }
//
// public FinalObject(Parcel src) {
// this.section = src.readString();
// this.time = src.readString();
// this.location = src.readString();
// this.date = src.readString();
// this.isOnline = src.readByte() == 1;
// }
//
// public static final Creator CREATOR = new Creator() {
// @Override
// public FinalObject createFromParcel(Parcel source) {
// return new FinalObject(source);
// }
//
// @Override
// public FinalObject[] newArray(int size) {
// return new FinalObject[size];
// }
// };
//
// public void setSection(String section) {
// this.section = section;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public void setIsOnline(boolean isOnline) {
// this.isOnline = isOnline;
// }
//
// public String getSection() {
// return section;
// }
//
// public String getTime() {
// return time;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getDate() {
// return date;
// }
//
// public boolean isOnline() {
// return isOnline;
// }
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
| import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.YC2010.MyClass.model.FinalObject;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.R;
import java.util.ArrayList; | package com.YC2010.MyClass.ui.adapters;
public class FinalsListAdapter extends BaseAdapter {
ArrayList<FinalObject> mArrayList;
Context mContext;
LayoutInflater mLayoutInflater;
public FinalsListAdapter(Context context, int textViewResourceId, Bundle bundle) {
mLayoutInflater = LayoutInflater.from(context); | // Path: app/src/main/java/com/YC2010/MyClass/model/FinalObject.java
// public class FinalObject implements Parcelable {
// private String section;
// private String time;
// private String location;
// private String date;
// private boolean isOnline;
//
// public FinalObject() {}
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(section);
// dest.writeString(time);
// dest.writeString(location);
// dest.writeString(date);
// dest.writeByte((byte) (isOnline ? 1 : 0));
// }
//
// public FinalObject(Parcel src) {
// this.section = src.readString();
// this.time = src.readString();
// this.location = src.readString();
// this.date = src.readString();
// this.isOnline = src.readByte() == 1;
// }
//
// public static final Creator CREATOR = new Creator() {
// @Override
// public FinalObject createFromParcel(Parcel source) {
// return new FinalObject(source);
// }
//
// @Override
// public FinalObject[] newArray(int size) {
// return new FinalObject[size];
// }
// };
//
// public void setSection(String section) {
// this.section = section;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public void setIsOnline(boolean isOnline) {
// this.isOnline = isOnline;
// }
//
// public String getSection() {
// return section;
// }
//
// public String getTime() {
// return time;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getDate() {
// return date;
// }
//
// public boolean isOnline() {
// return isOnline;
// }
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
// Path: app/src/main/java/com/YC2010/MyClass/ui/adapters/FinalsListAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.YC2010.MyClass.model.FinalObject;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.R;
import java.util.ArrayList;
package com.YC2010.MyClass.ui.adapters;
public class FinalsListAdapter extends BaseAdapter {
ArrayList<FinalObject> mArrayList;
Context mContext;
LayoutInflater mLayoutInflater;
public FinalsListAdapter(Context context, int textViewResourceId, Bundle bundle) {
mLayoutInflater = LayoutInflater.from(context); | mArrayList = bundle.getParcelableArrayList(Constants.finalObjectListKey); |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/ui/adapters/TutListAdapter.java | // Path: app/src/main/java/com/YC2010/MyClass/model/TutorialObject.java
// public class TutorialObject implements Parcelable {
// private String number;
// private String section;
// private String time;
// private String location;
// private String capacity;
// private String total;
//
// public TutorialObject() {}
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(number);
// dest.writeString(section);
// dest.writeString(time);
// dest.writeString(location);
// dest.writeString(capacity);
// dest.writeString(total);
// }
//
// public TutorialObject(Parcel src) {
// this.number = src.readString();
// this.section = src.readString();
// this.time = src.readString();
// this.location = src.readString();
// this.capacity = src.readString();
// this.total = src.readString();
// }
//
// public static final Creator CREATOR = new Creator() {
// @Override
// public TutorialObject createFromParcel(Parcel source) {
// return new TutorialObject(source);
// }
//
// @Override
// public TutorialObject[] newArray(int size) {
// return new TutorialObject[size];
// }
// };
//
// public void setTotal(String total) {
// this.total = total;
// }
//
// public void setSection(String section) {
// this.section = section;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public void setCapacity(String capacity) {
// this.capacity = capacity;
// }
//
// public void setNumber(String number) {
// this.number = number;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getNumber() {
// return number;
// }
//
// public String getSection() {
// return section;
// }
//
// public String getTime() {
// return time;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCapacity() {
// return capacity;
// }
//
// public String getTotal() {
// return total;
// }
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
| import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.YC2010.MyClass.model.TutorialObject;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.R;
import java.util.ArrayList; | package com.YC2010.MyClass.ui.adapters;
public class TutListAdapter extends BaseAdapter {
ArrayList<TutorialObject> mArrayList;
Context mContext;
LayoutInflater mLayoutInflater;
public TutListAdapter(Context context, int textViewResourceId, Bundle bundle) {
mLayoutInflater = LayoutInflater.from(context); | // Path: app/src/main/java/com/YC2010/MyClass/model/TutorialObject.java
// public class TutorialObject implements Parcelable {
// private String number;
// private String section;
// private String time;
// private String location;
// private String capacity;
// private String total;
//
// public TutorialObject() {}
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(number);
// dest.writeString(section);
// dest.writeString(time);
// dest.writeString(location);
// dest.writeString(capacity);
// dest.writeString(total);
// }
//
// public TutorialObject(Parcel src) {
// this.number = src.readString();
// this.section = src.readString();
// this.time = src.readString();
// this.location = src.readString();
// this.capacity = src.readString();
// this.total = src.readString();
// }
//
// public static final Creator CREATOR = new Creator() {
// @Override
// public TutorialObject createFromParcel(Parcel source) {
// return new TutorialObject(source);
// }
//
// @Override
// public TutorialObject[] newArray(int size) {
// return new TutorialObject[size];
// }
// };
//
// public void setTotal(String total) {
// this.total = total;
// }
//
// public void setSection(String section) {
// this.section = section;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public void setCapacity(String capacity) {
// this.capacity = capacity;
// }
//
// public void setNumber(String number) {
// this.number = number;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getNumber() {
// return number;
// }
//
// public String getSection() {
// return section;
// }
//
// public String getTime() {
// return time;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCapacity() {
// return capacity;
// }
//
// public String getTotal() {
// return total;
// }
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
// Path: app/src/main/java/com/YC2010/MyClass/ui/adapters/TutListAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.YC2010.MyClass.model.TutorialObject;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.R;
import java.util.ArrayList;
package com.YC2010.MyClass.ui.adapters;
public class TutListAdapter extends BaseAdapter {
ArrayList<TutorialObject> mArrayList;
Context mContext;
LayoutInflater mLayoutInflater;
public TutListAdapter(Context context, int textViewResourceId, Bundle bundle) {
mLayoutInflater = LayoutInflater.from(context); | mArrayList = bundle.getParcelableArrayList(Constants.tutorialObjectListKey); |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/ui/fragments/CatalogNumFragment.java | // Path: app/src/main/java/com/YC2010/MyClass/callbacks/AsyncTaskCallbackInterface.java
// public interface AsyncTaskCallbackInterface {
// public void onOperationComplete(Bundle bundle);
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/data/fetchtasks/CatalogNumFetchTask.java
// public class CatalogNumFetchTask extends AsyncTask<String, Void, Bundle> {
//
// private Activity mActivity;
// AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;
// private ArrayList<String> mCatalogNum_arraylist = new ArrayList<>();
// private String mSubject;
// public CatalogNumFetchTask(String subject, AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
// mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
// mSubject = subject;
// }
//
// @Override
// protected Bundle doInBackground(String...params) {
// Bundle result = new Bundle();
// fetchCourse(result);
//
// return result;
// }
//
// private Bundle fetchCourse(Bundle bundle) {
// try{
// String url = Connections.getCatalogNumURL(mSubject);
//
// JSONObject jsonObject = Connections.getJSON_from_url(url);
// JSONArray subject_array = jsonObject.getJSONArray("data");
// Log.d("SubjectFetchTask", "subject array is " + subject_array.length());
//
// for(int i = 0; i < subject_array.length(); i++){
// JSONObject subject = subject_array.getJSONObject(i);
// mCatalogNum_arraylist.add(i,mSubject + " " + subject.getString("catalog_number"));
// }
//
// bundle.putStringArrayList("CatalogNum_arraylist", mCatalogNum_arraylist);
//
// return bundle;
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bundle;
// }
//
// @Override
// protected void onPostExecute(Bundle bundle) {
// mAsyncTaskCallbackInterface.onOperationComplete(bundle);
// }
//
//
// }
| import android.app.ListFragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.data.fetchtasks.CatalogNumFetchTask;
import com.YC2010.MyClass.R;
import java.util.ArrayList; | package com.YC2010.MyClass.ui.fragments;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
* interface.
*/
public class CatalogNumFragment extends ListFragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_SUBJECT = "SUBJECT";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String mSubject;
ArrayList<String> mCatalogNum_arraylist;
AlertDialog.Builder mBuilder;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
/*public static CatalogNumFragment newInstance(String param1, String param2) {
CatalogNumFragment fragment = new CatalogNumFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}*/
public CatalogNumFragment(){
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public void setSubject(String subject) {
mSubject = subject;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String subject = getArguments().getString(ARG_SUBJECT);
if(subject == null)
Toast.makeText(getActivity(), "subject string not found", Toast.LENGTH_SHORT).show();
mSubject = subject;
| // Path: app/src/main/java/com/YC2010/MyClass/callbacks/AsyncTaskCallbackInterface.java
// public interface AsyncTaskCallbackInterface {
// public void onOperationComplete(Bundle bundle);
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/data/fetchtasks/CatalogNumFetchTask.java
// public class CatalogNumFetchTask extends AsyncTask<String, Void, Bundle> {
//
// private Activity mActivity;
// AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;
// private ArrayList<String> mCatalogNum_arraylist = new ArrayList<>();
// private String mSubject;
// public CatalogNumFetchTask(String subject, AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
// mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
// mSubject = subject;
// }
//
// @Override
// protected Bundle doInBackground(String...params) {
// Bundle result = new Bundle();
// fetchCourse(result);
//
// return result;
// }
//
// private Bundle fetchCourse(Bundle bundle) {
// try{
// String url = Connections.getCatalogNumURL(mSubject);
//
// JSONObject jsonObject = Connections.getJSON_from_url(url);
// JSONArray subject_array = jsonObject.getJSONArray("data");
// Log.d("SubjectFetchTask", "subject array is " + subject_array.length());
//
// for(int i = 0; i < subject_array.length(); i++){
// JSONObject subject = subject_array.getJSONObject(i);
// mCatalogNum_arraylist.add(i,mSubject + " " + subject.getString("catalog_number"));
// }
//
// bundle.putStringArrayList("CatalogNum_arraylist", mCatalogNum_arraylist);
//
// return bundle;
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bundle;
// }
//
// @Override
// protected void onPostExecute(Bundle bundle) {
// mAsyncTaskCallbackInterface.onOperationComplete(bundle);
// }
//
//
// }
// Path: app/src/main/java/com/YC2010/MyClass/ui/fragments/CatalogNumFragment.java
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.data.fetchtasks.CatalogNumFetchTask;
import com.YC2010.MyClass.R;
import java.util.ArrayList;
package com.YC2010.MyClass.ui.fragments;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
* interface.
*/
public class CatalogNumFragment extends ListFragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_SUBJECT = "SUBJECT";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String mSubject;
ArrayList<String> mCatalogNum_arraylist;
AlertDialog.Builder mBuilder;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
/*public static CatalogNumFragment newInstance(String param1, String param2) {
CatalogNumFragment fragment = new CatalogNumFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}*/
public CatalogNumFragment(){
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public void setSubject(String subject) {
mSubject = subject;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String subject = getArguments().getString(ARG_SUBJECT);
if(subject == null)
Toast.makeText(getActivity(), "subject string not found", Toast.LENGTH_SHORT).show();
mSubject = subject;
| final CatalogNumFetchTask catalogNumFetchTask = new CatalogNumFetchTask(mSubject, new AsyncTaskCallbackInterface() { |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/ui/fragments/CatalogNumFragment.java | // Path: app/src/main/java/com/YC2010/MyClass/callbacks/AsyncTaskCallbackInterface.java
// public interface AsyncTaskCallbackInterface {
// public void onOperationComplete(Bundle bundle);
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/data/fetchtasks/CatalogNumFetchTask.java
// public class CatalogNumFetchTask extends AsyncTask<String, Void, Bundle> {
//
// private Activity mActivity;
// AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;
// private ArrayList<String> mCatalogNum_arraylist = new ArrayList<>();
// private String mSubject;
// public CatalogNumFetchTask(String subject, AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
// mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
// mSubject = subject;
// }
//
// @Override
// protected Bundle doInBackground(String...params) {
// Bundle result = new Bundle();
// fetchCourse(result);
//
// return result;
// }
//
// private Bundle fetchCourse(Bundle bundle) {
// try{
// String url = Connections.getCatalogNumURL(mSubject);
//
// JSONObject jsonObject = Connections.getJSON_from_url(url);
// JSONArray subject_array = jsonObject.getJSONArray("data");
// Log.d("SubjectFetchTask", "subject array is " + subject_array.length());
//
// for(int i = 0; i < subject_array.length(); i++){
// JSONObject subject = subject_array.getJSONObject(i);
// mCatalogNum_arraylist.add(i,mSubject + " " + subject.getString("catalog_number"));
// }
//
// bundle.putStringArrayList("CatalogNum_arraylist", mCatalogNum_arraylist);
//
// return bundle;
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bundle;
// }
//
// @Override
// protected void onPostExecute(Bundle bundle) {
// mAsyncTaskCallbackInterface.onOperationComplete(bundle);
// }
//
//
// }
| import android.app.ListFragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.data.fetchtasks.CatalogNumFetchTask;
import com.YC2010.MyClass.R;
import java.util.ArrayList; | package com.YC2010.MyClass.ui.fragments;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
* interface.
*/
public class CatalogNumFragment extends ListFragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_SUBJECT = "SUBJECT";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String mSubject;
ArrayList<String> mCatalogNum_arraylist;
AlertDialog.Builder mBuilder;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
/*public static CatalogNumFragment newInstance(String param1, String param2) {
CatalogNumFragment fragment = new CatalogNumFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}*/
public CatalogNumFragment(){
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public void setSubject(String subject) {
mSubject = subject;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String subject = getArguments().getString(ARG_SUBJECT);
if(subject == null)
Toast.makeText(getActivity(), "subject string not found", Toast.LENGTH_SHORT).show();
mSubject = subject;
| // Path: app/src/main/java/com/YC2010/MyClass/callbacks/AsyncTaskCallbackInterface.java
// public interface AsyncTaskCallbackInterface {
// public void onOperationComplete(Bundle bundle);
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/data/fetchtasks/CatalogNumFetchTask.java
// public class CatalogNumFetchTask extends AsyncTask<String, Void, Bundle> {
//
// private Activity mActivity;
// AsyncTaskCallbackInterface mAsyncTaskCallbackInterface;
// private ArrayList<String> mCatalogNum_arraylist = new ArrayList<>();
// private String mSubject;
// public CatalogNumFetchTask(String subject, AsyncTaskCallbackInterface asyncTaskCallbackInterface) {
// mAsyncTaskCallbackInterface = asyncTaskCallbackInterface;
// mSubject = subject;
// }
//
// @Override
// protected Bundle doInBackground(String...params) {
// Bundle result = new Bundle();
// fetchCourse(result);
//
// return result;
// }
//
// private Bundle fetchCourse(Bundle bundle) {
// try{
// String url = Connections.getCatalogNumURL(mSubject);
//
// JSONObject jsonObject = Connections.getJSON_from_url(url);
// JSONArray subject_array = jsonObject.getJSONArray("data");
// Log.d("SubjectFetchTask", "subject array is " + subject_array.length());
//
// for(int i = 0; i < subject_array.length(); i++){
// JSONObject subject = subject_array.getJSONObject(i);
// mCatalogNum_arraylist.add(i,mSubject + " " + subject.getString("catalog_number"));
// }
//
// bundle.putStringArrayList("CatalogNum_arraylist", mCatalogNum_arraylist);
//
// return bundle;
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bundle;
// }
//
// @Override
// protected void onPostExecute(Bundle bundle) {
// mAsyncTaskCallbackInterface.onOperationComplete(bundle);
// }
//
//
// }
// Path: app/src/main/java/com/YC2010/MyClass/ui/fragments/CatalogNumFragment.java
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.YC2010.MyClass.callbacks.AsyncTaskCallbackInterface;
import com.YC2010.MyClass.data.fetchtasks.CatalogNumFetchTask;
import com.YC2010.MyClass.R;
import java.util.ArrayList;
package com.YC2010.MyClass.ui.fragments;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
* interface.
*/
public class CatalogNumFragment extends ListFragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_SUBJECT = "SUBJECT";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String mSubject;
ArrayList<String> mCatalogNum_arraylist;
AlertDialog.Builder mBuilder;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
/*public static CatalogNumFragment newInstance(String param1, String param2) {
CatalogNumFragment fragment = new CatalogNumFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}*/
public CatalogNumFragment(){
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public void setSubject(String subject) {
mSubject = subject;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String subject = getArguments().getString(ARG_SUBJECT);
if(subject == null)
Toast.makeText(getActivity(), "subject string not found", Toast.LENGTH_SHORT).show();
mSubject = subject;
| final CatalogNumFetchTask catalogNumFetchTask = new CatalogNumFetchTask(mSubject, new AsyncTaskCallbackInterface() { |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/ui/adapters/TstListAdapter.java | // Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/model/TestObject.java
// public class TestObject implements Parcelable {
// private String section;
// private String time;
// private String location;
// private String capacity;
// private String total;
//
// public TestObject() {}
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(section);
// dest.writeString(time);
// dest.writeString(location);
// dest.writeString(capacity);
// dest.writeString(total);
// }
//
// public TestObject(Parcel src) {
// this.section = src.readString();
// this.time = src.readString();
// this.location = src.readString();
// this.capacity = src.readString();
// this.total = src.readString();
// }
//
// public static final Creator CREATOR = new Creator() {
// @Override
// public TestObject createFromParcel(Parcel source) {
// return new TestObject(source);
// }
//
// @Override
// public TestObject[] newArray(int size) {
// return new TestObject[size];
// }
// };
//
// // Setters
//
// public void setTotal(String total) {
// this.total = total;
// }
//
// public void setSection(String section) {
// this.section = section;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public void setCapacity(String capacity) {
// this.capacity = capacity;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getSection() {
// return section;
// }
//
// public String getTime() {
// return time;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCapacity() {
// return capacity;
// }
//
// public String getTotal() {
// return total;
// }
// }
| import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.model.TestObject;
import com.YC2010.MyClass.R;
import java.util.ArrayList; | package com.YC2010.MyClass.ui.adapters;
public class TstListAdapter extends BaseAdapter {
ArrayList<TestObject> mArrayList;
Context mContext;
LayoutInflater mLayoutInflater;
public TstListAdapter(Context context, int textViewResourceId, Bundle bundle) {
mLayoutInflater = LayoutInflater.from(context); | // Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
//
// Path: app/src/main/java/com/YC2010/MyClass/model/TestObject.java
// public class TestObject implements Parcelable {
// private String section;
// private String time;
// private String location;
// private String capacity;
// private String total;
//
// public TestObject() {}
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(section);
// dest.writeString(time);
// dest.writeString(location);
// dest.writeString(capacity);
// dest.writeString(total);
// }
//
// public TestObject(Parcel src) {
// this.section = src.readString();
// this.time = src.readString();
// this.location = src.readString();
// this.capacity = src.readString();
// this.total = src.readString();
// }
//
// public static final Creator CREATOR = new Creator() {
// @Override
// public TestObject createFromParcel(Parcel source) {
// return new TestObject(source);
// }
//
// @Override
// public TestObject[] newArray(int size) {
// return new TestObject[size];
// }
// };
//
// // Setters
//
// public void setTotal(String total) {
// this.total = total;
// }
//
// public void setSection(String section) {
// this.section = section;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public void setCapacity(String capacity) {
// this.capacity = capacity;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getSection() {
// return section;
// }
//
// public String getTime() {
// return time;
// }
//
// public String getLocation() {
// return location;
// }
//
// public String getCapacity() {
// return capacity;
// }
//
// public String getTotal() {
// return total;
// }
// }
// Path: app/src/main/java/com/YC2010/MyClass/ui/adapters/TstListAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.model.TestObject;
import com.YC2010.MyClass.R;
import java.util.ArrayList;
package com.YC2010.MyClass.ui.adapters;
public class TstListAdapter extends BaseAdapter {
ArrayList<TestObject> mArrayList;
Context mContext;
LayoutInflater mLayoutInflater;
public TstListAdapter(Context context, int textViewResourceId, Bundle bundle) {
mLayoutInflater = LayoutInflater.from(context); | mArrayList = bundle.getParcelableArrayList(Constants.testObjectListKey); |
IYCI/MyClass | app/src/main/java/com/YC2010/MyClass/data/Connections.java | // Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
| import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.utils.Tools;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator; | package com.YC2010.MyClass.data;
/**
* Created by Danny on 2015/10/25.
*/
public class Connections {
// /courses/{subject}/{catalog_number}
public static String getCourseInfoURL(String input) {
String subject = "";
String cataNum = "";
boolean isCoursePrefix = true;
input = input.replaceAll("\\s+","");
for (int i = 0; i < input.length(); i++) {
if(isCoursePrefix && Character.isDigit(input.charAt(i)))
isCoursePrefix = false;
if(isCoursePrefix){
subject += input.charAt(i);
}
else{
cataNum += input.charAt(i);
}
}
| // Path: app/src/main/java/com/YC2010/MyClass/utils/Constants.java
// public class Constants {
// public static String UWAPIROOT = "https://api.uwaterloo.ca/v2/";
// public static List<Reminder_item> holiday_2015;
// public static List<Reminder_item> sample_reminder;
//
// public static String lectureSectionObjectListKey = "LEC_OBJECTS";
// public static String testObjectListKey = "TST_OBJECTS";
// public static String tutorialObjectListKey = "TUT_OBJECTS";
// public static String finalObjectListKey = "FINAL_OBJECTS";
//
// // default term value
// public static Integer defaultCurTermNum = 1161;
// public static String defaultCurTermName = "Winter 2016 (Current)";
// public static Integer defaultNextTermNum = 1165;
// public static String defaultNextTermName = "Spring 2016 (Next)";
//
// // temporarily hardcoded
// // Note: month off by one because of unix time standard
// public static GregorianCalendar nextTermStartDate = new GregorianCalendar(2016, 4, 2);
//
//
//
// public static List<Reminder_item> get_sample_reminder(){
// sample_reminder = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Final end","", 2015, 7, 15, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Next term start","", 2015, 8, 14, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "First penalty end","", 2015, 9, 3, "d");
// sample_reminder.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Late fee for fall","", 2015, 7, 28, "d");
// sample_reminder.add(tmp);
//
// return sample_reminder;
// }
//
// public static List<Reminder_item> get_holidays(){
// holiday_2015 = new ArrayList<>();
// Reminder_item tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Civic Holiday","", 2015, 7, 3, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Labour Day","", 2015, 8, 7, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Thanksgiving","", 2015, 9, 12, "d");
// holiday_2015.add(tmp);
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Christmas","", 2015, 11, 25, "d");
// holiday_2015.add(tmp);
//
// tmp = new Reminder_item(UUID.randomUUID().toString(),
// "Boxing Day","", 2015, 11, 28, "d");
// holiday_2015.add(tmp);
//
// return holiday_2015;
// }
// }
// Path: app/src/main/java/com/YC2010/MyClass/data/Connections.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import com.YC2010.MyClass.utils.Constants;
import com.YC2010.MyClass.utils.Tools;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
package com.YC2010.MyClass.data;
/**
* Created by Danny on 2015/10/25.
*/
public class Connections {
// /courses/{subject}/{catalog_number}
public static String getCourseInfoURL(String input) {
String subject = "";
String cataNum = "";
boolean isCoursePrefix = true;
input = input.replaceAll("\\s+","");
for (int i = 0; i < input.length(); i++) {
if(isCoursePrefix && Character.isDigit(input.charAt(i)))
isCoursePrefix = false;
if(isCoursePrefix){
subject += input.charAt(i);
}
else{
cataNum += input.charAt(i);
}
}
| return Constants.UWAPIROOT + "courses/" + subject + "/" + cataNum + ".json" + URLEnding(); |
kuaijibird/palmsuda | src/com/mialab/palmsuda/tools/util/FileUtils.java | // Path: src/com/mialab/palmsuda/common/Constants.java
// public class Constants {
// public static boolean TEST_MODE = false;
// public static boolean DEBUG_MODE =true;
// public static final String APP_TAG = "PalmSuda";
// public static final String APP_DIR = "PalmSuda";
// public static final String APP_CACHE = "/cache";
//
// public static final boolean MARKET_VERSION = false;
//
// public static final String ACCOUNT_TYPE = "com.mialab.palmsuda_demo3.sync";
//
// public static final String HTTP_SCHEME = "http";
// //public static final String HTTP_HOST = "res.51wcity.com";
// //public static final String HTTP_HOST = "mialab.suda.edu.cn";
//
// public static final String HTTP_HOST = "192.168.0.119:8080";
//
// public static final String HTTP_PATH = "/city-service/service";
// //public static final String HTTP_PATH = "/palm-service/service";
//
// public static final String HTTP_PALM_DATA_ROOT = HTTP_SCHEME + "://"
// + HTTP_HOST;
// public static final String SERVER_URL = HTTP_PALM_DATA_ROOT + HTTP_PATH;
//
// public static final String APP_UNAME = "palmsuda";
//
// public static final String SAVE_SELECT_AREA = "CityName";
// public static final String SAVE_AREA_ID = "CityID";
//
// public static final String SAVE_MOBILE_NUM = "mobile_number";
//
// public static final String MODULE_URL = "module_url";
//
// //public static final String HTTP_MODULE_LIST = "http://res.51wcity.com/WirelessSZ/city/100_%1$s.html";
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import com.mialab.palmsuda.common.Constants;
import android.content.Context;
import android.os.Environment;
import android.util.Log; | * @param fileName
* @return
*/
public boolean isFileExist(String fileName) {
File file = new File(FileUtils.getSDPath() + fileName);
return file.exists();
}
public boolean delExistFile(String fileName) {
File file = new File(FileUtils.getSDPath() + fileName);
if (file.exists()) {
return file.delete();
}
return false;
}
public static boolean delFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
return file.delete();
}
return false;
}
public static String getSDPath() {
String path = "";
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
if (sdCardExist) {
path = Environment.getExternalStorageDirectory().getAbsolutePath() | // Path: src/com/mialab/palmsuda/common/Constants.java
// public class Constants {
// public static boolean TEST_MODE = false;
// public static boolean DEBUG_MODE =true;
// public static final String APP_TAG = "PalmSuda";
// public static final String APP_DIR = "PalmSuda";
// public static final String APP_CACHE = "/cache";
//
// public static final boolean MARKET_VERSION = false;
//
// public static final String ACCOUNT_TYPE = "com.mialab.palmsuda_demo3.sync";
//
// public static final String HTTP_SCHEME = "http";
// //public static final String HTTP_HOST = "res.51wcity.com";
// //public static final String HTTP_HOST = "mialab.suda.edu.cn";
//
// public static final String HTTP_HOST = "192.168.0.119:8080";
//
// public static final String HTTP_PATH = "/city-service/service";
// //public static final String HTTP_PATH = "/palm-service/service";
//
// public static final String HTTP_PALM_DATA_ROOT = HTTP_SCHEME + "://"
// + HTTP_HOST;
// public static final String SERVER_URL = HTTP_PALM_DATA_ROOT + HTTP_PATH;
//
// public static final String APP_UNAME = "palmsuda";
//
// public static final String SAVE_SELECT_AREA = "CityName";
// public static final String SAVE_AREA_ID = "CityID";
//
// public static final String SAVE_MOBILE_NUM = "mobile_number";
//
// public static final String MODULE_URL = "module_url";
//
// //public static final String HTTP_MODULE_LIST = "http://res.51wcity.com/WirelessSZ/city/100_%1$s.html";
//
// }
// Path: src/com/mialab/palmsuda/tools/util/FileUtils.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import com.mialab.palmsuda.common.Constants;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
* @param fileName
* @return
*/
public boolean isFileExist(String fileName) {
File file = new File(FileUtils.getSDPath() + fileName);
return file.exists();
}
public boolean delExistFile(String fileName) {
File file = new File(FileUtils.getSDPath() + fileName);
if (file.exists()) {
return file.delete();
}
return false;
}
public static boolean delFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
return file.delete();
}
return false;
}
public static String getSDPath() {
String path = "";
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
if (sdCardExist) {
path = Environment.getExternalStorageDirectory().getAbsolutePath() | + "/" + Constants.APP_DIR;// 获取根目录 |
Asqatasun/Contrast-Finder | engine/impl/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorResultFactoryImpl.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorResult.java
// public interface ColorResult {
//
// /**
// * @param foreground
// * @param backgroud
// * @param threashold
// */
// void setSubmittedColors(Color foreground, Color backgroud, Float threashold);
//
// /**
// * @return ColorCombinaison object
// */
// ColorCombinaison getSubmittedCombinaisonColor();
//
// /**
// * @return true if is valid combinaison
// */
// boolean isCombinaisonValid();
//
// /**
// *
// * @return Collection object of ColorCombinaison objects
// */
// Collection<ColorCombinaison> getSuggestedColors();
//
// /**
// * @return the number of suggested colors
// */
// int getNumberOfSuggestedColors();
//
// /**
// * @param combinaison
// */
// void addSuggestedColor(ColorCombinaison combinaison);
//
// /**
// * @return Threashold
// */
// Float getThreashold();
//
// /**
// * @return the number of tested colors
// */
// int getNumberOfTestedColors();
//
// /**
// * set the number of tested colors
// * @param testedColors
// */
// void setNumberOfTestedColors(int testedColors);
//
// }
//
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java
// public class ColorResultImpl implements ColorResult {
//
// private static final int MAX_SUGGESTED_COLOR = 20;
// /* the colorCombinaisonFactory instance*/
// private ColorCombinaisonFactory colorCombinaisonFactory;
// /* the submitted color combinaison*/
// private ColorCombinaison submittedColors;
// /* the suggested colors */
// private Set<ColorCombinaison> suggestedColors =
// new LinkedHashSet<ColorCombinaison>();
// private int numberOfTestedColors;
//
// /*
// * Constructor
// */
// public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) {
// this.colorCombinaisonFactory = colorCombinaisonFactory;
// }
//
// @Override
// public Float getThreashold() {
// return Float.valueOf(submittedColors.getThreshold().floatValue());
// }
//
// @Override
// public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) {
// submittedColors =
// colorCombinaisonFactory.getColorCombinaison(
// colorToChange,
// colorToKeep,
// Double.valueOf(threashold));
// }
//
// @Override
// public ColorCombinaison getSubmittedCombinaisonColor() {
// return submittedColors;
// }
//
// @Override
// public boolean isCombinaisonValid() {
// return submittedColors.isContrastValid();
// }
//
// @Override
// public Collection<ColorCombinaison> getSuggestedColors() {
// return suggestedColors;
// }
//
// @Override
// public void addSuggestedColor(ColorCombinaison colorCombinaison) {
// colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor()));
// suggestedColors.add(colorCombinaison);
// }
//
// @Override
// public int getNumberOfSuggestedColors() {
// return suggestedColors.size();
// }
//
// /**
// *
// * @return whether the max number suggested colors is reached
// */
// public boolean isSuggestedColorsFull() {
// return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR;
// }
//
// @Override
// public int getNumberOfTestedColors() {
// return numberOfTestedColors;
// }
//
// @Override
// public void setNumberOfTestedColors(int numberOfTestedColors) {
// this.numberOfTestedColors = numberOfTestedColors;
// }
// }
| import org.asqatasun.contrastfinder.result.ColorResult;
import org.asqatasun.contrastfinder.result.ColorResultImpl; | /*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.result.factory;
/**
*
* @author alingua
*/
public class ColorResultFactoryImpl implements ColorResultFactory {
@Override | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorResult.java
// public interface ColorResult {
//
// /**
// * @param foreground
// * @param backgroud
// * @param threashold
// */
// void setSubmittedColors(Color foreground, Color backgroud, Float threashold);
//
// /**
// * @return ColorCombinaison object
// */
// ColorCombinaison getSubmittedCombinaisonColor();
//
// /**
// * @return true if is valid combinaison
// */
// boolean isCombinaisonValid();
//
// /**
// *
// * @return Collection object of ColorCombinaison objects
// */
// Collection<ColorCombinaison> getSuggestedColors();
//
// /**
// * @return the number of suggested colors
// */
// int getNumberOfSuggestedColors();
//
// /**
// * @param combinaison
// */
// void addSuggestedColor(ColorCombinaison combinaison);
//
// /**
// * @return Threashold
// */
// Float getThreashold();
//
// /**
// * @return the number of tested colors
// */
// int getNumberOfTestedColors();
//
// /**
// * set the number of tested colors
// * @param testedColors
// */
// void setNumberOfTestedColors(int testedColors);
//
// }
//
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java
// public class ColorResultImpl implements ColorResult {
//
// private static final int MAX_SUGGESTED_COLOR = 20;
// /* the colorCombinaisonFactory instance*/
// private ColorCombinaisonFactory colorCombinaisonFactory;
// /* the submitted color combinaison*/
// private ColorCombinaison submittedColors;
// /* the suggested colors */
// private Set<ColorCombinaison> suggestedColors =
// new LinkedHashSet<ColorCombinaison>();
// private int numberOfTestedColors;
//
// /*
// * Constructor
// */
// public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) {
// this.colorCombinaisonFactory = colorCombinaisonFactory;
// }
//
// @Override
// public Float getThreashold() {
// return Float.valueOf(submittedColors.getThreshold().floatValue());
// }
//
// @Override
// public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) {
// submittedColors =
// colorCombinaisonFactory.getColorCombinaison(
// colorToChange,
// colorToKeep,
// Double.valueOf(threashold));
// }
//
// @Override
// public ColorCombinaison getSubmittedCombinaisonColor() {
// return submittedColors;
// }
//
// @Override
// public boolean isCombinaisonValid() {
// return submittedColors.isContrastValid();
// }
//
// @Override
// public Collection<ColorCombinaison> getSuggestedColors() {
// return suggestedColors;
// }
//
// @Override
// public void addSuggestedColor(ColorCombinaison colorCombinaison) {
// colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor()));
// suggestedColors.add(colorCombinaison);
// }
//
// @Override
// public int getNumberOfSuggestedColors() {
// return suggestedColors.size();
// }
//
// /**
// *
// * @return whether the max number suggested colors is reached
// */
// public boolean isSuggestedColorsFull() {
// return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR;
// }
//
// @Override
// public int getNumberOfTestedColors() {
// return numberOfTestedColors;
// }
//
// @Override
// public void setNumberOfTestedColors(int numberOfTestedColors) {
// this.numberOfTestedColors = numberOfTestedColors;
// }
// }
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorResultFactoryImpl.java
import org.asqatasun.contrastfinder.result.ColorResult;
import org.asqatasun.contrastfinder.result.ColorResultImpl;
/*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.result.factory;
/**
*
* @author alingua
*/
public class ColorResultFactoryImpl implements ColorResultFactory {
@Override | public ColorResult getColorResult() { |
Asqatasun/Contrast-Finder | engine/impl/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorResultFactoryImpl.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorResult.java
// public interface ColorResult {
//
// /**
// * @param foreground
// * @param backgroud
// * @param threashold
// */
// void setSubmittedColors(Color foreground, Color backgroud, Float threashold);
//
// /**
// * @return ColorCombinaison object
// */
// ColorCombinaison getSubmittedCombinaisonColor();
//
// /**
// * @return true if is valid combinaison
// */
// boolean isCombinaisonValid();
//
// /**
// *
// * @return Collection object of ColorCombinaison objects
// */
// Collection<ColorCombinaison> getSuggestedColors();
//
// /**
// * @return the number of suggested colors
// */
// int getNumberOfSuggestedColors();
//
// /**
// * @param combinaison
// */
// void addSuggestedColor(ColorCombinaison combinaison);
//
// /**
// * @return Threashold
// */
// Float getThreashold();
//
// /**
// * @return the number of tested colors
// */
// int getNumberOfTestedColors();
//
// /**
// * set the number of tested colors
// * @param testedColors
// */
// void setNumberOfTestedColors(int testedColors);
//
// }
//
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java
// public class ColorResultImpl implements ColorResult {
//
// private static final int MAX_SUGGESTED_COLOR = 20;
// /* the colorCombinaisonFactory instance*/
// private ColorCombinaisonFactory colorCombinaisonFactory;
// /* the submitted color combinaison*/
// private ColorCombinaison submittedColors;
// /* the suggested colors */
// private Set<ColorCombinaison> suggestedColors =
// new LinkedHashSet<ColorCombinaison>();
// private int numberOfTestedColors;
//
// /*
// * Constructor
// */
// public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) {
// this.colorCombinaisonFactory = colorCombinaisonFactory;
// }
//
// @Override
// public Float getThreashold() {
// return Float.valueOf(submittedColors.getThreshold().floatValue());
// }
//
// @Override
// public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) {
// submittedColors =
// colorCombinaisonFactory.getColorCombinaison(
// colorToChange,
// colorToKeep,
// Double.valueOf(threashold));
// }
//
// @Override
// public ColorCombinaison getSubmittedCombinaisonColor() {
// return submittedColors;
// }
//
// @Override
// public boolean isCombinaisonValid() {
// return submittedColors.isContrastValid();
// }
//
// @Override
// public Collection<ColorCombinaison> getSuggestedColors() {
// return suggestedColors;
// }
//
// @Override
// public void addSuggestedColor(ColorCombinaison colorCombinaison) {
// colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor()));
// suggestedColors.add(colorCombinaison);
// }
//
// @Override
// public int getNumberOfSuggestedColors() {
// return suggestedColors.size();
// }
//
// /**
// *
// * @return whether the max number suggested colors is reached
// */
// public boolean isSuggestedColorsFull() {
// return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR;
// }
//
// @Override
// public int getNumberOfTestedColors() {
// return numberOfTestedColors;
// }
//
// @Override
// public void setNumberOfTestedColors(int numberOfTestedColors) {
// this.numberOfTestedColors = numberOfTestedColors;
// }
// }
| import org.asqatasun.contrastfinder.result.ColorResult;
import org.asqatasun.contrastfinder.result.ColorResultImpl; | /*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.result.factory;
/**
*
* @author alingua
*/
public class ColorResultFactoryImpl implements ColorResultFactory {
@Override
public ColorResult getColorResult() { | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorResult.java
// public interface ColorResult {
//
// /**
// * @param foreground
// * @param backgroud
// * @param threashold
// */
// void setSubmittedColors(Color foreground, Color backgroud, Float threashold);
//
// /**
// * @return ColorCombinaison object
// */
// ColorCombinaison getSubmittedCombinaisonColor();
//
// /**
// * @return true if is valid combinaison
// */
// boolean isCombinaisonValid();
//
// /**
// *
// * @return Collection object of ColorCombinaison objects
// */
// Collection<ColorCombinaison> getSuggestedColors();
//
// /**
// * @return the number of suggested colors
// */
// int getNumberOfSuggestedColors();
//
// /**
// * @param combinaison
// */
// void addSuggestedColor(ColorCombinaison combinaison);
//
// /**
// * @return Threashold
// */
// Float getThreashold();
//
// /**
// * @return the number of tested colors
// */
// int getNumberOfTestedColors();
//
// /**
// * set the number of tested colors
// * @param testedColors
// */
// void setNumberOfTestedColors(int testedColors);
//
// }
//
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java
// public class ColorResultImpl implements ColorResult {
//
// private static final int MAX_SUGGESTED_COLOR = 20;
// /* the colorCombinaisonFactory instance*/
// private ColorCombinaisonFactory colorCombinaisonFactory;
// /* the submitted color combinaison*/
// private ColorCombinaison submittedColors;
// /* the suggested colors */
// private Set<ColorCombinaison> suggestedColors =
// new LinkedHashSet<ColorCombinaison>();
// private int numberOfTestedColors;
//
// /*
// * Constructor
// */
// public ColorResultImpl(ColorCombinaisonFactory colorCombinaisonFactory) {
// this.colorCombinaisonFactory = colorCombinaisonFactory;
// }
//
// @Override
// public Float getThreashold() {
// return Float.valueOf(submittedColors.getThreshold().floatValue());
// }
//
// @Override
// public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) {
// submittedColors =
// colorCombinaisonFactory.getColorCombinaison(
// colorToChange,
// colorToKeep,
// Double.valueOf(threashold));
// }
//
// @Override
// public ColorCombinaison getSubmittedCombinaisonColor() {
// return submittedColors;
// }
//
// @Override
// public boolean isCombinaisonValid() {
// return submittedColors.isContrastValid();
// }
//
// @Override
// public Collection<ColorCombinaison> getSuggestedColors() {
// return suggestedColors;
// }
//
// @Override
// public void addSuggestedColor(ColorCombinaison colorCombinaison) {
// colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor()));
// suggestedColors.add(colorCombinaison);
// }
//
// @Override
// public int getNumberOfSuggestedColors() {
// return suggestedColors.size();
// }
//
// /**
// *
// * @return whether the max number suggested colors is reached
// */
// public boolean isSuggestedColorsFull() {
// return getNumberOfSuggestedColors() >= MAX_SUGGESTED_COLOR;
// }
//
// @Override
// public int getNumberOfTestedColors() {
// return numberOfTestedColors;
// }
//
// @Override
// public void setNumberOfTestedColors(int numberOfTestedColors) {
// this.numberOfTestedColors = numberOfTestedColors;
// }
// }
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorResultFactoryImpl.java
import org.asqatasun.contrastfinder.result.ColorResult;
import org.asqatasun.contrastfinder.result.ColorResultImpl;
/*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.result.factory;
/**
*
* @author alingua
*/
public class ColorResultFactoryImpl implements ColorResultFactory {
@Override
public ColorResult getColorResult() { | return (new ColorResultImpl(new ColorCombinaisonFactoryImpl())); |
Asqatasun/Contrast-Finder | engine/hsv/src/test/java/org/asqatasun/contrastfinder/hsv/ColorFinderHsvTest.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorCombinaison.java
// public interface ColorCombinaison {
//
//
// /**
// * @return Gap
// */
// Float getGap();
//
// /**
// * @return Color object
// */
// Color getColor();
//
// /**
// * @param color
// */
// void setColor(Color color);
//
// /**
// * @return contrast
// */
// Double getContrast();
//
// /**
// * @param distance from initial color
// */
// void setDistanceFromInitialColor(Double distance);
//
// /**
// * @return distance
// */
// Double getDistance();
//
// /**
// * @param threshold
// */
// void setThreshold(Double threshold);
//
// /**
// * @return threshold
// */
// Double getThreshold();
//
// /**
// * @return true if is valid contrast
// */
// boolean isContrastValid();
//
// /**
// * @return Color object
// */
// Color getComparisonColor();
//
// /**
// * @param color
// */
// void setComparisonColor(Color color);
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColor();
//
// /**
// *
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColor();
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColorComp();
//
// /**
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColorComp();
// }
| import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import junit.framework.TestCase;
import org.junit.Test; // Junit 4 anotation @Test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.asqatasun.contrastfinder.result.ColorCombinaison; | /*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.hsv;
/**
*
* @author alingua
*/
public class ColorFinderHsvTest extends TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(ColorFinderHsvTest.class);
public ColorFinderHsvTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of findColors method, of class ColorFinderHsv.
*/
@Test
public void testFindColorsWithFgAndBg() {
System.out.println("FindColorsWithFgAndBg");
Color foregroundColor = new Color(127, 127, 127);
Color backgroundColor = new Color(128, 128, 128);
Float coefficientLevel = 4.5f;
ColorFinderHsv instance = new ColorFinderHsv();
instance.findColors(foregroundColor, backgroundColor, true, coefficientLevel); | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorCombinaison.java
// public interface ColorCombinaison {
//
//
// /**
// * @return Gap
// */
// Float getGap();
//
// /**
// * @return Color object
// */
// Color getColor();
//
// /**
// * @param color
// */
// void setColor(Color color);
//
// /**
// * @return contrast
// */
// Double getContrast();
//
// /**
// * @param distance from initial color
// */
// void setDistanceFromInitialColor(Double distance);
//
// /**
// * @return distance
// */
// Double getDistance();
//
// /**
// * @param threshold
// */
// void setThreshold(Double threshold);
//
// /**
// * @return threshold
// */
// Double getThreshold();
//
// /**
// * @return true if is valid contrast
// */
// boolean isContrastValid();
//
// /**
// * @return Color object
// */
// Color getComparisonColor();
//
// /**
// * @param color
// */
// void setComparisonColor(Color color);
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColor();
//
// /**
// *
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColor();
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColorComp();
//
// /**
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColorComp();
// }
// Path: engine/hsv/src/test/java/org/asqatasun/contrastfinder/hsv/ColorFinderHsvTest.java
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import junit.framework.TestCase;
import org.junit.Test; // Junit 4 anotation @Test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.asqatasun.contrastfinder.result.ColorCombinaison;
/*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.hsv;
/**
*
* @author alingua
*/
public class ColorFinderHsvTest extends TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(ColorFinderHsvTest.class);
public ColorFinderHsvTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of findColors method, of class ColorFinderHsv.
*/
@Test
public void testFindColorsWithFgAndBg() {
System.out.println("FindColorsWithFgAndBg");
Color foregroundColor = new Color(127, 127, 127);
Color backgroundColor = new Color(128, 128, 128);
Float coefficientLevel = 4.5f;
ColorFinderHsv instance = new ColorFinderHsv();
instance.findColors(foregroundColor, backgroundColor, true, coefficientLevel); | List<ColorCombinaison> colorCombinaison = new ArrayList<ColorCombinaison>(); |
Asqatasun/Contrast-Finder | engine/api/src/main/java/org/asqatasun/contrastfinder/ColorFinder.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorResult.java
// public interface ColorResult {
//
// /**
// * @param foreground
// * @param backgroud
// * @param threashold
// */
// void setSubmittedColors(Color foreground, Color backgroud, Float threashold);
//
// /**
// * @return ColorCombinaison object
// */
// ColorCombinaison getSubmittedCombinaisonColor();
//
// /**
// * @return true if is valid combinaison
// */
// boolean isCombinaisonValid();
//
// /**
// *
// * @return Collection object of ColorCombinaison objects
// */
// Collection<ColorCombinaison> getSuggestedColors();
//
// /**
// * @return the number of suggested colors
// */
// int getNumberOfSuggestedColors();
//
// /**
// * @param combinaison
// */
// void addSuggestedColor(ColorCombinaison combinaison);
//
// /**
// * @return Threashold
// */
// Float getThreashold();
//
// /**
// * @return the number of tested colors
// */
// int getNumberOfTestedColors();
//
// /**
// * set the number of tested colors
// * @param testedColors
// */
// void setNumberOfTestedColors(int testedColors);
//
// }
| import java.awt.Color;
import org.asqatasun.contrastfinder.result.ColorResult; | /*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder;
/**
*
* @author alingua
*/
public interface ColorFinder {
/**
* @param foregroundColor
* @param backgroundColor
* @param isBackgroundTested
* @param coefficientLevel
*/
void findColors (
Color foregroundColor,
Color backgroundColor,
boolean isBackgroundTested,
Float coefficientLevel);
/**
* @return ColorResult object
*/ | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorResult.java
// public interface ColorResult {
//
// /**
// * @param foreground
// * @param backgroud
// * @param threashold
// */
// void setSubmittedColors(Color foreground, Color backgroud, Float threashold);
//
// /**
// * @return ColorCombinaison object
// */
// ColorCombinaison getSubmittedCombinaisonColor();
//
// /**
// * @return true if is valid combinaison
// */
// boolean isCombinaisonValid();
//
// /**
// *
// * @return Collection object of ColorCombinaison objects
// */
// Collection<ColorCombinaison> getSuggestedColors();
//
// /**
// * @return the number of suggested colors
// */
// int getNumberOfSuggestedColors();
//
// /**
// * @param combinaison
// */
// void addSuggestedColor(ColorCombinaison combinaison);
//
// /**
// * @return Threashold
// */
// Float getThreashold();
//
// /**
// * @return the number of tested colors
// */
// int getNumberOfTestedColors();
//
// /**
// * set the number of tested colors
// * @param testedColors
// */
// void setNumberOfTestedColors(int testedColors);
//
// }
// Path: engine/api/src/main/java/org/asqatasun/contrastfinder/ColorFinder.java
import java.awt.Color;
import org.asqatasun.contrastfinder.result.ColorResult;
/*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder;
/**
*
* @author alingua
*/
public interface ColorFinder {
/**
* @param foregroundColor
* @param backgroundColor
* @param isBackgroundTested
* @param coefficientLevel
*/
void findColors (
Color foregroundColor,
Color backgroundColor,
boolean isBackgroundTested,
Float coefficientLevel);
/**
* @return ColorResult object
*/ | ColorResult getColorResult(); |
Asqatasun/Contrast-Finder | engine/impl/src/main/java/org/asqatasun/contrastfinder/factory/ColorFinderFactoryImpl.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/ColorFinder.java
// public interface ColorFinder {
//
// /**
// * @param foregroundColor
// * @param backgroundColor
// * @param isBackgroundTested
// * @param coefficientLevel
// */
// void findColors (
// Color foregroundColor,
// Color backgroundColor,
// boolean isBackgroundTested,
// Float coefficientLevel);
//
// /**
// * @return ColorResult object
// */
// ColorResult getColorResult();
//
// /**
// * @return a key that represents the colorFinder
// */
// String getColorFinderKey();
// }
| import org.asqatasun.contrastfinder.ColorFinder;
import java.util.HashMap;
import java.util.Map; | /*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.factory;
/**
*
* @author alingua
*/
public class ColorFinderFactoryImpl implements ColorFinderFactory {
private Map<String, ColorFinderFactory> colorFinderMap =
new HashMap<String, ColorFinderFactory>();
public void setColorFinderMap(Map<String, ColorFinderFactory> colorFinderMap) {
this.colorFinderMap = colorFinderMap;
}
@Override | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/ColorFinder.java
// public interface ColorFinder {
//
// /**
// * @param foregroundColor
// * @param backgroundColor
// * @param isBackgroundTested
// * @param coefficientLevel
// */
// void findColors (
// Color foregroundColor,
// Color backgroundColor,
// boolean isBackgroundTested,
// Float coefficientLevel);
//
// /**
// * @return ColorResult object
// */
// ColorResult getColorResult();
//
// /**
// * @return a key that represents the colorFinder
// */
// String getColorFinderKey();
// }
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/factory/ColorFinderFactoryImpl.java
import org.asqatasun.contrastfinder.ColorFinder;
import java.util.HashMap;
import java.util.Map;
/*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.factory;
/**
*
* @author alingua
*/
public class ColorFinderFactoryImpl implements ColorFinderFactory {
private Map<String, ColorFinderFactory> colorFinderMap =
new HashMap<String, ColorFinderFactory>();
public void setColorFinderMap(Map<String, ColorFinderFactory> colorFinderMap) {
this.colorFinderMap = colorFinderMap;
}
@Override | public ColorFinder getColorFinder(String colorFinderKey) { |
Asqatasun/Contrast-Finder | engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorCombinaisonFactory.java
// public interface ColorCombinaisonFactory {
//
// /**
// *
// * @param color1
// * @param color2
// * @param threashold
// * @return a ColorCombinaison instance
// */
// ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold);
//
// }
//
// Path: engine/utils/src/main/java/org/asqatasun/utils/distancecalculator/DistanceCalculator.java
// public final class DistanceCalculator {
//
// private static final int CUBIC = 3;
// private static final int ROUND_VALUE = 100;
//
// private DistanceCalculator() {
// }
//
// /**
// *
// * @param colorToChange
// * @param colorToKeep
// * @return the calculated distance between 2 colors regarding the
// * distance definition that can be found here
// * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions
// */
// public static double calculate(Color colorToChange, Color colorToKeep) {
// return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE;
// }
// }
| import java.awt.Color;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.asqatasun.contrastfinder.result.factory.ColorCombinaisonFactory;
import org.asqatasun.utils.distancecalculator.DistanceCalculator; | /*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.result;
/**
*
* @author alingua
*/
public class ColorResultImpl implements ColorResult {
private static final int MAX_SUGGESTED_COLOR = 20;
/* the colorCombinaisonFactory instance*/ | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorCombinaisonFactory.java
// public interface ColorCombinaisonFactory {
//
// /**
// *
// * @param color1
// * @param color2
// * @param threashold
// * @return a ColorCombinaison instance
// */
// ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold);
//
// }
//
// Path: engine/utils/src/main/java/org/asqatasun/utils/distancecalculator/DistanceCalculator.java
// public final class DistanceCalculator {
//
// private static final int CUBIC = 3;
// private static final int ROUND_VALUE = 100;
//
// private DistanceCalculator() {
// }
//
// /**
// *
// * @param colorToChange
// * @param colorToKeep
// * @return the calculated distance between 2 colors regarding the
// * distance definition that can be found here
// * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions
// */
// public static double calculate(Color colorToChange, Color colorToKeep) {
// return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE;
// }
// }
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java
import java.awt.Color;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.asqatasun.contrastfinder.result.factory.ColorCombinaisonFactory;
import org.asqatasun.utils.distancecalculator.DistanceCalculator;
/*
* Contrast Finder
* Copyright (C) 2008-2019 Contrast-Finder.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.contrastfinder.result;
/**
*
* @author alingua
*/
public class ColorResultImpl implements ColorResult {
private static final int MAX_SUGGESTED_COLOR = 20;
/* the colorCombinaisonFactory instance*/ | private ColorCombinaisonFactory colorCombinaisonFactory; |
Asqatasun/Contrast-Finder | engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorCombinaisonFactory.java
// public interface ColorCombinaisonFactory {
//
// /**
// *
// * @param color1
// * @param color2
// * @param threashold
// * @return a ColorCombinaison instance
// */
// ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold);
//
// }
//
// Path: engine/utils/src/main/java/org/asqatasun/utils/distancecalculator/DistanceCalculator.java
// public final class DistanceCalculator {
//
// private static final int CUBIC = 3;
// private static final int ROUND_VALUE = 100;
//
// private DistanceCalculator() {
// }
//
// /**
// *
// * @param colorToChange
// * @param colorToKeep
// * @return the calculated distance between 2 colors regarding the
// * distance definition that can be found here
// * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions
// */
// public static double calculate(Color colorToChange, Color colorToKeep) {
// return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE;
// }
// }
| import java.awt.Color;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.asqatasun.contrastfinder.result.factory.ColorCombinaisonFactory;
import org.asqatasun.utils.distancecalculator.DistanceCalculator; | public Float getThreashold() {
return Float.valueOf(submittedColors.getThreshold().floatValue());
}
@Override
public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) {
submittedColors =
colorCombinaisonFactory.getColorCombinaison(
colorToChange,
colorToKeep,
Double.valueOf(threashold));
}
@Override
public ColorCombinaison getSubmittedCombinaisonColor() {
return submittedColors;
}
@Override
public boolean isCombinaisonValid() {
return submittedColors.isContrastValid();
}
@Override
public Collection<ColorCombinaison> getSuggestedColors() {
return suggestedColors;
}
@Override
public void addSuggestedColor(ColorCombinaison colorCombinaison) { | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/factory/ColorCombinaisonFactory.java
// public interface ColorCombinaisonFactory {
//
// /**
// *
// * @param color1
// * @param color2
// * @param threashold
// * @return a ColorCombinaison instance
// */
// ColorCombinaison getColorCombinaison(Color color1, Color color2, Double threashold);
//
// }
//
// Path: engine/utils/src/main/java/org/asqatasun/utils/distancecalculator/DistanceCalculator.java
// public final class DistanceCalculator {
//
// private static final int CUBIC = 3;
// private static final int ROUND_VALUE = 100;
//
// private DistanceCalculator() {
// }
//
// /**
// *
// * @param colorToChange
// * @param colorToKeep
// * @return the calculated distance between 2 colors regarding the
// * distance definition that can be found here
// * http://en.wikipedia.org/wiki/Euclidean_distance#Three_dimensions
// */
// public static double calculate(Color colorToChange, Color colorToKeep) {
// return (double) Math.round(Math.abs((Math.cbrt(Math.pow(Double.valueOf(colorToChange.getRed()) - Double.valueOf(colorToKeep.getRed()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getGreen()) - Double.valueOf(colorToKeep.getGreen()), CUBIC)
// + Math.pow(Double.valueOf(colorToChange.getBlue()) - Double.valueOf(colorToKeep.getBlue()), CUBIC)))) * ROUND_VALUE) / ROUND_VALUE;
// }
// }
// Path: engine/impl/src/main/java/org/asqatasun/contrastfinder/result/ColorResultImpl.java
import java.awt.Color;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.asqatasun.contrastfinder.result.factory.ColorCombinaisonFactory;
import org.asqatasun.utils.distancecalculator.DistanceCalculator;
public Float getThreashold() {
return Float.valueOf(submittedColors.getThreshold().floatValue());
}
@Override
public void setSubmittedColors(Color colorToChange, Color colorToKeep, Float threashold) {
submittedColors =
colorCombinaisonFactory.getColorCombinaison(
colorToChange,
colorToKeep,
Double.valueOf(threashold));
}
@Override
public ColorCombinaison getSubmittedCombinaisonColor() {
return submittedColors;
}
@Override
public boolean isCombinaisonValid() {
return submittedColors.isContrastValid();
}
@Override
public Collection<ColorCombinaison> getSuggestedColors() {
return suggestedColors;
}
@Override
public void addSuggestedColor(ColorCombinaison colorCombinaison) { | colorCombinaison.setDistanceFromInitialColor(DistanceCalculator.calculate(submittedColors.getColor(), colorCombinaison.getColor())); |
Asqatasun/Contrast-Finder | engine/hsv/src/test/java/org/asqatasun/contrastfinder/hsv/ColorFinderRgbTest.java | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorCombinaison.java
// public interface ColorCombinaison {
//
//
// /**
// * @return Gap
// */
// Float getGap();
//
// /**
// * @return Color object
// */
// Color getColor();
//
// /**
// * @param color
// */
// void setColor(Color color);
//
// /**
// * @return contrast
// */
// Double getContrast();
//
// /**
// * @param distance from initial color
// */
// void setDistanceFromInitialColor(Double distance);
//
// /**
// * @return distance
// */
// Double getDistance();
//
// /**
// * @param threshold
// */
// void setThreshold(Double threshold);
//
// /**
// * @return threshold
// */
// Double getThreshold();
//
// /**
// * @return true if is valid contrast
// */
// boolean isContrastValid();
//
// /**
// * @return Color object
// */
// Color getComparisonColor();
//
// /**
// * @param color
// */
// void setComparisonColor(Color color);
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColor();
//
// /**
// *
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColor();
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColorComp();
//
// /**
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColorComp();
// }
| import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test; // Junit 4 anotation @Test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.asqatasun.contrastfinder.result.ColorCombinaison; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.asqatasun.contrastfinder.hsv;
/**
*
* @author alingua
*/
public class ColorFinderRgbTest extends TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(ColorFinderRgbTest.class);
public ColorFinderRgbTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testFindColorsNearColorOrange() {
System.out.println("FindColorsNearColor");
Color foregroundColor = new Color(255, 255, 255);
Color backgroundColor = new Color(255, 192, 7);
Float coefficientLevel = 3.0f;
ColorFinderRgb instance = new ColorFinderRgb(); | // Path: engine/api/src/main/java/org/asqatasun/contrastfinder/result/ColorCombinaison.java
// public interface ColorCombinaison {
//
//
// /**
// * @return Gap
// */
// Float getGap();
//
// /**
// * @return Color object
// */
// Color getColor();
//
// /**
// * @param color
// */
// void setColor(Color color);
//
// /**
// * @return contrast
// */
// Double getContrast();
//
// /**
// * @param distance from initial color
// */
// void setDistanceFromInitialColor(Double distance);
//
// /**
// * @return distance
// */
// Double getDistance();
//
// /**
// * @param threshold
// */
// void setThreshold(Double threshold);
//
// /**
// * @return threshold
// */
// Double getThreshold();
//
// /**
// * @return true if is valid contrast
// */
// boolean isContrastValid();
//
// /**
// * @return Color object
// */
// Color getComparisonColor();
//
// /**
// * @param color
// */
// void setComparisonColor(Color color);
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColor();
//
// /**
// *
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColor();
//
// /**
// * @return color in hexadecimal format, example: #FFFFFF
// */
// String getHexaColorComp();
//
// /**
// * @return color in HSL format, example: hsl(0, 0%, 100%)
// */
// String getHslColorComp();
// }
// Path: engine/hsv/src/test/java/org/asqatasun/contrastfinder/hsv/ColorFinderRgbTest.java
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Test; // Junit 4 anotation @Test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.asqatasun.contrastfinder.result.ColorCombinaison;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.asqatasun.contrastfinder.hsv;
/**
*
* @author alingua
*/
public class ColorFinderRgbTest extends TestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(ColorFinderRgbTest.class);
public ColorFinderRgbTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testFindColorsNearColorOrange() {
System.out.println("FindColorsNearColor");
Color foregroundColor = new Color(255, 255, 255);
Color backgroundColor = new Color(255, 192, 7);
Float coefficientLevel = 3.0f;
ColorFinderRgb instance = new ColorFinderRgb(); | List<ColorCombinaison> colorCombinaison = new ArrayList<ColorCombinaison>(); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/ContractedDijkstra.java | // Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class DownwardSolution extends PartialSolution {
// public DownwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public DownwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
//
// Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class UpwardSolution extends PartialSolution {
// public UpwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public UpwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
| import java.nio.IntBuffer;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import uk.me.mjt.ch.PartialSolution.DownwardSolution;
import uk.me.mjt.ch.PartialSolution.UpwardSolution; |
package uk.me.mjt.ch;
public class ContractedDijkstra {
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
throw new UnsupportedOperationException("Temporarily broken");
}
/*public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
Future<UpwardSolution> fUpwardSolution = futureUpwardSolution(allNodes, startNode, es);
Future<DownwardSolution> fDownwardSolution = futureDownwardSolution(allNodes, endNode, es);
return mergeUpwardAndDownwardSolutions(allNodes, getFutureQuietly(fUpwardSolution), getFutureQuietly(fDownwardSolution));
}
private static <E> E getFutureQuietly(Future<E> f) {
try {
return f.get();
} catch (ExecutionException|InterruptedException e) {
throw new RuntimeException(e);
}
}
private static Future<UpwardSolution> futureUpwardSolution(final MapData allNodes, final Node startNode, final ExecutorService es) {
return es.submit(new Callable<UpwardSolution>() {
@Override
public UpwardSolution call() throws Exception {
return calculateUpwardSolution(allNodes, startNode);
}
});
}
private static Future<DownwardSolution> futureDownwardSolution(final MapData allNodes, final Node endNode, final ExecutorService es) {
return es.submit(new Callable<DownwardSolution>() {
@Override
public DownwardSolution call() throws Exception {
return calculateDownwardSolution(allNodes, endNode);
}
});
}*/
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
return contractedGraphDijkstra(allNodes, ColocatedNodeSet.singleton(startNode), ColocatedNodeSet.singleton(endNode));
}
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, ColocatedNodeSet startNode, ColocatedNodeSet endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode); | // Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class DownwardSolution extends PartialSolution {
// public DownwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public DownwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
//
// Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class UpwardSolution extends PartialSolution {
// public UpwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public UpwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
// Path: src/main/java/uk/me/mjt/ch/ContractedDijkstra.java
import java.nio.IntBuffer;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import uk.me.mjt.ch.PartialSolution.DownwardSolution;
import uk.me.mjt.ch.PartialSolution.UpwardSolution;
package uk.me.mjt.ch;
public class ContractedDijkstra {
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
throw new UnsupportedOperationException("Temporarily broken");
}
/*public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
Future<UpwardSolution> fUpwardSolution = futureUpwardSolution(allNodes, startNode, es);
Future<DownwardSolution> fDownwardSolution = futureDownwardSolution(allNodes, endNode, es);
return mergeUpwardAndDownwardSolutions(allNodes, getFutureQuietly(fUpwardSolution), getFutureQuietly(fDownwardSolution));
}
private static <E> E getFutureQuietly(Future<E> f) {
try {
return f.get();
} catch (ExecutionException|InterruptedException e) {
throw new RuntimeException(e);
}
}
private static Future<UpwardSolution> futureUpwardSolution(final MapData allNodes, final Node startNode, final ExecutorService es) {
return es.submit(new Callable<UpwardSolution>() {
@Override
public UpwardSolution call() throws Exception {
return calculateUpwardSolution(allNodes, startNode);
}
});
}
private static Future<DownwardSolution> futureDownwardSolution(final MapData allNodes, final Node endNode, final ExecutorService es) {
return es.submit(new Callable<DownwardSolution>() {
@Override
public DownwardSolution call() throws Exception {
return calculateDownwardSolution(allNodes, endNode);
}
});
}*/
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
return contractedGraphDijkstra(allNodes, ColocatedNodeSet.singleton(startNode), ColocatedNodeSet.singleton(endNode));
}
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, ColocatedNodeSet startNode, ColocatedNodeSet endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode); | UpwardSolution upwardSolution = calculateUpwardSolution(startNode); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/ContractedDijkstra.java | // Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class DownwardSolution extends PartialSolution {
// public DownwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public DownwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
//
// Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class UpwardSolution extends PartialSolution {
// public UpwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public UpwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
| import java.nio.IntBuffer;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import uk.me.mjt.ch.PartialSolution.DownwardSolution;
import uk.me.mjt.ch.PartialSolution.UpwardSolution; |
package uk.me.mjt.ch;
public class ContractedDijkstra {
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
throw new UnsupportedOperationException("Temporarily broken");
}
/*public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
Future<UpwardSolution> fUpwardSolution = futureUpwardSolution(allNodes, startNode, es);
Future<DownwardSolution> fDownwardSolution = futureDownwardSolution(allNodes, endNode, es);
return mergeUpwardAndDownwardSolutions(allNodes, getFutureQuietly(fUpwardSolution), getFutureQuietly(fDownwardSolution));
}
private static <E> E getFutureQuietly(Future<E> f) {
try {
return f.get();
} catch (ExecutionException|InterruptedException e) {
throw new RuntimeException(e);
}
}
private static Future<UpwardSolution> futureUpwardSolution(final MapData allNodes, final Node startNode, final ExecutorService es) {
return es.submit(new Callable<UpwardSolution>() {
@Override
public UpwardSolution call() throws Exception {
return calculateUpwardSolution(allNodes, startNode);
}
});
}
private static Future<DownwardSolution> futureDownwardSolution(final MapData allNodes, final Node endNode, final ExecutorService es) {
return es.submit(new Callable<DownwardSolution>() {
@Override
public DownwardSolution call() throws Exception {
return calculateDownwardSolution(allNodes, endNode);
}
});
}*/
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
return contractedGraphDijkstra(allNodes, ColocatedNodeSet.singleton(startNode), ColocatedNodeSet.singleton(endNode));
}
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, ColocatedNodeSet startNode, ColocatedNodeSet endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
UpwardSolution upwardSolution = calculateUpwardSolution(startNode); | // Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class DownwardSolution extends PartialSolution {
// public DownwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public DownwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
//
// Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class UpwardSolution extends PartialSolution {
// public UpwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public UpwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
// Path: src/main/java/uk/me/mjt/ch/ContractedDijkstra.java
import java.nio.IntBuffer;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import uk.me.mjt.ch.PartialSolution.DownwardSolution;
import uk.me.mjt.ch.PartialSolution.UpwardSolution;
package uk.me.mjt.ch;
public class ContractedDijkstra {
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
throw new UnsupportedOperationException("Temporarily broken");
}
/*public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode, ExecutorService es) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
Future<UpwardSolution> fUpwardSolution = futureUpwardSolution(allNodes, startNode, es);
Future<DownwardSolution> fDownwardSolution = futureDownwardSolution(allNodes, endNode, es);
return mergeUpwardAndDownwardSolutions(allNodes, getFutureQuietly(fUpwardSolution), getFutureQuietly(fDownwardSolution));
}
private static <E> E getFutureQuietly(Future<E> f) {
try {
return f.get();
} catch (ExecutionException|InterruptedException e) {
throw new RuntimeException(e);
}
}
private static Future<UpwardSolution> futureUpwardSolution(final MapData allNodes, final Node startNode, final ExecutorService es) {
return es.submit(new Callable<UpwardSolution>() {
@Override
public UpwardSolution call() throws Exception {
return calculateUpwardSolution(allNodes, startNode);
}
});
}
private static Future<DownwardSolution> futureDownwardSolution(final MapData allNodes, final Node endNode, final ExecutorService es) {
return es.submit(new Callable<DownwardSolution>() {
@Override
public DownwardSolution call() throws Exception {
return calculateDownwardSolution(allNodes, endNode);
}
});
}*/
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, Node startNode, Node endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
return contractedGraphDijkstra(allNodes, ColocatedNodeSet.singleton(startNode), ColocatedNodeSet.singleton(endNode));
}
public static DijkstraSolution contractedGraphDijkstra(MapData allNodes, ColocatedNodeSet startNode, ColocatedNodeSet endNode) {
Preconditions.checkNoneNull(allNodes, startNode, endNode);
UpwardSolution upwardSolution = calculateUpwardSolution(startNode); | DownwardSolution downwardSolution = calculateDownwardSolution(endNode); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/cache/UpAndDownPair.java | // Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class DownwardSolution extends PartialSolution {
// public DownwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public DownwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
//
// Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class UpwardSolution extends PartialSolution {
// public UpwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public UpwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
| import uk.me.mjt.ch.PartialSolution.DownwardSolution;
import uk.me.mjt.ch.PartialSolution.UpwardSolution; |
package uk.me.mjt.ch.cache;
public class UpAndDownPair {
public final UpwardSolution up; | // Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class DownwardSolution extends PartialSolution {
// public DownwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public DownwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
//
// Path: src/main/java/uk/me/mjt/ch/PartialSolution.java
// public static class UpwardSolution extends PartialSolution {
// public UpwardSolution(List<DijkstraSolution> ds) {
// super(ds);
// }
// public UpwardSolution(ByteBuffer bb) {
// super(bb);
// }
// }
// Path: src/main/java/uk/me/mjt/ch/cache/UpAndDownPair.java
import uk.me.mjt.ch.PartialSolution.DownwardSolution;
import uk.me.mjt.ch.PartialSolution.UpwardSolution;
package uk.me.mjt.ch.cache;
public class UpAndDownPair {
public final UpwardSolution up; | public final DownwardSolution down; |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/profile/ArrayTimeProfile.java | // Path: src/main/java/uk/me/mjt/ch/Preconditions.java
// public class Preconditions {
// public static void checkNoneNull(Object... args) {
// for (int i=0 ; i<args.length ; i++) {
// if (args[i] == null) {
// throw new IllegalArgumentException("Argument index " + i + " was null?");
// }
// }
// }
//
// public static void require(boolean... args) {
// for (int i=0 ; i<args.length ; i++) {
// if (args[i] == false) {
// throw new IllegalArgumentException("Argument index " + i + " was false?");
// }
// }
// }
//
// }
| import java.util.Arrays;
import uk.me.mjt.ch.Preconditions; | if (toCheck[i] < 0)
throw new IllegalArgumentException("Invalid array - negative");
int delta = toCheck[i]-lastVal;
if (delta < -SEGMENT_WIDTH_MS) {
throw new IllegalArgumentException("Invalid array - profile to steep");
}
}
}
@Override
public int transitTimeAt(int milliseconds) {
if (milliseconds < SEGMENT_MIDPOINT_MS) {
return transitDurationMs[0];
} else if (milliseconds > SEGMENT_WIDTH_MS*(ARRAY_LENGTH_SEGMENTS-1)) {
return transitDurationMs[ARRAY_LENGTH_SEGMENTS-1];
}
int firstBlock = (milliseconds-SEGMENT_MIDPOINT_MS)/SEGMENT_WIDTH_MS;
int remainder = (milliseconds-SEGMENT_MIDPOINT_MS)%SEGMENT_WIDTH_MS;
int firstTransitDuration = transitDurationMs[firstBlock];
int secondTransitDuration = transitDurationMs[firstBlock+1];
long numerator = secondTransitDuration*(long)remainder + firstTransitDuration*(long)(SEGMENT_WIDTH_MS-remainder);
return (int)(numerator/SEGMENT_WIDTH_MS);
}
public ArrayTimeProfile followedBy(ArrayTimeProfile after) { | // Path: src/main/java/uk/me/mjt/ch/Preconditions.java
// public class Preconditions {
// public static void checkNoneNull(Object... args) {
// for (int i=0 ; i<args.length ; i++) {
// if (args[i] == null) {
// throw new IllegalArgumentException("Argument index " + i + " was null?");
// }
// }
// }
//
// public static void require(boolean... args) {
// for (int i=0 ; i<args.length ; i++) {
// if (args[i] == false) {
// throw new IllegalArgumentException("Argument index " + i + " was false?");
// }
// }
// }
//
// }
// Path: src/main/java/uk/me/mjt/ch/profile/ArrayTimeProfile.java
import java.util.Arrays;
import uk.me.mjt.ch.Preconditions;
if (toCheck[i] < 0)
throw new IllegalArgumentException("Invalid array - negative");
int delta = toCheck[i]-lastVal;
if (delta < -SEGMENT_WIDTH_MS) {
throw new IllegalArgumentException("Invalid array - profile to steep");
}
}
}
@Override
public int transitTimeAt(int milliseconds) {
if (milliseconds < SEGMENT_MIDPOINT_MS) {
return transitDurationMs[0];
} else if (milliseconds > SEGMENT_WIDTH_MS*(ARRAY_LENGTH_SEGMENTS-1)) {
return transitDurationMs[ARRAY_LENGTH_SEGMENTS-1];
}
int firstBlock = (milliseconds-SEGMENT_MIDPOINT_MS)/SEGMENT_WIDTH_MS;
int remainder = (milliseconds-SEGMENT_MIDPOINT_MS)%SEGMENT_WIDTH_MS;
int firstTransitDuration = transitDurationMs[firstBlock];
int secondTransitDuration = transitDurationMs[firstBlock+1];
long numerator = secondTransitDuration*(long)remainder + firstTransitDuration*(long)(SEGMENT_WIDTH_MS-remainder);
return (int)(numerator/SEGMENT_WIDTH_MS);
}
public ArrayTimeProfile followedBy(ArrayTimeProfile after) { | Preconditions.checkNoneNull(after); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/MapData.java | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/MonitoredProcess.java
// public enum MonitoredProcess {
// LOAD_NODES, LOAD_WAYS, INDEX_MAP_DATA, VALIDATE_DATA
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/StatusMonitor.java
// public interface StatusMonitor {
//
// public void updateStatus(MonitoredProcess process, long completed, long total);
//
// }
| import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
import uk.me.mjt.ch.status.MonitoredProcess;
import uk.me.mjt.ch.status.StatusMonitor; |
package uk.me.mjt.ch;
public class MapData {
private final HashMap<Long,Node> nodesById;
private final Set<TurnRestriction> turnRestrictions;
private final AtomicLong maxEdgeId = new AtomicLong();
private final Multimap<Long,Node> nodesBySourceDataNodeId = new Multimap<>();
public MapData(Collection<Node> nodes) { | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/MonitoredProcess.java
// public enum MonitoredProcess {
// LOAD_NODES, LOAD_WAYS, INDEX_MAP_DATA, VALIDATE_DATA
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/StatusMonitor.java
// public interface StatusMonitor {
//
// public void updateStatus(MonitoredProcess process, long completed, long total);
//
// }
// Path: src/main/java/uk/me/mjt/ch/MapData.java
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
import uk.me.mjt.ch.status.MonitoredProcess;
import uk.me.mjt.ch.status.StatusMonitor;
package uk.me.mjt.ch;
public class MapData {
private final HashMap<Long,Node> nodesById;
private final Set<TurnRestriction> turnRestrictions;
private final AtomicLong maxEdgeId = new AtomicLong();
private final Multimap<Long,Node> nodesBySourceDataNodeId = new Multimap<>();
public MapData(Collection<Node> nodes) { | this(indexNodesById(nodes), new HashSet(), new DiscardingStatusMonitor()); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/MapData.java | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/MonitoredProcess.java
// public enum MonitoredProcess {
// LOAD_NODES, LOAD_WAYS, INDEX_MAP_DATA, VALIDATE_DATA
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/StatusMonitor.java
// public interface StatusMonitor {
//
// public void updateStatus(MonitoredProcess process, long completed, long total);
//
// }
| import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
import uk.me.mjt.ch.status.MonitoredProcess;
import uk.me.mjt.ch.status.StatusMonitor; |
package uk.me.mjt.ch;
public class MapData {
private final HashMap<Long,Node> nodesById;
private final Set<TurnRestriction> turnRestrictions;
private final AtomicLong maxEdgeId = new AtomicLong();
private final Multimap<Long,Node> nodesBySourceDataNodeId = new Multimap<>();
public MapData(Collection<Node> nodes) {
this(indexNodesById(nodes), new HashSet(), new DiscardingStatusMonitor());
}
public MapData(HashMap<Long,Node> nodesById) {
this(nodesById, new HashSet(), new DiscardingStatusMonitor());
}
| // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/MonitoredProcess.java
// public enum MonitoredProcess {
// LOAD_NODES, LOAD_WAYS, INDEX_MAP_DATA, VALIDATE_DATA
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/StatusMonitor.java
// public interface StatusMonitor {
//
// public void updateStatus(MonitoredProcess process, long completed, long total);
//
// }
// Path: src/main/java/uk/me/mjt/ch/MapData.java
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
import uk.me.mjt.ch.status.MonitoredProcess;
import uk.me.mjt.ch.status.StatusMonitor;
package uk.me.mjt.ch;
public class MapData {
private final HashMap<Long,Node> nodesById;
private final Set<TurnRestriction> turnRestrictions;
private final AtomicLong maxEdgeId = new AtomicLong();
private final Multimap<Long,Node> nodesBySourceDataNodeId = new Multimap<>();
public MapData(Collection<Node> nodes) {
this(indexNodesById(nodes), new HashSet(), new DiscardingStatusMonitor());
}
public MapData(HashMap<Long,Node> nodesById) {
this(nodesById, new HashSet(), new DiscardingStatusMonitor());
}
| public MapData(HashMap<Long,Node> nodesById, Set<TurnRestriction> turnRestrictions, StatusMonitor monitor) { |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/MapData.java | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/MonitoredProcess.java
// public enum MonitoredProcess {
// LOAD_NODES, LOAD_WAYS, INDEX_MAP_DATA, VALIDATE_DATA
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/StatusMonitor.java
// public interface StatusMonitor {
//
// public void updateStatus(MonitoredProcess process, long completed, long total);
//
// }
| import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
import uk.me.mjt.ch.status.MonitoredProcess;
import uk.me.mjt.ch.status.StatusMonitor; |
package uk.me.mjt.ch;
public class MapData {
private final HashMap<Long,Node> nodesById;
private final Set<TurnRestriction> turnRestrictions;
private final AtomicLong maxEdgeId = new AtomicLong();
private final Multimap<Long,Node> nodesBySourceDataNodeId = new Multimap<>();
public MapData(Collection<Node> nodes) {
this(indexNodesById(nodes), new HashSet(), new DiscardingStatusMonitor());
}
public MapData(HashMap<Long,Node> nodesById) {
this(nodesById, new HashSet(), new DiscardingStatusMonitor());
}
public MapData(HashMap<Long,Node> nodesById, Set<TurnRestriction> turnRestrictions, StatusMonitor monitor) {
Preconditions.checkNoneNull(nodesById, turnRestrictions);
this.nodesById = nodesById;
this.turnRestrictions = turnRestrictions;
generateIndexAndAggregates(monitor);
}
private void generateIndexAndAggregates(StatusMonitor monitor) {
long nodesCheckedSoFar = 0; | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/MonitoredProcess.java
// public enum MonitoredProcess {
// LOAD_NODES, LOAD_WAYS, INDEX_MAP_DATA, VALIDATE_DATA
// }
//
// Path: src/main/java/uk/me/mjt/ch/status/StatusMonitor.java
// public interface StatusMonitor {
//
// public void updateStatus(MonitoredProcess process, long completed, long total);
//
// }
// Path: src/main/java/uk/me/mjt/ch/MapData.java
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
import uk.me.mjt.ch.status.MonitoredProcess;
import uk.me.mjt.ch.status.StatusMonitor;
package uk.me.mjt.ch;
public class MapData {
private final HashMap<Long,Node> nodesById;
private final Set<TurnRestriction> turnRestrictions;
private final AtomicLong maxEdgeId = new AtomicLong();
private final Multimap<Long,Node> nodesBySourceDataNodeId = new Multimap<>();
public MapData(Collection<Node> nodes) {
this(indexNodesById(nodes), new HashSet(), new DiscardingStatusMonitor());
}
public MapData(HashMap<Long,Node> nodesById) {
this(nodesById, new HashSet(), new DiscardingStatusMonitor());
}
public MapData(HashMap<Long,Node> nodesById, Set<TurnRestriction> turnRestrictions, StatusMonitor monitor) {
Preconditions.checkNoneNull(nodesById, turnRestrictions);
this.nodesById = nodesById;
this.turnRestrictions = turnRestrictions;
generateIndexAndAggregates(monitor);
}
private void generateIndexAndAggregates(StatusMonitor monitor) {
long nodesCheckedSoFar = 0; | monitor.updateStatus(MonitoredProcess.INDEX_MAP_DATA, nodesCheckedSoFar, nodesById.size()); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/AdjustGraphForRestrictions.java | // Path: src/main/java/uk/me/mjt/ch/TurnRestriction.java
// public static enum TurnRestrictionType { NOT_ALLOWED, ONLY_ALLOWED }
| import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.TurnRestriction.TurnRestrictionType; |
return new NodeAndState(toNode, turnRestrictionsAfter, aos, gs, us, toEdge);
}
private HashSet<TurnRestriction> getUpdatedTurnRestrictionsIfLegal(DirectedEdge fromEdge, NodeAndState fromNode, DirectedEdge toEdge, Multimap<Long,TurnRestriction> turnRestrictionsByStartEdge, DirectedEdge priorFromEdge) {
Preconditions.checkNoneNull(fromNode,toEdge,turnRestrictionsByStartEdge);
if (isUturnEdge(toEdge) || isPublicToPrivateEdge(toEdge)) { // U-turns don't deactivate turn restrictions.
return fromNode.activeTurnRestrictions;
}
HashSet<TurnRestriction> turnRestrictionsAfter = new HashSet();
turnRestrictionsAfter.addAll(turnRestrictionsByStartEdge.get(toEdge.edgeId));
if (fromEdge == null) { // Start node.
return turnRestrictionsAfter;
}
if (priorFromEdge == null)
priorFromEdge = fromEdge;
for (TurnRestriction tr : fromNode.activeTurnRestrictions) {
List<Long> edgeIds = tr.directedEdgeIds;
int fromEdgeIdx = edgeIds.indexOf(priorFromEdge.edgeId);
int toEdgeIdx = edgeIds.indexOf(toEdge.edgeId);
boolean endOfRestriction = (fromEdgeIdx==edgeIds.size()-2);
boolean restrictionCoversMove = (fromEdgeIdx+1==toEdgeIdx);
if (endOfRestriction) { | // Path: src/main/java/uk/me/mjt/ch/TurnRestriction.java
// public static enum TurnRestrictionType { NOT_ALLOWED, ONLY_ALLOWED }
// Path: src/main/java/uk/me/mjt/ch/AdjustGraphForRestrictions.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import uk.me.mjt.ch.TurnRestriction.TurnRestrictionType;
return new NodeAndState(toNode, turnRestrictionsAfter, aos, gs, us, toEdge);
}
private HashSet<TurnRestriction> getUpdatedTurnRestrictionsIfLegal(DirectedEdge fromEdge, NodeAndState fromNode, DirectedEdge toEdge, Multimap<Long,TurnRestriction> turnRestrictionsByStartEdge, DirectedEdge priorFromEdge) {
Preconditions.checkNoneNull(fromNode,toEdge,turnRestrictionsByStartEdge);
if (isUturnEdge(toEdge) || isPublicToPrivateEdge(toEdge)) { // U-turns don't deactivate turn restrictions.
return fromNode.activeTurnRestrictions;
}
HashSet<TurnRestriction> turnRestrictionsAfter = new HashSet();
turnRestrictionsAfter.addAll(turnRestrictionsByStartEdge.get(toEdge.edgeId));
if (fromEdge == null) { // Start node.
return turnRestrictionsAfter;
}
if (priorFromEdge == null)
priorFromEdge = fromEdge;
for (TurnRestriction tr : fromNode.activeTurnRestrictions) {
List<Long> edgeIds = tr.directedEdgeIds;
int fromEdgeIdx = edgeIds.indexOf(priorFromEdge.edgeId);
int toEdgeIdx = edgeIds.indexOf(toEdge.edgeId);
boolean endOfRestriction = (fromEdgeIdx==edgeIds.size()-2);
boolean restrictionCoversMove = (fromEdgeIdx+1==toEdgeIdx);
if (endOfRestriction) { | if (tr.type == TurnRestrictionType.ONLY_ALLOWED && !restrictionCoversMove) { |
michaeltandy/contraction-hierarchies | src/test/java/uk/me/mjt/ch/MakeTestData.java | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
| import java.util.*;
import uk.me.mjt.ch.status.DiscardingStatusMonitor; | /**
* No right turn 3->2->5
* <pre>
* 1 4
* | |
* 2---5
* | |
* 3 6
* </pre>
*/
public static MapData makeTurnRestrictedH() {
HashMap<Long,Node> nodes = new HashMap();
for (long i=1 ; i<=6 ; i++) {
nodes.put(i, new Node(i, 52f, 0f, Barrier.FALSE));
}
makeBidirectionalEdgesAndAddToNodes(nodes.get(1L), nodes.get(2L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(2L), nodes.get(3L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(4L), nodes.get(5L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(5L), nodes.get(6L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(2L), nodes.get(5L));
List<Long> noRight = new ArrayList();
noRight.add(3000002L);
noRight.add(2000005L);
TurnRestriction tr = new TurnRestriction(12345, TurnRestriction.TurnRestrictionType.NOT_ALLOWED, noRight);
Node.sortNeighborListsAll(nodes.values()); | // Path: src/main/java/uk/me/mjt/ch/status/DiscardingStatusMonitor.java
// public class DiscardingStatusMonitor implements StatusMonitor {
// @Override
// public void updateStatus(MonitoredProcess process, long completed, long total) { }
// }
// Path: src/test/java/uk/me/mjt/ch/MakeTestData.java
import java.util.*;
import uk.me.mjt.ch.status.DiscardingStatusMonitor;
/**
* No right turn 3->2->5
* <pre>
* 1 4
* | |
* 2---5
* | |
* 3 6
* </pre>
*/
public static MapData makeTurnRestrictedH() {
HashMap<Long,Node> nodes = new HashMap();
for (long i=1 ; i<=6 ; i++) {
nodes.put(i, new Node(i, 52f, 0f, Barrier.FALSE));
}
makeBidirectionalEdgesAndAddToNodes(nodes.get(1L), nodes.get(2L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(2L), nodes.get(3L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(4L), nodes.get(5L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(5L), nodes.get(6L));
makeBidirectionalEdgesAndAddToNodes(nodes.get(2L), nodes.get(5L));
List<Long> noRight = new ArrayList();
noRight.add(3000002L);
noRight.add(2000005L);
TurnRestriction tr = new TurnRestriction(12345, TurnRestriction.TurnRestrictionType.NOT_ALLOWED, noRight);
Node.sortNeighborListsAll(nodes.values()); | return new MapData(nodes,Collections.singleton(tr), new DiscardingStatusMonitor()); |
michaeltandy/contraction-hierarchies | src/main/java/uk/me/mjt/ch/GraphContractor.java | // Path: src/main/java/uk/me/mjt/ch/Dijkstra.java
// public enum Direction{FORWARDS,BACKWARDS};
| import uk.me.mjt.ch.Dijkstra.Direction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger; | DirectedEdge newShortcut = s.cloneWithEdgeId(allNodes.getEdgeIdCounter().incrementAndGet());
newShortcut.from.edgesFrom.add(newShortcut);
newShortcut.to.edgesTo.add(newShortcut);
}
n.contractionOrder = order;
}
public ArrayList<DirectedEdge> findShortcuts(Node n) {
findShortcutsCalls.incrementAndGet();
ArrayList<DirectedEdge> shortcuts = new ArrayList<DirectedEdge>();
HashSet<Node> destinationNodes = new HashSet<Node>();
int maxOutTime = 0;
for (DirectedEdge outgoing : n.edgesFrom) {
if (!outgoing.to.isContracted()) {
destinationNodes.add(outgoing.to);
if (outgoing.driveTimeMs > maxOutTime)
maxOutTime = outgoing.driveTimeMs;
}
}
for (DirectedEdge incoming : n.edgesTo) {
Node startNode = incoming.from;
if (startNode.isContracted())
continue;
List<DijkstraSolution> routed = Dijkstra.dijkstrasAlgorithm(
startNode,
new HashSet<>(destinationNodes),
incoming.driveTimeMs+maxOutTime, | // Path: src/main/java/uk/me/mjt/ch/Dijkstra.java
// public enum Direction{FORWARDS,BACKWARDS};
// Path: src/main/java/uk/me/mjt/ch/GraphContractor.java
import uk.me.mjt.ch.Dijkstra.Direction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
DirectedEdge newShortcut = s.cloneWithEdgeId(allNodes.getEdgeIdCounter().incrementAndGet());
newShortcut.from.edgesFrom.add(newShortcut);
newShortcut.to.edgesTo.add(newShortcut);
}
n.contractionOrder = order;
}
public ArrayList<DirectedEdge> findShortcuts(Node n) {
findShortcutsCalls.incrementAndGet();
ArrayList<DirectedEdge> shortcuts = new ArrayList<DirectedEdge>();
HashSet<Node> destinationNodes = new HashSet<Node>();
int maxOutTime = 0;
for (DirectedEdge outgoing : n.edgesFrom) {
if (!outgoing.to.isContracted()) {
destinationNodes.add(outgoing.to);
if (outgoing.driveTimeMs > maxOutTime)
maxOutTime = outgoing.driveTimeMs;
}
}
for (DirectedEdge incoming : n.edgesTo) {
Node startNode = incoming.from;
if (startNode.isContracted())
continue;
List<DijkstraSolution> routed = Dijkstra.dijkstrasAlgorithm(
startNode,
new HashSet<>(destinationNodes),
incoming.driveTimeMs+maxOutTime, | Direction.FORWARDS); |
sindremehus/subsonic | subsonic-main/src/test/java/net/sourceforge/subsonic/io/RangeOutputStreamTestCase.java | // Path: subsonic-main/src/main/java/net/sourceforge/subsonic/util/HttpRange.java
// public class HttpRange {
//
// private static final Pattern PATTERN = Pattern.compile("bytes=(\\d+)-(\\d*)");
// private final Long firstBytePos;
// private final Long lastBytePos;
//
// /**
// * Parses the given string as a HTTP header byte range. See chapter 14.36.1 in RFC 2068
// * for details.
// * <p/>
// * Only a subset of the allowed syntaxes are supported. Only ranges which specify first-byte-pos
// * are supported. The last-byte-pos is optional.
// *
// * @param range The range from the HTTP header, for instance "bytes=0-499" or "bytes=500-"
// * @return A range object (using inclusive values). If the last-byte-pos is not given, the end of
// * the returned range is {@code null}. The method returns <code>null</code> if the syntax
// * of the given range is not supported.
// */
// public static HttpRange valueOf(String range) {
// if (range == null) {
// return null;
// }
//
// Matcher matcher = PATTERN.matcher(range);
// if (matcher.matches()) {
// String firstString = matcher.group(1);
// String lastString = StringUtils.trimToNull(matcher.group(2));
//
// Long first = Long.parseLong(firstString);
// Long last = lastString == null ? null : Long.parseLong(lastString);
//
// if (last != null && first > last) {
// return null;
// }
// return new HttpRange(first, last);
// }
// return null;
// }
//
// public HttpRange(long firstBytePos, Long lastBytePos) {
// this.firstBytePos = firstBytePos;
// this.lastBytePos = lastBytePos;
// }
//
// /**
// * @return The first byte position (inclusive) in the range. Never {@code null}.
// */
// public Long getFirstBytePos() {
// return firstBytePos;
// }
//
// /**
// * @return The last byte position (inclusive) in the range. Can be {@code null}.
// */
// public Long getLastBytePos() {
// return lastBytePos;
// }
//
// /**
// * @return Whether this is a closed range (both first and last byte position specified).
// */
// public boolean isClosed() {
// return firstBytePos != null && lastBytePos != null;
// }
//
// /**
// * @return The size in bytes if the range is closed, -1 otherwise.
// */
// public long size() {
// return isClosed() ? (lastBytePos - firstBytePos + 1) : -1;
// }
//
// /**
// * @return Returns whether the given byte position is within this range.
// */
// public boolean contains(long pos) {
// if (pos < firstBytePos) {
// return false;
// }
// return lastBytePos == null || pos <= lastBytePos;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append(firstBytePos).append('-');
// if (lastBytePos != null) {
// builder.append(lastBytePos);
// }
// return builder.toString();
// }
// }
| import junit.framework.TestCase;
import net.sourceforge.subsonic.util.HttpRange;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; | doTestWrap(0, 99, 100, 100);
doTestWrap(10, 99, 100, 1);
doTestWrap(10, 99, 100, 10);
doTestWrap(10, 99, 100, 13);
doTestWrap(10, 99, 100, 70);
doTestWrap(10, 99, 100, 100);
doTestWrap(66, 66, 100, 1);
doTestWrap(66, 66, 100, 2);
doTestWrap(10, 20, 100, 1);
doTestWrap(10, 20, 100, 10);
doTestWrap(10, 20, 100, 13);
doTestWrap(10, 20, 100, 70);
doTestWrap(10, 20, 100, 100);
for (int start = 0; start < 10; start++) {
for (int end = start; end < 10; end++) {
for (int bufferSize = 1; bufferSize < 10; bufferSize++) {
doTestWrap(start, end, 10, bufferSize);
doTestWrap(start, null, 10, bufferSize);
}
}
}
}
private void doTestWrap(int first, Integer last, int sourceSize, int bufferSize) throws Exception {
byte[] source = createSource(sourceSize);
ByteArrayOutputStream out = new ByteArrayOutputStream(); | // Path: subsonic-main/src/main/java/net/sourceforge/subsonic/util/HttpRange.java
// public class HttpRange {
//
// private static final Pattern PATTERN = Pattern.compile("bytes=(\\d+)-(\\d*)");
// private final Long firstBytePos;
// private final Long lastBytePos;
//
// /**
// * Parses the given string as a HTTP header byte range. See chapter 14.36.1 in RFC 2068
// * for details.
// * <p/>
// * Only a subset of the allowed syntaxes are supported. Only ranges which specify first-byte-pos
// * are supported. The last-byte-pos is optional.
// *
// * @param range The range from the HTTP header, for instance "bytes=0-499" or "bytes=500-"
// * @return A range object (using inclusive values). If the last-byte-pos is not given, the end of
// * the returned range is {@code null}. The method returns <code>null</code> if the syntax
// * of the given range is not supported.
// */
// public static HttpRange valueOf(String range) {
// if (range == null) {
// return null;
// }
//
// Matcher matcher = PATTERN.matcher(range);
// if (matcher.matches()) {
// String firstString = matcher.group(1);
// String lastString = StringUtils.trimToNull(matcher.group(2));
//
// Long first = Long.parseLong(firstString);
// Long last = lastString == null ? null : Long.parseLong(lastString);
//
// if (last != null && first > last) {
// return null;
// }
// return new HttpRange(first, last);
// }
// return null;
// }
//
// public HttpRange(long firstBytePos, Long lastBytePos) {
// this.firstBytePos = firstBytePos;
// this.lastBytePos = lastBytePos;
// }
//
// /**
// * @return The first byte position (inclusive) in the range. Never {@code null}.
// */
// public Long getFirstBytePos() {
// return firstBytePos;
// }
//
// /**
// * @return The last byte position (inclusive) in the range. Can be {@code null}.
// */
// public Long getLastBytePos() {
// return lastBytePos;
// }
//
// /**
// * @return Whether this is a closed range (both first and last byte position specified).
// */
// public boolean isClosed() {
// return firstBytePos != null && lastBytePos != null;
// }
//
// /**
// * @return The size in bytes if the range is closed, -1 otherwise.
// */
// public long size() {
// return isClosed() ? (lastBytePos - firstBytePos + 1) : -1;
// }
//
// /**
// * @return Returns whether the given byte position is within this range.
// */
// public boolean contains(long pos) {
// if (pos < firstBytePos) {
// return false;
// }
// return lastBytePos == null || pos <= lastBytePos;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append(firstBytePos).append('-');
// if (lastBytePos != null) {
// builder.append(lastBytePos);
// }
// return builder.toString();
// }
// }
// Path: subsonic-main/src/test/java/net/sourceforge/subsonic/io/RangeOutputStreamTestCase.java
import junit.framework.TestCase;
import net.sourceforge.subsonic.util.HttpRange;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
doTestWrap(0, 99, 100, 100);
doTestWrap(10, 99, 100, 1);
doTestWrap(10, 99, 100, 10);
doTestWrap(10, 99, 100, 13);
doTestWrap(10, 99, 100, 70);
doTestWrap(10, 99, 100, 100);
doTestWrap(66, 66, 100, 1);
doTestWrap(66, 66, 100, 2);
doTestWrap(10, 20, 100, 1);
doTestWrap(10, 20, 100, 10);
doTestWrap(10, 20, 100, 13);
doTestWrap(10, 20, 100, 70);
doTestWrap(10, 20, 100, 100);
for (int start = 0; start < 10; start++) {
for (int end = start; end < 10; end++) {
for (int bufferSize = 1; bufferSize < 10; bufferSize++) {
doTestWrap(start, end, 10, bufferSize);
doTestWrap(start, null, 10, bufferSize);
}
}
}
}
private void doTestWrap(int first, Integer last, int sourceSize, int bufferSize) throws Exception {
byte[] source = createSource(sourceSize);
ByteArrayOutputStream out = new ByteArrayOutputStream(); | OutputStream rangeOut = RangeOutputStream.wrap(out, new HttpRange((long) first, last == null ? null : last.longValue())); |
sindremehus/subsonic | subsonic-main/src/main/java/net/sourceforge/subsonic/dao/ShareDao.java | // Path: subsonic-main/src/main/java/net/sourceforge/subsonic/domain/Share.java
// public class Share {
//
// private int id;
// private String name;
// private String description;
// private String username;
// private Date created;
// private Date expires;
// private Date lastVisited;
// private int visitCount;
//
// public Share() {
// }
//
// public Share(int id, String name, String description, String username, Date created,
// Date expires, Date lastVisited, int visitCount) {
// this.id = id;
// this.name = name;
// this.description = description;
// this.username = username;
// this.created = created;
// this.expires = expires;
// this.lastVisited = lastVisited;
// this.visitCount = visitCount;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public Date getCreated() {
// return created;
// }
//
// public void setCreated(Date created) {
// this.created = created;
// }
//
// public Date getExpires() {
// return expires;
// }
//
// public void setExpires(Date expires) {
// this.expires = expires;
// }
//
// public Date getLastVisited() {
// return lastVisited;
// }
//
// public void setLastVisited(Date lastVisited) {
// this.lastVisited = lastVisited;
// }
//
// public int getVisitCount() {
// return visitCount;
// }
//
// public void setVisitCount(int visitCount) {
// this.visitCount = visitCount;
// }
// }
| import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import net.sourceforge.subsonic.domain.MusicFolder;
import net.sourceforge.subsonic.domain.Share; | /*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package net.sourceforge.subsonic.dao;
/**
* Provides database services for shared media.
*
* @author Sindre Mehus
*/
public class ShareDao extends AbstractDao {
private static final String COLUMNS = "id, name, description, username, created, expires, last_visited, visit_count";
private ShareRowMapper shareRowMapper = new ShareRowMapper();
private ShareFileRowMapper shareFileRowMapper = new ShareFileRowMapper();
/**
* Creates a new share.
*
* @param share The share to create. The ID of the share will be set by this method.
*/ | // Path: subsonic-main/src/main/java/net/sourceforge/subsonic/domain/Share.java
// public class Share {
//
// private int id;
// private String name;
// private String description;
// private String username;
// private Date created;
// private Date expires;
// private Date lastVisited;
// private int visitCount;
//
// public Share() {
// }
//
// public Share(int id, String name, String description, String username, Date created,
// Date expires, Date lastVisited, int visitCount) {
// this.id = id;
// this.name = name;
// this.description = description;
// this.username = username;
// this.created = created;
// this.expires = expires;
// this.lastVisited = lastVisited;
// this.visitCount = visitCount;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public Date getCreated() {
// return created;
// }
//
// public void setCreated(Date created) {
// this.created = created;
// }
//
// public Date getExpires() {
// return expires;
// }
//
// public void setExpires(Date expires) {
// this.expires = expires;
// }
//
// public Date getLastVisited() {
// return lastVisited;
// }
//
// public void setLastVisited(Date lastVisited) {
// this.lastVisited = lastVisited;
// }
//
// public int getVisitCount() {
// return visitCount;
// }
//
// public void setVisitCount(int visitCount) {
// this.visitCount = visitCount;
// }
// }
// Path: subsonic-main/src/main/java/net/sourceforge/subsonic/dao/ShareDao.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import net.sourceforge.subsonic.domain.MusicFolder;
import net.sourceforge.subsonic.domain.Share;
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package net.sourceforge.subsonic.dao;
/**
* Provides database services for shared media.
*
* @author Sindre Mehus
*/
public class ShareDao extends AbstractDao {
private static final String COLUMNS = "id, name, description, username, created, expires, last_visited, visit_count";
private ShareRowMapper shareRowMapper = new ShareRowMapper();
private ShareFileRowMapper shareFileRowMapper = new ShareFileRowMapper();
/**
* Creates a new share.
*
* @param share The share to create. The ID of the share will be set by this method.
*/ | public synchronized void createShare(Share share) { |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/ | public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password) |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>( | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>( | new GrantTypeParam("password"), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("password"), | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("password"), | new UsernameParam(username), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("password"),
new UsernameParam(username), | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("password"),
new UsernameParam(username), | new PasswordParam(password)), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("password"),
new UsernameParam(username),
new PasswordParam(password)), | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/PasswordParam.java
// public final class PasswordParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public PasswordParam(CharSequence password)
// {
// super("password", password);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/UsernameParam.java
// public final class UsernameParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public UsernameParam(CharSequence username)
// {
// super("username", username);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.PasswordParam;
import org.dmfs.oauth2.client.http.requests.parameters.UsernameParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Resource Owner Password Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ResourceOwnerPasswordTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ResourceOwnerPasswordTokenRequest} with the given scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param username
* The user name of the resource owner.
* @param password
* The password of the resource owner.
*/
public ResourceOwnerPasswordTokenRequest(OAuth2Scope scope, CharSequence username, CharSequence password)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("password"),
new UsernameParam(username),
new PasswordParam(password)), | new PresentValues<>(new OptionalScopeParam(scope))))); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/tokens/JsonAccessTokenTest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.StringScope;
import org.hamcrest.Matchers;
import org.json.JSONObject;
import org.junit.Test;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.dmfs.jems.mockito.doubles.TestDoubles.dummy;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
/**
* @author Marten Gajda
*/
public class JsonAccessTokenTest
{
@Test
public void testNoScope() throws Exception
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/tokens/JsonAccessTokenTest.java
import org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.StringScope;
import org.hamcrest.Matchers;
import org.json.JSONObject;
import org.junit.Test;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.dmfs.jems.mockito.doubles.TestDoubles.dummy;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
/**
* @author Marten Gajda
*/
public class JsonAccessTokenTest
{
@Test
public void testNoScope() throws Exception
{ | OAuth2Scope dummyScope = dummy(OAuth2Scope.class); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/tokens/JsonAccessTokenTest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.StringScope;
import org.hamcrest.Matchers;
import org.json.JSONObject;
import org.junit.Test;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.dmfs.jems.mockito.doubles.TestDoubles.dummy;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
/**
* @author Marten Gajda
*/
public class JsonAccessTokenTest
{
@Test
public void testNoScope() throws Exception
{
OAuth2Scope dummyScope = dummy(OAuth2Scope.class);
JSONObject jsonObject = new JSONObject();
assertThat(new JsonAccessToken(jsonObject, dummyScope).scope(), sameInstance(dummyScope));
}
@Test
public void testScope() throws Exception
{
OAuth2Scope dummyScope = dummy(OAuth2Scope.class);
// note: we don't use a mock here, because there are multiple ways to get a String value and we don't want to make assumptions on that
JSONObject jsonObject = new JSONObject("{\"scope\": \"scope1 scope2\"}");
| // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/tokens/JsonAccessTokenTest.java
import org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.StringScope;
import org.hamcrest.Matchers;
import org.json.JSONObject;
import org.junit.Test;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.dmfs.jems.mockito.doubles.TestDoubles.dummy;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
/**
* @author Marten Gajda
*/
public class JsonAccessTokenTest
{
@Test
public void testNoScope() throws Exception
{
OAuth2Scope dummyScope = dummy(OAuth2Scope.class);
JSONObject jsonObject = new JSONObject();
assertThat(new JsonAccessToken(jsonObject, dummyScope).scope(), sameInstance(dummyScope));
}
@Test
public void testScope() throws Exception
{
OAuth2Scope dummyScope = dummy(OAuth2Scope.class);
// note: we don't use a mock here, because there are multiple ways to get a String value and we don't want to make assumptions on that
JSONObject jsonObject = new JSONObject("{\"scope\": \"scope1 scope2\"}");
| assertThat(new JsonAccessToken(jsonObject, dummyScope).scope(), Matchers.<OAuth2Scope>is(new StringScope("scope1 scope2"))); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/OAuth2AuthorizationRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java
// public interface PkceCodeChallenge
// {
// /**
// * Returns a {@link Token} that identifies the method this code challenge uses.
// *
// * @return A {@link Token} containing the method name.
// */
// Token method();
//
// /**
// * Returns the value of the code challenge.
// *
// * @return
// */
// CharSequence challenge();
// }
| import org.dmfs.oauth2.client.pkce.PkceCodeChallenge;
import org.dmfs.rfc3986.Uri;
import java.net.URI; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* Represents an authorization request for an interactive grant type.
*
* @author Marten Gajda
*/
public interface OAuth2AuthorizationRequest
{
/**
* Creates a new {@link OAuth2AuthorizationRequest} using the given client id.
*
* @param clientId
* The client id of the client application that requests authorization.
*
* @return A new {@link OAuth2AuthorizationRequest} with the updated value.
*/
OAuth2AuthorizationRequest withClientId(String clientId);
/**
* Creates a new {@link OAuth2AuthorizationRequest} using the given redirect {@link URI}.
*
* @param redirectUri
* The redirect URI the server is expected to redirect the user agent to.
*
* @return A new {@link OAuth2AuthorizationRequest} with the updated value.
*/
OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri);
/**
* Creates a new {@link OAuth2AuthorizationRequest} using the given {@link PkceCodeChallenge}.
*
* @param codeChallenge
*
* @return A new {@link OAuth2AuthorizationRequest} with a code challenge.
*/ | // Path: src/main/java/org/dmfs/oauth2/client/pkce/PkceCodeChallenge.java
// public interface PkceCodeChallenge
// {
// /**
// * Returns a {@link Token} that identifies the method this code challenge uses.
// *
// * @return A {@link Token} containing the method name.
// */
// Token method();
//
// /**
// * Returns the value of the code challenge.
// *
// * @return
// */
// CharSequence challenge();
// }
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthorizationRequest.java
import org.dmfs.oauth2.client.pkce.PkceCodeChallenge;
import org.dmfs.rfc3986.Uri;
import java.net.URI;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* Represents an authorization request for an interactive grant type.
*
* @author Marten Gajda
*/
public interface OAuth2AuthorizationRequest
{
/**
* Creates a new {@link OAuth2AuthorizationRequest} using the given client id.
*
* @param clientId
* The client id of the client application that requests authorization.
*
* @return A new {@link OAuth2AuthorizationRequest} with the updated value.
*/
OAuth2AuthorizationRequest withClientId(String clientId);
/**
* Creates a new {@link OAuth2AuthorizationRequest} using the given redirect {@link URI}.
*
* @param redirectUri
* The redirect URI the server is expected to redirect the user agent to.
*
* @return A new {@link OAuth2AuthorizationRequest} with the updated value.
*/
OAuth2AuthorizationRequest withRedirectUri(Uri redirectUri);
/**
* Creates a new {@link OAuth2AuthorizationRequest} using the given {@link PkceCodeChallenge}.
*
* @param codeChallenge
*
* @return A new {@link OAuth2AuthorizationRequest} with a code challenge.
*/ | OAuth2AuthorizationRequest withCodeChallenge(PkceCodeChallenge codeChallenge); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/BasicOAuth2ClientCredentials.java | // Path: src/main/java/org/dmfs/oauth2/client/http/decorators/BasicAuthHeaderDecoration.java
// public final class BasicAuthHeaderDecoration implements Decoration<Headers>
// {
// // TODO: use a generic authorization header instead (once we have one)
// private final HeaderType<String> AUTHORIZATION_HEADER_TYPE = new BasicSingletonHeaderType<String>("Authorization", new PlainStringHeaderConverter());
//
// private final String mUsername;
// private final String mPassword;
//
//
// public BasicAuthHeaderDecoration(String username, String password)
// {
// if (username == null)
// {
// throw new IllegalArgumentException("username must not be null");
// }
// if (password == null)
// {
// throw new IllegalArgumentException("password must not be null");
// }
// mUsername = username;
// mPassword = password;
// }
//
//
// @Override
// public Headers decorated(Headers original)
// {
// String authHeaderValue = "Basic " + Base64.encodeBytes(usernameAndPasswordBytes());
// return new UpdatedHeaders(original, AUTHORIZATION_HEADER_TYPE.entity(authHeaderValue));
// }
//
//
// private byte[] usernameAndPasswordBytes()
// {
// try
// {
// return String.format("%s:%s", mUsername, mPassword).getBytes("UTF-8");
// }
// catch (UnsupportedEncodingException e)
// {
// throw new RuntimeException("Charset UTF-8 not supported by runtime!", e);
// }
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.decoration.HeaderDecorated;
import org.dmfs.oauth2.client.http.decorators.BasicAuthHeaderDecoration; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* Basic implementation of {@link OAuth2ClientCredentials}.
*
* @author Marten Gajda
*/
public final class BasicOAuth2ClientCredentials implements OAuth2ClientCredentials
{
private final String mClientId;
private final String mClientSecret;
public BasicOAuth2ClientCredentials(String clientId, String clientSecret)
{
mClientId = clientId;
mClientSecret = clientSecret;
}
@Override
public <T> HttpRequest<T> authenticatedRequest(HttpRequest<T> request)
{ | // Path: src/main/java/org/dmfs/oauth2/client/http/decorators/BasicAuthHeaderDecoration.java
// public final class BasicAuthHeaderDecoration implements Decoration<Headers>
// {
// // TODO: use a generic authorization header instead (once we have one)
// private final HeaderType<String> AUTHORIZATION_HEADER_TYPE = new BasicSingletonHeaderType<String>("Authorization", new PlainStringHeaderConverter());
//
// private final String mUsername;
// private final String mPassword;
//
//
// public BasicAuthHeaderDecoration(String username, String password)
// {
// if (username == null)
// {
// throw new IllegalArgumentException("username must not be null");
// }
// if (password == null)
// {
// throw new IllegalArgumentException("password must not be null");
// }
// mUsername = username;
// mPassword = password;
// }
//
//
// @Override
// public Headers decorated(Headers original)
// {
// String authHeaderValue = "Basic " + Base64.encodeBytes(usernameAndPasswordBytes());
// return new UpdatedHeaders(original, AUTHORIZATION_HEADER_TYPE.entity(authHeaderValue));
// }
//
//
// private byte[] usernameAndPasswordBytes()
// {
// try
// {
// return String.format("%s:%s", mUsername, mPassword).getBytes("UTF-8");
// }
// catch (UnsupportedEncodingException e)
// {
// throw new RuntimeException("Charset UTF-8 not supported by runtime!", e);
// }
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2ClientCredentials.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.decoration.HeaderDecorated;
import org.dmfs.oauth2.client.http.decorators.BasicAuthHeaderDecoration;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* Basic implementation of {@link OAuth2ClientCredentials}.
*
* @author Marten Gajda
*/
public final class BasicOAuth2ClientCredentials implements OAuth2ClientCredentials
{
private final String mClientId;
private final String mClientSecret;
public BasicOAuth2ClientCredentials(String clientId, String clientSecret)
{
mClientId = clientId;
mClientSecret = clientSecret;
}
@Override
public <T> HttpRequest<T> authenticatedRequest(HttpRequest<T> request)
{ | return new HeaderDecorated<>(request, new BasicAuthHeaderDecoration(mClientId, mClientSecret)); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/utils/Parameters.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
| import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterType;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.Duration; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.utils;
/**
* A collection of parameter types as specified in <a href="https://tools.ietf.org/html/rfc6749">RFC 6749</a>.
*
* @author Marten Gajda
*/
public final class Parameters
{
public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> AUTH_CODE = new BasicParameterType<>("code", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE);
public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType());
public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE);
| // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterType;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.Duration;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.utils;
/**
* A collection of parameter types as specified in <a href="https://tools.ietf.org/html/rfc6749">RFC 6749</a>.
*
* @author Marten Gajda
*/
public final class Parameters
{
public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> AUTH_CODE = new BasicParameterType<>("code", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> CLIENT_ID = new BasicParameterType<>("client_id", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> CODE_CHALLENGE = new BasicParameterType<>("code_challenge", TextValueType.INSTANCE);
public final static ParameterType<CharSequence> CODE_CHALLENGE_METHOD = new BasicParameterType<>("code_challenge_method", TextValueType.INSTANCE);
public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
public final static ParameterType<Uri> REDIRECT_URI = new BasicParameterType<>("redirect_uri", new UriValueType());
public final static ParameterType<CharSequence> RESPONSE_TYPE = new BasicParameterType<>("response_type", TextValueType.INSTANCE);
| public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType()); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
| import static org.dmfs.jems.hamcrest.matchers.LambdaMatcher.having;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.allOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException; | /*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* Unit test for {@link RefreshTokenRequest}.
*
* @author Marten Gajda
*/
public class RefreshTokenRequestTest
{
@Test
public void test() throws IOException
{
// get the entity to test | // Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequestTest.java
import static org.dmfs.jems.hamcrest.matchers.LambdaMatcher.having;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.allOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* Unit test for {@link RefreshTokenRequest}.
*
* @author Marten Gajda
*/
public class RefreshTokenRequestTest
{
@Test
public void test() throws IOException
{
// get the entity to test | HttpRequestEntity entity = new RefreshTokenRequest(new StringScope("s1 s2"), "token").requestEntity(); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated | public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope) |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated
public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope)
{
this(scope, refreshToken);
}
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param refreshToken
* The refresh token.
*/
public RefreshTokenRequest(OAuth2Scope scope, CharSequence refreshToken)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>( | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated
public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope)
{
this(scope, refreshToken);
}
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param refreshToken
* The refresh token.
*/
public RefreshTokenRequest(OAuth2Scope scope, CharSequence refreshToken)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>( | new GrantTypeParam("refresh_token"), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated
public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope)
{
this(scope, refreshToken);
}
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param refreshToken
* The refresh token.
*/
public RefreshTokenRequest(OAuth2Scope scope, CharSequence refreshToken)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("refresh_token"), | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated
public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope)
{
this(scope, refreshToken);
}
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param refreshToken
* The refresh token.
*/
public RefreshTokenRequest(OAuth2Scope scope, CharSequence refreshToken)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("refresh_token"), | new RefreshTokenParam(refreshToken)), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated
public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope)
{
this(scope, refreshToken);
}
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param refreshToken
* The refresh token.
*/
public RefreshTokenRequest(OAuth2Scope scope, CharSequence refreshToken)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("refresh_token"),
new RefreshTokenParam(refreshToken)), | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/RefreshTokenParam.java
// public final class RefreshTokenParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public RefreshTokenParam(CharSequence refreshToken)
// {
// super("refresh_token", refreshToken);
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/RefreshTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.jems.iterable.elementary.Seq;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.http.requests.parameters.RefreshTokenParam;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* An {@link HttpRequest} to refresh an OAuth2 access token.
*
* @author Marten Gajda
*/
public final class RefreshTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param refreshToken
* The refresh token.
* @param scope
* An {@link OAuth2Scope}.
*
* @deprecated in favour of {@link #RefreshTokenRequest(OAuth2Scope, CharSequence)}
*/
@Deprecated
public RefreshTokenRequest(CharSequence refreshToken, OAuth2Scope scope)
{
this(scope, refreshToken);
}
/**
* Creates an {@link RefreshTokenRequest} using the given refresh token and scopes.
*
* @param scope
* An {@link OAuth2Scope}.
* @param refreshToken
* The refresh token.
*/
public RefreshTokenRequest(OAuth2Scope scope, CharSequence refreshToken)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new Seq<>(
new GrantTypeParam("refresh_token"),
new RefreshTokenParam(refreshToken)), | new PresentValues<>(new OptionalScopeParam(scope))))); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/BasicOAuth2AuthCodeAuthorizationTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Test;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* @author Marten Gajda <[email protected]>
*/
public class BasicOAuth2AuthCodeAuthorizationTest
{
@Test(expected = ProtocolException.class)
public void invalidState() throws Exception
{
new BasicOAuth2AuthCodeAuthorization(
new LazyUri(new Precoded("https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz")), | // Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/BasicOAuth2AuthCodeAuthorizationTest.java
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* @author Marten Gajda <[email protected]>
*/
public class BasicOAuth2AuthCodeAuthorizationTest
{
@Test(expected = ProtocolException.class)
public void invalidState() throws Exception
{
new BasicOAuth2AuthCodeAuthorization(
new LazyUri(new Precoded("https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz")), | new BasicScope("scope"), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>("token_type", TextValueType.INSTANCE);
| import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
/**
* Represents an {@link OAuth2AccessToken} received from an Implicit Grant.
*
* @author Marten Gajda
*/
public final class ImplicitGrantAccessToken implements OAuth2AccessToken
{
private final Uri mRedirectUri;
private final ParameterList mRedirectUriParameters;
private final DateTime mIssueDate; | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>("token_type", TextValueType.INSTANCE);
// Path: src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
/**
* Represents an {@link OAuth2AccessToken} received from an Implicit Grant.
*
* @author Marten Gajda
*/
public final class ImplicitGrantAccessToken implements OAuth2AccessToken
{
private final Uri mRedirectUri;
private final ParameterList mRedirectUriParameters;
private final DateTime mIssueDate; | private final OAuth2Scope mScope; |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>("token_type", TextValueType.INSTANCE);
| import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE; | @Override
public CharSequence tokenType() throws ProtocolException
{
OptionalParameter<CharSequence> tokenType = new OptionalParameter<>(TOKEN_TYPE, mRedirectUriParameters);
if (!tokenType.isPresent())
{
throw new ProtocolException(String.format("Missing token_type in fragment '%s'", mRedirectUri.fragment().value()));
}
return tokenType.value("");
}
@Override
public boolean hasRefreshToken()
{
// implicit grants don't issue a refresh token
return false;
}
@Override
public CharSequence refreshToken() throws ProtocolException
{
throw new NoSuchElementException("Implicit grants do no issue refresh tokens");
}
@Override
public DateTime expirationDate() throws ProtocolException
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>("token_type", TextValueType.INSTANCE);
// Path: src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE;
@Override
public CharSequence tokenType() throws ProtocolException
{
OptionalParameter<CharSequence> tokenType = new OptionalParameter<>(TOKEN_TYPE, mRedirectUriParameters);
if (!tokenType.isPresent())
{
throw new ProtocolException(String.format("Missing token_type in fragment '%s'", mRedirectUri.fragment().value()));
}
return tokenType.value("");
}
@Override
public boolean hasRefreshToken()
{
// implicit grants don't issue a refresh token
return false;
}
@Override
public CharSequence refreshToken() throws ProtocolException
{
throw new NoSuchElementException("Implicit grants do no issue refresh tokens");
}
@Override
public DateTime expirationDate() throws ProtocolException
{ | return mIssueDate.addDuration(new OptionalParameter<>(EXPIRES_IN, mRedirectUriParameters).value(mDefaultExpiresIn)); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>("token_type", TextValueType.INSTANCE);
| import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE; | }
return tokenType.value("");
}
@Override
public boolean hasRefreshToken()
{
// implicit grants don't issue a refresh token
return false;
}
@Override
public CharSequence refreshToken() throws ProtocolException
{
throw new NoSuchElementException("Implicit grants do no issue refresh tokens");
}
@Override
public DateTime expirationDate() throws ProtocolException
{
return mIssueDate.addDuration(new OptionalParameter<>(EXPIRES_IN, mRedirectUriParameters).value(mDefaultExpiresIn));
}
@Override
public OAuth2Scope scope() throws ProtocolException
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> ACCESS_TOKEN = new BasicParameterType<>("access_token", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<Duration> EXPIRES_IN = new BasicParameterType<>("expires_in", new DurationValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<OAuth2Scope> SCOPE = new BasicParameterType<OAuth2Scope>("scope", new OAuth2ScopeValueType());
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> TOKEN_TYPE = new BasicParameterType<>("token_type", TextValueType.INSTANCE);
// Path: src/main/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessToken.java
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.jems.optional.Optional;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc5545.DateTime;
import org.dmfs.rfc5545.Duration;
import java.util.NoSuchElementException;
import static org.dmfs.oauth2.client.utils.Parameters.ACCESS_TOKEN;
import static org.dmfs.oauth2.client.utils.Parameters.EXPIRES_IN;
import static org.dmfs.oauth2.client.utils.Parameters.SCOPE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
import static org.dmfs.oauth2.client.utils.Parameters.TOKEN_TYPE;
}
return tokenType.value("");
}
@Override
public boolean hasRefreshToken()
{
// implicit grants don't issue a refresh token
return false;
}
@Override
public CharSequence refreshToken() throws ProtocolException
{
throw new NoSuchElementException("Implicit grants do no issue refresh tokens");
}
@Override
public DateTime expirationDate() throws ProtocolException
{
return mIssueDate.addDuration(new OptionalParameter<>(EXPIRES_IN, mRedirectUriParameters).value(mDefaultExpiresIn));
}
@Override
public OAuth2Scope scope() throws ProtocolException
{ | return new OptionalParameter<>(SCOPE, mRedirectUriParameters).value(mScope); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/utils/OAuth2ScopeValueType.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.parameters.ValueType; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.utils;
/**
* The {@link ValueType} {@link OAuth2Scope} parameters.
*
* @author Marten Gajda
*/
public final class OAuth2ScopeValueType implements ValueType<OAuth2Scope>
{
@Override
public OAuth2Scope parsedValue(CharSequence valueText)
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/utils/OAuth2ScopeValueType.java
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.parameters.ValueType;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.utils;
/**
* The {@link ValueType} {@link OAuth2Scope} parameters.
*
* @author Marten Gajda
*/
public final class OAuth2ScopeValueType implements ValueType<OAuth2Scope>
{
@Override
public OAuth2Scope parsedValue(CharSequence valueText)
{ | return new StringScope(valueText.toString()); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.oauth2.client.scope.EmptyScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.ParameterType;
import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Test;
import java.net.URI;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
public class BasicOAuth2AuthorizationRequestTest
{
@Test
public void testBasicOAuth2AuthorizationRequestStringString()
{
assertEquals(URI.create("http://example.com/auth/?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth/")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234%2F"),
new BasicOAuth2AuthorizationRequest("code", "1234/").authorizationUri(
URI.create("http://example.com/auth")));
}
@Test
public void testBasicOAuth2AuthorizationRequestStringOAuth2ScopeString()
{
// note this test makes assumptions about the order of query parameters which is wrong.
assertEquals(URI.create("http://example.com/auth?response_type=code&scope=&state=1234"),
new BasicOAuth2AuthorizationRequest("code", | // Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequestTest.java
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.oauth2.client.scope.EmptyScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.ParameterType;
import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Test;
import java.net.URI;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
public class BasicOAuth2AuthorizationRequestTest
{
@Test
public void testBasicOAuth2AuthorizationRequestStringString()
{
assertEquals(URI.create("http://example.com/auth/?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth/")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234%2F"),
new BasicOAuth2AuthorizationRequest("code", "1234/").authorizationUri(
URI.create("http://example.com/auth")));
}
@Test
public void testBasicOAuth2AuthorizationRequestStringOAuth2ScopeString()
{
// note this test makes assumptions about the order of query parameters which is wrong.
assertEquals(URI.create("http://example.com/auth?response_type=code&scope=&state=1234"),
new BasicOAuth2AuthorizationRequest("code", | EmptyScope.INSTANCE, "1234") |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.oauth2.client.scope.EmptyScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.ParameterType;
import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Test;
import java.net.URI;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
public class BasicOAuth2AuthorizationRequestTest
{
@Test
public void testBasicOAuth2AuthorizationRequestStringString()
{
assertEquals(URI.create("http://example.com/auth/?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth/")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234%2F"),
new BasicOAuth2AuthorizationRequest("code", "1234/").authorizationUri(
URI.create("http://example.com/auth")));
}
@Test
public void testBasicOAuth2AuthorizationRequestStringOAuth2ScopeString()
{
// note this test makes assumptions about the order of query parameters which is wrong.
assertEquals(URI.create("http://example.com/auth?response_type=code&scope=&state=1234"),
new BasicOAuth2AuthorizationRequest("code",
EmptyScope.INSTANCE, "1234")
.authorizationUri(URI.create("http://example.com/auth")));
assertEquals(URI.create("http://example.com/auth?response_type=code&scope=calendar&state=1234"),
new BasicOAuth2AuthorizationRequest("code", | // Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/BasicOAuth2AuthorizationRequestTest.java
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.oauth2.client.scope.EmptyScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.ParameterType;
import org.dmfs.rfc3986.parameters.parametersets.BasicParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Test;
import java.net.URI;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
public class BasicOAuth2AuthorizationRequestTest
{
@Test
public void testBasicOAuth2AuthorizationRequestStringString()
{
assertEquals(URI.create("http://example.com/auth/?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth/")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234"),
new BasicOAuth2AuthorizationRequest("code", "1234").authorizationUri(
URI.create("http://example.com/auth")));
assertEquals(URI.create("http://example.com/auth?response_type=code&state=1234%2F"),
new BasicOAuth2AuthorizationRequest("code", "1234/").authorizationUri(
URI.create("http://example.com/auth")));
}
@Test
public void testBasicOAuth2AuthorizationRequestStringOAuth2ScopeString()
{
// note this test makes assumptions about the order of query parameters which is wrong.
assertEquals(URI.create("http://example.com/auth?response_type=code&scope=&state=1234"),
new BasicOAuth2AuthorizationRequest("code",
EmptyScope.INSTANCE, "1234")
.authorizationUri(URI.create("http://example.com/auth")));
assertEquals(URI.create("http://example.com/auth?response_type=code&scope=calendar&state=1234"),
new BasicOAuth2AuthorizationRequest("code", | new BasicScope("calendar"), "1234") |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
| import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization; | /*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests.parameters;
/**
* The OAuth2 {@code code} parameter.
*
* @author Marten Gajda
*/
public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence>
{
| // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/AuthCodeParam.java
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
/*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests.parameters;
/**
* The OAuth2 {@code code} parameter.
*
* @author Marten Gajda
*/
public final class AuthCodeParam extends DelegatingPair<CharSequence, CharSequence>
{
| public AuthCodeParam(OAuth2AuthCodeAuthorization authorization) |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
| import static org.dmfs.jems.hamcrest.matchers.LambdaMatcher.having;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.allOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException; | /*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* Unit test for {@link ClientCredentialsTokenRequest}.
*
* @author Marten Gajda
*/
public class ClientCredentialsTokenRequestTest
{
@Test
public void test() throws IOException
{
// get the entity to test | // Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequestTest.java
import static org.dmfs.jems.hamcrest.matchers.LambdaMatcher.having;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.allOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* Unit test for {@link ClientCredentialsTokenRequest}.
*
* @author Marten Gajda
*/
public class ClientCredentialsTokenRequestTest
{
@Test
public void test() throws IOException
{
// get the entity to test | HttpRequestEntity entity = new ClientCredentialsTokenRequest(new StringScope("s1 s2")).requestEntity(); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{ | this(EmptyScope.INSTANCE); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{
this(EmptyScope.INSTANCE);
}
/**
* Creates a {@link ClientCredentialsTokenRequest} with the given scopes.
*
* @param scope
* The {@link OAuth2Scope} to request.
*/ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{
this(EmptyScope.INSTANCE);
}
/**
* Creates a {@link ClientCredentialsTokenRequest} with the given scopes.
*
* @param scope
* The {@link OAuth2Scope} to request.
*/ | public ClientCredentialsTokenRequest(OAuth2Scope scope) |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{
this(EmptyScope.INSTANCE);
}
/**
* Creates a {@link ClientCredentialsTokenRequest} with the given scopes.
*
* @param scope
* The {@link OAuth2Scope} to request.
*/
public ClientCredentialsTokenRequest(OAuth2Scope scope)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new SingletonIterable<>( | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{
this(EmptyScope.INSTANCE);
}
/**
* Creates a {@link ClientCredentialsTokenRequest} with the given scopes.
*
* @param scope
* The {@link OAuth2Scope} to request.
*/
public ClientCredentialsTokenRequest(OAuth2Scope scope)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new SingletonIterable<>( | new GrantTypeParam("client_credentials")), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{
this(EmptyScope.INSTANCE);
}
/**
* Creates a {@link ClientCredentialsTokenRequest} with the given scopes.
*
* @param scope
* The {@link OAuth2Scope} to request.
*/
public ClientCredentialsTokenRequest(OAuth2Scope scope)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new SingletonIterable<>(
new GrantTypeParam("client_credentials")),
new PresentValues<>( | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/GrantTypeParam.java
// public final class GrantTypeParam extends DelegatingPair<CharSequence, CharSequence>
// {
// public GrantTypeParam(CharSequence grantType)
// {
// super("grant_type", grantType);
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
// public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
// {
// public OptionalScopeParam(OAuth2Scope scope)
// {
// super(new Mapped<>(
// s -> new ValuePair<>("scope", s.toString()),
// new Conditional<>(s -> !s.isEmpty(), scope)));
// }
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/ClientCredentialsTokenRequest.java
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.entities.XWwwFormUrlEncodedEntity;
import org.dmfs.iterables.SingletonIterable;
import org.dmfs.iterables.elementary.PresentValues;
import org.dmfs.jems.iterable.composite.Joined;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.http.requests.parameters.GrantTypeParam;
import org.dmfs.oauth2.client.http.requests.parameters.OptionalScopeParam;
import org.dmfs.oauth2.client.scope.EmptyScope;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* {@link HttpRequest} to retrieve an access token in an OAuth2 Client Credentials Grant.
* <p>
* Note that this request must be authenticated using the client credentials.
*
* @author Marten Gajda
*/
public final class ClientCredentialsTokenRequest extends AbstractAccessTokenRequest
{
/**
* Creates a {@link ClientCredentialsTokenRequest} without a specific scope.
*/
public ClientCredentialsTokenRequest()
{
this(EmptyScope.INSTANCE);
}
/**
* Creates a {@link ClientCredentialsTokenRequest} with the given scopes.
*
* @param scope
* The {@link OAuth2Scope} to request.
*/
public ClientCredentialsTokenRequest(OAuth2Scope scope)
{
super(scope,
new XWwwFormUrlEncodedEntity(
new Joined<>(
new SingletonIterable<>(
new GrantTypeParam("client_credentials")),
new PresentValues<>( | new OptionalScopeParam(scope))))); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessTokenTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
| import org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher;
import org.dmfs.oauth2.client.scope.EmptyScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.uris.LazyUri;
import org.dmfs.rfc5545.Duration;
import org.hamcrest.Matchers;
import org.junit.Test;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
public class ImplicitGrantAccessTokenTest
{
@Test
public void testExtraParameter() throws Exception
{
assertThat(new ImplicitGrantAccessToken(
new LazyUri(new Precoded("http://localhost#state=1&key=value")), | // Path: src/main/java/org/dmfs/oauth2/client/scope/EmptyScope.java
// public final class EmptyScope implements OAuth2Scope
// {
// public final static EmptyScope INSTANCE = new EmptyScope();
//
//
// @Override
// public boolean isEmpty()
// {
// return true;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// // no tokens in here
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return 0;
// }
//
//
// @Override
// public String toString()
// {
// return "";
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// return ((OAuth2Scope) obj).isEmpty();
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/tokens/ImplicitGrantAccessTokenTest.java
import org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher;
import org.dmfs.oauth2.client.scope.EmptyScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.uris.LazyUri;
import org.dmfs.rfc5545.Duration;
import org.hamcrest.Matchers;
import org.junit.Test;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.tokens;
public class ImplicitGrantAccessTokenTest
{
@Test
public void testExtraParameter() throws Exception
{
assertThat(new ImplicitGrantAccessToken(
new LazyUri(new Precoded("http://localhost#state=1&key=value")), | new EmptyScope(), |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/responsehandlers/TokenErrorResponseHandler.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/errors/TokenRequestError.java
// public final class TokenRequestError extends ProtocolError
// {
// private static final long serialVersionUID = 1L;
//
// private final String mErrorResponse;
//
// /**
// * {@link JSONObject} is not a {@link Serializable}, so we mark it transient and restore it from String if necessary.
// */
// private transient JSONObject mErrorObject;
//
//
// public TokenRequestError(JSONObject errorObject) throws JSONException
// {
// super(errorObject.getString("error"));
// mErrorObject = errorObject;
// mErrorResponse = errorObject.toString();
// }
//
//
// /**
// * Returns the error code token that was returned by the server.
// *
// * @return A String containing the error code token.
// */
// public String error()
// {
// return errorObject().optString("error", "unknown");
// }
//
//
// /**
// * Returns the error description that was returned by the server.
// *
// * @return A String containing the error description.
// */
// public String description()
// {
// return errorObject().optString("error_description", "");
// }
//
//
// /**
// * Returns the optional error URI returned by the server.
// *
// * @return A URI pointing to a more descriptive error page or <code>null</code>.
// */
// public URI uri()
// {
// return errorObject().has("error_uri") ? URI.create(errorObject().optString("error_uri")) : null;
// }
//
//
// private JSONObject errorObject()
// {
// if (mErrorObject == null)
// {
// try
// {
// mErrorObject = new JSONObject(mErrorResponse);
// }
// catch (JSONException e)
// {
// throw new RuntimeException(String.format("Can't restore JSONObject from String", mErrorResponse), e);
// }
// }
// return mErrorObject;
// }
// }
| import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.responsehandlers.StringResponseHandler;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StructuredMediaType;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.errors.TokenRequestError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.responsehandlers;
/**
* {@link HttpResponseHandler} for OAuth2 token request errors with status code 400.
*
* @author Marten Gajda
*/
public final class TokenErrorResponseHandler implements HttpResponseHandler<OAuth2AccessToken>
{
private final static MediaType APPLICATION_JSON = new StructuredMediaType("application", "json");
public TokenErrorResponseHandler()
{
// nothing to do here
}
@Override
public OAuth2AccessToken handleResponse(HttpResponse response) throws IOException, ProtocolError, ProtocolException
{
if (!APPLICATION_JSON.equals(response.responseEntity().contentType().value()))
{
throw new ProtocolException(
String.format("Illegal response content-type %s, exected %s",
response.responseEntity().contentType().value(), APPLICATION_JSON));
}
String responseString = new StringResponseHandler("UTF-8").handleResponse(response);
try
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/errors/TokenRequestError.java
// public final class TokenRequestError extends ProtocolError
// {
// private static final long serialVersionUID = 1L;
//
// private final String mErrorResponse;
//
// /**
// * {@link JSONObject} is not a {@link Serializable}, so we mark it transient and restore it from String if necessary.
// */
// private transient JSONObject mErrorObject;
//
//
// public TokenRequestError(JSONObject errorObject) throws JSONException
// {
// super(errorObject.getString("error"));
// mErrorObject = errorObject;
// mErrorResponse = errorObject.toString();
// }
//
//
// /**
// * Returns the error code token that was returned by the server.
// *
// * @return A String containing the error code token.
// */
// public String error()
// {
// return errorObject().optString("error", "unknown");
// }
//
//
// /**
// * Returns the error description that was returned by the server.
// *
// * @return A String containing the error description.
// */
// public String description()
// {
// return errorObject().optString("error_description", "");
// }
//
//
// /**
// * Returns the optional error URI returned by the server.
// *
// * @return A URI pointing to a more descriptive error page or <code>null</code>.
// */
// public URI uri()
// {
// return errorObject().has("error_uri") ? URI.create(errorObject().optString("error_uri")) : null;
// }
//
//
// private JSONObject errorObject()
// {
// if (mErrorObject == null)
// {
// try
// {
// mErrorObject = new JSONObject(mErrorResponse);
// }
// catch (JSONException e)
// {
// throw new RuntimeException(String.format("Can't restore JSONObject from String", mErrorResponse), e);
// }
// }
// return mErrorObject;
// }
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/responsehandlers/TokenErrorResponseHandler.java
import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.responsehandlers.StringResponseHandler;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StructuredMediaType;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.dmfs.oauth2.client.errors.TokenRequestError;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.responsehandlers;
/**
* {@link HttpResponseHandler} for OAuth2 token request errors with status code 400.
*
* @author Marten Gajda
*/
public final class TokenErrorResponseHandler implements HttpResponseHandler<OAuth2AccessToken>
{
private final static MediaType APPLICATION_JSON = new StructuredMediaType("application", "json");
public TokenErrorResponseHandler()
{
// nothing to do here
}
@Override
public OAuth2AccessToken handleResponse(HttpResponse response) throws IOException, ProtocolError, ProtocolException
{
if (!APPLICATION_JSON.equals(response.responseEntity().contentType().value()))
{
throw new ProtocolException(
String.format("Illegal response content-type %s, exected %s",
response.responseEntity().contentType().value(), APPLICATION_JSON));
}
String responseString = new StringResponseHandler("UTF-8").handleResponse(response);
try
{ | throw new TokenRequestError(new JSONObject(responseString)); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher;
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* @author Marten Gajda
*/
public class AuthorizationCodeTokenRequestTest
{
@Test
public void testRequestEntity() throws Exception
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequestTest.java
import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher;
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* @author Marten Gajda
*/
public class AuthorizationCodeTokenRequestTest
{
@Test
public void testRequestEntity() throws Exception
{ | OAuth2AuthCodeAuthorization authorization = new OAuth2AuthCodeAuthorization() |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher;
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* @author Marten Gajda
*/
public class AuthorizationCodeTokenRequestTest
{
@Test
public void testRequestEntity() throws Exception
{
OAuth2AuthCodeAuthorization authorization = new OAuth2AuthCodeAuthorization()
{
@Override
public CharSequence code()
{
return "authcode";
}
@Override | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequestTest.java
import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher;
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* @author Marten Gajda
*/
public class AuthorizationCodeTokenRequestTest
{
@Test
public void testRequestEntity() throws Exception
{
OAuth2AuthCodeAuthorization authorization = new OAuth2AuthCodeAuthorization()
{
@Override
public CharSequence code()
{
return "authcode";
}
@Override | public OAuth2Scope scope() |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
| import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher;
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; | /*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* @author Marten Gajda
*/
public class AuthorizationCodeTokenRequestTest
{
@Test
public void testRequestEntity() throws Exception
{
OAuth2AuthCodeAuthorization authorization = new OAuth2AuthCodeAuthorization()
{
@Override
public CharSequence code()
{
return "authcode";
}
@Override
public OAuth2Scope scope()
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AuthCodeAuthorization.java
// public interface OAuth2AuthCodeAuthorization
// {
// /**
// * Returns the actual authorization code.
// *
// * @return
// */
// public CharSequence code();
//
// /**
// * Returns the scope that this authorization has been granted for.
// *
// * @return
// */
// public OAuth2Scope scope();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
//
// Path: src/main/java/org/dmfs/oauth2/client/scope/BasicScope.java
// public final class BasicScope implements OAuth2Scope
// {
// private final String[] mTokens;
//
//
// /**
// * Creates a new {@link OAuth2Scope} that contains the given tokens.
// *
// * @param tokens
// * The scope tokens in this scope. Must not contain <code>null</code> or empty {@link String}s.
// */
// public BasicScope(String... tokens)
// {
// mTokens = tokens.clone();
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mTokens.length == 0;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// for (String scopeToken : mTokens)
// {
// if (scopeToken.equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// return mTokens.length;
// }
//
//
// @Override
// public String toString()
// {
// StringBuilder result = new StringBuilder(mTokens.length * 30);
// boolean first = true;
//
// for (String token : mTokens)
// {
// if (first)
// {
// first = false;
// }
// else
// {
// result.append(' ');
// }
// result.append(token);
// }
// return result.toString();
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// for (String token : mTokens)
// {
// if (!other.hasToken(token))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/requests/AuthorizationCodeTokenRequestTest.java
import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.MediaType;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher;
import org.dmfs.oauth2.client.OAuth2AuthCodeAuthorization;
import org.dmfs.oauth2.client.OAuth2Scope;
import org.dmfs.oauth2.client.scope.BasicScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.dmfs.rfc3986.uris.LazyUri;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/*
* Copyright 2017 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* @author Marten Gajda
*/
public class AuthorizationCodeTokenRequestTest
{
@Test
public void testRequestEntity() throws Exception
{
OAuth2AuthCodeAuthorization authorization = new OAuth2AuthCodeAuthorization()
{
@Override
public CharSequence code()
{
return "authcode";
}
@Override
public OAuth2Scope scope()
{ | return new BasicScope("scope1", "scope2"); |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
| import static org.dmfs.jems.hamcrest.matchers.LambdaMatcher.having;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.allOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException; | /*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* Unit test for {@link ResourceOwnerPasswordTokenRequest}.
*
* @author Marten Gajda
*/
public class ResourceOwnerPasswordTokenRequestTest
{
@Test
public void test() throws IOException
{
// get the entity to test | // Path: src/main/java/org/dmfs/oauth2/client/scope/StringScope.java
// public final class StringScope implements OAuth2Scope
// {
// private final String mScope;
//
//
// /**
// * Creates an {@link OAuth2Scope} from the given space separated token list.
// *
// * @param scope
// */
// public StringScope(String scope)
// {
// mScope = scope;
// }
//
//
// @Override
// public boolean hasToken(String token)
// {
// Iterator<CharSequence> tokenIterator = new UnquotedSplit(mScope, ' ');
// while (tokenIterator.hasNext())
// {
// if (tokenIterator.next().toString().equals(token))
// {
// return true;
// }
// }
// return false;
// }
//
//
// @Override
// public int tokenCount()
// {
// if (mScope.isEmpty())
// {
// return 0;
// }
// int count = 0;
// for (CharSequence token : new Split(mScope, ' '))
// {
// count += 1;
// }
// return count;
// }
//
//
// @Override
// public boolean isEmpty()
// {
// return mScope.isEmpty();
// }
//
//
// @Override
// public String toString()
// {
// return mScope;
// }
//
//
// @Override
// public boolean equals(Object obj)
// {
// if (!(obj instanceof OAuth2Scope))
// {
// return false;
// }
//
// OAuth2Scope other = (OAuth2Scope) obj;
// if (isEmpty() && other.isEmpty())
// {
// return true;
// }
//
// if (tokenCount() != other.tokenCount())
// {
// return false;
// }
//
// Iterator<CharSequence> tokens = new UnquotedSplit(mScope, ' ');
// while (tokens.hasNext())
// {
// if (!other.hasToken(tokens.next().toString()))
// {
// return false;
// }
// }
// return true;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/requests/ResourceOwnerPasswordTokenRequestTest.java
import static org.dmfs.jems.hamcrest.matchers.LambdaMatcher.having;
import static org.dmfs.jems.hamcrest.matchers.optional.PresentMatcher.present;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.allOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.types.StringMediaType;
import org.dmfs.oauth2.client.scope.StringScope;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import org.dmfs.rfc3986.parameters.parametertypes.BasicParameterType;
import org.dmfs.rfc3986.parameters.valuetypes.TextValueType;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests;
/**
* Unit test for {@link ResourceOwnerPasswordTokenRequest}.
*
* @author Marten Gajda
*/
public class ResourceOwnerPasswordTokenRequestTest
{
@Test
public void test() throws IOException
{
// get the entity to test | HttpRequestEntity entity = new ResourceOwnerPasswordTokenRequest(new StringScope("s1 s2"), "user", "pass").requestEntity(); |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthCodeAuthorization.java | // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> AUTH_CODE = new BasicParameterType<>("code", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
| import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import static org.dmfs.oauth2.client.utils.Parameters.AUTH_CODE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* A basic {@link OAuth2AuthCodeAuthorization} implementation.
* <p>
* Note: Usually you don't need to instantiate this directly.
*
* @author Marten Gajda
*/
public final class BasicOAuth2AuthCodeAuthorization implements OAuth2AuthCodeAuthorization
{
private final ParameterList mQueryParameters;
private final OAuth2Scope mScope;
public BasicOAuth2AuthCodeAuthorization(Uri redirectUri, OAuth2Scope requestedScope, CharSequence state) throws ProtocolException
{
mQueryParameters = new XwfueParameterList(redirectUri.query().value()); | // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> AUTH_CODE = new BasicParameterType<>("code", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
// Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthCodeAuthorization.java
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import static org.dmfs.oauth2.client.utils.Parameters.AUTH_CODE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* A basic {@link OAuth2AuthCodeAuthorization} implementation.
* <p>
* Note: Usually you don't need to instantiate this directly.
*
* @author Marten Gajda
*/
public final class BasicOAuth2AuthCodeAuthorization implements OAuth2AuthCodeAuthorization
{
private final ParameterList mQueryParameters;
private final OAuth2Scope mScope;
public BasicOAuth2AuthCodeAuthorization(Uri redirectUri, OAuth2Scope requestedScope, CharSequence state) throws ProtocolException
{
mQueryParameters = new XwfueParameterList(redirectUri.query().value()); | if (!state.toString().equals(new TextParameter(STATE, mQueryParameters).toString())) |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthCodeAuthorization.java | // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> AUTH_CODE = new BasicParameterType<>("code", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
| import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import static org.dmfs.oauth2.client.utils.Parameters.AUTH_CODE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* A basic {@link OAuth2AuthCodeAuthorization} implementation.
* <p>
* Note: Usually you don't need to instantiate this directly.
*
* @author Marten Gajda
*/
public final class BasicOAuth2AuthCodeAuthorization implements OAuth2AuthCodeAuthorization
{
private final ParameterList mQueryParameters;
private final OAuth2Scope mScope;
public BasicOAuth2AuthCodeAuthorization(Uri redirectUri, OAuth2Scope requestedScope, CharSequence state) throws ProtocolException
{
mQueryParameters = new XwfueParameterList(redirectUri.query().value());
if (!state.toString().equals(new TextParameter(STATE, mQueryParameters).toString()))
{
throw new ProtocolException("State in redirect uri doesn't match the original state!");
} | // Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> AUTH_CODE = new BasicParameterType<>("code", TextValueType.INSTANCE);
//
// Path: src/main/java/org/dmfs/oauth2/client/utils/Parameters.java
// public final static ParameterType<CharSequence> STATE = new BasicParameterType<>("state", TextValueType.INSTANCE);
// Path: src/main/java/org/dmfs/oauth2/client/BasicOAuth2AuthCodeAuthorization.java
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.parameters.ParameterList;
import org.dmfs.rfc3986.parameters.adapters.OptionalParameter;
import org.dmfs.rfc3986.parameters.adapters.TextParameter;
import org.dmfs.rfc3986.parameters.adapters.XwfueParameterList;
import static org.dmfs.oauth2.client.utils.Parameters.AUTH_CODE;
import static org.dmfs.oauth2.client.utils.Parameters.STATE;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client;
/**
* A basic {@link OAuth2AuthCodeAuthorization} implementation.
* <p>
* Note: Usually you don't need to instantiate this directly.
*
* @author Marten Gajda
*/
public final class BasicOAuth2AuthCodeAuthorization implements OAuth2AuthCodeAuthorization
{
private final ParameterList mQueryParameters;
private final OAuth2Scope mScope;
public BasicOAuth2AuthCodeAuthorization(Uri redirectUri, OAuth2Scope requestedScope, CharSequence state) throws ProtocolException
{
mQueryParameters = new XwfueParameterList(redirectUri.query().value());
if (!state.toString().equals(new TextParameter(STATE, mQueryParameters).toString()))
{
throw new ProtocolException("State in redirect uri doesn't match the original state!");
} | if (!new OptionalParameter<CharSequence>(AUTH_CODE, mQueryParameters).isPresent()) |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/decorators/BearerAuthenticatedRequest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
| import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.converters.PlainStringHeaderConverter;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.headers.BasicSingletonHeaderType;
import org.dmfs.httpessentials.headers.Headers;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import java.io.IOException; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.decorators;
/**
* An {@link HttpRequest} decorator that adds a Bearer authorization header.
*
* @param <T>
* The type of the expected response.
*
* @author Marten Gajda
*/
public final class BearerAuthenticatedRequest<T> implements HttpRequest<T>
{
// TODO: use a generic authorization header instead (once we have one)
private final static BasicSingletonHeaderType<String> AUTHORIZATION_HEADER = new BasicSingletonHeaderType<String>(
"Authorization",
new PlainStringHeaderConverter());
| // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/decorators/BearerAuthenticatedRequest.java
import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.converters.PlainStringHeaderConverter;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.headers.BasicSingletonHeaderType;
import org.dmfs.httpessentials.headers.Headers;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import java.io.IOException;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.decorators;
/**
* An {@link HttpRequest} decorator that adds a Bearer authorization header.
*
* @param <T>
* The type of the expected response.
*
* @author Marten Gajda
*/
public final class BearerAuthenticatedRequest<T> implements HttpRequest<T>
{
// TODO: use a generic authorization header instead (once we have one)
private final static BasicSingletonHeaderType<String> AUTHORIZATION_HEADER = new BasicSingletonHeaderType<String>(
"Authorization",
new PlainStringHeaderConverter());
| private final OAuth2AccessToken mAccessToken; |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/decorators/BearerAuthenticatedRequestTest.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
| import mockit.Expectations;
import mockit.Injectable;
import mockit.integration.junit4.JMockit;
import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.converters.PlainStringHeaderConverter;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.headers.BasicSingletonHeaderType;
import org.dmfs.httpessentials.headers.EmptyHeaders;
import org.dmfs.httpessentials.headers.Headers;
import org.dmfs.httpessentials.headers.HttpHeaders;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.decorators;
/**
* Unit test for {@link BearerAuthenticatedRequest}.
*
* @author Gabor Keszthelyi
*/
@Ignore
@RunWith(JMockit.class)
public class BearerAuthenticatedRequestTest
{
// TODO: use a generic authorization header instead (once we have one)
private final static BasicSingletonHeaderType<String> AUTHORIZATION_HEADER = new BasicSingletonHeaderType<String>(
"Authorization",
new PlainStringHeaderConverter());
private static final Headers ORIGINAL_HEADER = EmptyHeaders.INSTANCE.withHeader(
HttpHeaders.CONTENT_LENGTH.entity(15));
private static final String ACCESS_TOKEN_STRING = "access token";
@Injectable
private HttpRequest<Result> originalRequest;
@Injectable
private HttpRequestEntity originalEntity;
@Injectable
private HttpMethod originalHttpMethod;
@Injectable
private HttpResponseHandler<Result> originalResponseHandler;
@Injectable
private HttpResponse response;
@Injectable | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2AccessToken.java
// public interface OAuth2AccessToken
// {
// /**
// * Returns the actual access token String.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence accessToken() throws ProtocolException;
//
// /**
// * Returns the access token type.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public CharSequence tokenType() throws ProtocolException;
//
// /**
// * Returns whether the response also contained a refresh token.
// *
// * @return
// */
// public boolean hasRefreshToken();
//
// /**
// * Returns the refresh token. Before calling this use {@link #hasRefreshToken()} to check if there actually is a refresh token.
// *
// * @return
// *
// * @throws NoSuchElementException
// * If the token doesn't contain a refresh token.
// * @throws ProtocolException
// */
// public CharSequence refreshToken() throws ProtocolException;
//
// /**
// * Returns the expected expiration date of the access token.
// *
// * @return
// *
// * @throws ProtocolException
// */
// public DateTime expirationDate() throws ProtocolException;
//
// /**
// * The scope this {@link OAuth2AccessToken} was issued for. May be an empty scope if the scope is not known.
// *
// * @return An {@link OAuth2Scope}.
// *
// * @throws ProtocolException
// */
// public OAuth2Scope scope() throws ProtocolException;
//
// /**
// * Returns a value stored in the token response under the {@code parameterName}.
// *
// * @param parameterName
// * the key under which the value is stored in the response
// */
// public Optional<CharSequence> extraParameter(final String parameterName);
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/decorators/BearerAuthenticatedRequestTest.java
import mockit.Expectations;
import mockit.Injectable;
import mockit.integration.junit4.JMockit;
import org.dmfs.httpessentials.HttpMethod;
import org.dmfs.httpessentials.client.HttpRequest;
import org.dmfs.httpessentials.client.HttpRequestEntity;
import org.dmfs.httpessentials.client.HttpResponse;
import org.dmfs.httpessentials.client.HttpResponseHandler;
import org.dmfs.httpessentials.converters.PlainStringHeaderConverter;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.headers.BasicSingletonHeaderType;
import org.dmfs.httpessentials.headers.EmptyHeaders;
import org.dmfs.httpessentials.headers.Headers;
import org.dmfs.httpessentials.headers.HttpHeaders;
import org.dmfs.oauth2.client.OAuth2AccessToken;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.decorators;
/**
* Unit test for {@link BearerAuthenticatedRequest}.
*
* @author Gabor Keszthelyi
*/
@Ignore
@RunWith(JMockit.class)
public class BearerAuthenticatedRequestTest
{
// TODO: use a generic authorization header instead (once we have one)
private final static BasicSingletonHeaderType<String> AUTHORIZATION_HEADER = new BasicSingletonHeaderType<String>(
"Authorization",
new PlainStringHeaderConverter());
private static final Headers ORIGINAL_HEADER = EmptyHeaders.INSTANCE.withHeader(
HttpHeaders.CONTENT_LENGTH.entity(15));
private static final String ACCESS_TOKEN_STRING = "access token";
@Injectable
private HttpRequest<Result> originalRequest;
@Injectable
private HttpRequestEntity originalEntity;
@Injectable
private HttpMethod originalHttpMethod;
@Injectable
private HttpResponseHandler<Result> originalResponseHandler;
@Injectable
private HttpResponse response;
@Injectable | private OAuth2AccessToken accessToken; |
dmfs/oauth2-essentials | src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
| import org.dmfs.jems.optional.adapters.Conditional;
import org.dmfs.jems.optional.decorators.DelegatingOptional;
import org.dmfs.jems.optional.decorators.Mapped;
import org.dmfs.jems.pair.Pair;
import org.dmfs.jems.pair.elementary.ValuePair;
import org.dmfs.oauth2.client.OAuth2Scope; | /*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests.parameters;
/**
* An Optional OAuth2 {@code scope} parameter.
*
* @author Marten Gajda
*/
public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
{ | // Path: src/main/java/org/dmfs/oauth2/client/OAuth2Scope.java
// public interface OAuth2Scope
// {
// /**
// * Returns whether this scope is empty.
// *
// * @return <code>true</code> if this scope is empty, <code>false</code> otherwise.
// */
// boolean isEmpty();
//
// /**
// * Returns whether this scope contains the given scope token or not.
// *
// * @param token
// * The scope token to check for.
// *
// * @return <code>true</code> if the scope token is contained in this scope, <code>false</code> otherwise.
// */
// boolean hasToken(String token);
//
// /**
// * Returns the number of tokens in this {@link OAuth2Scope}.
// *
// * @return The number of tokens in this {@link OAuth2Scope}.
// */
// int tokenCount();
//
// /**
// * Returns a string version of this scope as described in <a href="https://tools.ietf.org/html/rfc6749#section-3.3">RFC 6749, section 3.3</a>, i.e. a list
// * of scope tokens separated by spaces.
// *
// * @return A String containing a list scope tokens, separated by spaces, or an empty String if {@link #isEmpty()} returns <code>true</code>.
// */
// String toString();
// }
// Path: src/main/java/org/dmfs/oauth2/client/http/requests/parameters/OptionalScopeParam.java
import org.dmfs.jems.optional.adapters.Conditional;
import org.dmfs.jems.optional.decorators.DelegatingOptional;
import org.dmfs.jems.optional.decorators.Mapped;
import org.dmfs.jems.pair.Pair;
import org.dmfs.jems.pair.elementary.ValuePair;
import org.dmfs.oauth2.client.OAuth2Scope;
/*
* Copyright 2019 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.requests.parameters;
/**
* An Optional OAuth2 {@code scope} parameter.
*
* @author Marten Gajda
*/
public final class OptionalScopeParam extends DelegatingOptional<Pair<CharSequence, CharSequence>>
{ | public OptionalScopeParam(OAuth2Scope scope) |
dmfs/oauth2-essentials | src/test/java/org/dmfs/oauth2/client/http/responsehandlers/TokenErrorResponseHandlerTest.java | // Path: src/main/java/org/dmfs/oauth2/client/errors/TokenRequestError.java
// public final class TokenRequestError extends ProtocolError
// {
// private static final long serialVersionUID = 1L;
//
// private final String mErrorResponse;
//
// /**
// * {@link JSONObject} is not a {@link Serializable}, so we mark it transient and restore it from String if necessary.
// */
// private transient JSONObject mErrorObject;
//
//
// public TokenRequestError(JSONObject errorObject) throws JSONException
// {
// super(errorObject.getString("error"));
// mErrorObject = errorObject;
// mErrorResponse = errorObject.toString();
// }
//
//
// /**
// * Returns the error code token that was returned by the server.
// *
// * @return A String containing the error code token.
// */
// public String error()
// {
// return errorObject().optString("error", "unknown");
// }
//
//
// /**
// * Returns the error description that was returned by the server.
// *
// * @return A String containing the error description.
// */
// public String description()
// {
// return errorObject().optString("error_description", "");
// }
//
//
// /**
// * Returns the optional error URI returned by the server.
// *
// * @return A URI pointing to a more descriptive error page or <code>null</code>.
// */
// public URI uri()
// {
// return errorObject().has("error_uri") ? URI.create(errorObject().optString("error_uri")) : null;
// }
//
//
// private JSONObject errorObject()
// {
// if (mErrorObject == null)
// {
// try
// {
// mErrorObject = new JSONObject(mErrorResponse);
// }
// catch (JSONException e)
// {
// throw new RuntimeException(String.format("Can't restore JSONObject from String", mErrorResponse), e);
// }
// }
// return mErrorObject;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.dmfs.httpessentials.HttpStatus;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.headers.EmptyHeaders;
import org.dmfs.httpessentials.mockutils.entities.StaticMockResponseEntity;
import org.dmfs.httpessentials.mockutils.responses.StaticMockResponse;
import org.dmfs.httpessentials.types.StructuredMediaType;
import org.dmfs.oauth2.client.errors.TokenRequestError;
import org.junit.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI; | /*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.responsehandlers;
/**
* Test the {@link TokenErrorResponseHandler}.
* <p/>
* TODO: also test some invalid responses.
*
* @author Marten Gajda <[email protected]>
*/
public class TokenErrorResponseHandlerTest
{
@Test
public void testHandleResponseNoUri() throws UnsupportedEncodingException, IOException, ProtocolError, ProtocolException
{
final String accessTokenResponse = "{" + "\"error\":\"invalid_grant\"," + "\"error_description\":\"DESCRIPTION\"," + "}";
try
{
new TokenErrorResponseHandler().handleResponse(
new StaticMockResponse(HttpStatus.BAD_REQUEST, EmptyHeaders.INSTANCE, new StaticMockResponseEntity(
new StructuredMediaType("application", "json", "utf-8"), accessTokenResponse)));
fail("No exception thrown");
} | // Path: src/main/java/org/dmfs/oauth2/client/errors/TokenRequestError.java
// public final class TokenRequestError extends ProtocolError
// {
// private static final long serialVersionUID = 1L;
//
// private final String mErrorResponse;
//
// /**
// * {@link JSONObject} is not a {@link Serializable}, so we mark it transient and restore it from String if necessary.
// */
// private transient JSONObject mErrorObject;
//
//
// public TokenRequestError(JSONObject errorObject) throws JSONException
// {
// super(errorObject.getString("error"));
// mErrorObject = errorObject;
// mErrorResponse = errorObject.toString();
// }
//
//
// /**
// * Returns the error code token that was returned by the server.
// *
// * @return A String containing the error code token.
// */
// public String error()
// {
// return errorObject().optString("error", "unknown");
// }
//
//
// /**
// * Returns the error description that was returned by the server.
// *
// * @return A String containing the error description.
// */
// public String description()
// {
// return errorObject().optString("error_description", "");
// }
//
//
// /**
// * Returns the optional error URI returned by the server.
// *
// * @return A URI pointing to a more descriptive error page or <code>null</code>.
// */
// public URI uri()
// {
// return errorObject().has("error_uri") ? URI.create(errorObject().optString("error_uri")) : null;
// }
//
//
// private JSONObject errorObject()
// {
// if (mErrorObject == null)
// {
// try
// {
// mErrorObject = new JSONObject(mErrorResponse);
// }
// catch (JSONException e)
// {
// throw new RuntimeException(String.format("Can't restore JSONObject from String", mErrorResponse), e);
// }
// }
// return mErrorObject;
// }
// }
// Path: src/test/java/org/dmfs/oauth2/client/http/responsehandlers/TokenErrorResponseHandlerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.dmfs.httpessentials.HttpStatus;
import org.dmfs.httpessentials.exceptions.ProtocolError;
import org.dmfs.httpessentials.exceptions.ProtocolException;
import org.dmfs.httpessentials.headers.EmptyHeaders;
import org.dmfs.httpessentials.mockutils.entities.StaticMockResponseEntity;
import org.dmfs.httpessentials.mockutils.responses.StaticMockResponse;
import org.dmfs.httpessentials.types.StructuredMediaType;
import org.dmfs.oauth2.client.errors.TokenRequestError;
import org.junit.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
/*
* Copyright 2016 dmfs GmbH
*
* 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 org.dmfs.oauth2.client.http.responsehandlers;
/**
* Test the {@link TokenErrorResponseHandler}.
* <p/>
* TODO: also test some invalid responses.
*
* @author Marten Gajda <[email protected]>
*/
public class TokenErrorResponseHandlerTest
{
@Test
public void testHandleResponseNoUri() throws UnsupportedEncodingException, IOException, ProtocolError, ProtocolException
{
final String accessTokenResponse = "{" + "\"error\":\"invalid_grant\"," + "\"error_description\":\"DESCRIPTION\"," + "}";
try
{
new TokenErrorResponseHandler().handleResponse(
new StaticMockResponse(HttpStatus.BAD_REQUEST, EmptyHeaders.INSTANCE, new StaticMockResponseEntity(
new StructuredMediaType("application", "json", "utf-8"), accessTokenResponse)));
fail("No exception thrown");
} | catch (TokenRequestError e) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.