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 |
|---|---|---|---|---|---|---|
Kaysoro/KaellyBot | src/main/java/data/JobUser.java | // Path: src/main/java/enums/Job.java
// public enum Job {
//
// ALCHIMISTE("job.alchimiste"),
// BIJOUTIER("job.bijoutier"),
// BRICOLEUR("job.bricoleur"),
// BUCHERON("job.bucheron"),
// CHASSEUR("job.chasseur"),
// CORDOMAGE("job.cordomage"),
// CORDONNIER("job.cordonnier"),
// COSTUMAGE("job.costumage"),
// FACONNEUR("job.faconneur"),
// FORGEMAGE("job.forgemage"),
// FORGERON("job.forgeron"),
// JOAILLOMAGE("job.joaillomage"),
// MINEUR("job.mineur"),
// PAYSAN("job.paysan"),
// PECHEUR("job.pecheur"),
// SCULPTEMAGE("job.sculptemage"),
// SCULPTEUR("job.sculpteur"),
// TAILLEUR("job.tailleur"),
// FACOMAGE("job.facomage");
//
// private static Map<String, Job> jobs;
// private String name;
//
// Job(String name){this.name = name;}
//
// public String getName(){
// return name;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// /**
// *
// * @param name Nom du métier
// * @return L'énumération Job correspondant à name
// * @throws IllegalArgumentException si aucun Job n'est trouvé pour le nom proposé.
// */
// public static synchronized Job getJob(String name){
// if (jobs == null){
// jobs = new HashMap<>();
// for(Job job : Job.values())
// jobs.put(job.getName(), job);
// }
//
// if (jobs.containsKey(name))
// return jobs.get(name);
// throw new IllegalArgumentException("No job found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.Job;
import enums.Language;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer; | package data;
/**
* Created by steve on 12/11/2016.
*/
public class JobUser extends ObjectUser {
private final static Logger LOG = LoggerFactory.getLogger(JobUser.class);
private static final String JOB_PREFIX = "job";
private static final int NUMBER_FIELD = 3;
private static MultiKeySearch<JobUser> jobs; | // Path: src/main/java/enums/Job.java
// public enum Job {
//
// ALCHIMISTE("job.alchimiste"),
// BIJOUTIER("job.bijoutier"),
// BRICOLEUR("job.bricoleur"),
// BUCHERON("job.bucheron"),
// CHASSEUR("job.chasseur"),
// CORDOMAGE("job.cordomage"),
// CORDONNIER("job.cordonnier"),
// COSTUMAGE("job.costumage"),
// FACONNEUR("job.faconneur"),
// FORGEMAGE("job.forgemage"),
// FORGERON("job.forgeron"),
// JOAILLOMAGE("job.joaillomage"),
// MINEUR("job.mineur"),
// PAYSAN("job.paysan"),
// PECHEUR("job.pecheur"),
// SCULPTEMAGE("job.sculptemage"),
// SCULPTEUR("job.sculpteur"),
// TAILLEUR("job.tailleur"),
// FACOMAGE("job.facomage");
//
// private static Map<String, Job> jobs;
// private String name;
//
// Job(String name){this.name = name;}
//
// public String getName(){
// return name;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// /**
// *
// * @param name Nom du métier
// * @return L'énumération Job correspondant à name
// * @throws IllegalArgumentException si aucun Job n'est trouvé pour le nom proposé.
// */
// public static synchronized Job getJob(String name){
// if (jobs == null){
// jobs = new HashMap<>();
// for(Job job : Job.values())
// jobs.put(job.getName(), job);
// }
//
// if (jobs.containsKey(name))
// return jobs.get(name);
// throw new IllegalArgumentException("No job found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/data/JobUser.java
import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.Job;
import enums.Language;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
package data;
/**
* Created by steve on 12/11/2016.
*/
public class JobUser extends ObjectUser {
private final static Logger LOG = LoggerFactory.getLogger(JobUser.class);
private static final String JOB_PREFIX = "job";
private static final int NUMBER_FIELD = 3;
private static MultiKeySearch<JobUser> jobs; | private Job job; |
Kaysoro/KaellyBot | src/main/java/data/JobUser.java | // Path: src/main/java/enums/Job.java
// public enum Job {
//
// ALCHIMISTE("job.alchimiste"),
// BIJOUTIER("job.bijoutier"),
// BRICOLEUR("job.bricoleur"),
// BUCHERON("job.bucheron"),
// CHASSEUR("job.chasseur"),
// CORDOMAGE("job.cordomage"),
// CORDONNIER("job.cordonnier"),
// COSTUMAGE("job.costumage"),
// FACONNEUR("job.faconneur"),
// FORGEMAGE("job.forgemage"),
// FORGERON("job.forgeron"),
// JOAILLOMAGE("job.joaillomage"),
// MINEUR("job.mineur"),
// PAYSAN("job.paysan"),
// PECHEUR("job.pecheur"),
// SCULPTEMAGE("job.sculptemage"),
// SCULPTEUR("job.sculpteur"),
// TAILLEUR("job.tailleur"),
// FACOMAGE("job.facomage");
//
// private static Map<String, Job> jobs;
// private String name;
//
// Job(String name){this.name = name;}
//
// public String getName(){
// return name;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// /**
// *
// * @param name Nom du métier
// * @return L'énumération Job correspondant à name
// * @throws IllegalArgumentException si aucun Job n'est trouvé pour le nom proposé.
// */
// public static synchronized Job getJob(String name){
// if (jobs == null){
// jobs = new HashMap<>();
// for(Job job : Job.values())
// jobs.put(job.getName(), job);
// }
//
// if (jobs.containsKey(name))
// return jobs.get(name);
// throw new IllegalArgumentException("No job found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.Job;
import enums.Language;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer; | jobs = new MultiKeySearch<>(NUMBER_FIELD);
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement query = connection.prepareStatement(
"SELECT id_user, server_dofus, name_job, level FROM Job_User;");
ResultSet resultSet = query.executeQuery();
while (resultSet.next()) {
Long idUser = resultSet.getLong("id_user");
ServerDofus server = ServerDofus.getServersMap().get(resultSet.getString("server_dofus"));
Job job = Job.getJob(resultSet.getString("name_job"));
int level = resultSet.getInt("level");
jobs.add(new JobUser(idUser, server, job, level), idUser, server, job);
}
} catch (SQLException e) {
Reporter.report(e);
LOG.error("getJobs", e);
}
}
return jobs;
}
/**
* @param user Joueur de la guilde
* @param server Serveur dofus
* @return Liste des résultats de la recherche
*/ | // Path: src/main/java/enums/Job.java
// public enum Job {
//
// ALCHIMISTE("job.alchimiste"),
// BIJOUTIER("job.bijoutier"),
// BRICOLEUR("job.bricoleur"),
// BUCHERON("job.bucheron"),
// CHASSEUR("job.chasseur"),
// CORDOMAGE("job.cordomage"),
// CORDONNIER("job.cordonnier"),
// COSTUMAGE("job.costumage"),
// FACONNEUR("job.faconneur"),
// FORGEMAGE("job.forgemage"),
// FORGERON("job.forgeron"),
// JOAILLOMAGE("job.joaillomage"),
// MINEUR("job.mineur"),
// PAYSAN("job.paysan"),
// PECHEUR("job.pecheur"),
// SCULPTEMAGE("job.sculptemage"),
// SCULPTEUR("job.sculpteur"),
// TAILLEUR("job.tailleur"),
// FACOMAGE("job.facomage");
//
// private static Map<String, Job> jobs;
// private String name;
//
// Job(String name){this.name = name;}
//
// public String getName(){
// return name;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// /**
// *
// * @param name Nom du métier
// * @return L'énumération Job correspondant à name
// * @throws IllegalArgumentException si aucun Job n'est trouvé pour le nom proposé.
// */
// public static synchronized Job getJob(String name){
// if (jobs == null){
// jobs = new HashMap<>();
// for(Job job : Job.values())
// jobs.put(job.getName(), job);
// }
//
// if (jobs.containsKey(name))
// return jobs.get(name);
// throw new IllegalArgumentException("No job found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/data/JobUser.java
import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.Job;
import enums.Language;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
jobs = new MultiKeySearch<>(NUMBER_FIELD);
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement query = connection.prepareStatement(
"SELECT id_user, server_dofus, name_job, level FROM Job_User;");
ResultSet resultSet = query.executeQuery();
while (resultSet.next()) {
Long idUser = resultSet.getLong("id_user");
ServerDofus server = ServerDofus.getServersMap().get(resultSet.getString("server_dofus"));
Job job = Job.getJob(resultSet.getString("name_job"));
int level = resultSet.getInt("level");
jobs.add(new JobUser(idUser, server, job, level), idUser, server, job);
}
} catch (SQLException e) {
Reporter.report(e);
LOG.error("getJobs", e);
}
}
return jobs;
}
/**
* @param user Joueur de la guilde
* @param server Serveur dofus
* @return Liste des résultats de la recherche
*/ | public static List<EmbedCreateSpec> getJobsFromUser(Member user, ServerDofus server, Language lg){ |
Kaysoro/KaellyBot | src/main/java/util/Connexion.java | // Path: src/main/java/data/Constants.java
// public class Constants {
//
// /**
// * Application name
// */
// public final static String name = "Kaelly";
//
// /**
// * Application version
// */
// public final static String version = "1.6.4";
//
// /**
// * Changelog
// */
// public final static String changelog = "https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png";
//
// /**
// * Author id
// */
// public final static long authorId = 162842827183751169L;
//
// /**
// * Author name
// */
// public final static String authorName = "Kaysoro#8327";
//
// /**
// * Author avatar
// */
// public final static String authorAvatar = "https://avatars0.githubusercontent.com/u/5544670?s=460&v=4";
//
// /**
// * URL for Kaelly twitter account
// */
// public final static String twitterAccount = "https://twitter.com/KaellyBot";
//
// /**
// * URL for github KaellyBot repository
// */
// public final static String git = "https://github.com/Kaysoro/KaellyBot";
//
// /**
// * Official link invite
// */
// public final static String invite = "https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot";
//
// /**
// * Official paypal link
// */
// public final static String paypal = "https://paypal.me/kaysoro";
//
// /**
// * Database name
// */
// public final static String database = "bdd.sqlite";
//
// /**
// * Path to the database (can be left empty)
// */
// public final static String database_path = "";
//
// /**
// * Path to the folder containing sounds (can be left empty)
// */
// public final static String sound_path = "";
//
// /**
// * prefix used for command call.
// * WARN : it is injected into regex expression.
// * If you use special characters as '$', don't forget to prefix it with '\\' like this : "\\$"
// */
// public final static String prefixCommand = "!";
//
// public final static Language defaultLanguage = Language.FR;
//
// /**
// * Game desserved
// */
// public final static Game game = Game.DOFUS;
//
// /**
// * Official Ankama Game Logo
// */
// public final static String officialLogo = "https://s.ankama.com/www/static.ankama.com/g/modules/masterpage/block/header/navbar/dofus/logo.png";
//
// /**
// * Tutorial URL
// */
// public final static String dofusPourLesNoobURL = "http://www.dofuspourlesnoobs.com";
//
// /**
// * Tutorial Search URL
// */
// public final static String dofusPourLesNoobSearch = "/apps/search";
//
// /**
// * DofusRoom build URL
// */
// public final static String dofusRoomBuildUrl = "https://www.dofusroom.com/buildroom/build/show/";
//
// public final static String turnamentMapImg = "https://dofus-tournaments.fr/_default/src/img/maps/A{number}.jpg";
//
// /**
// * Twitter Icon from Wikipedia
// */
// public final static String twitterIcon = "https://upload.wikimedia.org/wikipedia/fr/thumb/c/c8/Twitter_Bird.svg/langfr-20px-Twitter_Bird.svg.png";
//
// /**
// * RSS Icon from Wikipedia
// */
// public final static String rssIcon = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Feed-icon.svg/20px-Feed-icon.svg.png";
//
// /**
// * Character limit for nickname discord
// */
// public final static int nicknameLimit = 32;
//
// /**
// * Character limit for prefixe discord
// */
// public final static int prefixeLimit = 3;
//
// /**
// * User or channel dedicated to receive info logs.
// */
// public final static long chanReportID = 321197720629149698L;
//
// /**
// * User or channel dedicated to receive error logs.
// */
// public final static long chanErrorID = 358201712600678400L;
//
// /**
// * Official changelog
// */
// public final static long newsChan = 330475075381886976L;
//
// /**
// * Almanax API URL
// */
// public final static String almanaxURL = "https://alm.dofusdu.de/{game}/v1/{language}/{date}";
//
// /**
// * Almanax Redis cache time to live for each cached day
// */
// public final static int almanaxCacheHoursTTL = 3;
//
// /**
// * Discord invite link
// */
// public final static String discordInvite = "https://discord.gg/VsrbrYC";
// }
| import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import data.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.SQLiteConfig; | package util;
public class Connexion {
private final static Logger LOG = LoggerFactory.getLogger(Connexion.class);
private static Connexion instance = null;
private Connection connection = null;
private Statement statement = null;
private static String database_path = System.getProperty("user.dir") + File.separator;
public void connect() { | // Path: src/main/java/data/Constants.java
// public class Constants {
//
// /**
// * Application name
// */
// public final static String name = "Kaelly";
//
// /**
// * Application version
// */
// public final static String version = "1.6.4";
//
// /**
// * Changelog
// */
// public final static String changelog = "https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png";
//
// /**
// * Author id
// */
// public final static long authorId = 162842827183751169L;
//
// /**
// * Author name
// */
// public final static String authorName = "Kaysoro#8327";
//
// /**
// * Author avatar
// */
// public final static String authorAvatar = "https://avatars0.githubusercontent.com/u/5544670?s=460&v=4";
//
// /**
// * URL for Kaelly twitter account
// */
// public final static String twitterAccount = "https://twitter.com/KaellyBot";
//
// /**
// * URL for github KaellyBot repository
// */
// public final static String git = "https://github.com/Kaysoro/KaellyBot";
//
// /**
// * Official link invite
// */
// public final static String invite = "https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot";
//
// /**
// * Official paypal link
// */
// public final static String paypal = "https://paypal.me/kaysoro";
//
// /**
// * Database name
// */
// public final static String database = "bdd.sqlite";
//
// /**
// * Path to the database (can be left empty)
// */
// public final static String database_path = "";
//
// /**
// * Path to the folder containing sounds (can be left empty)
// */
// public final static String sound_path = "";
//
// /**
// * prefix used for command call.
// * WARN : it is injected into regex expression.
// * If you use special characters as '$', don't forget to prefix it with '\\' like this : "\\$"
// */
// public final static String prefixCommand = "!";
//
// public final static Language defaultLanguage = Language.FR;
//
// /**
// * Game desserved
// */
// public final static Game game = Game.DOFUS;
//
// /**
// * Official Ankama Game Logo
// */
// public final static String officialLogo = "https://s.ankama.com/www/static.ankama.com/g/modules/masterpage/block/header/navbar/dofus/logo.png";
//
// /**
// * Tutorial URL
// */
// public final static String dofusPourLesNoobURL = "http://www.dofuspourlesnoobs.com";
//
// /**
// * Tutorial Search URL
// */
// public final static String dofusPourLesNoobSearch = "/apps/search";
//
// /**
// * DofusRoom build URL
// */
// public final static String dofusRoomBuildUrl = "https://www.dofusroom.com/buildroom/build/show/";
//
// public final static String turnamentMapImg = "https://dofus-tournaments.fr/_default/src/img/maps/A{number}.jpg";
//
// /**
// * Twitter Icon from Wikipedia
// */
// public final static String twitterIcon = "https://upload.wikimedia.org/wikipedia/fr/thumb/c/c8/Twitter_Bird.svg/langfr-20px-Twitter_Bird.svg.png";
//
// /**
// * RSS Icon from Wikipedia
// */
// public final static String rssIcon = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Feed-icon.svg/20px-Feed-icon.svg.png";
//
// /**
// * Character limit for nickname discord
// */
// public final static int nicknameLimit = 32;
//
// /**
// * Character limit for prefixe discord
// */
// public final static int prefixeLimit = 3;
//
// /**
// * User or channel dedicated to receive info logs.
// */
// public final static long chanReportID = 321197720629149698L;
//
// /**
// * User or channel dedicated to receive error logs.
// */
// public final static long chanErrorID = 358201712600678400L;
//
// /**
// * Official changelog
// */
// public final static long newsChan = 330475075381886976L;
//
// /**
// * Almanax API URL
// */
// public final static String almanaxURL = "https://alm.dofusdu.de/{game}/v1/{language}/{date}";
//
// /**
// * Almanax Redis cache time to live for each cached day
// */
// public final static int almanaxCacheHoursTTL = 3;
//
// /**
// * Discord invite link
// */
// public final static String discordInvite = "https://discord.gg/VsrbrYC";
// }
// Path: src/main/java/util/Connexion.java
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import data.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.SQLiteConfig;
package util;
public class Connexion {
private final static Logger LOG = LoggerFactory.getLogger(Connexion.class);
private static Connexion instance = null;
private Connection connection = null;
private Statement statement = null;
private static String database_path = System.getProperty("user.dir") + File.separator;
public void connect() { | if (! Constants.database_path.trim().isEmpty()) { |
adragomir/hbase-indexing-library | src/hbaseindex/src/main/java/org/lilycms/hbaseindex/StringIndexFieldDefinition.java | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
//
// Path: src/util/src/main/java/org/lilycms/util/LocaleHelper.java
// public class LocaleHelper {
// public static Locale parseLocale(String localeString) {
// StringTokenizer localeParser = new StringTokenizer(localeString, "-_");
//
// String lang = null, country = null, variant = null;
//
// if (localeParser.hasMoreTokens())
// lang = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// country = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// variant = localeParser.nextToken();
//
// if (lang != null && country != null && variant != null)
// return new Locale(lang, country, variant);
// else if (lang != null && country != null)
// return new Locale(lang, country);
// else if (lang != null)
// return new Locale(lang);
// else
// return new Locale("");
// }
//
// public static String getString(Locale locale) {
// return getString(locale, "_");
// }
//
// public static String getString(Locale locale, String separator) {
// boolean hasLanguage = !locale.getLanguage().equals("");
// boolean hasCountry = !locale.getCountry().equals("");
// boolean hasVariant = !locale.getVariant().equals("");
//
// if (hasLanguage && hasCountry && hasVariant)
// return locale.getLanguage() + separator + locale.getCountry() + separator + locale.getVariant();
// else if (hasLanguage && hasCountry)
// return locale.getLanguage() + separator + locale.getCountry();
// else if (hasLanguage)
// return locale.getLanguage();
// else
// return "";
// }
// }
| import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import org.lilycms.util.LocaleHelper;
import java.io.UnsupportedEncodingException;
import java.text.Collator;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* A string field in an index.
*
* <p>Strings can be of variable length, therefore the {#setLength} method returns -1.
*
* <p>Various options can be set for this field:
*
* <ul>
* <li>{@link #setByteEncodeMode}: the way a string should be mapped onto bytes: as utf8,
* by folding everything to ascii, or by using collation keys.
* <li>
* <li>{@link #setLocale}
* <li>{@link #setCaseSensitive}
* </ul>
*/
public class StringIndexFieldDefinition extends IndexFieldDefinition {
public enum ByteEncodeMode { UTF8, ASCII_FOLDING, COLLATOR }
private Locale locale = Locale.US;
private ByteEncodeMode byteEncodeMode = ByteEncodeMode.UTF8;
private boolean caseSensitive = true;
private static Map<ByteEncodeMode, StringEncoder> ENCODERS;
static {
ENCODERS = new HashMap<ByteEncodeMode, StringEncoder>();
ENCODERS.put(ByteEncodeMode.UTF8, new Utf8StringEncoder());
ENCODERS.put(ByteEncodeMode.ASCII_FOLDING, new AsciiFoldingStringEncoder());
ENCODERS.put(ByteEncodeMode.COLLATOR, new CollatorStringEncoder());
}
/**
* The end-of-field marker consists of all-zero-bits bytes. This is to achieve the effect
* that shorter strings would always sort before those that contain an additional character.
* Supposing a zero is an allowed byte within an encoded string, the further bytes should
* again be zeros for the same purpose.
*
* <p>This makes the assumption that a sequence of zero bytes will not occur in an encoded
* string (see also the toBytes method where this is checked, and where the same sequence is also hardcoded!)
*/
private static final byte[] EOF_MARKER = new byte[] {0, 0, 0, 0};
public StringIndexFieldDefinition(String name) {
super(name, IndexValueType.STRING);
}
public StringIndexFieldDefinition(String name, ObjectNode jsonObject) {
super(name, IndexValueType.STRING, jsonObject);
if (jsonObject.get("locale") != null) | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
//
// Path: src/util/src/main/java/org/lilycms/util/LocaleHelper.java
// public class LocaleHelper {
// public static Locale parseLocale(String localeString) {
// StringTokenizer localeParser = new StringTokenizer(localeString, "-_");
//
// String lang = null, country = null, variant = null;
//
// if (localeParser.hasMoreTokens())
// lang = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// country = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// variant = localeParser.nextToken();
//
// if (lang != null && country != null && variant != null)
// return new Locale(lang, country, variant);
// else if (lang != null && country != null)
// return new Locale(lang, country);
// else if (lang != null)
// return new Locale(lang);
// else
// return new Locale("");
// }
//
// public static String getString(Locale locale) {
// return getString(locale, "_");
// }
//
// public static String getString(Locale locale, String separator) {
// boolean hasLanguage = !locale.getLanguage().equals("");
// boolean hasCountry = !locale.getCountry().equals("");
// boolean hasVariant = !locale.getVariant().equals("");
//
// if (hasLanguage && hasCountry && hasVariant)
// return locale.getLanguage() + separator + locale.getCountry() + separator + locale.getVariant();
// else if (hasLanguage && hasCountry)
// return locale.getLanguage() + separator + locale.getCountry();
// else if (hasLanguage)
// return locale.getLanguage();
// else
// return "";
// }
// }
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/StringIndexFieldDefinition.java
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import org.lilycms.util.LocaleHelper;
import java.io.UnsupportedEncodingException;
import java.text.Collator;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* A string field in an index.
*
* <p>Strings can be of variable length, therefore the {#setLength} method returns -1.
*
* <p>Various options can be set for this field:
*
* <ul>
* <li>{@link #setByteEncodeMode}: the way a string should be mapped onto bytes: as utf8,
* by folding everything to ascii, or by using collation keys.
* <li>
* <li>{@link #setLocale}
* <li>{@link #setCaseSensitive}
* </ul>
*/
public class StringIndexFieldDefinition extends IndexFieldDefinition {
public enum ByteEncodeMode { UTF8, ASCII_FOLDING, COLLATOR }
private Locale locale = Locale.US;
private ByteEncodeMode byteEncodeMode = ByteEncodeMode.UTF8;
private boolean caseSensitive = true;
private static Map<ByteEncodeMode, StringEncoder> ENCODERS;
static {
ENCODERS = new HashMap<ByteEncodeMode, StringEncoder>();
ENCODERS.put(ByteEncodeMode.UTF8, new Utf8StringEncoder());
ENCODERS.put(ByteEncodeMode.ASCII_FOLDING, new AsciiFoldingStringEncoder());
ENCODERS.put(ByteEncodeMode.COLLATOR, new CollatorStringEncoder());
}
/**
* The end-of-field marker consists of all-zero-bits bytes. This is to achieve the effect
* that shorter strings would always sort before those that contain an additional character.
* Supposing a zero is an allowed byte within an encoded string, the further bytes should
* again be zeros for the same purpose.
*
* <p>This makes the assumption that a sequence of zero bytes will not occur in an encoded
* string (see also the toBytes method where this is checked, and where the same sequence is also hardcoded!)
*/
private static final byte[] EOF_MARKER = new byte[] {0, 0, 0, 0};
public StringIndexFieldDefinition(String name) {
super(name, IndexValueType.STRING);
}
public StringIndexFieldDefinition(String name, ObjectNode jsonObject) {
super(name, IndexValueType.STRING, jsonObject);
if (jsonObject.get("locale") != null) | this.locale = LocaleHelper.parseLocale(jsonObject.get("locale").getTextValue()); |
adragomir/hbase-indexing-library | src/hbaseindex/src/main/java/org/lilycms/hbaseindex/StringIndexFieldDefinition.java | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
//
// Path: src/util/src/main/java/org/lilycms/util/LocaleHelper.java
// public class LocaleHelper {
// public static Locale parseLocale(String localeString) {
// StringTokenizer localeParser = new StringTokenizer(localeString, "-_");
//
// String lang = null, country = null, variant = null;
//
// if (localeParser.hasMoreTokens())
// lang = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// country = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// variant = localeParser.nextToken();
//
// if (lang != null && country != null && variant != null)
// return new Locale(lang, country, variant);
// else if (lang != null && country != null)
// return new Locale(lang, country);
// else if (lang != null)
// return new Locale(lang);
// else
// return new Locale("");
// }
//
// public static String getString(Locale locale) {
// return getString(locale, "_");
// }
//
// public static String getString(Locale locale, String separator) {
// boolean hasLanguage = !locale.getLanguage().equals("");
// boolean hasCountry = !locale.getCountry().equals("");
// boolean hasVariant = !locale.getVariant().equals("");
//
// if (hasLanguage && hasCountry && hasVariant)
// return locale.getLanguage() + separator + locale.getCountry() + separator + locale.getVariant();
// else if (hasLanguage && hasCountry)
// return locale.getLanguage() + separator + locale.getCountry();
// else if (hasLanguage)
// return locale.getLanguage();
// else
// return "";
// }
// }
| import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import org.lilycms.util.LocaleHelper;
import java.io.UnsupportedEncodingException;
import java.text.Collator;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* A string field in an index.
*
* <p>Strings can be of variable length, therefore the {#setLength} method returns -1.
*
* <p>Various options can be set for this field:
*
* <ul>
* <li>{@link #setByteEncodeMode}: the way a string should be mapped onto bytes: as utf8,
* by folding everything to ascii, or by using collation keys.
* <li>
* <li>{@link #setLocale}
* <li>{@link #setCaseSensitive}
* </ul>
*/
public class StringIndexFieldDefinition extends IndexFieldDefinition {
public enum ByteEncodeMode { UTF8, ASCII_FOLDING, COLLATOR }
private Locale locale = Locale.US;
private ByteEncodeMode byteEncodeMode = ByteEncodeMode.UTF8;
private boolean caseSensitive = true;
private static Map<ByteEncodeMode, StringEncoder> ENCODERS;
static {
ENCODERS = new HashMap<ByteEncodeMode, StringEncoder>();
ENCODERS.put(ByteEncodeMode.UTF8, new Utf8StringEncoder());
ENCODERS.put(ByteEncodeMode.ASCII_FOLDING, new AsciiFoldingStringEncoder());
ENCODERS.put(ByteEncodeMode.COLLATOR, new CollatorStringEncoder());
}
/**
* The end-of-field marker consists of all-zero-bits bytes. This is to achieve the effect
* that shorter strings would always sort before those that contain an additional character.
* Supposing a zero is an allowed byte within an encoded string, the further bytes should
* again be zeros for the same purpose.
*
* <p>This makes the assumption that a sequence of zero bytes will not occur in an encoded
* string (see also the toBytes method where this is checked, and where the same sequence is also hardcoded!)
*/
private static final byte[] EOF_MARKER = new byte[] {0, 0, 0, 0};
public StringIndexFieldDefinition(String name) {
super(name, IndexValueType.STRING);
}
public StringIndexFieldDefinition(String name, ObjectNode jsonObject) {
super(name, IndexValueType.STRING, jsonObject);
if (jsonObject.get("locale") != null)
this.locale = LocaleHelper.parseLocale(jsonObject.get("locale").getTextValue());
if (jsonObject.get("byteEncodeMode") != null)
this.byteEncodeMode = ByteEncodeMode.valueOf(jsonObject.get("byteEncodeMode").getTextValue());
if (jsonObject.get("caseSensitive") != null)
this.caseSensitive = jsonObject.get("caseSensitive").getBooleanValue();
}
public Locale getLocale() {
return locale;
}
/**
* The Locale to use. This locale is used to fold the case when
* case sensitivity is not desired, and is used in case the
* {@link ByteEncodeMode#COLLATOR} mode is selected.
*/
public void setLocale(Locale locale) { | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
//
// Path: src/util/src/main/java/org/lilycms/util/LocaleHelper.java
// public class LocaleHelper {
// public static Locale parseLocale(String localeString) {
// StringTokenizer localeParser = new StringTokenizer(localeString, "-_");
//
// String lang = null, country = null, variant = null;
//
// if (localeParser.hasMoreTokens())
// lang = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// country = localeParser.nextToken();
// if (localeParser.hasMoreTokens())
// variant = localeParser.nextToken();
//
// if (lang != null && country != null && variant != null)
// return new Locale(lang, country, variant);
// else if (lang != null && country != null)
// return new Locale(lang, country);
// else if (lang != null)
// return new Locale(lang);
// else
// return new Locale("");
// }
//
// public static String getString(Locale locale) {
// return getString(locale, "_");
// }
//
// public static String getString(Locale locale, String separator) {
// boolean hasLanguage = !locale.getLanguage().equals("");
// boolean hasCountry = !locale.getCountry().equals("");
// boolean hasVariant = !locale.getVariant().equals("");
//
// if (hasLanguage && hasCountry && hasVariant)
// return locale.getLanguage() + separator + locale.getCountry() + separator + locale.getVariant();
// else if (hasLanguage && hasCountry)
// return locale.getLanguage() + separator + locale.getCountry();
// else if (hasLanguage)
// return locale.getLanguage();
// else
// return "";
// }
// }
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/StringIndexFieldDefinition.java
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import org.lilycms.util.LocaleHelper;
import java.io.UnsupportedEncodingException;
import java.text.Collator;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* A string field in an index.
*
* <p>Strings can be of variable length, therefore the {#setLength} method returns -1.
*
* <p>Various options can be set for this field:
*
* <ul>
* <li>{@link #setByteEncodeMode}: the way a string should be mapped onto bytes: as utf8,
* by folding everything to ascii, or by using collation keys.
* <li>
* <li>{@link #setLocale}
* <li>{@link #setCaseSensitive}
* </ul>
*/
public class StringIndexFieldDefinition extends IndexFieldDefinition {
public enum ByteEncodeMode { UTF8, ASCII_FOLDING, COLLATOR }
private Locale locale = Locale.US;
private ByteEncodeMode byteEncodeMode = ByteEncodeMode.UTF8;
private boolean caseSensitive = true;
private static Map<ByteEncodeMode, StringEncoder> ENCODERS;
static {
ENCODERS = new HashMap<ByteEncodeMode, StringEncoder>();
ENCODERS.put(ByteEncodeMode.UTF8, new Utf8StringEncoder());
ENCODERS.put(ByteEncodeMode.ASCII_FOLDING, new AsciiFoldingStringEncoder());
ENCODERS.put(ByteEncodeMode.COLLATOR, new CollatorStringEncoder());
}
/**
* The end-of-field marker consists of all-zero-bits bytes. This is to achieve the effect
* that shorter strings would always sort before those that contain an additional character.
* Supposing a zero is an allowed byte within an encoded string, the further bytes should
* again be zeros for the same purpose.
*
* <p>This makes the assumption that a sequence of zero bytes will not occur in an encoded
* string (see also the toBytes method where this is checked, and where the same sequence is also hardcoded!)
*/
private static final byte[] EOF_MARKER = new byte[] {0, 0, 0, 0};
public StringIndexFieldDefinition(String name) {
super(name, IndexValueType.STRING);
}
public StringIndexFieldDefinition(String name, ObjectNode jsonObject) {
super(name, IndexValueType.STRING, jsonObject);
if (jsonObject.get("locale") != null)
this.locale = LocaleHelper.parseLocale(jsonObject.get("locale").getTextValue());
if (jsonObject.get("byteEncodeMode") != null)
this.byteEncodeMode = ByteEncodeMode.valueOf(jsonObject.get("byteEncodeMode").getTextValue());
if (jsonObject.get("caseSensitive") != null)
this.caseSensitive = jsonObject.get("caseSensitive").getBooleanValue();
}
public Locale getLocale() {
return locale;
}
/**
* The Locale to use. This locale is used to fold the case when
* case sensitivity is not desired, and is used in case the
* {@link ByteEncodeMode#COLLATOR} mode is selected.
*/
public void setLocale(Locale locale) { | ArgumentValidator.notNull(locale, "locale"); |
adragomir/hbase-indexing-library | src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/IndexTest.java | // Path: src/testfw/src/main/java/org/lilycms/testfw/TestHelper.java
// public class TestHelper {
// /**
// * Sets up logging such that errors are logged to the console, and info level
// * logging is sent to a file in target directory.
// */
// public static void setupLogging() throws IOException {
// final String LAYOUT = "[%t] %-5p %c - %m%n";
//
// Logger logger = Logger.getRootLogger();
// logger.removeAllAppenders();
// logger.setLevel(Level.INFO);
//
// //
// // Log to a file
// //
// FileAppender appender = new FileAppender();
// appender.setLayout(new PatternLayout(LAYOUT));
//
// // Maven sets a property basedir, but if the testcases are run outside Maven (e.g. by an IDE),
// // then fall back to the working directory
// String targetDir = System.getProperty("basedir");
// if (targetDir == null)
// targetDir = System.getProperty("user.dir");
// String logFileName = targetDir + "/target/log.txt";
//
// System.out.println("Log output will go to " + logFileName);
//
// appender.setFile(logFileName, false, false, 0);
//
// appender.activateOptions();
// logger.addAppender(appender);
//
// //
// // Add a console appender to show ERROR level errors on the console
// //
// ConsoleAppender consoleAppender = new ConsoleAppender();
// consoleAppender.setLayout(new PatternLayout(LAYOUT));
//
// LevelRangeFilter errorFilter = new LevelRangeFilter();
// errorFilter.setAcceptOnMatch(true);
// errorFilter.setLevelMin(Level.ERROR);
// errorFilter.setLevelMax(Level.ERROR);
// consoleAppender.addFilter(errorFilter);
// consoleAppender.activateOptions();
//
// logger.addAppender(consoleAppender);
// }
// }
| import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.lilycms.hbaseindex.*;
import org.lilycms.testfw.TestHelper;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class IndexTest {
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
@BeforeClass
public static void setUpBeforeClass() throws Exception { | // Path: src/testfw/src/main/java/org/lilycms/testfw/TestHelper.java
// public class TestHelper {
// /**
// * Sets up logging such that errors are logged to the console, and info level
// * logging is sent to a file in target directory.
// */
// public static void setupLogging() throws IOException {
// final String LAYOUT = "[%t] %-5p %c - %m%n";
//
// Logger logger = Logger.getRootLogger();
// logger.removeAllAppenders();
// logger.setLevel(Level.INFO);
//
// //
// // Log to a file
// //
// FileAppender appender = new FileAppender();
// appender.setLayout(new PatternLayout(LAYOUT));
//
// // Maven sets a property basedir, but if the testcases are run outside Maven (e.g. by an IDE),
// // then fall back to the working directory
// String targetDir = System.getProperty("basedir");
// if (targetDir == null)
// targetDir = System.getProperty("user.dir");
// String logFileName = targetDir + "/target/log.txt";
//
// System.out.println("Log output will go to " + logFileName);
//
// appender.setFile(logFileName, false, false, 0);
//
// appender.activateOptions();
// logger.addAppender(appender);
//
// //
// // Add a console appender to show ERROR level errors on the console
// //
// ConsoleAppender consoleAppender = new ConsoleAppender();
// consoleAppender.setLayout(new PatternLayout(LAYOUT));
//
// LevelRangeFilter errorFilter = new LevelRangeFilter();
// errorFilter.setAcceptOnMatch(true);
// errorFilter.setLevelMin(Level.ERROR);
// errorFilter.setLevelMax(Level.ERROR);
// consoleAppender.addFilter(errorFilter);
// consoleAppender.activateOptions();
//
// logger.addAppender(consoleAppender);
// }
// }
// Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/IndexTest.java
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.lilycms.hbaseindex.*;
import org.lilycms.testfw.TestHelper;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class IndexTest {
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
@BeforeClass
public static void setUpBeforeClass() throws Exception { | TestHelper.setupLogging(); |
adragomir/hbase-indexing-library | src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/IdentifierEncodingTest.java | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IdentifierEncoding.java
// public class IdentifierEncoding {
// public static byte[] encode(byte[] bytes) {
// byte[] result = new byte[bytes.length + Bytes.SIZEOF_INT];
// System.arraycopy(bytes, 0, result, 0, bytes.length);
// Bytes.putInt(result, bytes.length, bytes.length);
// return result;
// }
//
// /**
// * Extracts the identifier from an index row key.
// *
// * @param bytes byte array containing an encoded row key at its end (and arbitrary bytes before that).
// * Note that this method modifies the bytes in case inverted is true!
// * @param inverted indicates if the bits in the row key are inverted (can be the case for descending ordering)
// */
// public static byte[] decode(byte[] bytes, boolean inverted) {
// if (inverted) {
// for (int i = 0; i < Bytes.SIZEOF_INT; i++) {
// int pos = bytes.length - i - 1;
// bytes[pos] = bytes[pos] ^= 0xFF;
// }
// }
//
// int keyLength = Bytes.toInt(bytes, bytes.length - Bytes.SIZEOF_INT);
// byte[] result = new byte[keyLength];
// System.arraycopy(bytes, bytes.length - keyLength - Bytes.SIZEOF_INT, result, 0, keyLength);
//
// if (inverted) {
// for (int j = 0; j < result.length; j++) {
// result[j] ^= 0xFF;
// }
// }
//
// return result;
// }
// }
| import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.IdentifierEncoding;
import static org.junit.Assert.*; | package org.lilycms.hbaseindex.test;
public class IdentifierEncodingTest {
@Test
public void test() {
byte[] key = Bytes.toBytes("foobar"); | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IdentifierEncoding.java
// public class IdentifierEncoding {
// public static byte[] encode(byte[] bytes) {
// byte[] result = new byte[bytes.length + Bytes.SIZEOF_INT];
// System.arraycopy(bytes, 0, result, 0, bytes.length);
// Bytes.putInt(result, bytes.length, bytes.length);
// return result;
// }
//
// /**
// * Extracts the identifier from an index row key.
// *
// * @param bytes byte array containing an encoded row key at its end (and arbitrary bytes before that).
// * Note that this method modifies the bytes in case inverted is true!
// * @param inverted indicates if the bits in the row key are inverted (can be the case for descending ordering)
// */
// public static byte[] decode(byte[] bytes, boolean inverted) {
// if (inverted) {
// for (int i = 0; i < Bytes.SIZEOF_INT; i++) {
// int pos = bytes.length - i - 1;
// bytes[pos] = bytes[pos] ^= 0xFF;
// }
// }
//
// int keyLength = Bytes.toInt(bytes, bytes.length - Bytes.SIZEOF_INT);
// byte[] result = new byte[keyLength];
// System.arraycopy(bytes, bytes.length - keyLength - Bytes.SIZEOF_INT, result, 0, keyLength);
//
// if (inverted) {
// for (int j = 0; j < result.length; j++) {
// result[j] ^= 0xFF;
// }
// }
//
// return result;
// }
// }
// Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/IdentifierEncodingTest.java
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.IdentifierEncoding;
import static org.junit.Assert.*;
package org.lilycms.hbaseindex.test;
public class IdentifierEncodingTest {
@Test
public void test() {
byte[] key = Bytes.toBytes("foobar"); | assertEquals("foobar", Bytes.toString(IdentifierEncoding.decode(IdentifierEncoding.encode(key), false))); |
adragomir/hbase-indexing-library | src/hbaseindex/src/main/java/org/lilycms/hbaseindex/DateTimeIndexFieldDefinition.java | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
| import org.apache.hadoop.hbase.util.Bytes;
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import java.util.*; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Index field for datetimes, dates, times.
*
* <p>The instant is stored in the index as a long, or in case there is only a time
* component, as an integer.
*
* <p>This class accepts java.util.Date as date/time representation. It is up to the
* user to make sure any timezone corrections have happened already.
*/
public class DateTimeIndexFieldDefinition extends IndexFieldDefinition {
public enum Precision {DATETIME, DATETIME_NOMILLIS, DATE, TIME, TIME_NOMILLIS}
private Precision precision = Precision.DATETIME_NOMILLIS;
public DateTimeIndexFieldDefinition(String name) {
super(name, IndexValueType.DATETIME);
}
public DateTimeIndexFieldDefinition(String name, ObjectNode jsonObject) {
super(name, IndexValueType.DATETIME);
if (jsonObject.get("precision") != null)
this.precision = Precision.valueOf(jsonObject.get("precision").getTextValue());
}
public Precision getPrecision() {
return precision;
}
public void setPrecision(Precision precision) { | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/DateTimeIndexFieldDefinition.java
import org.apache.hadoop.hbase.util.Bytes;
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import java.util.*;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Index field for datetimes, dates, times.
*
* <p>The instant is stored in the index as a long, or in case there is only a time
* component, as an integer.
*
* <p>This class accepts java.util.Date as date/time representation. It is up to the
* user to make sure any timezone corrections have happened already.
*/
public class DateTimeIndexFieldDefinition extends IndexFieldDefinition {
public enum Precision {DATETIME, DATETIME_NOMILLIS, DATE, TIME, TIME_NOMILLIS}
private Precision precision = Precision.DATETIME_NOMILLIS;
public DateTimeIndexFieldDefinition(String name) {
super(name, IndexValueType.DATETIME);
}
public DateTimeIndexFieldDefinition(String name, ObjectNode jsonObject) {
super(name, IndexValueType.DATETIME);
if (jsonObject.get("precision") != null)
this.precision = Precision.valueOf(jsonObject.get("precision").getTextValue());
}
public Precision getPrecision() {
return precision;
}
public void setPrecision(Precision precision) { | ArgumentValidator.notNull(precision, "precision"); |
adragomir/hbase-indexing-library | src/util/src/main/java/org/lilycms/util/location/LocationImpl.java | // Path: src/util/src/main/java/org/lilycms/util/ObjectUtils.java
// public class ObjectUtils {
// public static boolean safeEquals(Object obj1, Object obj2) {
// if (obj1 == null && obj2 == null)
// return true;
// else if (obj1 == null || obj2 == null)
// return false;
// else
// return obj1.equals(obj2);
// }
// }
| import org.lilycms.util.ObjectUtils;
import java.io.Serializable; | return this.uri;
}
/**
* Get the line number of this location
*
* @return the line number (<code>-1</code> if unknown)
*/
public int getLineNumber() {
return this.line;
}
/**
* Get the column number of this location
*
* @return the column number (<code>-1</code> if unknown)
*/
public int getColumnNumber() {
return this.column;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Location) {
Location other = (Location) obj;
return this.line == other.getLineNumber() &&
this.column == other.getColumnNumber() && | // Path: src/util/src/main/java/org/lilycms/util/ObjectUtils.java
// public class ObjectUtils {
// public static boolean safeEquals(Object obj1, Object obj2) {
// if (obj1 == null && obj2 == null)
// return true;
// else if (obj1 == null || obj2 == null)
// return false;
// else
// return obj1.equals(obj2);
// }
// }
// Path: src/util/src/main/java/org/lilycms/util/location/LocationImpl.java
import org.lilycms.util.ObjectUtils;
import java.io.Serializable;
return this.uri;
}
/**
* Get the line number of this location
*
* @return the line number (<code>-1</code> if unknown)
*/
public int getLineNumber() {
return this.line;
}
/**
* Get the column number of this location
*
* @return the column number (<code>-1</code> if unknown)
*/
public int getColumnNumber() {
return this.column;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Location) {
Location other = (Location) obj;
return this.line == other.getLineNumber() &&
this.column == other.getColumnNumber() && | ObjectUtils.safeEquals(this.uri, other.getURI()) && |
adragomir/hbase-indexing-library | src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IndexDefinition.java | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
| import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import java.lang.reflect.Constructor;
import java.util.*; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Defines the structure of an index.
*
* <p>An index is defined by instantiating an object of this class, adding one
* or more fields to it using the methods like {@link #addStringField},
* {@link #addIntegerField}, etc. Finally the index is created by calling
* {@link IndexManager#createIndex}. After creation, the definition of an index
* cannot be modified.
*/
public class IndexDefinition {
private String table;
private String name;
private List<IndexFieldDefinition> fields = new ArrayList<IndexFieldDefinition>();
private Map<String, IndexFieldDefinition> fieldsByName = new HashMap<String, IndexFieldDefinition>();
private Order identifierOrder = Order.ASCENDING;
public IndexDefinition(String table, String name) { | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IndexDefinition.java
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
import java.lang.reflect.Constructor;
import java.util.*;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Defines the structure of an index.
*
* <p>An index is defined by instantiating an object of this class, adding one
* or more fields to it using the methods like {@link #addStringField},
* {@link #addIntegerField}, etc. Finally the index is created by calling
* {@link IndexManager#createIndex}. After creation, the definition of an index
* cannot be modified.
*/
public class IndexDefinition {
private String table;
private String name;
private List<IndexFieldDefinition> fields = new ArrayList<IndexFieldDefinition>();
private Map<String, IndexFieldDefinition> fieldsByName = new HashMap<String, IndexFieldDefinition>();
private Order identifierOrder = Order.ASCENDING;
public IndexDefinition(String table, String name) { | ArgumentValidator.notNull(name, "table"); |
adragomir/hbase-indexing-library | src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java
// public class Conjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
//
// public Conjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// byte[] key1 = result1.next();
// byte[] key2 = result2.next();
//
// if (key1 == null || key2 == null)
// return null;
//
// int cmp = Bytes.compareTo(key1, key2);
//
// while (cmp != 0) {
// if (cmp < 0) {
// while (cmp < 0) {
// key1 = result1.next();
// if (key1 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// } else if (cmp > 0) {
// while (cmp > 0) {
// key2 = result2.next();
// if (key2 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// }
// }
//
// currentQResult = result1;
// return key1;
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java
// public class Disjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
// private byte[] key1;
// private byte[] key2;
// private boolean init = false;
//
// public Disjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// if (!init) {
// key1 = result1.next();
// key2 = result2.next();
// init = true;
// }
//
// if (key1 == null && key2 == null) {
// return null;
// } else if (key1 == null) {
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// } else if (key2 == null) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// }
//
// int cmp = Bytes.compareTo(key1, key2);
//
// if (cmp == 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// key2 = result2.next();
// return result;
// } else if (cmp < 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// } else { // cmp > 0
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// }
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java
// public interface QueryResult {
//
// /**
// * Move to and return the next result.
// *
// * @return the identifier of the next matching query result, or null if the end is reached.
// */
// public byte[] next() throws IOException;
//
// /**
// * Retrieves data that was stored as part of the {@link IndexEntry} from the current index
// * entry (corresponding to the last {@link #next} call).
// */
// public byte[] getData(byte[] qualifier);
//
// public byte[] getData(String qualifier);
//
// public String getDataAsString(String qualifier);
// }
| import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.Conjunction;
import org.lilycms.hbaseindex.Disjunction;
import org.lilycms.hbaseindex.QueryResult;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class MergeJoinTest {
@Test
public void testConjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
| // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java
// public class Conjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
//
// public Conjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// byte[] key1 = result1.next();
// byte[] key2 = result2.next();
//
// if (key1 == null || key2 == null)
// return null;
//
// int cmp = Bytes.compareTo(key1, key2);
//
// while (cmp != 0) {
// if (cmp < 0) {
// while (cmp < 0) {
// key1 = result1.next();
// if (key1 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// } else if (cmp > 0) {
// while (cmp > 0) {
// key2 = result2.next();
// if (key2 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// }
// }
//
// currentQResult = result1;
// return key1;
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java
// public class Disjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
// private byte[] key1;
// private byte[] key2;
// private boolean init = false;
//
// public Disjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// if (!init) {
// key1 = result1.next();
// key2 = result2.next();
// init = true;
// }
//
// if (key1 == null && key2 == null) {
// return null;
// } else if (key1 == null) {
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// } else if (key2 == null) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// }
//
// int cmp = Bytes.compareTo(key1, key2);
//
// if (cmp == 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// key2 = result2.next();
// return result;
// } else if (cmp < 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// } else { // cmp > 0
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// }
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java
// public interface QueryResult {
//
// /**
// * Move to and return the next result.
// *
// * @return the identifier of the next matching query result, or null if the end is reached.
// */
// public byte[] next() throws IOException;
//
// /**
// * Retrieves data that was stored as part of the {@link IndexEntry} from the current index
// * entry (corresponding to the last {@link #next} call).
// */
// public byte[] getData(byte[] qualifier);
//
// public byte[] getData(String qualifier);
//
// public String getDataAsString(String qualifier);
// }
// Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.Conjunction;
import org.lilycms.hbaseindex.Disjunction;
import org.lilycms.hbaseindex.QueryResult;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class MergeJoinTest {
@Test
public void testConjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
| QueryResult result = new Conjunction(buildQueryResult(values1), buildQueryResult(values2)); |
adragomir/hbase-indexing-library | src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java
// public class Conjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
//
// public Conjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// byte[] key1 = result1.next();
// byte[] key2 = result2.next();
//
// if (key1 == null || key2 == null)
// return null;
//
// int cmp = Bytes.compareTo(key1, key2);
//
// while (cmp != 0) {
// if (cmp < 0) {
// while (cmp < 0) {
// key1 = result1.next();
// if (key1 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// } else if (cmp > 0) {
// while (cmp > 0) {
// key2 = result2.next();
// if (key2 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// }
// }
//
// currentQResult = result1;
// return key1;
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java
// public class Disjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
// private byte[] key1;
// private byte[] key2;
// private boolean init = false;
//
// public Disjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// if (!init) {
// key1 = result1.next();
// key2 = result2.next();
// init = true;
// }
//
// if (key1 == null && key2 == null) {
// return null;
// } else if (key1 == null) {
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// } else if (key2 == null) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// }
//
// int cmp = Bytes.compareTo(key1, key2);
//
// if (cmp == 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// key2 = result2.next();
// return result;
// } else if (cmp < 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// } else { // cmp > 0
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// }
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java
// public interface QueryResult {
//
// /**
// * Move to and return the next result.
// *
// * @return the identifier of the next matching query result, or null if the end is reached.
// */
// public byte[] next() throws IOException;
//
// /**
// * Retrieves data that was stored as part of the {@link IndexEntry} from the current index
// * entry (corresponding to the last {@link #next} call).
// */
// public byte[] getData(byte[] qualifier);
//
// public byte[] getData(String qualifier);
//
// public String getDataAsString(String qualifier);
// }
| import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.Conjunction;
import org.lilycms.hbaseindex.Disjunction;
import org.lilycms.hbaseindex.QueryResult;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class MergeJoinTest {
@Test
public void testConjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
| // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java
// public class Conjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
//
// public Conjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// byte[] key1 = result1.next();
// byte[] key2 = result2.next();
//
// if (key1 == null || key2 == null)
// return null;
//
// int cmp = Bytes.compareTo(key1, key2);
//
// while (cmp != 0) {
// if (cmp < 0) {
// while (cmp < 0) {
// key1 = result1.next();
// if (key1 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// } else if (cmp > 0) {
// while (cmp > 0) {
// key2 = result2.next();
// if (key2 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// }
// }
//
// currentQResult = result1;
// return key1;
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java
// public class Disjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
// private byte[] key1;
// private byte[] key2;
// private boolean init = false;
//
// public Disjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// if (!init) {
// key1 = result1.next();
// key2 = result2.next();
// init = true;
// }
//
// if (key1 == null && key2 == null) {
// return null;
// } else if (key1 == null) {
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// } else if (key2 == null) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// }
//
// int cmp = Bytes.compareTo(key1, key2);
//
// if (cmp == 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// key2 = result2.next();
// return result;
// } else if (cmp < 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// } else { // cmp > 0
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// }
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java
// public interface QueryResult {
//
// /**
// * Move to and return the next result.
// *
// * @return the identifier of the next matching query result, or null if the end is reached.
// */
// public byte[] next() throws IOException;
//
// /**
// * Retrieves data that was stored as part of the {@link IndexEntry} from the current index
// * entry (corresponding to the last {@link #next} call).
// */
// public byte[] getData(byte[] qualifier);
//
// public byte[] getData(String qualifier);
//
// public String getDataAsString(String qualifier);
// }
// Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.Conjunction;
import org.lilycms.hbaseindex.Disjunction;
import org.lilycms.hbaseindex.QueryResult;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class MergeJoinTest {
@Test
public void testConjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
| QueryResult result = new Conjunction(buildQueryResult(values1), buildQueryResult(values2)); |
adragomir/hbase-indexing-library | src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java
// public class Conjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
//
// public Conjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// byte[] key1 = result1.next();
// byte[] key2 = result2.next();
//
// if (key1 == null || key2 == null)
// return null;
//
// int cmp = Bytes.compareTo(key1, key2);
//
// while (cmp != 0) {
// if (cmp < 0) {
// while (cmp < 0) {
// key1 = result1.next();
// if (key1 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// } else if (cmp > 0) {
// while (cmp > 0) {
// key2 = result2.next();
// if (key2 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// }
// }
//
// currentQResult = result1;
// return key1;
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java
// public class Disjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
// private byte[] key1;
// private byte[] key2;
// private boolean init = false;
//
// public Disjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// if (!init) {
// key1 = result1.next();
// key2 = result2.next();
// init = true;
// }
//
// if (key1 == null && key2 == null) {
// return null;
// } else if (key1 == null) {
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// } else if (key2 == null) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// }
//
// int cmp = Bytes.compareTo(key1, key2);
//
// if (cmp == 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// key2 = result2.next();
// return result;
// } else if (cmp < 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// } else { // cmp > 0
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// }
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java
// public interface QueryResult {
//
// /**
// * Move to and return the next result.
// *
// * @return the identifier of the next matching query result, or null if the end is reached.
// */
// public byte[] next() throws IOException;
//
// /**
// * Retrieves data that was stored as part of the {@link IndexEntry} from the current index
// * entry (corresponding to the last {@link #next} call).
// */
// public byte[] getData(byte[] qualifier);
//
// public byte[] getData(String qualifier);
//
// public String getDataAsString(String qualifier);
// }
| import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.Conjunction;
import org.lilycms.hbaseindex.Disjunction;
import org.lilycms.hbaseindex.QueryResult;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class MergeJoinTest {
@Test
public void testConjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
QueryResult result = new Conjunction(buildQueryResult(values1), buildQueryResult(values2));
assertEquals("b", Bytes.toString(result.next()));
assertEquals("c", Bytes.toString(result.next()));
assertEquals("f", Bytes.toString(result.next()));
assertNull(result.next());
}
@Test
public void testDisjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
| // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java
// public class Conjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
//
// public Conjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// byte[] key1 = result1.next();
// byte[] key2 = result2.next();
//
// if (key1 == null || key2 == null)
// return null;
//
// int cmp = Bytes.compareTo(key1, key2);
//
// while (cmp != 0) {
// if (cmp < 0) {
// while (cmp < 0) {
// key1 = result1.next();
// if (key1 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// } else if (cmp > 0) {
// while (cmp > 0) {
// key2 = result2.next();
// if (key2 == null)
// return null;
// cmp = Bytes.compareTo(key1, key2);
// }
// }
// }
//
// currentQResult = result1;
// return key1;
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java
// public class Disjunction extends BaseQueryResult {
// private QueryResult result1;
// private QueryResult result2;
// private byte[] key1;
// private byte[] key2;
// private boolean init = false;
//
// public Disjunction(QueryResult result1, QueryResult result2) {
// this.result1 = result1;
// this.result2 = result2;
// }
//
// public byte[] next() throws IOException {
// if (!init) {
// key1 = result1.next();
// key2 = result2.next();
// init = true;
// }
//
// if (key1 == null && key2 == null) {
// return null;
// } else if (key1 == null) {
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// } else if (key2 == null) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// }
//
// int cmp = Bytes.compareTo(key1, key2);
//
// if (cmp == 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// key2 = result2.next();
// return result;
// } else if (cmp < 0) {
// byte[] result = key1;
// currentQResult = result1;
// key1 = result1.next();
// return result;
// } else { // cmp > 0
// byte[] result = key2;
// currentQResult = result2;
// key2 = result2.next();
// return result;
// }
// }
// }
//
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java
// public interface QueryResult {
//
// /**
// * Move to and return the next result.
// *
// * @return the identifier of the next matching query result, or null if the end is reached.
// */
// public byte[] next() throws IOException;
//
// /**
// * Retrieves data that was stored as part of the {@link IndexEntry} from the current index
// * entry (corresponding to the last {@link #next} call).
// */
// public byte[] getData(byte[] qualifier);
//
// public byte[] getData(String qualifier);
//
// public String getDataAsString(String qualifier);
// }
// Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.Conjunction;
import org.lilycms.hbaseindex.Disjunction;
import org.lilycms.hbaseindex.QueryResult;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex.test;
public class MergeJoinTest {
@Test
public void testConjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
QueryResult result = new Conjunction(buildQueryResult(values1), buildQueryResult(values2));
assertEquals("b", Bytes.toString(result.next()));
assertEquals("c", Bytes.toString(result.next()));
assertEquals("f", Bytes.toString(result.next()));
assertNull(result.next());
}
@Test
public void testDisjunction() throws Exception {
String[] values1 = {"a", "b", "c", "f", "g"};
String[] values2 = { "b", "c", "d", "e", "f"};
| QueryResult result = new Disjunction(buildQueryResult(values1), buildQueryResult(values2)); |
adragomir/hbase-indexing-library | src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IndexFieldDefinition.java | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
| import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Defines a field that is part of an {@link IndexDefinition}.
*/
public abstract class IndexFieldDefinition {
private final String name;
private Order order;
private IndexValueType type;
private static final byte[] EOF_MARKER = new byte[0];
public IndexFieldDefinition(String name, IndexValueType type) {
this(name, type, Order.ASCENDING);
}
public IndexFieldDefinition(String name, IndexValueType type, Order order) {
this.name = name;
this.order = order;
this.type = type;
}
public IndexFieldDefinition(String name, IndexValueType type, ObjectNode jsonObject) {
this(name, type);
if (jsonObject.get("order") != null)
this.order = Order.valueOf(jsonObject.get("order").getTextValue());
}
public String getName() {
return name;
}
public IndexValueType getType() {
return type;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) { | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IndexFieldDefinition.java
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.lilycms.util.ArgumentValidator;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Defines a field that is part of an {@link IndexDefinition}.
*/
public abstract class IndexFieldDefinition {
private final String name;
private Order order;
private IndexValueType type;
private static final byte[] EOF_MARKER = new byte[0];
public IndexFieldDefinition(String name, IndexValueType type) {
this(name, type, Order.ASCENDING);
}
public IndexFieldDefinition(String name, IndexValueType type, Order order) {
this.name = name;
this.order = order;
this.type = type;
}
public IndexFieldDefinition(String name, IndexValueType type, ObjectNode jsonObject) {
this(name, type);
if (jsonObject.get("order") != null)
this.order = Order.valueOf(jsonObject.get("order").getTextValue());
}
public String getName() {
return name;
}
public IndexValueType getType() {
return type;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) { | ArgumentValidator.notNull(order, "order"); |
adragomir/hbase-indexing-library | src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Index.java | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
| import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.util.Bytes;
import org.lilycms.util.ArgumentValidator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Allows to query an index, and add entries to it or remove entries from it.
*
* <p>An Index instance can be obtained from {@link IndexManager#getIndex}.
*
* <p>The Index class <b>is not thread safe</b> for writes, because the underlying
* HBase HTable is not thread safe for writes.
*
*/
public class Index {
private HTable htable;
private IndexDefinition definition;
protected static final byte[] DATA_FAMILY = Bytes.toBytes("data");
private static final byte[] DUMMY_QUALIFIER = Bytes.toBytes("dummy");
private static final byte[] DUMMY_VALUE = Bytes.toBytes("dummy");
/** Number of bytes overhead per field. */
private static final int FIELD_FLAGS_SIZE = 1;
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
protected Index(HTable htable, IndexDefinition definition) {
this.htable = htable;
this.definition = definition;
}
/**
* Adds an entry to this index. See {@link IndexEntry} for more information.
*
* @param entry the values to be part of the index key, should correspond to the fields
* defined in the {@link IndexDefinition}
* @param identifier the identifier of the indexed object, typically the key of a row in
* another HBase table
*/
public void addEntry(IndexEntry entry, byte[] identifier) throws IOException { | // Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java
// public class ArgumentValidator {
// public static void notNull(Object object, String argName) {
// if (object == null)
// throw new IllegalArgumentException("Null argument: " + argName);
// }
// }
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Index.java
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.util.Bytes;
import org.lilycms.util.ArgumentValidator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
* Copyright 2010 Outerthought bvba
*
* 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.lilycms.hbaseindex;
/**
* Allows to query an index, and add entries to it or remove entries from it.
*
* <p>An Index instance can be obtained from {@link IndexManager#getIndex}.
*
* <p>The Index class <b>is not thread safe</b> for writes, because the underlying
* HBase HTable is not thread safe for writes.
*
*/
public class Index {
private HTable htable;
private IndexDefinition definition;
protected static final byte[] DATA_FAMILY = Bytes.toBytes("data");
private static final byte[] DUMMY_QUALIFIER = Bytes.toBytes("dummy");
private static final byte[] DUMMY_VALUE = Bytes.toBytes("dummy");
/** Number of bytes overhead per field. */
private static final int FIELD_FLAGS_SIZE = 1;
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
protected Index(HTable htable, IndexDefinition definition) {
this.htable = htable;
this.definition = definition;
}
/**
* Adds an entry to this index. See {@link IndexEntry} for more information.
*
* @param entry the values to be part of the index key, should correspond to the fields
* defined in the {@link IndexDefinition}
* @param identifier the identifier of the indexed object, typically the key of a row in
* another HBase table
*/
public void addEntry(IndexEntry entry, byte[] identifier) throws IOException { | ArgumentValidator.notNull(entry, "entry"); |
adragomir/hbase-indexing-library | src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/ByteComparisonTest.java | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/DateTimeIndexFieldDefinition.java
// public enum Precision {DATETIME, DATETIME_NOMILLIS, DATE, TIME, TIME_NOMILLIS}
| import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.*;
import org.lilycms.hbaseindex.DateTimeIndexFieldDefinition.Precision;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals; | }
}
}
}
// Verify cutoff of precision
DecimalIndexFieldDefinition fieldDef = new DecimalIndexFieldDefinition("foobar");
fieldDef.setLength(5);
byte[] r1 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000001"));
byte[] r2 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000002"));
assertEquals(5, r1.length);
assertEquals(5, r2.length);
assertEquals(0, Bytes.compareTo(r1, r2));
// Verify checks on maximum supported exponents
try {
toSortableBytes(new BigDecimal("0.1E16384"));
fail("Expected error");
} catch (RuntimeException e) {}
try {
toSortableBytes(new BigDecimal("0.1E-16385"));
fail("Expected error");
} catch (RuntimeException e) {}
}
@Test
public void testDateCompare() throws Exception { | // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/DateTimeIndexFieldDefinition.java
// public enum Precision {DATETIME, DATETIME_NOMILLIS, DATE, TIME, TIME_NOMILLIS}
// Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/ByteComparisonTest.java
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.lilycms.hbaseindex.*;
import org.lilycms.hbaseindex.DateTimeIndexFieldDefinition.Precision;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
}
}
}
}
// Verify cutoff of precision
DecimalIndexFieldDefinition fieldDef = new DecimalIndexFieldDefinition("foobar");
fieldDef.setLength(5);
byte[] r1 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000001"));
byte[] r2 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000002"));
assertEquals(5, r1.length);
assertEquals(5, r2.length);
assertEquals(0, Bytes.compareTo(r1, r2));
// Verify checks on maximum supported exponents
try {
toSortableBytes(new BigDecimal("0.1E16384"));
fail("Expected error");
} catch (RuntimeException e) {}
try {
toSortableBytes(new BigDecimal("0.1E-16385"));
fail("Expected error");
} catch (RuntimeException e) {}
}
@Test
public void testDateCompare() throws Exception { | byte[] bytes1 = date(Precision.DATE, 2010, 2, 1, 14, 20, 10, 333); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/utils/Functions.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Streams.java
// public static <T> Stream<T> asStream(Iterable<T> iterable) {
// return asStream(iterable, false);
// }
| import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.pugnascotia.reactdemo.utils.Streams.asStream; | package com.pugnascotia.reactdemo.utils;
/**
* Utility methods for making it easier to map over a Java list.
*/
public final class Functions {
public static <T,V> List<V> map(final List<T> in, final Function<T, V> function) {
return in == null ? null : map(in.stream(), function);
}
public static <T,V> List<V> map(final Stream<T> in, final Function<T, V> function) {
return in == null ? null : in
.map(function)
.collect(Collectors.toList());
}
public static <T,V> List<V> map(final Iterable<T> in, final Function<T, V> function) { | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Streams.java
// public static <T> Stream<T> asStream(Iterable<T> iterable) {
// return asStream(iterable, false);
// }
// Path: src/main/java/com/pugnascotia/reactdemo/utils/Functions.java
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.pugnascotia.reactdemo.utils.Streams.asStream;
package com.pugnascotia.reactdemo.utils;
/**
* Utility methods for making it easier to map over a Java list.
*/
public final class Functions {
public static <T,V> List<V> map(final List<T> in, final Function<T, V> function) {
return in == null ? null : map(in.stream(), function);
}
public static <T,V> List<V> map(final Stream<T> in, final Function<T, V> function) {
return in == null ? null : in
.map(function)
.collect(Collectors.toList());
}
public static <T,V> List<V> map(final Iterable<T> in, final Function<T, V> function) { | return map(asStream(in), function); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/home/HomeController.java | // Path: src/main/java/com/pugnascotia/reactdemo/comments/CommentRepository.java
// public interface CommentRepository {
//
// Iterable<Comment> findAll();
//
// Comment save(Comment comment);
//
// Comment find(Long id);
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
| import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import com.pugnascotia.reactdemo.comments.CommentRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
import static org.springframework.web.bind.annotation.RequestMethod.GET; | package com.pugnascotia.reactdemo.home;
/**
* Renders the home page. It loads all the comments in the repository
* and passes them to the render context in the same shape that Redux
* uses.
*/
@Controller
public class HomeController {
| // Path: src/main/java/com/pugnascotia/reactdemo/comments/CommentRepository.java
// public interface CommentRepository {
//
// Iterable<Comment> findAll();
//
// Comment save(Comment comment);
//
// Comment find(Long id);
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
// Path: src/main/java/com/pugnascotia/reactdemo/home/HomeController.java
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import com.pugnascotia.reactdemo.comments.CommentRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
package com.pugnascotia.reactdemo.home;
/**
* Renders the home page. It loads all the comments in the repository
* and passes them to the render context in the same shape that Redux
* uses.
*/
@Controller
public class HomeController {
| private final CommentRepository repository; |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/home/HomeController.java | // Path: src/main/java/com/pugnascotia/reactdemo/comments/CommentRepository.java
// public interface CommentRepository {
//
// Iterable<Comment> findAll();
//
// Comment save(Comment comment);
//
// Comment find(Long id);
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
| import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import com.pugnascotia.reactdemo.comments.CommentRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
import static org.springframework.web.bind.annotation.RequestMethod.GET; | package com.pugnascotia.reactdemo.home;
/**
* Renders the home page. It loads all the comments in the repository
* and passes them to the render context in the same shape that Redux
* uses.
*/
@Controller
public class HomeController {
private final CommentRepository repository;
@Inject
public HomeController(CommentRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/", method = GET)
public String index(Model model, HttpServletRequest request) { | // Path: src/main/java/com/pugnascotia/reactdemo/comments/CommentRepository.java
// public interface CommentRepository {
//
// Iterable<Comment> findAll();
//
// Comment save(Comment comment);
//
// Comment find(Long id);
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
// Path: src/main/java/com/pugnascotia/reactdemo/home/HomeController.java
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import com.pugnascotia.reactdemo.comments.CommentRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
package com.pugnascotia.reactdemo.home;
/**
* Renders the home page. It loads all the comments in the repository
* and passes them to the render context in the same shape that Redux
* uses.
*/
@Controller
public class HomeController {
private final CommentRepository repository;
@Inject
public HomeController(CommentRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/", method = GET)
public String index(Model model, HttpServletRequest request) { | populateModel(model, request); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/config/CsrfHeaderFilter.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Cookies.java
// public final class Cookies {
//
// public static final String XSRF_TOKEN_NAME = "XSRF-TOKEN";
//
// /** Ensures that if a request does not supply a CSRF token in a cookie, or
// * if the token is not up-to-date, we set it in our response so that subsequent
// * requests can succeed. */
// public static void setSecurityTokens(HttpServletRequest request, HttpServletResponse response) {
// CsrfToken csrf = (CsrfToken) request.getAttribute("_csrf");
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, XSRF_TOKEN_NAME);
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie(XSRF_TOKEN_NAME, token);
// cookie.setPath("/");
// cookie.setHttpOnly(false);
// response.addCookie(cookie);
// }
// }
// }
// }
| import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import com.pugnascotia.reactdemo.utils.Cookies; | package com.pugnascotia.reactdemo.config;
/**
* This filter ensures that if a request does not supply a CSRF token in a cookie,
* or if the token is not up-to-date, we set it in our response so that subsequent
* requests can succeed.
*/
class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Cookies.java
// public final class Cookies {
//
// public static final String XSRF_TOKEN_NAME = "XSRF-TOKEN";
//
// /** Ensures that if a request does not supply a CSRF token in a cookie, or
// * if the token is not up-to-date, we set it in our response so that subsequent
// * requests can succeed. */
// public static void setSecurityTokens(HttpServletRequest request, HttpServletResponse response) {
// CsrfToken csrf = (CsrfToken) request.getAttribute("_csrf");
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, XSRF_TOKEN_NAME);
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie(XSRF_TOKEN_NAME, token);
// cookie.setPath("/");
// cookie.setHttpOnly(false);
// response.addCookie(cookie);
// }
// }
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/config/CsrfHeaderFilter.java
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import com.pugnascotia.reactdemo.utils.Cookies;
package com.pugnascotia.reactdemo.config;
/**
* This filter ensures that if a request does not supply a CSRF token in a cookie,
* or if the token is not up-to-date, we set it in our response so that subsequent
* requests can succeed.
*/
class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | Cookies.setSecurityTokens(request, response); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/comments/CommentResource.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Functions.java
// public final class Functions {
//
// public static <T,V> List<V> map(final List<T> in, final Function<T, V> function) {
// return in == null ? null : map(in.stream(), function);
// }
//
// public static <T,V> List<V> map(final Stream<T> in, final Function<T, V> function) {
// return in == null ? null : in
// .map(function)
// .collect(Collectors.toList());
// }
//
// public static <T,V> List<V> map(final Iterable<T> in, final Function<T, V> function) {
// return map(asStream(in), function);
// }
// }
| import java.util.List;
import javax.inject.Inject;
import com.pugnascotia.reactdemo.utils.Functions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST; | package com.pugnascotia.reactdemo.comments;
/**
* Handles creating new comments and fetching all comments via AJAX.
*/
@RestController
@RequestMapping(value = "/api", produces = APPLICATION_JSON_VALUE)
@Slf4j
public class CommentResource {
private final CommentRepository repository;
@Inject
public CommentResource(CommentRepository repository) {
this.repository = repository;
}
@RequestMapping(path = "/comments", method = POST)
public Comment add(@RequestBody Comment comment) {
log.info("{}", comment);
return repository.save(comment);
}
@RequestMapping(path = "/comments", method = GET)
public List<Comment> comments() {
// You shouldn't do this in a real app - you should page the data! | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Functions.java
// public final class Functions {
//
// public static <T,V> List<V> map(final List<T> in, final Function<T, V> function) {
// return in == null ? null : map(in.stream(), function);
// }
//
// public static <T,V> List<V> map(final Stream<T> in, final Function<T, V> function) {
// return in == null ? null : in
// .map(function)
// .collect(Collectors.toList());
// }
//
// public static <T,V> List<V> map(final Iterable<T> in, final Function<T, V> function) {
// return map(asStream(in), function);
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/comments/CommentResource.java
import java.util.List;
import javax.inject.Inject;
import com.pugnascotia.reactdemo.utils.Functions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
package com.pugnascotia.reactdemo.comments;
/**
* Handles creating new comments and fetching all comments via AJAX.
*/
@RestController
@RequestMapping(value = "/api", produces = APPLICATION_JSON_VALUE)
@Slf4j
public class CommentResource {
private final CommentRepository repository;
@Inject
public CommentResource(CommentRepository repository) {
this.repository = repository;
}
@RequestMapping(path = "/comments", method = POST)
public Comment add(@RequestBody Comment comment) {
log.info("{}", comment);
return repository.save(comment);
}
@RequestMapping(path = "/comments", method = GET)
public List<Comment> comments() {
// You shouldn't do this in a real app - you should page the data! | return Functions.map(repository.findAll(), c -> c); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/account/AccountResource.java | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
| import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler;
import com.pugnascotia.reactdemo.utils.State;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; | package com.pugnascotia.reactdemo.account;
/**
* Returns the user's current authentication status.
*
* @see AjaxLogoutSuccessHandler for how this is used.
*/
@RestController
@RequestMapping(value = "/api", produces = APPLICATION_JSON_VALUE)
public class AccountResource {
@RequestMapping("/account")
public Map<String,Object> getAccountStatus(HttpServletRequest request) { | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/account/AccountResource.java
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler;
import com.pugnascotia.reactdemo.utils.State;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
package com.pugnascotia.reactdemo.account;
/**
* Returns the user's current authentication status.
*
* @see AjaxLogoutSuccessHandler for how this is used.
*/
@RestController
@RequestMapping(value = "/api", produces = APPLICATION_JSON_VALUE)
public class AccountResource {
@RequestMapping("/account")
public Map<String,Object> getAccountStatus(HttpServletRequest request) { | return State.getAuthState(request); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/config/SecurityConfig.java | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
// @Component
// public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
// private final ObjectMapper mapper;
//
// @Inject
// public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
// this.mapper = mapper;
// }
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.setStatus(HttpServletResponse.SC_OK);
// Cookies.setSecurityTokens(request, response);
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// mapper.writeValue(outputStream, State.getAuthState(request));
//
// outputStream.close();
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationFailureHandler.java
// @Component
// public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
// /** Send a 401 Unauthorized if authentication failed */
//
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
| import javax.inject.Inject;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationFailureHandler;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler; | package com.pugnascotia.reactdemo.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
// @Component
// public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
// private final ObjectMapper mapper;
//
// @Inject
// public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
// this.mapper = mapper;
// }
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.setStatus(HttpServletResponse.SC_OK);
// Cookies.setSecurityTokens(request, response);
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// mapper.writeValue(outputStream, State.getAuthState(request));
//
// outputStream.close();
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationFailureHandler.java
// @Component
// public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
// /** Send a 401 Unauthorized if authentication failed */
//
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/config/SecurityConfig.java
import javax.inject.Inject;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationFailureHandler;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler;
package com.pugnascotia.reactdemo.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject | private AjaxAuthenticationSuccessHandler authSuccessHandler; |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/config/SecurityConfig.java | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
// @Component
// public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
// private final ObjectMapper mapper;
//
// @Inject
// public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
// this.mapper = mapper;
// }
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.setStatus(HttpServletResponse.SC_OK);
// Cookies.setSecurityTokens(request, response);
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// mapper.writeValue(outputStream, State.getAuthState(request));
//
// outputStream.close();
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationFailureHandler.java
// @Component
// public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
// /** Send a 401 Unauthorized if authentication failed */
//
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
| import javax.inject.Inject;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationFailureHandler;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler; | package com.pugnascotia.reactdemo.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject
private AjaxAuthenticationSuccessHandler authSuccessHandler;
@Inject | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
// @Component
// public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
// private final ObjectMapper mapper;
//
// @Inject
// public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
// this.mapper = mapper;
// }
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.setStatus(HttpServletResponse.SC_OK);
// Cookies.setSecurityTokens(request, response);
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// mapper.writeValue(outputStream, State.getAuthState(request));
//
// outputStream.close();
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationFailureHandler.java
// @Component
// public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
// /** Send a 401 Unauthorized if authentication failed */
//
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/config/SecurityConfig.java
import javax.inject.Inject;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationFailureHandler;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler;
package com.pugnascotia.reactdemo.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject
private AjaxAuthenticationSuccessHandler authSuccessHandler;
@Inject | private AjaxAuthenticationFailureHandler authFailureHandler; |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/config/SecurityConfig.java | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
// @Component
// public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
// private final ObjectMapper mapper;
//
// @Inject
// public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
// this.mapper = mapper;
// }
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.setStatus(HttpServletResponse.SC_OK);
// Cookies.setSecurityTokens(request, response);
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// mapper.writeValue(outputStream, State.getAuthState(request));
//
// outputStream.close();
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationFailureHandler.java
// @Component
// public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
// /** Send a 401 Unauthorized if authentication failed */
//
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
| import javax.inject.Inject;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationFailureHandler;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler; | package com.pugnascotia.reactdemo.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject
private AjaxAuthenticationSuccessHandler authSuccessHandler;
@Inject
private AjaxAuthenticationFailureHandler authFailureHandler;
@Inject | // Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
// @Component
// public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
// private final ObjectMapper mapper;
//
// @Inject
// public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
// this.mapper = mapper;
// }
//
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.setStatus(HttpServletResponse.SC_OK);
// Cookies.setSecurityTokens(request, response);
//
// ServletOutputStream outputStream = response.getOutputStream();
//
// mapper.writeValue(outputStream, State.getAuthState(request));
//
// outputStream.close();
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationFailureHandler.java
// @Component
// public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
// /** Send a 401 Unauthorized if authentication failed */
//
// @Override
// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxLogoutSuccessHandler.java
// @Component
// public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {
//
// /**
// * On a successful AJAX logout, send a redirect to /api/account. The response body
// * won't contain anything particularly useful, but the response headers will contain
// * the latest session and security (CSRF) tokens, meaning that subsequent POST requests
// * can work.
// */
// @Override
// public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// response.sendRedirect("/api/account");
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/config/SecurityConfig.java
import javax.inject.Inject;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationSuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import com.pugnascotia.reactdemo.config.ajax.AjaxAuthenticationFailureHandler;
import com.pugnascotia.reactdemo.config.ajax.AjaxLogoutSuccessHandler;
package com.pugnascotia.reactdemo.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject
private AjaxAuthenticationSuccessHandler authSuccessHandler;
@Inject
private AjaxAuthenticationFailureHandler authFailureHandler;
@Inject | private AjaxLogoutSuccessHandler logoutSuccessHandler; |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/errors/ReactErrorController.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
| import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pugnascotia.reactdemo.utils.State;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | package com.pugnascotia.reactdemo.errors;
/**
* Largely pinched from {@link org.springframework.boot.autoconfigure.web.BasicErrorController}
* and customised to render our React template, along with an appropriate populated state.
*/
@Controller
@RequestMapping("/error")
public class ReactErrorController extends AbstractErrorController {
private final ServerProperties serverProperties;
@Inject
public ReactErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
super(errorAttributes);
this.serverProperties = serverProperties;
}
/**
* Render the standard template, but include all the error information we know about. In
* a production application, you may not want to pass all that information to the client.
*/
@RequestMapping(produces = "text/html")
public String errorHtml(Model model, HttpServletRequest request, HttpServletResponse response) {
response.setStatus(getStatus(request).value());
model.addAttribute("errors", getErrorAttributes(request, isIncludeStackTrace(request)));
| // Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/errors/ReactErrorController.java
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pugnascotia.reactdemo.utils.State;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
package com.pugnascotia.reactdemo.errors;
/**
* Largely pinched from {@link org.springframework.boot.autoconfigure.web.BasicErrorController}
* and customised to render our React template, along with an appropriate populated state.
*/
@Controller
@RequestMapping("/error")
public class ReactErrorController extends AbstractErrorController {
private final ServerProperties serverProperties;
@Inject
public ReactErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
super(errorAttributes);
this.serverProperties = serverProperties;
}
/**
* Render the standard template, but include all the error information we know about. In
* a production application, you may not want to pass all that information to the client.
*/
@RequestMapping(produces = "text/html")
public String errorHtml(Model model, HttpServletRequest request, HttpServletResponse response) {
response.setStatus(getStatus(request).value());
model.addAttribute("errors", getErrorAttributes(request, isIncludeStackTrace(request)));
| State.populateModel(model, request); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Cookies.java
// public final class Cookies {
//
// public static final String XSRF_TOKEN_NAME = "XSRF-TOKEN";
//
// /** Ensures that if a request does not supply a CSRF token in a cookie, or
// * if the token is not up-to-date, we set it in our response so that subsequent
// * requests can succeed. */
// public static void setSecurityTokens(HttpServletRequest request, HttpServletResponse response) {
// CsrfToken csrf = (CsrfToken) request.getAttribute("_csrf");
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, XSRF_TOKEN_NAME);
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie(XSRF_TOKEN_NAME, token);
// cookie.setPath("/");
// cookie.setHttpOnly(false);
// response.addCookie(cookie);
// }
// }
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
| import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.pugnascotia.reactdemo.utils.Cookies;
import com.pugnascotia.reactdemo.utils.State; | package com.pugnascotia.reactdemo.config.ajax;
/**
* A handler that returns HTTP 200 OK for successful AJAX authentications,
* and includes the user's roles in the response body.
*/
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final ObjectMapper mapper;
@Inject
public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK); | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Cookies.java
// public final class Cookies {
//
// public static final String XSRF_TOKEN_NAME = "XSRF-TOKEN";
//
// /** Ensures that if a request does not supply a CSRF token in a cookie, or
// * if the token is not up-to-date, we set it in our response so that subsequent
// * requests can succeed. */
// public static void setSecurityTokens(HttpServletRequest request, HttpServletResponse response) {
// CsrfToken csrf = (CsrfToken) request.getAttribute("_csrf");
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, XSRF_TOKEN_NAME);
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie(XSRF_TOKEN_NAME, token);
// cookie.setPath("/");
// cookie.setHttpOnly(false);
// response.addCookie(cookie);
// }
// }
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.pugnascotia.reactdemo.utils.Cookies;
import com.pugnascotia.reactdemo.utils.State;
package com.pugnascotia.reactdemo.config.ajax;
/**
* A handler that returns HTTP 200 OK for successful AJAX authentications,
* and includes the user's roles in the response body.
*/
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final ObjectMapper mapper;
@Inject
public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK); | Cookies.setSecurityTokens(request, response); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/Cookies.java
// public final class Cookies {
//
// public static final String XSRF_TOKEN_NAME = "XSRF-TOKEN";
//
// /** Ensures that if a request does not supply a CSRF token in a cookie, or
// * if the token is not up-to-date, we set it in our response so that subsequent
// * requests can succeed. */
// public static void setSecurityTokens(HttpServletRequest request, HttpServletResponse response) {
// CsrfToken csrf = (CsrfToken) request.getAttribute("_csrf");
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, XSRF_TOKEN_NAME);
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie(XSRF_TOKEN_NAME, token);
// cookie.setPath("/");
// cookie.setHttpOnly(false);
// response.addCookie(cookie);
// }
// }
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
| import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.pugnascotia.reactdemo.utils.Cookies;
import com.pugnascotia.reactdemo.utils.State; | package com.pugnascotia.reactdemo.config.ajax;
/**
* A handler that returns HTTP 200 OK for successful AJAX authentications,
* and includes the user's roles in the response body.
*/
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final ObjectMapper mapper;
@Inject
public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
Cookies.setSecurityTokens(request, response);
ServletOutputStream outputStream = response.getOutputStream();
| // Path: src/main/java/com/pugnascotia/reactdemo/utils/Cookies.java
// public final class Cookies {
//
// public static final String XSRF_TOKEN_NAME = "XSRF-TOKEN";
//
// /** Ensures that if a request does not supply a CSRF token in a cookie, or
// * if the token is not up-to-date, we set it in our response so that subsequent
// * requests can succeed. */
// public static void setSecurityTokens(HttpServletRequest request, HttpServletResponse response) {
// CsrfToken csrf = (CsrfToken) request.getAttribute("_csrf");
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, XSRF_TOKEN_NAME);
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie(XSRF_TOKEN_NAME, token);
// cookie.setPath("/");
// cookie.setHttpOnly(false);
// response.addCookie(cookie);
// }
// }
// }
// }
//
// Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public final class State {
//
// /** Populates standard parts of the shared client/server model into the Spring {@link Model}.
// * Values prefixed with "__" will be made available to the JavaScript
// * render function only. All other values will be passed in the client's state object.
// */
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
//
// /**
// * Returns the request string, including the query fragment, so that it can be made available
// * during server-side react-router rendering.
// */
// private static String getRequestPath(HttpServletRequest request) {
// String queryString = request.getQueryString();
// return request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
// }
//
// /**
// * Returns a representation of the user's authentication state, in the shape expected by the client.
// */
// public static Map<String, Object> getAuthState(HttpServletRequest request) {
// Optional<List<String>> optionalRoles = getRoles(request);
//
// return optionalRoles.map(roles -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", !roles.contains("ROLE_ANONYMOUS"));
// authState.put("roles", roles);
//
// return authState;
// })
// .orElseGet(() -> {
// Map<String, Object> authState = new HashMap<>();
// authState.put("signedIn", false);
// authState.put("roles", Collections.singletonList("ROLE_ANONYMOUS"));
//
// return authState;
// });
// }
//
// /**
// * Return a list of the current user's roles. If they are not authenticated then they will
// * have "ROLE_ANONYMOUS".
// */
// private static Optional<List<String>> getRoles(HttpServletRequest request) {
// return getAuthentication(request)
// .map(a -> Functions.map(a.getAuthorities(), GrantedAuthority::getAuthority));
// }
//
// /**
// * Getting the current authentication object ought to be easy, by getting a context with
// * {@link SecurityContextHolder#getContext()}, then calling {@link SecurityContext#getAuthentication()}.
// * However there are circumstances where that doesn't work reliably, such as when handling
// * exceptions. This method makes several attempts to get an {@link Authentication} instance.
// */
// private static Optional<Authentication> getAuthentication(HttpServletRequest request) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
// if (authentication == null) {
// RequestAttributes requestAttributes = new ServletRequestAttributes(request);
// SecurityContext securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_SESSION);
// if (securityContext == null) {
// securityContext = (SecurityContext) requestAttributes.getAttribute("SPRING_SECURITY_CONTEXT", RequestAttributes.SCOPE_GLOBAL_SESSION);
// }
// if (securityContext != null) {
// authentication = securityContext.getAuthentication();
// }
// }
//
// return Optional.ofNullable(authentication);
// }
// }
// Path: src/main/java/com/pugnascotia/reactdemo/config/ajax/AjaxAuthenticationSuccessHandler.java
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.pugnascotia.reactdemo.utils.Cookies;
import com.pugnascotia.reactdemo.utils.State;
package com.pugnascotia.reactdemo.config.ajax;
/**
* A handler that returns HTTP 200 OK for successful AJAX authentications,
* and includes the user's roles in the response body.
*/
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final ObjectMapper mapper;
@Inject
public AjaxAuthenticationSuccessHandler(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
Cookies.setSecurityTokens(request, response);
ServletOutputStream outputStream = response.getOutputStream();
| mapper.writeValue(outputStream, State.getAuthState(request)); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/comments/CommentController.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
| import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
import static org.springframework.web.bind.annotation.RequestMethod.GET; | package com.pugnascotia.reactdemo.comments;
/**
* Handles requests for the "add a comment" page. This is handled
* by our UI stack without any additional context.
*/
@Controller
public class CommentController {
@RequestMapping(value = "/add", method = GET)
public String index(Model model, HttpServletRequest request) { | // Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
// Path: src/main/java/com/pugnascotia/reactdemo/comments/CommentController.java
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
package com.pugnascotia.reactdemo.comments;
/**
* Handles requests for the "add a comment" page. This is handled
* by our UI stack without any additional context.
*/
@Controller
public class CommentController {
@RequestMapping(value = "/add", method = GET)
public String index(Model model, HttpServletRequest request) { | populateModel(model, request); |
pugnascotia/spring-react-boilerplate | src/main/java/com/pugnascotia/reactdemo/account/AccountController.java | // Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
| import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel; | package com.pugnascotia.reactdemo.account;
/**
* Handles a request for the signin page and renders the
* app. React Router takes care of showing the right page.
*/
@Controller
public class AccountController {
@RequestMapping("/signin")
public String showSignIn(Model model, HttpServletRequest request) { | // Path: src/main/java/com/pugnascotia/reactdemo/utils/State.java
// public static void populateModel(Model model, HttpServletRequest request) {
// model.addAttribute("__requestPath", getRequestPath(request));
// model.addAttribute("auth", getAuthState(request));
// }
// Path: src/main/java/com/pugnascotia/reactdemo/account/AccountController.java
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static com.pugnascotia.reactdemo.utils.State.populateModel;
package com.pugnascotia.reactdemo.account;
/**
* Handles a request for the signin page and renders the
* app. React Router takes care of showing the right page.
*/
@Controller
public class AccountController {
@RequestMapping("/signin")
public String showSignIn(Model model, HttpServletRequest request) { | populateModel(model, request); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception { | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java
import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception { | RxCache underlyingCache = mock(RxCache.class); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception {
RxCache underlyingCache = mock(RxCache.class);
LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS,
simpleTimeProvider);
long currentTime = TimeUnit.HOURS.toMillis(2);
when(simpleTimeProvider.currentTime()).thenReturn(currentTime);
String cacheKey = "cache_key";
String testValue = "test";
when(underlyingCache.get(eq(cacheKey), any()))
.thenReturn(Observable.just( | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java
import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception {
RxCache underlyingCache = mock(RxCache.class);
LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS,
simpleTimeProvider);
long currentTime = TimeUnit.HOURS.toMillis(2);
when(simpleTimeProvider.currentTime()).thenReturn(currentTime);
String cacheKey = "cache_key";
String testValue = "test";
when(underlyingCache.get(eq(cacheKey), any()))
.thenReturn(Observable.just( | new TimedValue<>(new SimpleObject(testValue), currentTime - TimeUnit.SECONDS.toMillis(5)))); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception {
RxCache underlyingCache = mock(RxCache.class);
LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS,
simpleTimeProvider);
long currentTime = TimeUnit.HOURS.toMillis(2);
when(simpleTimeProvider.currentTime()).thenReturn(currentTime);
String cacheKey = "cache_key";
String testValue = "test";
when(underlyingCache.get(eq(cacheKey), any()))
.thenReturn(Observable.just( | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java
import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception {
RxCache underlyingCache = mock(RxCache.class);
LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS,
simpleTimeProvider);
long currentTime = TimeUnit.HOURS.toMillis(2);
when(simpleTimeProvider.currentTime()).thenReturn(currentTime);
String cacheKey = "cache_key";
String testValue = "test";
when(underlyingCache.get(eq(cacheKey), any()))
.thenReturn(Observable.just( | new TimedValue<>(new SimpleObject(testValue), currentTime - TimeUnit.SECONDS.toMillis(5)))); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception {
RxCache underlyingCache = mock(RxCache.class);
LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS,
simpleTimeProvider);
long currentTime = TimeUnit.HOURS.toMillis(2);
when(simpleTimeProvider.currentTime()).thenReturn(currentTime);
String cacheKey = "cache_key";
String testValue = "test";
when(underlyingCache.get(eq(cacheKey), any()))
.thenReturn(Observable.just(
new TimedValue<>(new SimpleObject(testValue), currentTime - TimeUnit.SECONDS.toMillis(5))));
Observable<SimpleObject> observable = lazyExpirableCache.get(cacheKey, SimpleObject.class); | // Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/ObservableTestUtils.java
// public final class ObservableTestUtils {
//
// private ObservableTestUtils() {
// //no instance
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction, boolean assertNotNull) {
// observable = observable.subscribeOn(Schedulers.immediate());
//
// TestSubscriber<T> testSubscriber = new TestSubscriber<>();
// observable.subscribe(testSubscriber);
//
// testSubscriber.assertNoErrors();
// testSubscriber.assertValueCount(1);
//
// List<T> onNextEvents = testSubscriber.getOnNextEvents();
// assertEquals(1, onNextEvents.size());
//
// T value = onNextEvents.get(0);
//
// if (assertNotNull) {
// assertNotNull(value);
// }
//
// assertAction.call(value);
// }
//
// public static <T> void testObservable(Observable<T> observable, Action1<T> assertAction) {
// testObservable(observable, assertAction, true);
// }
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
// static class TimedValue<T> {
// T value;
// long addedOn;
//
// TimedValue(T value, long time) {
// this.value = value;
// this.addedOn = time;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCacheTest.java
import com.github.simonpercic.waterfallcache.ObservableTestUtils;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.expire.LazyExpirableCache.TimedValue;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache.expire;
/**
* LazyExpirableCache tests
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class LazyExpirableCacheTest {
@Mock SimpleTimeProvider simpleTimeProvider;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetNotExpired() throws Exception {
RxCache underlyingCache = mock(RxCache.class);
LazyExpirableCache lazyExpirableCache = LazyExpirableCache.fromCache(underlyingCache, 10, TimeUnit.SECONDS,
simpleTimeProvider);
long currentTime = TimeUnit.HOURS.toMillis(2);
when(simpleTimeProvider.currentTime()).thenReturn(currentTime);
String cacheKey = "cache_key";
String testValue = "test";
when(underlyingCache.get(eq(cacheKey), any()))
.thenReturn(Observable.just(
new TimedValue<>(new SimpleObject(testValue), currentTime - TimeUnit.SECONDS.toMillis(5))));
Observable<SimpleObject> observable = lazyExpirableCache.get(cacheKey, SimpleObject.class); | ObservableTestUtils.testObservable(observable, |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/AsyncCache.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
| import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import java.lang.reflect.Type; | package com.github.simonpercic.waterfallcache.cache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public interface AsyncCache {
/**
* Get from cache - async, using a callback.
*
* @param key key
* @param typeOfT type of cache value
* @param callback callback that will be invoked to return the value
* @param <T> T of cache value
*/
<T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback);
/**
* Put value to cache - async, using a callback.
*
* @param key key
* @param object object
* @param callback callback that will be invoked to report status
*/ | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/AsyncCache.java
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import java.lang.reflect.Type;
package com.github.simonpercic.waterfallcache.cache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public interface AsyncCache {
/**
* Get from cache - async, using a callback.
*
* @param key key
* @param typeOfT type of cache value
* @param callback callback that will be invoked to return the value
* @param <T> T of cache value
*/
<T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback);
/**
* Put value to cache - async, using a callback.
*
* @param key key
* @param object object
* @param callback callback that will be invoked to report status
*/ | void putAsync(String key, Object object, WaterfallCallback callback); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheAsyncTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheAsyncTest {
@Mock RxCache cache;
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
waterfallCache = WaterfallCache.builder()
.addCache(cache)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testGetAsync() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheAsyncTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheAsyncTest {
@Mock RxCache cache;
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
waterfallCache = WaterfallCache.builder()
.addCache(cache)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testGetAsync() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
| when(cache.get(eq(key), eq(SimpleObject.class))).thenReturn(Observable.just(new SimpleObject(value))); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheAsyncTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when; |
CountDownLatch countDownLatch = new CountDownLatch(1);
waterfallCache.<Boolean>clearAsync(new TestWaterfallCallback() {
@Override public void onSuccess() {
countDownLatch.countDown();
}
});
assertCountDownLatchCalled(countDownLatch);
}
@Test
public void testClearAsyncError() throws Exception {
Throwable throwable = new RuntimeException();
when(cache.clear()).thenReturn(Observable.error(throwable));
CountDownLatch countDownLatch = new CountDownLatch(1);
waterfallCache.<Boolean>clearAsync(new TestWaterfallErrorCallback(throwable, t -> countDownLatch.countDown()));
assertCountDownLatchCalled(countDownLatch);
}
private void assertCountDownLatchCalled(CountDownLatch countDownLatch) throws InterruptedException {
if (!countDownLatch.await(100, TimeUnit.MILLISECONDS)) {
fail();
}
}
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheAsyncTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
CountDownLatch countDownLatch = new CountDownLatch(1);
waterfallCache.<Boolean>clearAsync(new TestWaterfallCallback() {
@Override public void onSuccess() {
countDownLatch.countDown();
}
});
assertCountDownLatchCalled(countDownLatch);
}
@Test
public void testClearAsyncError() throws Exception {
Throwable throwable = new RuntimeException();
when(cache.clear()).thenReturn(Observable.error(throwable));
CountDownLatch countDownLatch = new CountDownLatch(1);
waterfallCache.<Boolean>clearAsync(new TestWaterfallErrorCallback(throwable, t -> countDownLatch.countDown()));
assertCountDownLatchCalled(countDownLatch);
}
private void assertCountDownLatchCalled(CountDownLatch countDownLatch) throws InterruptedException {
if (!countDownLatch.await(100, TimeUnit.MILLISECONDS)) {
fail();
}
}
| private static class TestWaterfallGetCallback<T> implements WaterfallGetCallback<T> { |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheAsyncTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when; | @Override public void onSuccess(T t) {
assertNotNull(t);
assertAction.call(t);
}
@Override public void onFailure(Throwable throwable) {
fail(throwable.getMessage());
}
}
private static class TestWaterfallGetErrorCallback<T> implements WaterfallGetCallback<T> {
private final Throwable expectedThrowable;
private final Action1<Throwable> assertAction;
private TestWaterfallGetErrorCallback(Throwable expectedThrowable, Action1<Throwable> assertAction) {
this.expectedThrowable = expectedThrowable;
this.assertAction = assertAction;
}
@Override public void onSuccess(Object object) {
fail("Success called");
}
@Override public void onFailure(Throwable throwable) {
assertEquals(expectedThrowable, throwable);
assertAction.call(throwable);
}
}
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheAsyncTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
@Override public void onSuccess(T t) {
assertNotNull(t);
assertAction.call(t);
}
@Override public void onFailure(Throwable throwable) {
fail(throwable.getMessage());
}
}
private static class TestWaterfallGetErrorCallback<T> implements WaterfallGetCallback<T> {
private final Throwable expectedThrowable;
private final Action1<Throwable> assertAction;
private TestWaterfallGetErrorCallback(Throwable expectedThrowable, Action1<Throwable> assertAction) {
this.expectedThrowable = expectedThrowable;
this.assertAction = assertAction;
}
@Override public void onSuccess(Object object) {
fail("Success called");
}
@Override public void onFailure(Throwable throwable) {
assertEquals(expectedThrowable, throwable);
assertAction.call(throwable);
}
}
| private static abstract class TestWaterfallCallback implements WaterfallCallback { |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/App.java
// public class App extends Application {
//
// private Cache waterfallCache;
//
// @Override public void onCreate() {
// super.onCreate();
// setStrictMode();
// waterfallCache = createCache();
// }
//
// public Cache getWaterfallCache() {
// return waterfallCache;
// }
//
// private Cache createCache() {
// Cache cache = WaterfallCache.builder()
// .addMemoryCache(1000)
// .addDiskCache(this, 1024 * 1024)
// .build();
//
// return LazyExpirableCache.fromCache(cache, 10, TimeUnit.MINUTES);
// }
//
// private void setStrictMode() {
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads()
// .detectDiskWrites()
// .detectAll()
// .penaltyLog()
// .build());
//
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects()
// .detectLeakedClosableObjects()
// .penaltyLog()
// .penaltyDeath()
// .build());
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.App;
import com.github.simonpercic.waterfallcachesample.R; | package com.github.simonpercic.waterfallcachesample.test.base;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
private static final String DEFAULT_KEY = "test";
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/App.java
// public class App extends Application {
//
// private Cache waterfallCache;
//
// @Override public void onCreate() {
// super.onCreate();
// setStrictMode();
// waterfallCache = createCache();
// }
//
// public Cache getWaterfallCache() {
// return waterfallCache;
// }
//
// private Cache createCache() {
// Cache cache = WaterfallCache.builder()
// .addMemoryCache(1000)
// .addDiskCache(this, 1024 * 1024)
// .build();
//
// return LazyExpirableCache.fromCache(cache, 10, TimeUnit.MINUTES);
// }
//
// private void setStrictMode() {
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads()
// .detectDiskWrites()
// .detectAll()
// .penaltyLog()
// .build());
//
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects()
// .detectLeakedClosableObjects()
// .penaltyLog()
// .penaltyDeath()
// .build());
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.App;
import com.github.simonpercic.waterfallcachesample.R;
package com.github.simonpercic.waterfallcachesample.test.base;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
private static final String DEFAULT_KEY = "test";
| private Cache waterfallCache; |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/App.java
// public class App extends Application {
//
// private Cache waterfallCache;
//
// @Override public void onCreate() {
// super.onCreate();
// setStrictMode();
// waterfallCache = createCache();
// }
//
// public Cache getWaterfallCache() {
// return waterfallCache;
// }
//
// private Cache createCache() {
// Cache cache = WaterfallCache.builder()
// .addMemoryCache(1000)
// .addDiskCache(this, 1024 * 1024)
// .build();
//
// return LazyExpirableCache.fromCache(cache, 10, TimeUnit.MINUTES);
// }
//
// private void setStrictMode() {
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads()
// .detectDiskWrites()
// .detectAll()
// .penaltyLog()
// .build());
//
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects()
// .detectLeakedClosableObjects()
// .penaltyLog()
// .penaltyDeath()
// .build());
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.App;
import com.github.simonpercic.waterfallcachesample.R; | package com.github.simonpercic.waterfallcachesample.test.base;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
private static final String DEFAULT_KEY = "test";
private Cache waterfallCache;
private TextView tvValueDisplay;
private EditText etValueInput;
private EditText etKeyInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test); | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/App.java
// public class App extends Application {
//
// private Cache waterfallCache;
//
// @Override public void onCreate() {
// super.onCreate();
// setStrictMode();
// waterfallCache = createCache();
// }
//
// public Cache getWaterfallCache() {
// return waterfallCache;
// }
//
// private Cache createCache() {
// Cache cache = WaterfallCache.builder()
// .addMemoryCache(1000)
// .addDiskCache(this, 1024 * 1024)
// .build();
//
// return LazyExpirableCache.fromCache(cache, 10, TimeUnit.MINUTES);
// }
//
// private void setStrictMode() {
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads()
// .detectDiskWrites()
// .detectAll()
// .penaltyLog()
// .build());
//
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects()
// .detectLeakedClosableObjects()
// .penaltyLog()
// .penaltyDeath()
// .build());
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.App;
import com.github.simonpercic.waterfallcachesample.R;
package com.github.simonpercic.waterfallcachesample.test.base;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
private static final String DEFAULT_KEY = "test";
private Cache waterfallCache;
private TextView tvValueDisplay;
private EditText etValueInput;
private EditText etKeyInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test); | waterfallCache = ((App) getApplication()).getWaterfallCache(); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryOnlyTest.java | // Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals; | package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheInlineMemoryOnlyTest {
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
waterfallCache = WaterfallCache.builder()
.addMemoryCache(100)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testGetNoValue() throws Exception {
String key = "TEST_KEY";
| // Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryOnlyTest.java
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheInlineMemoryOnlyTest {
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
waterfallCache = WaterfallCache.builder()
.addMemoryCache(100)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testGetNoValue() throws Exception {
String key = "TEST_KEY";
| Observable<SimpleObject> observable = waterfallCache.get(key, SimpleObject.class); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryOnlyTest.java | // Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals; | public void testContainsNoValue() throws Exception {
String key = "TEST_KEY";
Observable<Boolean> observable = waterfallCache.contains(key);
ObservableTestUtils.testObservable(observable, Assert::assertFalse);
}
@Test
public void testSimple() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
SimpleObject object = new SimpleObject(value);
ObservableTestUtils.testObservable(waterfallCache.put(key, object), Assert::assertTrue);
Observable<SimpleObject> getObservable = waterfallCache.get(key, SimpleObject.class);
ObservableTestUtils.testObservable(getObservable, simpleObject -> assertEquals(value, simpleObject.getValue()));
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
}
@Test
public void testWrapped() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
| // Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryOnlyTest.java
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
public void testContainsNoValue() throws Exception {
String key = "TEST_KEY";
Observable<Boolean> observable = waterfallCache.contains(key);
ObservableTestUtils.testObservable(observable, Assert::assertFalse);
}
@Test
public void testSimple() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
SimpleObject object = new SimpleObject(value);
ObservableTestUtils.testObservable(waterfallCache.put(key, object), Assert::assertTrue);
Observable<SimpleObject> getObservable = waterfallCache.get(key, SimpleObject.class);
ObservableTestUtils.testObservable(getObservable, simpleObject -> assertEquals(value, simpleObject.getValue()));
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
}
@Test
public void testWrapped() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
| WrappedObject wrapped = new WrappedObject(); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryOnlyTest.java | // Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals; | SimpleObject simple = new SimpleObject(simpleValue);
WrappedObject wrapped = new WrappedObject();
wrapped.setObject(simple);
wrapped.setValue(wrappedValue);
ObservableTestUtils.testObservable(waterfallCache.put(key, wrapped), Assert::assertTrue);
Observable<WrappedObject> getObservable = waterfallCache.get(key, WrappedObject.class);
ObservableTestUtils.testObservable(getObservable, wrappedObject -> {
assertEquals(wrappedValue, wrappedObject.getValue());
assertEquals(simpleValue, wrappedObject.getObject().getValue());
});
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
}
@Test
public void testGeneric() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
String genericValue = "TEST_GENERIC_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
WrappedObject wrapped = new WrappedObject();
wrapped.setObject(simple);
wrapped.setValue(wrappedValue);
| // Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryOnlyTest.java
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
SimpleObject simple = new SimpleObject(simpleValue);
WrappedObject wrapped = new WrappedObject();
wrapped.setObject(simple);
wrapped.setValue(wrappedValue);
ObservableTestUtils.testObservable(waterfallCache.put(key, wrapped), Assert::assertTrue);
Observable<WrappedObject> getObservable = waterfallCache.get(key, WrappedObject.class);
ObservableTestUtils.testObservable(getObservable, wrappedObject -> {
assertEquals(wrappedValue, wrappedObject.getValue());
assertEquals(simpleValue, wrappedObject.getObject().getValue());
});
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
}
@Test
public void testGeneric() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
String genericValue = "TEST_GENERIC_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
WrappedObject wrapped = new WrappedObject();
wrapped.setObject(simple);
wrapped.setValue(wrappedValue);
| GenericObject<WrappedObject> generic = new GenericObject<>(); |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallFailureCallback.java
// public interface WaterfallFailureCallback {
//
// /**
// * Called on failure.
// *
// * @param throwable throwable
// */
// void onFailure(Throwable throwable);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
| import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallFailureCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import rx.Observable;
import rx.functions.Action1; | package com.github.simonpercic.waterfallcache.utils;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public final class AsyncUtils {
private AsyncUtils() {
//no instance
}
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallFailureCallback.java
// public interface WaterfallFailureCallback {
//
// /**
// * Called on failure.
// *
// * @param throwable throwable
// */
// void onFailure(Throwable throwable);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallFailureCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import rx.Observable;
import rx.functions.Action1;
package com.github.simonpercic.waterfallcache.utils;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public final class AsyncUtils {
private AsyncUtils() {
//no instance
}
| public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) { |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallFailureCallback.java
// public interface WaterfallFailureCallback {
//
// /**
// * Called on failure.
// *
// * @param throwable throwable
// */
// void onFailure(Throwable throwable);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
| import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallFailureCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import rx.Observable;
import rx.functions.Action1; | package com.github.simonpercic.waterfallcache.utils;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public final class AsyncUtils {
private AsyncUtils() {
//no instance
}
public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
observable.subscribe(success -> {
if (callback != null) {
callback.onSuccess();
}
}, asyncOnError(callback));
}
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallFailureCallback.java
// public interface WaterfallFailureCallback {
//
// /**
// * Called on failure.
// *
// * @param throwable throwable
// */
// void onFailure(Throwable throwable);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallFailureCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import rx.Observable;
import rx.functions.Action1;
package com.github.simonpercic.waterfallcache.utils;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public final class AsyncUtils {
private AsyncUtils() {
//no instance
}
public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
observable.subscribe(success -> {
if (callback != null) {
callback.onSuccess();
}
}, asyncOnError(callback));
}
| public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) { |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallFailureCallback.java
// public interface WaterfallFailureCallback {
//
// /**
// * Called on failure.
// *
// * @param throwable throwable
// */
// void onFailure(Throwable throwable);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
| import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallFailureCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import rx.Observable;
import rx.functions.Action1; | package com.github.simonpercic.waterfallcache.utils;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public final class AsyncUtils {
private AsyncUtils() {
//no instance
}
public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
observable.subscribe(success -> {
if (callback != null) {
callback.onSuccess();
}
}, asyncOnError(callback));
}
public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
observable.subscribe(value -> {
if (callback != null) {
callback.onSuccess(value);
}
}, asyncOnError(callback));
}
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallFailureCallback.java
// public interface WaterfallFailureCallback {
//
// /**
// * Called on failure.
// *
// * @param throwable throwable
// */
// void onFailure(Throwable throwable);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallFailureCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import rx.Observable;
import rx.functions.Action1;
package com.github.simonpercic.waterfallcache.utils;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public final class AsyncUtils {
private AsyncUtils() {
//no instance
}
public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
observable.subscribe(success -> {
if (callback != null) {
callback.onSuccess();
}
}, asyncOnError(callback));
}
public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
observable.subscribe(value -> {
if (callback != null) {
callback.onSuccess(value);
}
}, asyncOnError(callback));
}
| private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) { |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
// public final class AsyncUtils {
//
// private AsyncUtils() {
// //no instance
// }
//
// public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
// observable.subscribe(success -> {
// if (callback != null) {
// callback.onSuccess();
// }
// }, asyncOnError(callback));
// }
//
// public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
// observable.subscribe(value -> {
// if (callback != null) {
// callback.onSuccess(value);
// }
// }, asyncOnError(callback));
// }
//
// private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) {
// return throwable -> {
// if (callback != null) {
// callback.onFailure(throwable);
// }
// };
// }
// }
| import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.utils.AsyncUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import rx.Observable; | }
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> contains(String key) {
return get(key, Object.class).flatMap(o -> Observable.just(o != null));
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> remove(String key) {
return underlyingCache.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> clear() {
return underlyingCache.clear();
}
// endregion Reactive methods
// region asynchronous methods
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
// public final class AsyncUtils {
//
// private AsyncUtils() {
// //no instance
// }
//
// public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
// observable.subscribe(success -> {
// if (callback != null) {
// callback.onSuccess();
// }
// }, asyncOnError(callback));
// }
//
// public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
// observable.subscribe(value -> {
// if (callback != null) {
// callback.onSuccess(value);
// }
// }, asyncOnError(callback));
// }
//
// private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) {
// return throwable -> {
// if (callback != null) {
// callback.onFailure(throwable);
// }
// };
// }
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.utils.AsyncUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import rx.Observable;
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> contains(String key) {
return get(key, Object.class).flatMap(o -> Observable.just(o != null));
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> remove(String key) {
return underlyingCache.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> clear() {
return underlyingCache.clear();
}
// endregion Reactive methods
// region asynchronous methods
| @Override public <T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback) { |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
// public final class AsyncUtils {
//
// private AsyncUtils() {
// //no instance
// }
//
// public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
// observable.subscribe(success -> {
// if (callback != null) {
// callback.onSuccess();
// }
// }, asyncOnError(callback));
// }
//
// public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
// observable.subscribe(value -> {
// if (callback != null) {
// callback.onSuccess(value);
// }
// }, asyncOnError(callback));
// }
//
// private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) {
// return throwable -> {
// if (callback != null) {
// callback.onFailure(throwable);
// }
// };
// }
// }
| import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.utils.AsyncUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import rx.Observable; |
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> contains(String key) {
return get(key, Object.class).flatMap(o -> Observable.just(o != null));
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> remove(String key) {
return underlyingCache.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> clear() {
return underlyingCache.clear();
}
// endregion Reactive methods
// region asynchronous methods
@Override public <T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback) { | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
// public final class AsyncUtils {
//
// private AsyncUtils() {
// //no instance
// }
//
// public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
// observable.subscribe(success -> {
// if (callback != null) {
// callback.onSuccess();
// }
// }, asyncOnError(callback));
// }
//
// public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
// observable.subscribe(value -> {
// if (callback != null) {
// callback.onSuccess(value);
// }
// }, asyncOnError(callback));
// }
//
// private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) {
// return throwable -> {
// if (callback != null) {
// callback.onFailure(throwable);
// }
// };
// }
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.utils.AsyncUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import rx.Observable;
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> contains(String key) {
return get(key, Object.class).flatMap(o -> Observable.just(o != null));
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> remove(String key) {
return underlyingCache.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> clear() {
return underlyingCache.clear();
}
// endregion Reactive methods
// region asynchronous methods
@Override public <T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback) { | AsyncUtils.doAsync(get(key, typeOfT), callback); |
simonpercic/WaterfallCache | waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
// public final class AsyncUtils {
//
// private AsyncUtils() {
// //no instance
// }
//
// public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
// observable.subscribe(success -> {
// if (callback != null) {
// callback.onSuccess();
// }
// }, asyncOnError(callback));
// }
//
// public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
// observable.subscribe(value -> {
// if (callback != null) {
// callback.onSuccess(value);
// }
// }, asyncOnError(callback));
// }
//
// private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) {
// return throwable -> {
// if (callback != null) {
// callback.onFailure(throwable);
// }
// };
// }
// }
| import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.utils.AsyncUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import rx.Observable; | */
@Override
public Observable<Boolean> contains(String key) {
return get(key, Object.class).flatMap(o -> Observable.just(o != null));
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> remove(String key) {
return underlyingCache.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> clear() {
return underlyingCache.clear();
}
// endregion Reactive methods
// region asynchronous methods
@Override public <T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback) {
AsyncUtils.doAsync(get(key, typeOfT), callback);
}
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/utils/AsyncUtils.java
// public final class AsyncUtils {
//
// private AsyncUtils() {
// //no instance
// }
//
// public static void doAsync(Observable<Boolean> observable, final WaterfallCallback callback) {
// observable.subscribe(success -> {
// if (callback != null) {
// callback.onSuccess();
// }
// }, asyncOnError(callback));
// }
//
// public static <T> void doAsync(Observable<T> observable, final WaterfallGetCallback<T> callback) {
// observable.subscribe(value -> {
// if (callback != null) {
// callback.onSuccess(value);
// }
// }, asyncOnError(callback));
// }
//
// private static Action1<Throwable> asyncOnError(final WaterfallFailureCallback callback) {
// return throwable -> {
// if (callback != null) {
// callback.onFailure(throwable);
// }
// };
// }
// }
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/expire/LazyExpirableCache.java
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcache.utils.AsyncUtils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import rx.Observable;
*/
@Override
public Observable<Boolean> contains(String key) {
return get(key, Object.class).flatMap(o -> Observable.just(o != null));
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> remove(String key) {
return underlyingCache.remove(key);
}
/**
* {@inheritDoc}
*/
@Override
public Observable<Boolean> clear() {
return underlyingCache.clear();
}
// endregion Reactive methods
// region asynchronous methods
@Override public <T> void getAsync(String key, Type typeOfT, WaterfallGetCallback<T> callback) {
AsyncUtils.doAsync(get(key, typeOfT), callback);
}
| @Override public void putAsync(String key, Object object, WaterfallCallback callback) { |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/IntroActivity.java | // Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
// public class AsyncActivity extends BaseTestActivity {
//
// @Override protected void getTest(Cache waterfallCache, String key) {
// waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() {
// @Override public void onSuccess(SimpleObject object) {
// showValue(object);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Get", throwable);
// }
// });
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.putAsync(key, new SimpleObject(value), new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Put", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Put", throwable);
// }
// });
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.removeAsync(key, new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Remove", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Remove", throwable);
// }
// });
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.containsAsync(key, new WaterfallGetCallback<Boolean>() {
// @Override public void onSuccess(Boolean contains) {
// showMessage(String.format("Contains: %s", contains));
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Contains", throwable);
// }
// });
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clearAsync(new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Clear", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Clear", throwable);
// }
// });
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, AsyncActivity.class);
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java
// public class RxActivity extends BaseTestActivity {
//
// @Override
// protected void getTest(Cache waterfallCache, String key) {
// Observable<SimpleObject> test = waterfallCache.get(key, SimpleObject.class);
// test.subscribe((simpleObject) -> {
// showValue(simpleObject);
// }, throwable -> showErrorMessage("Get", throwable));
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.put(key, new SimpleObject(value)).subscribe(
// success -> showSuccessMessage("Put", success),
// throwable -> showErrorMessage("Put", throwable));
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.remove(key).subscribe(
// success -> showSuccessMessage("Remove", success),
// throwable -> showErrorMessage("Remove", throwable));
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.contains(key).subscribe(
// contains -> showMessage(String.format("Contains: %s", contains)),
// throwable -> showErrorMessage("Contains", throwable));
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clear().subscribe(
// success -> showSuccessMessage("Clear", success),
// throwable -> showErrorMessage("Clear", throwable));
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, RxActivity.class);
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import com.github.simonpercic.waterfallcachesample.test.AsyncActivity;
import com.github.simonpercic.waterfallcachesample.test.RxActivity; | package com.github.simonpercic.waterfallcachesample;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class IntroActivity extends AppCompatActivity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
findViewById(R.id.btn_rx_test).setOnClickListener(this);
findViewById(R.id.btn_async_test).setOnClickListener(this);
}
@Override public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_rx_test: | // Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
// public class AsyncActivity extends BaseTestActivity {
//
// @Override protected void getTest(Cache waterfallCache, String key) {
// waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() {
// @Override public void onSuccess(SimpleObject object) {
// showValue(object);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Get", throwable);
// }
// });
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.putAsync(key, new SimpleObject(value), new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Put", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Put", throwable);
// }
// });
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.removeAsync(key, new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Remove", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Remove", throwable);
// }
// });
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.containsAsync(key, new WaterfallGetCallback<Boolean>() {
// @Override public void onSuccess(Boolean contains) {
// showMessage(String.format("Contains: %s", contains));
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Contains", throwable);
// }
// });
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clearAsync(new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Clear", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Clear", throwable);
// }
// });
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, AsyncActivity.class);
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java
// public class RxActivity extends BaseTestActivity {
//
// @Override
// protected void getTest(Cache waterfallCache, String key) {
// Observable<SimpleObject> test = waterfallCache.get(key, SimpleObject.class);
// test.subscribe((simpleObject) -> {
// showValue(simpleObject);
// }, throwable -> showErrorMessage("Get", throwable));
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.put(key, new SimpleObject(value)).subscribe(
// success -> showSuccessMessage("Put", success),
// throwable -> showErrorMessage("Put", throwable));
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.remove(key).subscribe(
// success -> showSuccessMessage("Remove", success),
// throwable -> showErrorMessage("Remove", throwable));
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.contains(key).subscribe(
// contains -> showMessage(String.format("Contains: %s", contains)),
// throwable -> showErrorMessage("Contains", throwable));
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clear().subscribe(
// success -> showSuccessMessage("Clear", success),
// throwable -> showErrorMessage("Clear", throwable));
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, RxActivity.class);
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/IntroActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import com.github.simonpercic.waterfallcachesample.test.AsyncActivity;
import com.github.simonpercic.waterfallcachesample.test.RxActivity;
package com.github.simonpercic.waterfallcachesample;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class IntroActivity extends AppCompatActivity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
findViewById(R.id.btn_rx_test).setOnClickListener(this);
findViewById(R.id.btn_async_test).setOnClickListener(this);
}
@Override public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_rx_test: | startActivity(RxActivity.getIntent(this)); |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/IntroActivity.java | // Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
// public class AsyncActivity extends BaseTestActivity {
//
// @Override protected void getTest(Cache waterfallCache, String key) {
// waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() {
// @Override public void onSuccess(SimpleObject object) {
// showValue(object);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Get", throwable);
// }
// });
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.putAsync(key, new SimpleObject(value), new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Put", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Put", throwable);
// }
// });
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.removeAsync(key, new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Remove", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Remove", throwable);
// }
// });
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.containsAsync(key, new WaterfallGetCallback<Boolean>() {
// @Override public void onSuccess(Boolean contains) {
// showMessage(String.format("Contains: %s", contains));
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Contains", throwable);
// }
// });
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clearAsync(new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Clear", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Clear", throwable);
// }
// });
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, AsyncActivity.class);
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java
// public class RxActivity extends BaseTestActivity {
//
// @Override
// protected void getTest(Cache waterfallCache, String key) {
// Observable<SimpleObject> test = waterfallCache.get(key, SimpleObject.class);
// test.subscribe((simpleObject) -> {
// showValue(simpleObject);
// }, throwable -> showErrorMessage("Get", throwable));
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.put(key, new SimpleObject(value)).subscribe(
// success -> showSuccessMessage("Put", success),
// throwable -> showErrorMessage("Put", throwable));
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.remove(key).subscribe(
// success -> showSuccessMessage("Remove", success),
// throwable -> showErrorMessage("Remove", throwable));
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.contains(key).subscribe(
// contains -> showMessage(String.format("Contains: %s", contains)),
// throwable -> showErrorMessage("Contains", throwable));
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clear().subscribe(
// success -> showSuccessMessage("Clear", success),
// throwable -> showErrorMessage("Clear", throwable));
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, RxActivity.class);
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import com.github.simonpercic.waterfallcachesample.test.AsyncActivity;
import com.github.simonpercic.waterfallcachesample.test.RxActivity; | package com.github.simonpercic.waterfallcachesample;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class IntroActivity extends AppCompatActivity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
findViewById(R.id.btn_rx_test).setOnClickListener(this);
findViewById(R.id.btn_async_test).setOnClickListener(this);
}
@Override public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_rx_test:
startActivity(RxActivity.getIntent(this));
break;
case R.id.btn_async_test: | // Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
// public class AsyncActivity extends BaseTestActivity {
//
// @Override protected void getTest(Cache waterfallCache, String key) {
// waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() {
// @Override public void onSuccess(SimpleObject object) {
// showValue(object);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Get", throwable);
// }
// });
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.putAsync(key, new SimpleObject(value), new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Put", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Put", throwable);
// }
// });
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.removeAsync(key, new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Remove", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Remove", throwable);
// }
// });
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.containsAsync(key, new WaterfallGetCallback<Boolean>() {
// @Override public void onSuccess(Boolean contains) {
// showMessage(String.format("Contains: %s", contains));
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Contains", throwable);
// }
// });
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clearAsync(new WaterfallCallback() {
// @Override public void onSuccess() {
// showSuccessMessage("Clear", true);
// }
//
// @Override public void onFailure(Throwable throwable) {
// showErrorMessage("Clear", throwable);
// }
// });
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, AsyncActivity.class);
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java
// public class RxActivity extends BaseTestActivity {
//
// @Override
// protected void getTest(Cache waterfallCache, String key) {
// Observable<SimpleObject> test = waterfallCache.get(key, SimpleObject.class);
// test.subscribe((simpleObject) -> {
// showValue(simpleObject);
// }, throwable -> showErrorMessage("Get", throwable));
// }
//
// @Override protected void putTest(Cache waterfallCache, String value, String key) {
// waterfallCache.put(key, new SimpleObject(value)).subscribe(
// success -> showSuccessMessage("Put", success),
// throwable -> showErrorMessage("Put", throwable));
// }
//
// @Override protected void removeTest(Cache waterfallCache, String key) {
// waterfallCache.remove(key).subscribe(
// success -> showSuccessMessage("Remove", success),
// throwable -> showErrorMessage("Remove", throwable));
// }
//
// @Override protected void containsTest(Cache waterfallCache, String key) {
// waterfallCache.contains(key).subscribe(
// contains -> showMessage(String.format("Contains: %s", contains)),
// throwable -> showErrorMessage("Contains", throwable));
// }
//
// @Override protected void clearTest(Cache waterfallCache) {
// waterfallCache.clear().subscribe(
// success -> showSuccessMessage("Clear", success),
// throwable -> showErrorMessage("Clear", throwable));
// }
//
// public static Intent getIntent(Context context) {
// return new Intent(context, RxActivity.class);
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/IntroActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import com.github.simonpercic.waterfallcachesample.test.AsyncActivity;
import com.github.simonpercic.waterfallcachesample.test.RxActivity;
package com.github.simonpercic.waterfallcachesample;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class IntroActivity extends AppCompatActivity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
findViewById(R.id.btn_rx_test).setOnClickListener(this);
findViewById(R.id.btn_async_test).setOnClickListener(this);
}
@Override public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_rx_test:
startActivity(RxActivity.getIntent(this));
break;
case R.id.btn_async_test: | startActivity(AsyncActivity.getIntent(this)); |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject; | package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class AsyncActivity extends BaseTestActivity {
@Override protected void getTest(Cache waterfallCache, String key) { | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class AsyncActivity extends BaseTestActivity {
@Override protected void getTest(Cache waterfallCache, String key) { | waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() { |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject; | package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class AsyncActivity extends BaseTestActivity {
@Override protected void getTest(Cache waterfallCache, String key) { | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class AsyncActivity extends BaseTestActivity {
@Override protected void getTest(Cache waterfallCache, String key) { | waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() { |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject; | package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class AsyncActivity extends BaseTestActivity {
@Override protected void getTest(Cache waterfallCache, String key) {
waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() {
@Override public void onSuccess(SimpleObject object) {
showValue(object);
}
@Override public void onFailure(Throwable throwable) {
showErrorMessage("Get", throwable);
}
});
}
@Override protected void putTest(Cache waterfallCache, String value, String key) { | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallCallback.java
// public interface WaterfallCallback extends WaterfallFailureCallback {
//
// /**
// * Called on success.
// */
// void onSuccess();
// }
//
// Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/callback/WaterfallGetCallback.java
// public interface WaterfallGetCallback<T> extends WaterfallFailureCallback {
//
// /**
// * Called on success. Returns the value.
// *
// * @param object returned object
// */
// void onSuccess(T object);
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/AsyncActivity.java
import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcache.callback.WaterfallCallback;
import com.github.simonpercic.waterfallcache.callback.WaterfallGetCallback;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class AsyncActivity extends BaseTestActivity {
@Override protected void getTest(Cache waterfallCache, String key) {
waterfallCache.getAsync(key, SimpleObject.class, new WaterfallGetCallback<SimpleObject>() {
@Override public void onSuccess(SimpleObject object) {
showValue(object);
}
@Override public void onFailure(Throwable throwable) {
showErrorMessage("Get", throwable);
}
});
}
@Override protected void putTest(Cache waterfallCache, String value, String key) { | waterfallCache.putAsync(key, new SimpleObject(value), new WaterfallCallback() { |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheTest {
private static WaterfallCache waterfallCache;
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheTest {
private static WaterfallCache waterfallCache;
| private static RxCache mockCache; |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheTest {
private static WaterfallCache waterfallCache;
private static RxCache mockCache;
@BeforeClass
public static void setUpClass() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
mockCache = mock(RxCache.class);
waterfallCache = WaterfallCache.builder()
.addDiskCache(context, 1024 * 1024)
.addCache(mockCache)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Before
public void setUp() throws Exception {
reset(mockCache);
when(mockCache.clear()).thenReturn(Observable.just(true));
testObservable(waterfallCache.clear(), Assert::assertTrue);
}
@Test
public void testContainsPrefetchSimpleObject() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheTest {
private static WaterfallCache waterfallCache;
private static RxCache mockCache;
@BeforeClass
public static void setUpClass() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
mockCache = mock(RxCache.class);
waterfallCache = WaterfallCache.builder()
.addDiskCache(context, 1024 * 1024)
.addCache(mockCache)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Before
public void setUp() throws Exception {
reset(mockCache);
when(mockCache.clear()).thenReturn(Observable.just(true));
testObservable(waterfallCache.clear(), Assert::assertTrue);
}
@Test
public void testContainsPrefetchSimpleObject() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
| SimpleObject object = new SimpleObject(value); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | testObservable(waterfallCache.clear(), Assert::assertTrue);
}
@Test
public void testContainsPrefetchSimpleObject() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
SimpleObject object = new SimpleObject(value);
when(mockCache.contains(eq(key))).thenReturn(Observable.just(true));
when(mockCache.get(eq(key), eq(Object.class))).thenReturn(Observable.just(object));
testObservable(waterfallCache.contains(key), Assert::assertTrue);
Observable<SimpleObject> getObservable = waterfallCache.get(key, SimpleObject.class);
testObservable(getObservable, result -> assertEquals(value, result.getValue()));
verify(mockCache, never()).get(eq(key), eq(SimpleObject.class));
}
@Test
public void testContainsPrefetchWrappedObject() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
SimpleObject simpleObject = new SimpleObject(simpleValue);
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
testObservable(waterfallCache.clear(), Assert::assertTrue);
}
@Test
public void testContainsPrefetchSimpleObject() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
SimpleObject object = new SimpleObject(value);
when(mockCache.contains(eq(key))).thenReturn(Observable.just(true));
when(mockCache.get(eq(key), eq(Object.class))).thenReturn(Observable.just(object));
testObservable(waterfallCache.contains(key), Assert::assertTrue);
Observable<SimpleObject> getObservable = waterfallCache.get(key, SimpleObject.class);
testObservable(getObservable, result -> assertEquals(value, result.getValue()));
verify(mockCache, never()).get(eq(key), eq(SimpleObject.class));
}
@Test
public void testContainsPrefetchWrappedObject() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
SimpleObject simpleObject = new SimpleObject(simpleValue);
| WrappedObject wrappedObject = new WrappedObject(); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | wrappedObject.setValue(wrappedValue);
when(mockCache.contains(eq(key))).thenReturn(Observable.just(true));
when(mockCache.get(eq(key), eq(Object.class))).thenReturn(Observable.just(wrappedObject));
testObservable(waterfallCache.contains(key), Assert::assertTrue);
Observable<WrappedObject> getObservable = waterfallCache.get(key, WrappedObject.class);
testObservable(getObservable, result -> {
assertEquals(wrappedValue, result.getValue());
assertEquals(simpleValue, result.getObject().getValue());
});
verify(mockCache, never()).get(eq(key), eq(WrappedObject.class));
}
@Test
public void testContainsPrefetchGenericObject() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
String genericValue = "TEST_GENERIC_VALUE";
SimpleObject simpleObject = new SimpleObject(simpleValue);
WrappedObject wrappedObject = new WrappedObject();
wrappedObject.setObject(simpleObject);
wrappedObject.setValue(wrappedValue);
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
wrappedObject.setValue(wrappedValue);
when(mockCache.contains(eq(key))).thenReturn(Observable.just(true));
when(mockCache.get(eq(key), eq(Object.class))).thenReturn(Observable.just(wrappedObject));
testObservable(waterfallCache.contains(key), Assert::assertTrue);
Observable<WrappedObject> getObservable = waterfallCache.get(key, WrappedObject.class);
testObservable(getObservable, result -> {
assertEquals(wrappedValue, result.getValue());
assertEquals(simpleValue, result.getObject().getValue());
});
verify(mockCache, never()).get(eq(key), eq(WrappedObject.class));
}
@Test
public void testContainsPrefetchGenericObject() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
String genericValue = "TEST_GENERIC_VALUE";
SimpleObject simpleObject = new SimpleObject(simpleValue);
WrappedObject wrappedObject = new WrappedObject();
wrappedObject.setObject(simpleObject);
wrappedObject.setValue(wrappedValue);
| GenericObject<WrappedObject> genericObject = new GenericObject<>(); |
simonpercic/WaterfallCache | waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheTest {
@Mock RxCache cache1;
@Mock RxCache cache2;
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
waterfallCache = WaterfallCache.builder()
.addCache(cache1)
.addCache(cache2)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testPut() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/WaterfallCacheTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheTest {
@Mock RxCache cache1;
@Mock RxCache cache2;
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
waterfallCache = WaterfallCache.builder()
.addCache(cache1)
.addCache(cache2)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testPut() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
| SimpleObject object = new SimpleObject(value); |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
import rx.Observable; | package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class RxActivity extends BaseTestActivity {
@Override | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java
import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
import rx.Observable;
package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class RxActivity extends BaseTestActivity {
@Override | protected void getTest(Cache waterfallCache, String key) { |
simonpercic/WaterfallCache | waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
| import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
import rx.Observable; | package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class RxActivity extends BaseTestActivity {
@Override
protected void getTest(Cache waterfallCache, String key) { | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/Cache.java
// public interface Cache extends RxCache, AsyncCache {
//
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/BaseTestActivity.java
// public abstract class BaseTestActivity extends AppCompatActivity implements OnClickListener {
//
// private static final String DEFAULT_KEY = "test";
//
// private Cache waterfallCache;
// private TextView tvValueDisplay;
// private EditText etValueInput;
// private EditText etKeyInput;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_test);
// waterfallCache = ((App) getApplication()).getWaterfallCache();
//
// tvValueDisplay = (TextView) findViewById(R.id.tv_value_display);
// etValueInput = (EditText) findViewById(R.id.et_value_input);
// etKeyInput = (EditText) findViewById(R.id.et_key_input);
// etKeyInput.setText(DEFAULT_KEY);
//
// findViewById(R.id.btn_get_value).setOnClickListener(this);
// findViewById(R.id.btn_put_value).setOnClickListener(this);
// findViewById(R.id.btn_remove_value).setOnClickListener(this);
// findViewById(R.id.btn_contains_value).setOnClickListener(this);
// findViewById(R.id.btn_clear).setOnClickListener(this);
// }
//
// @Override public void onClick(View v) {
// int id = v.getId();
//
// switch (id) {
// case R.id.btn_get_value:
// getTest(waterfallCache, getKey());
// break;
// case R.id.btn_put_value:
// putTest();
// break;
// case R.id.btn_remove_value:
// removeTest(waterfallCache, getKey());
// break;
// case R.id.btn_contains_value:
// containsTest(waterfallCache, getKey());
// break;
// case R.id.btn_clear:
// clearTest(waterfallCache);
// break;
// }
// }
//
// protected abstract void getTest(Cache waterfallCache, String key);
//
// private void putTest() {
// if (TextUtils.isEmpty(etValueInput.getText())) {
// return;
// }
//
// putTest(waterfallCache, etValueInput.getText().toString(), getKey());
// }
//
// protected abstract void putTest(Cache waterfallCache, String value, String key);
//
// protected abstract void removeTest(Cache waterfallCache, String key);
//
// protected abstract void containsTest(Cache waterfallCache, String key);
//
// protected abstract void clearTest(Cache waterfallCache);
//
// protected void showValue(SimpleObject simpleObject) {
// tvValueDisplay.setText(simpleObject != null ? simpleObject.getValue() : "");
// }
//
// protected void showSuccessMessage(String tag, boolean success) {
// showMessage(String.format("%s: %s", tag, success ? "success" : "failed"));
// }
//
// protected void showErrorMessage(String tag, Throwable throwable) {
// showMessage(String.format("%s error: %s", tag, throwable.getMessage()));
// }
//
// protected void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// private String getKey() {
// String key = etKeyInput.getText().toString();
//
// if (TextUtils.isEmpty(key)) {
// return DEFAULT_KEY;
// }
//
// return key;
// }
// }
//
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/base/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
// Path: waterfallcache-sample/src/main/java/com/github/simonpercic/waterfallcachesample/test/RxActivity.java
import android.content.Context;
import android.content.Intent;
import com.github.simonpercic.waterfallcache.cache.Cache;
import com.github.simonpercic.waterfallcachesample.test.base.BaseTestActivity;
import com.github.simonpercic.waterfallcachesample.test.base.SimpleObject;
import rx.Observable;
package com.github.simonpercic.waterfallcachesample.test;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class RxActivity extends BaseTestActivity {
@Override
protected void getTest(Cache waterfallCache, String key) { | Observable<SimpleObject> test = waterfallCache.get(key, SimpleObject.class); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; | package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheInlineMemoryTest {
@Mock RxCache cache;
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
waterfallCache = WaterfallCache.builder()
.addMemoryCache(100)
.addCache(cache)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testGetNoValue() throws Exception {
String key = "TEST_KEY";
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
package com.github.simonpercic.waterfallcache;
/**
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class WaterfallCacheInlineMemoryTest {
@Mock RxCache cache;
WaterfallCache waterfallCache;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
waterfallCache = WaterfallCache.builder()
.addMemoryCache(100)
.addCache(cache)
.withObserveOnScheduler(Schedulers.immediate())
.build();
}
@Test
public void testGetNoValue() throws Exception {
String key = "TEST_KEY";
| when(cache.get(eq(key), eq(SimpleObject.class))).thenReturn(Observable.just(null)); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; |
@Test
public void testSimple() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
SimpleObject object = new SimpleObject(value);
when(cache.put(eq(key), eq(object))).thenReturn(Observable.just(true));
ObservableTestUtils.testObservable(waterfallCache.put(key, object), Assert::assertTrue);
verify(cache).put(eq(key), eq(object));
Observable<SimpleObject> getObservable = waterfallCache.get(key, SimpleObject.class);
ObservableTestUtils.testObservable(getObservable, simpleObject -> assertEquals(value, simpleObject.getValue()));
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
verifyNoMoreInteractions(cache);
}
@Test
public void testWrapped() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@Test
public void testSimple() throws Exception {
String key = "TEST_KEY";
String value = "TEST_VALUE";
SimpleObject object = new SimpleObject(value);
when(cache.put(eq(key), eq(object))).thenReturn(Observable.just(true));
ObservableTestUtils.testObservable(waterfallCache.put(key, object), Assert::assertTrue);
verify(cache).put(eq(key), eq(object));
Observable<SimpleObject> getObservable = waterfallCache.get(key, SimpleObject.class);
ObservableTestUtils.testObservable(getObservable, simpleObject -> assertEquals(value, simpleObject.getValue()));
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
verifyNoMoreInteractions(cache);
}
@Test
public void testWrapped() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
| WrappedObject wrapped = new WrappedObject(); |
simonpercic/WaterfallCache | waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryTest.java | // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
| import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; | when(cache.put(eq(key), eq(wrapped))).thenReturn(Observable.just(true));
ObservableTestUtils.testObservable(waterfallCache.put(key, wrapped), Assert::assertTrue);
verify(cache).put(eq(key), eq(wrapped));
Observable<WrappedObject> getObservable = waterfallCache.get(key, WrappedObject.class);
ObservableTestUtils.testObservable(getObservable, wrappedObject -> {
assertEquals(wrappedValue, wrappedObject.getValue());
assertEquals(simpleValue, wrappedObject.getObject().getValue());
});
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
verifyNoMoreInteractions(cache);
}
@Test
public void testGeneric() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
String genericValue = "TEST_GENERIC_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
WrappedObject wrapped = new WrappedObject();
wrapped.setObject(simple);
wrapped.setValue(wrappedValue);
| // Path: waterfallcache/src/main/java/com/github/simonpercic/waterfallcache/cache/RxCache.java
// public interface RxCache {
//
// /**
// * Get from cache.
// *
// * @param key key
// * @param typeOfT type of cache value
// * @param <T> T of cache value
// * @return Observable that emits the cache value
// */
// <T> Observable<T> get(String key, Type typeOfT);
//
// /**
// * Put value to cache.
// *
// * @param key key
// * @param object value
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> put(String key, Object object);
//
// /**
// * Cache contains key.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if cache contains key, <tt>false</tt> otherwise
// */
// Observable<Boolean> contains(String key);
//
// /**
// * Remove cache value.
// *
// * @param key key
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> remove(String key);
//
// /**
// * Clear all cache values.
// *
// * @return Observable that emits <tt>true</tt> if successful, <tt>false</tt> otherwise
// */
// Observable<Boolean> clear();
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/GenericObject.java
// public class GenericObject<T> {
//
// private T object;
//
// private String value;
//
// public T getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(T object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
//
// Path: waterfallcache/src/test/java/com/github/simonpercic/waterfallcache/model/SimpleObject.java
// public class SimpleObject {
//
// private String value;
//
// public SimpleObject(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/model/WrappedObject.java
// public class WrappedObject {
//
// private SimpleObject object;
//
// private String value;
//
// public SimpleObject getObject() {
// return object;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setObject(SimpleObject object) {
// this.object = object;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: waterfallcache/src/androidTest/java/com/github/simonpercic/waterfallcache/WaterfallCacheInlineMemoryTest.java
import com.github.simonpercic.waterfallcache.cache.RxCache;
import com.github.simonpercic.waterfallcache.model.GenericObject;
import com.github.simonpercic.waterfallcache.model.SimpleObject;
import com.github.simonpercic.waterfallcache.model.WrappedObject;
import com.google.gson.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Type;
import rx.Observable;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
when(cache.put(eq(key), eq(wrapped))).thenReturn(Observable.just(true));
ObservableTestUtils.testObservable(waterfallCache.put(key, wrapped), Assert::assertTrue);
verify(cache).put(eq(key), eq(wrapped));
Observable<WrappedObject> getObservable = waterfallCache.get(key, WrappedObject.class);
ObservableTestUtils.testObservable(getObservable, wrappedObject -> {
assertEquals(wrappedValue, wrappedObject.getValue());
assertEquals(simpleValue, wrappedObject.getObject().getValue());
});
ObservableTestUtils.testObservable(waterfallCache.contains(key), Assert::assertTrue);
verifyNoMoreInteractions(cache);
}
@Test
public void testGeneric() throws Exception {
String key = "TEST_KEY";
String simpleValue = "TEST_SIMPLE_VALUE";
String wrappedValue = "TEST_WRAPPED_VALUE";
String genericValue = "TEST_GENERIC_VALUE";
SimpleObject simple = new SimpleObject(simpleValue);
WrappedObject wrapped = new WrappedObject();
wrapped.setObject(simple);
wrapped.setValue(wrappedValue);
| GenericObject<WrappedObject> generic = new GenericObject<>(); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthSecurityMessage.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityMessage.java
// public interface RfbSecurityMessage {
//
// SecurityType getSecurityType();
//
// void setCredentials(ProtocolConfiguration config);
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
| import org.jfxvnc.net.rfb.codec.security.RfbSecurityMessage;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
import java.util.Arrays; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthSecurityMessage implements RfbSecurityMessage {
private final byte[] challenge;
private byte[] password; | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityMessage.java
// public interface RfbSecurityMessage {
//
// SecurityType getSecurityType();
//
// void setCredentials(ProtocolConfiguration config);
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthSecurityMessage.java
import org.jfxvnc.net.rfb.codec.security.RfbSecurityMessage;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
import java.util.Arrays;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthSecurityMessage implements RfbSecurityMessage {
private final byte[] challenge;
private byte[] password; | private ProtocolConfiguration config; |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthSecurityMessage.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityMessage.java
// public interface RfbSecurityMessage {
//
// SecurityType getSecurityType();
//
// void setCredentials(ProtocolConfiguration config);
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
| import org.jfxvnc.net.rfb.codec.security.RfbSecurityMessage;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
import java.util.Arrays; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthSecurityMessage implements RfbSecurityMessage {
private final byte[] challenge;
private byte[] password;
private ProtocolConfiguration config;
public VncAuthSecurityMessage(byte[] challenge) {
this.challenge = challenge;
}
public byte[] getChallenge() {
return challenge;
}
public String getPassword() {
return config.passwordProperty().get();
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityMessage.java
// public interface RfbSecurityMessage {
//
// SecurityType getSecurityType();
//
// void setCredentials(ProtocolConfiguration config);
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthSecurityMessage.java
import org.jfxvnc.net.rfb.codec.security.RfbSecurityMessage;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
import java.util.Arrays;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthSecurityMessage implements RfbSecurityMessage {
private final byte[] challenge;
private byte[] password;
private ProtocolConfiguration config;
public VncAuthSecurityMessage(byte[] challenge) {
this.challenge = challenge;
}
public byte[] getChallenge() {
return challenge;
}
public String getPassword() {
return config.passwordProperty().get();
}
@Override | public SecurityType getSecurityType() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/SecurityTypesEvent.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.security.SecurityType;
import java.util.Arrays; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker.event;
public class SecurityTypesEvent implements HandshakeEvent {
private final boolean response;
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/SecurityTypesEvent.java
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import java.util.Arrays;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker.event;
public class SecurityTypesEvent implements HandshakeEvent {
private final boolean response;
| private final SecurityType[] securityTypes; |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/KeyButtonEventEncoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
| import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.jfxvnc.net.rfb.codec.ClientEventType; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class KeyButtonEventEncoder extends MessageToByteEncoder<KeyButtonEvent> {
@Override
protected void encode(ChannelHandlerContext ctx, KeyButtonEvent msg, ByteBuf out) throws Exception {
ByteBuf buf = ctx.alloc().buffer(8);
try { | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/KeyButtonEventEncoder.java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.jfxvnc.net.rfb.codec.ClientEventType;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class KeyButtonEventEncoder extends MessageToByteEncoder<KeyButtonEvent> {
@Override
protected void encode(ChannelHandlerContext ctx, KeyButtonEvent msg, ByteBuf out) throws Exception {
ByteBuf buf = ctx.alloc().buffer(8);
try { | buf.writeByte(ClientEventType.KEY_EVENT); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthHandshaker.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityDecoder.java
// public interface RfbSecurityDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityEncoder.java
// public interface RfbSecurityEncoder extends ChannelOutboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java
// public abstract class RfbSecurityHandshaker {
//
// public abstract RfbSecurityDecoder newSecurityDecoder();
//
// public abstract RfbSecurityEncoder newSecurityEncoder();
//
// private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
//
// private final SecurityType securityType;
//
// public RfbSecurityHandshaker(SecurityType securityType) {
// this.securityType = securityType;
// }
//
// public boolean isHandshakeComplete() {
// return handshakeComplete.get();
// }
//
// private void setHandshakeComplete() {
// handshakeComplete.set(true);
// }
//
// public ChannelFuture handshake(Channel channel, boolean sendResponse) {
// return handshake(channel, sendResponse, channel.newPromise());
// }
//
// public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
// ChannelPipeline p = channel.pipeline();
// ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
// p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());
//
// ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class);
// p.addBefore(ctx2.name(), "rfb-security-encoder", newSecurityEncoder());
// if (!sendResponse) {
// return promise.setSuccess();
// }
// channel.writeAndFlush(Unpooled.buffer(1).writeByte(securityType.getType()), promise);
// return promise;
// }
//
// public final void finishHandshake(Channel channel, RfbSecurityMessage message) {
// setHandshakeComplete();
//
// ChannelPipeline p = channel.pipeline();
// p.remove("rfb-security-decoder");
// p.remove("rfb-security-encoder");
//
// }
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.security.RfbSecurityEncoder;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityHandshaker;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityDecoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthHandshaker extends RfbSecurityHandshaker {
public VncAuthHandshaker(SecurityType securityType) {
super(securityType);
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityDecoder.java
// public interface RfbSecurityDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityEncoder.java
// public interface RfbSecurityEncoder extends ChannelOutboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java
// public abstract class RfbSecurityHandshaker {
//
// public abstract RfbSecurityDecoder newSecurityDecoder();
//
// public abstract RfbSecurityEncoder newSecurityEncoder();
//
// private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
//
// private final SecurityType securityType;
//
// public RfbSecurityHandshaker(SecurityType securityType) {
// this.securityType = securityType;
// }
//
// public boolean isHandshakeComplete() {
// return handshakeComplete.get();
// }
//
// private void setHandshakeComplete() {
// handshakeComplete.set(true);
// }
//
// public ChannelFuture handshake(Channel channel, boolean sendResponse) {
// return handshake(channel, sendResponse, channel.newPromise());
// }
//
// public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
// ChannelPipeline p = channel.pipeline();
// ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
// p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());
//
// ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class);
// p.addBefore(ctx2.name(), "rfb-security-encoder", newSecurityEncoder());
// if (!sendResponse) {
// return promise.setSuccess();
// }
// channel.writeAndFlush(Unpooled.buffer(1).writeByte(securityType.getType()), promise);
// return promise;
// }
//
// public final void finishHandshake(Channel channel, RfbSecurityMessage message) {
// setHandshakeComplete();
//
// ChannelPipeline p = channel.pipeline();
// p.remove("rfb-security-decoder");
// p.remove("rfb-security-encoder");
//
// }
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthHandshaker.java
import org.jfxvnc.net.rfb.codec.security.RfbSecurityEncoder;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityHandshaker;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityDecoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthHandshaker extends RfbSecurityHandshaker {
public VncAuthHandshaker(SecurityType securityType) {
super(securityType);
}
@Override | public RfbSecurityDecoder newSecurityDecoder() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthHandshaker.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityDecoder.java
// public interface RfbSecurityDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityEncoder.java
// public interface RfbSecurityEncoder extends ChannelOutboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java
// public abstract class RfbSecurityHandshaker {
//
// public abstract RfbSecurityDecoder newSecurityDecoder();
//
// public abstract RfbSecurityEncoder newSecurityEncoder();
//
// private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
//
// private final SecurityType securityType;
//
// public RfbSecurityHandshaker(SecurityType securityType) {
// this.securityType = securityType;
// }
//
// public boolean isHandshakeComplete() {
// return handshakeComplete.get();
// }
//
// private void setHandshakeComplete() {
// handshakeComplete.set(true);
// }
//
// public ChannelFuture handshake(Channel channel, boolean sendResponse) {
// return handshake(channel, sendResponse, channel.newPromise());
// }
//
// public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
// ChannelPipeline p = channel.pipeline();
// ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
// p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());
//
// ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class);
// p.addBefore(ctx2.name(), "rfb-security-encoder", newSecurityEncoder());
// if (!sendResponse) {
// return promise.setSuccess();
// }
// channel.writeAndFlush(Unpooled.buffer(1).writeByte(securityType.getType()), promise);
// return promise;
// }
//
// public final void finishHandshake(Channel channel, RfbSecurityMessage message) {
// setHandshakeComplete();
//
// ChannelPipeline p = channel.pipeline();
// p.remove("rfb-security-decoder");
// p.remove("rfb-security-encoder");
//
// }
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.security.RfbSecurityEncoder;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityHandshaker;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityDecoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthHandshaker extends RfbSecurityHandshaker {
public VncAuthHandshaker(SecurityType securityType) {
super(securityType);
}
@Override
public RfbSecurityDecoder newSecurityDecoder() {
return new VncAuthDecoder();
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityDecoder.java
// public interface RfbSecurityDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityEncoder.java
// public interface RfbSecurityEncoder extends ChannelOutboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java
// public abstract class RfbSecurityHandshaker {
//
// public abstract RfbSecurityDecoder newSecurityDecoder();
//
// public abstract RfbSecurityEncoder newSecurityEncoder();
//
// private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
//
// private final SecurityType securityType;
//
// public RfbSecurityHandshaker(SecurityType securityType) {
// this.securityType = securityType;
// }
//
// public boolean isHandshakeComplete() {
// return handshakeComplete.get();
// }
//
// private void setHandshakeComplete() {
// handshakeComplete.set(true);
// }
//
// public ChannelFuture handshake(Channel channel, boolean sendResponse) {
// return handshake(channel, sendResponse, channel.newPromise());
// }
//
// public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
// ChannelPipeline p = channel.pipeline();
// ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
// p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());
//
// ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class);
// p.addBefore(ctx2.name(), "rfb-security-encoder", newSecurityEncoder());
// if (!sendResponse) {
// return promise.setSuccess();
// }
// channel.writeAndFlush(Unpooled.buffer(1).writeByte(securityType.getType()), promise);
// return promise;
// }
//
// public final void finishHandshake(Channel channel, RfbSecurityMessage message) {
// setHandshakeComplete();
//
// ChannelPipeline p = channel.pipeline();
// p.remove("rfb-security-decoder");
// p.remove("rfb-security-encoder");
//
// }
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/SecurityType.java
// public enum SecurityType {
//
// UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);
//
// private final int type;
//
// private SecurityType(int type) {
// this.type = type;
// }
//
// public static SecurityType valueOf(int type) {
// for (SecurityType e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthHandshaker.java
import org.jfxvnc.net.rfb.codec.security.RfbSecurityEncoder;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityHandshaker;
import org.jfxvnc.net.rfb.codec.security.SecurityType;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityDecoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthHandshaker extends RfbSecurityHandshaker {
public VncAuthHandshaker(SecurityType securityType) {
super(securityType);
}
@Override
public RfbSecurityDecoder newSecurityDecoder() {
return new VncAuthDecoder();
}
@Override | public RfbSecurityEncoder newSecurityEncoder() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/rect/FrameRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.decoder.rect;
public class FrameRect {
private final int x, y, width, height; | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/rect/FrameRect.java
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.decoder.rect;
public class FrameRect {
private final int x, y, width, height; | private final Encoding encoding; |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientDecoder.java
// public interface RfbClientDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientEncoder.java
// public interface RfbClientEncoder extends ChannelOutboundHandler {
//
// }
| import java.util.concurrent.atomic.AtomicBoolean;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientDecoder;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientEncoder;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public abstract class RfbSecurityHandshaker {
public abstract RfbSecurityDecoder newSecurityDecoder();
public abstract RfbSecurityEncoder newSecurityEncoder();
private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
private final SecurityType securityType;
public RfbSecurityHandshaker(SecurityType securityType) {
this.securityType = securityType;
}
public boolean isHandshakeComplete() {
return handshakeComplete.get();
}
private void setHandshakeComplete() {
handshakeComplete.set(true);
}
public ChannelFuture handshake(Channel channel, boolean sendResponse) {
return handshake(channel, sendResponse, channel.newPromise());
}
public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
ChannelPipeline p = channel.pipeline(); | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientDecoder.java
// public interface RfbClientDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientEncoder.java
// public interface RfbClientEncoder extends ChannelOutboundHandler {
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java
import java.util.concurrent.atomic.AtomicBoolean;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientDecoder;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientEncoder;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public abstract class RfbSecurityHandshaker {
public abstract RfbSecurityDecoder newSecurityDecoder();
public abstract RfbSecurityEncoder newSecurityEncoder();
private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
private final SecurityType securityType;
public RfbSecurityHandshaker(SecurityType securityType) {
this.securityType = securityType;
}
public boolean isHandshakeComplete() {
return handshakeComplete.get();
}
private void setHandshakeComplete() {
handshakeComplete.set(true);
}
public ChannelFuture handshake(Channel channel, boolean sendResponse) {
return handshake(channel, sendResponse, channel.newPromise());
}
public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
ChannelPipeline p = channel.pipeline(); | ChannelHandlerContext ctx = p.context(RfbClientDecoder.class); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientDecoder.java
// public interface RfbClientDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientEncoder.java
// public interface RfbClientEncoder extends ChannelOutboundHandler {
//
// }
| import java.util.concurrent.atomic.AtomicBoolean;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientDecoder;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientEncoder;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public abstract class RfbSecurityHandshaker {
public abstract RfbSecurityDecoder newSecurityDecoder();
public abstract RfbSecurityEncoder newSecurityEncoder();
private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
private final SecurityType securityType;
public RfbSecurityHandshaker(SecurityType securityType) {
this.securityType = securityType;
}
public boolean isHandshakeComplete() {
return handshakeComplete.get();
}
private void setHandshakeComplete() {
handshakeComplete.set(true);
}
public ChannelFuture handshake(Channel channel, boolean sendResponse) {
return handshake(channel, sendResponse, channel.newPromise());
}
public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
ChannelPipeline p = channel.pipeline();
ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientDecoder.java
// public interface RfbClientDecoder extends ChannelInboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientEncoder.java
// public interface RfbClientEncoder extends ChannelOutboundHandler {
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshaker.java
import java.util.concurrent.atomic.AtomicBoolean;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientDecoder;
import org.jfxvnc.net.rfb.codec.handshaker.RfbClientEncoder;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public abstract class RfbSecurityHandshaker {
public abstract RfbSecurityDecoder newSecurityDecoder();
public abstract RfbSecurityEncoder newSecurityEncoder();
private AtomicBoolean handshakeComplete = new AtomicBoolean(false);
private final SecurityType securityType;
public RfbSecurityHandshaker(SecurityType securityType) {
this.securityType = securityType;
}
public boolean isHandshakeComplete() {
return handshakeComplete.get();
}
private void setHandshakeComplete() {
handshakeComplete.set(true);
}
public ChannelFuture handshake(Channel channel, boolean sendResponse) {
return handshake(channel, sendResponse, channel.newPromise());
}
public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
ChannelPipeline p = channel.pipeline();
ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());
| ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClient33Encoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/HandshakeEvent.java
// public interface HandshakeEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/SharedEvent.java
// public class SharedEvent implements HandshakeEvent {
//
// private final boolean shared;
//
// public SharedEvent(boolean shared) {
// this.shared = shared;
// }
//
// public boolean isShared() {
// return shared;
// }
//
// }
| import org.jfxvnc.net.rfb.codec.handshaker.event.HandshakeEvent;
import org.jfxvnc.net.rfb.codec.handshaker.event.SharedEvent;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker;
public class RfbClient33Encoder extends MessageToByteEncoder<HandshakeEvent> implements RfbClientEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, HandshakeEvent msg, ByteBuf out) throws Exception { | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/HandshakeEvent.java
// public interface HandshakeEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/SharedEvent.java
// public class SharedEvent implements HandshakeEvent {
//
// private final boolean shared;
//
// public SharedEvent(boolean shared) {
// this.shared = shared;
// }
//
// public boolean isShared() {
// return shared;
// }
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClient33Encoder.java
import org.jfxvnc.net.rfb.codec.handshaker.event.HandshakeEvent;
import org.jfxvnc.net.rfb.codec.handshaker.event.SharedEvent;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker;
public class RfbClient33Encoder extends MessageToByteEncoder<HandshakeEvent> implements RfbClientEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, HandshakeEvent msg, ByteBuf out) throws Exception { | if (msg instanceof SharedEvent) { |
comtel2000/jfxvnc | jfxvnc-app/src/test/java/org/jfxvnc/app/presentation/about/AboutViewTest.java | // Path: jfxvnc-app/src/main/java/org/jfxvnc/app/presentation/about/AboutViewPresenter.java
// public class AboutViewPresenter implements Initializable {
//
// @FXML
// private TextArea build;
// @FXML
// private TextArea license;
// @FXML
// private TextArea thirdLicense;
//
// @Override
// public void initialize(URL location, ResourceBundle resources) {
//
// String version = AboutViewPresenter.class.getPackage().getImplementationVersion();
// appendBuildLine(String.format("JavaFX VNC (%s)", version != null ? version : "DEV"));
// appendBuildLine("Copyright © 2015 - comtel2000");
// appendBuildLine(null);
// appendBuildLine(System.getProperty("java.runtime.name"));
// appendBuildLine(String.format("Version:\t%s (%s)", System.getProperty("java.runtime.version"), System.getProperty("java.vendor")));
// appendBuildLine(String.format("OS: \t%s (%s) %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")));
//
// }
//
// private void appendBuildLine(String text) {
// if (text != null) {
// build.appendText(text);
// }
// build.appendText(System.lineSeparator());
// }
// }
| import static org.junit.Assert.assertNotNull;
import org.jfxvnc.app.presentation.about.AboutViewPresenter;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import com.airhacks.afterburner.injection.Injector; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.app.presentation.about;
public class AboutViewTest {
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(AboutViewTest.class);
// private static Stage stage;
@BeforeClass
public static void init() {
Injector.setLogger((t) -> logger.info(t));
// AboutView view = new AboutView();
// stage = new Stage(StageStyle.UNDECORATED);
// stage.setScene(new Scene(view.getView()));
// stage.show();
}
public static void end() {
Injector.forgetAll();
// stage.close();
}
@Test
public void aboutView() {
| // Path: jfxvnc-app/src/main/java/org/jfxvnc/app/presentation/about/AboutViewPresenter.java
// public class AboutViewPresenter implements Initializable {
//
// @FXML
// private TextArea build;
// @FXML
// private TextArea license;
// @FXML
// private TextArea thirdLicense;
//
// @Override
// public void initialize(URL location, ResourceBundle resources) {
//
// String version = AboutViewPresenter.class.getPackage().getImplementationVersion();
// appendBuildLine(String.format("JavaFX VNC (%s)", version != null ? version : "DEV"));
// appendBuildLine("Copyright © 2015 - comtel2000");
// appendBuildLine(null);
// appendBuildLine(System.getProperty("java.runtime.name"));
// appendBuildLine(String.format("Version:\t%s (%s)", System.getProperty("java.runtime.version"), System.getProperty("java.vendor")));
// appendBuildLine(String.format("OS: \t%s (%s) %s", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")));
//
// }
//
// private void appendBuildLine(String text) {
// if (text != null) {
// build.appendText(text);
// }
// build.appendText(System.lineSeparator());
// }
// }
// Path: jfxvnc-app/src/test/java/org/jfxvnc/app/presentation/about/AboutViewTest.java
import static org.junit.Assert.assertNotNull;
import org.jfxvnc.app.presentation.about.AboutViewPresenter;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import com.airhacks.afterburner.injection.Injector;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.app.presentation.about;
public class AboutViewTest {
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(AboutViewTest.class);
// private static Stage stage;
@BeforeClass
public static void init() {
Injector.setLogger((t) -> logger.info(t));
// AboutView view = new AboutView();
// stage = new Stage(StageStyle.UNDECORATED);
// stage.setScene(new Scene(view.getView()));
// stage.show();
}
public static void end() {
Injector.forgetAll();
// stage.close();
}
@Test
public void aboutView() {
| AboutViewPresenter presenter = Injector.instantiatePresenter(AboutViewPresenter.class); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public abstract class ImageRect {
protected final int x;
protected final int y;
protected final int width;
protected final int height;
public ImageRect(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* @return the image {@link Encoding} type
*/ | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public abstract class ImageRect {
protected final int x;
protected final int y;
protected final int width;
protected final int height;
public ImageRect(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* @return the image {@link Encoding} type
*/ | public abstract Encoding getEncoding(); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthEncoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityEncoder.java
// public interface RfbSecurityEncoder extends ChannelOutboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/exception/ProtocolException.java
// public class ProtocolException extends Exception {
//
// private static final long serialVersionUID = 5616560775184943955L;
//
// public ProtocolException(String message) {
// super(message);
// }
//
// public ProtocolException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
| import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityEncoder;
import org.jfxvnc.net.rfb.exception.ProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthEncoder extends MessageToByteEncoder<VncAuthSecurityMessage> implements RfbSecurityEncoder {
private static Logger logger = LoggerFactory.getLogger(VncAuthEncoder.class);
@Override
protected void encode(ChannelHandlerContext ctx, VncAuthSecurityMessage msg, ByteBuf out) throws Exception {
byte[] enc = encryptPassword(msg);
logger.debug("VNC Auth encrypted: {}", enc);
out.writeBytes(enc);
}
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityEncoder.java
// public interface RfbSecurityEncoder extends ChannelOutboundHandler {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/exception/ProtocolException.java
// public class ProtocolException extends Exception {
//
// private static final long serialVersionUID = 5616560775184943955L;
//
// public ProtocolException(String message) {
// super(message);
// }
//
// public ProtocolException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthEncoder.java
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.jfxvnc.net.rfb.codec.security.RfbSecurityEncoder;
import org.jfxvnc.net.rfb.exception.ProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security.vncauth;
public class VncAuthEncoder extends MessageToByteEncoder<VncAuthSecurityMessage> implements RfbSecurityEncoder {
private static Logger logger = LoggerFactory.getLogger(VncAuthEncoder.class);
@Override
protected void encode(ChannelHandlerContext ctx, VncAuthSecurityMessage msg, ByteBuf out) throws Exception {
byte[] enc = encryptPassword(msg);
logger.debug("VNC Auth encrypted: {}", enc);
out.writeBytes(enc);
}
| private byte[] encryptPassword(VncAuthSecurityMessage msg) throws ProtocolException { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/CopyImageRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class CopyImageRect extends ImageRect {
protected final int srcX;
protected final int srcY;
public CopyImageRect(int x, int y, int width, int height, int srcx, int srcy) {
super(x, y, width, height);
this.srcX = srcx;
this.srcY = srcy;
}
public int getSrcX() {
return srcX;
}
public int getSrcY() {
return srcY;
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/CopyImageRect.java
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class CopyImageRect extends ImageRect {
protected final int srcX;
protected final int srcY;
public CopyImageRect(int x, int y, int width, int height, int srcx, int srcy) {
super(x, y, width, height);
this.srcX = srcx;
this.srcY = srcy;
}
public int getSrcX() {
return srcX;
}
public int getSrcY() {
return srcY;
}
@Override | public Encoding getEncoding() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/DesktopSizeRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class DesktopSizeRect extends ImageRect {
public DesktopSizeRect(int x, int y, int width, int height) {
super(x, y, width, height);
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/DesktopSizeRect.java
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class DesktopSizeRect extends ImageRect {
public DesktopSizeRect(int x, int y, int width, int height) {
super(x, y, width, height);
}
@Override | public Encoding getEncoding() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/PointerEventEncoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
| import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.jfxvnc.net.rfb.codec.ClientEventType; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class PointerEventEncoder extends MessageToByteEncoder<PointerEvent> {
@Override
protected void encode(ChannelHandlerContext ctx, PointerEvent msg, ByteBuf out) throws Exception {
ByteBuf buf = ctx.alloc().buffer(6);
try { | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/PointerEventEncoder.java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.jfxvnc.net.rfb.codec.ClientEventType;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class PointerEventEncoder extends MessageToByteEncoder<PointerEvent> {
@Override
protected void encode(ChannelHandlerContext ctx, PointerEvent msg, ByteBuf out) throws Exception {
ByteBuf buf = ctx.alloc().buffer(6);
try { | buf.writeByte(ClientEventType.POINTER_EVENT); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshakerFactory.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthHandshaker.java
// public class VncAuthHandshaker extends RfbSecurityHandshaker {
//
// public VncAuthHandshaker(SecurityType securityType) {
// super(securityType);
// }
//
// @Override
// public RfbSecurityDecoder newSecurityDecoder() {
// return new VncAuthDecoder();
// }
//
// @Override
// public RfbSecurityEncoder newSecurityEncoder() {
// return new VncAuthEncoder();
// }
//
// }
| import org.jfxvnc.net.rfb.codec.security.vncauth.VncAuthHandshaker; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public class RfbSecurityHandshakerFactory {
public RfbSecurityHandshakerFactory() {}
public RfbSecurityHandshaker newRfbSecurityHandshaker(SecurityType securityType) {
if (securityType == SecurityType.VNC_Auth) { | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/vncauth/VncAuthHandshaker.java
// public class VncAuthHandshaker extends RfbSecurityHandshaker {
//
// public VncAuthHandshaker(SecurityType securityType) {
// super(securityType);
// }
//
// @Override
// public RfbSecurityDecoder newSecurityDecoder() {
// return new VncAuthDecoder();
// }
//
// @Override
// public RfbSecurityEncoder newSecurityEncoder() {
// return new VncAuthEncoder();
// }
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityHandshakerFactory.java
import org.jfxvnc.net.rfb.codec.security.vncauth.VncAuthHandshaker;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public class RfbSecurityHandshakerFactory {
public RfbSecurityHandshakerFactory() {}
public RfbSecurityHandshaker newRfbSecurityHandshaker(SecurityType securityType) {
if (securityType == SecurityType.VNC_Auth) { | return new VncAuthHandshaker(securityType); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClient38Encoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/HandshakeEvent.java
// public interface HandshakeEvent {
//
// }
| import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.jfxvnc.net.rfb.codec.handshaker.event.HandshakeEvent; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker;
public class RfbClient38Encoder extends RfbClient33Encoder {
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/event/HandshakeEvent.java
// public interface HandshakeEvent {
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClient38Encoder.java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.jfxvnc.net.rfb.codec.handshaker.event.HandshakeEvent;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker;
public class RfbClient38Encoder extends RfbClient33Encoder {
@Override | protected void encode(ChannelHandlerContext ctx, HandshakeEvent msg, ByteBuf out) throws Exception { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/PreferedEncodingEncoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
| import java.util.Arrays;
import org.jfxvnc.net.rfb.codec.ClientEventType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class PreferedEncodingEncoder extends MessageToByteEncoder<PreferedEncoding> {
@Override
protected void encode(ChannelHandlerContext ctx, PreferedEncoding enc, ByteBuf out) throws Exception { | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/PreferedEncodingEncoder.java
import java.util.Arrays;
import org.jfxvnc.net.rfb.codec.ClientEventType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class PreferedEncodingEncoder extends MessageToByteEncoder<PreferedEncoding> {
@Override
protected void encode(ChannelHandlerContext ctx, PreferedEncoding enc, ByteBuf out) throws Exception { | out.writeByte(ClientEventType.SET_ENCODINGS); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ZlibImageRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import io.netty.buffer.ByteBuf;
import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class ZlibImageRect extends RawImageRect {
public ZlibImageRect(int x, int y, int width, int height, ByteBuf pixels, int scanlineStride) {
super(x, y, width, height, pixels, scanlineStride);
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ZlibImageRect.java
import io.netty.buffer.ByteBuf;
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class ZlibImageRect extends RawImageRect {
public ZlibImageRect(int x, int y, int width, int height, ByteBuf pixels, int scanlineStride) {
super(x, y, width, height, pixels, scanlineStride);
}
@Override | public Encoding getEncoding() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/HextileImageRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import java.util.List;
import org.jfxvnc.net.rfb.codec.Encoding;
import java.util.ArrayList; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class HextileImageRect extends ImageRect {
protected final List<RawImageRect> rects;
public HextileImageRect(int x, int y, int width, int height) {
super(x, y, width, height);
rects = new ArrayList<>();
}
public List<RawImageRect> getRects() {
return rects;
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/HextileImageRect.java
import java.util.List;
import org.jfxvnc.net.rfb.codec.Encoding;
import java.util.ArrayList;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class HextileImageRect extends ImageRect {
protected final List<RawImageRect> rects;
public HextileImageRect(int x, int y, int width, int height) {
super(x, y, width, height);
rects = new ArrayList<>();
}
public List<RawImageRect> getRects() {
return rects;
}
@Override | public Encoding getEncoding() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/RawImageRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import io.netty.buffer.ByteBuf;
import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class RawImageRect extends ImageRect {
protected final ByteBuf pixels;
protected final int scanlineStride;
public RawImageRect(int x, int y, int width, int height, ByteBuf pixels, int scanlineStride) {
super(x, y, width, height);
this.pixels = pixels;
this.scanlineStride = scanlineStride;
}
/**
* Returns a byte buffer of a pixel data
*
* @return pixels
*/
public ByteBuf getPixels() {
return pixels;
}
/**
* Returns the distance between the pixel data for the start of one row of data in the buffer to
* the start of the next row of data.
*
* @return scanlineStride
*/
public int getScanlineStride() {
return scanlineStride;
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/RawImageRect.java
import io.netty.buffer.ByteBuf;
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class RawImageRect extends ImageRect {
protected final ByteBuf pixels;
protected final int scanlineStride;
public RawImageRect(int x, int y, int width, int height, ByteBuf pixels, int scanlineStride) {
super(x, y, width, height);
this.pixels = pixels;
this.scanlineStride = scanlineStride;
}
/**
* Returns a byte buffer of a pixel data
*
* @return pixels
*/
public ByteBuf getPixels() {
return pixels;
}
/**
* Returns the distance between the pixel data for the start of one row of data in the buffer to
* the start of the next row of data.
*
* @return scanlineStride
*/
public int getScanlineStride() {
return scanlineStride;
}
@Override | public Encoding getEncoding() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ProtocolVersionDecoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolVersion.java
// public class ProtocolVersion implements Comparable<ProtocolVersion> {
//
// public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);
// public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);
// public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);
//
// private final Pattern VERSION_PAT = Pattern.compile("RFB ([0-9]{3}).([0-9]{3})");
//
// private int majorVersion;
//
// private int minorVersion;
//
// /**
// * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))
// *
// * @param version String
// */
// public ProtocolVersion(String version) {
// if (version == null) {
// throw new IllegalArgumentException("null can not parsed to version");
// }
// Matcher versionMatcher = VERSION_PAT.matcher(version);
// if (versionMatcher.find()) {
// majorVersion = Integer.parseInt(versionMatcher.group(1));
// minorVersion = Integer.parseInt(versionMatcher.group(2));
// } else {
// throw new IllegalArgumentException("version: " + version + " not supported");
// }
// }
//
// public ProtocolVersion(int major, int minor) {
// majorVersion = major;
// minorVersion = minor;
// }
//
// public int getMajorVersion() {
// return majorVersion;
// }
//
// public int getMinorVersion() {
// return minorVersion;
// }
//
// public boolean isGreaterThan(ProtocolVersion o) {
// return compareTo(o) > 0;
// }
//
// public boolean isGreaterThan(String v) {
// return compareTo(new ProtocolVersion(v)) > 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof ProtocolVersion)) {
// return false;
// }
// return compareTo((ProtocolVersion) obj) == 0;
// }
//
// @Override
// public int compareTo(ProtocolVersion v) {
// if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {
// return 0;
// }
// if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {
// return 1;
// }
// return -1;
// }
//
// /**
// * encoded ASCII bytes include LF
// *
// * @return expected RFB version bytes
// */
// public byte[] getBytes() {
// return String.format("RFB %03d.%03d\n", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);
// }
//
// @Override
// public String toString() {
// return String.format("RFB %03d.%03d", majorVersion, minorVersion);
// }
// }
| import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.jfxvnc.net.rfb.codec.ProtocolVersion;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.decoder;
public class ProtocolVersionDecoder extends ByteToMessageDecoder {
protected final Charset ASCII = StandardCharsets.US_ASCII;
private final int length = 12;
public ProtocolVersionDecoder() {
setSingleDecode(true);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (!in.isReadable(length)) {
return;
}
byte[] rfb = new byte[length];
in.readBytes(rfb);
String rfbVersion = new String(rfb, ASCII); | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolVersion.java
// public class ProtocolVersion implements Comparable<ProtocolVersion> {
//
// public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);
// public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);
// public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);
//
// private final Pattern VERSION_PAT = Pattern.compile("RFB ([0-9]{3}).([0-9]{3})");
//
// private int majorVersion;
//
// private int minorVersion;
//
// /**
// * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))
// *
// * @param version String
// */
// public ProtocolVersion(String version) {
// if (version == null) {
// throw new IllegalArgumentException("null can not parsed to version");
// }
// Matcher versionMatcher = VERSION_PAT.matcher(version);
// if (versionMatcher.find()) {
// majorVersion = Integer.parseInt(versionMatcher.group(1));
// minorVersion = Integer.parseInt(versionMatcher.group(2));
// } else {
// throw new IllegalArgumentException("version: " + version + " not supported");
// }
// }
//
// public ProtocolVersion(int major, int minor) {
// majorVersion = major;
// minorVersion = minor;
// }
//
// public int getMajorVersion() {
// return majorVersion;
// }
//
// public int getMinorVersion() {
// return minorVersion;
// }
//
// public boolean isGreaterThan(ProtocolVersion o) {
// return compareTo(o) > 0;
// }
//
// public boolean isGreaterThan(String v) {
// return compareTo(new ProtocolVersion(v)) > 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof ProtocolVersion)) {
// return false;
// }
// return compareTo((ProtocolVersion) obj) == 0;
// }
//
// @Override
// public int compareTo(ProtocolVersion v) {
// if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {
// return 0;
// }
// if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {
// return 1;
// }
// return -1;
// }
//
// /**
// * encoded ASCII bytes include LF
// *
// * @return expected RFB version bytes
// */
// public byte[] getBytes() {
// return String.format("RFB %03d.%03d\n", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);
// }
//
// @Override
// public String toString() {
// return String.format("RFB %03d.%03d", majorVersion, minorVersion);
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ProtocolVersionDecoder.java
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.jfxvnc.net.rfb.codec.ProtocolVersion;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.decoder;
public class ProtocolVersionDecoder extends ByteToMessageDecoder {
protected final Charset ASCII = StandardCharsets.US_ASCII;
private final int length = 12;
public ProtocolVersionDecoder() {
setSingleDecode(true);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (!in.isReadable(length)) {
return;
}
byte[] rfb = new byte[length];
in.readBytes(rfb);
String rfbVersion = new String(rfb, ASCII); | out.add(new ProtocolVersion(rfbVersion)); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/CursorImageRect.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
| import io.netty.buffer.ByteBuf;
import org.jfxvnc.net.rfb.codec.Encoding; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class CursorImageRect extends RawImageRect {
public CursorImageRect(int x, int y, int width, int height, ByteBuf pixels) {
super(x, y, width, height, pixels, 1);
}
public int getHotspotX() {
return x;
}
public int getHotspotY() {
return y;
}
@Override | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/Encoding.java
// public enum Encoding {
//
//
//
// UNKNOWN(Integer.MIN_VALUE),
//
// RAW(0),
//
// COPY_RECT(1),
//
// RRE(2),
//
// CO_RRE(4),
//
// HEXTILE(5),
//
// ZLIB(6),
//
// TIGHT(7),
//
// ZLIB_HEX(8),
//
// TRLE(15),
//
// ZRLE(16),
//
// H_ZYWRLE(17),
//
// AW_XZ(18),
//
// AW_XZYW(19),
//
// DESKTOP_SIZE(-223),
//
// CURSOR(-239);
//
// private static Logger logger = LoggerFactory.getLogger(Encoding.class);
//
// private final int type;
//
// private Encoding(int type) {
// this.type = type;
// }
//
// public static Encoding valueOf(int type) {
// for (Encoding e : values()) {
// if (e.type == type) {
// return e;
// }
// }
// logger.error("unknown encoding: {}", type);
// return UNKNOWN;
// }
//
// public int getType() {
// return type;
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/CursorImageRect.java
import io.netty.buffer.ByteBuf;
import org.jfxvnc.net.rfb.codec.Encoding;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render.rect;
public class CursorImageRect extends RawImageRect {
public CursorImageRect(int x, int y, int width, int height, ByteBuf pixels) {
super(x, y, width, height, pixels, 1);
}
public int getHotspotX() {
return x;
}
public int getHotspotY() {
return y;
}
@Override | public Encoding getEncoding() { |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolState.java
// public enum ProtocolState {
//
// LISTENING, HANDSHAKE_STARTED, SECURITY_STARTED, SECURITY_FAILED, SECURITY_COMPLETE, HANDSHAKE_COMPLETE, FBU_REQUEST, CLOSED
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ServerDecoderEvent.java
// public interface ServerDecoderEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/InputEventListener.java
// public interface InputEventListener extends EventListener {
//
// void sendInputEvent(InputEvent event);
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
// public abstract class ImageRect {
//
// protected final int x;
// protected final int y;
// protected final int width;
// protected final int height;
//
// public ImageRect(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
// }
//
// /**
// * @return the image {@link Encoding} type
// */
// public abstract Encoding getEncoding();
//
//
// /**
// * @return the X coordinate of the image rectangular
// */
// public int getX() {
// return x;
// }
//
// /**
// * @return the Y coordinate of the image rectangular
// */
// public int getY() {
// return y;
// }
//
// /**
// * @return the width of the image rectangular
// */
// public int getWidth() {
// return width;
// }
//
// /**
// * @return the height of the image rectangular
// */
// public int getHeight() {
// return height;
// }
//
// /**
// * Release the image buffer
// *
// * @return if successful
// */
// public boolean release() {
// return true;
// }
//
// @Override
// public String toString() {
// return "ImageRect [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
// }
//
// }
| import org.jfxvnc.net.rfb.codec.decoder.ServerDecoderEvent;
import org.jfxvnc.net.rfb.codec.encoder.InputEventListener;
import org.jfxvnc.net.rfb.render.rect.ImageRect;
import org.jfxvnc.net.rfb.codec.ProtocolState; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render;
public interface RenderProtocol {
void render(ImageRect rect);
void renderComplete(RenderCallback callback);
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolState.java
// public enum ProtocolState {
//
// LISTENING, HANDSHAKE_STARTED, SECURITY_STARTED, SECURITY_FAILED, SECURITY_COMPLETE, HANDSHAKE_COMPLETE, FBU_REQUEST, CLOSED
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ServerDecoderEvent.java
// public interface ServerDecoderEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/InputEventListener.java
// public interface InputEventListener extends EventListener {
//
// void sendInputEvent(InputEvent event);
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
// public abstract class ImageRect {
//
// protected final int x;
// protected final int y;
// protected final int width;
// protected final int height;
//
// public ImageRect(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
// }
//
// /**
// * @return the image {@link Encoding} type
// */
// public abstract Encoding getEncoding();
//
//
// /**
// * @return the X coordinate of the image rectangular
// */
// public int getX() {
// return x;
// }
//
// /**
// * @return the Y coordinate of the image rectangular
// */
// public int getY() {
// return y;
// }
//
// /**
// * @return the width of the image rectangular
// */
// public int getWidth() {
// return width;
// }
//
// /**
// * @return the height of the image rectangular
// */
// public int getHeight() {
// return height;
// }
//
// /**
// * Release the image buffer
// *
// * @return if successful
// */
// public boolean release() {
// return true;
// }
//
// @Override
// public String toString() {
// return "ImageRect [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
// }
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java
import org.jfxvnc.net.rfb.codec.decoder.ServerDecoderEvent;
import org.jfxvnc.net.rfb.codec.encoder.InputEventListener;
import org.jfxvnc.net.rfb.render.rect.ImageRect;
import org.jfxvnc.net.rfb.codec.ProtocolState;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render;
public interface RenderProtocol {
void render(ImageRect rect);
void renderComplete(RenderCallback callback);
| void eventReceived(ServerDecoderEvent event); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolState.java
// public enum ProtocolState {
//
// LISTENING, HANDSHAKE_STARTED, SECURITY_STARTED, SECURITY_FAILED, SECURITY_COMPLETE, HANDSHAKE_COMPLETE, FBU_REQUEST, CLOSED
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ServerDecoderEvent.java
// public interface ServerDecoderEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/InputEventListener.java
// public interface InputEventListener extends EventListener {
//
// void sendInputEvent(InputEvent event);
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
// public abstract class ImageRect {
//
// protected final int x;
// protected final int y;
// protected final int width;
// protected final int height;
//
// public ImageRect(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
// }
//
// /**
// * @return the image {@link Encoding} type
// */
// public abstract Encoding getEncoding();
//
//
// /**
// * @return the X coordinate of the image rectangular
// */
// public int getX() {
// return x;
// }
//
// /**
// * @return the Y coordinate of the image rectangular
// */
// public int getY() {
// return y;
// }
//
// /**
// * @return the width of the image rectangular
// */
// public int getWidth() {
// return width;
// }
//
// /**
// * @return the height of the image rectangular
// */
// public int getHeight() {
// return height;
// }
//
// /**
// * Release the image buffer
// *
// * @return if successful
// */
// public boolean release() {
// return true;
// }
//
// @Override
// public String toString() {
// return "ImageRect [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
// }
//
// }
| import org.jfxvnc.net.rfb.codec.decoder.ServerDecoderEvent;
import org.jfxvnc.net.rfb.codec.encoder.InputEventListener;
import org.jfxvnc.net.rfb.render.rect.ImageRect;
import org.jfxvnc.net.rfb.codec.ProtocolState; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render;
public interface RenderProtocol {
void render(ImageRect rect);
void renderComplete(RenderCallback callback);
void eventReceived(ServerDecoderEvent event);
void exceptionCaught(Throwable t);
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolState.java
// public enum ProtocolState {
//
// LISTENING, HANDSHAKE_STARTED, SECURITY_STARTED, SECURITY_FAILED, SECURITY_COMPLETE, HANDSHAKE_COMPLETE, FBU_REQUEST, CLOSED
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ServerDecoderEvent.java
// public interface ServerDecoderEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/InputEventListener.java
// public interface InputEventListener extends EventListener {
//
// void sendInputEvent(InputEvent event);
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
// public abstract class ImageRect {
//
// protected final int x;
// protected final int y;
// protected final int width;
// protected final int height;
//
// public ImageRect(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
// }
//
// /**
// * @return the image {@link Encoding} type
// */
// public abstract Encoding getEncoding();
//
//
// /**
// * @return the X coordinate of the image rectangular
// */
// public int getX() {
// return x;
// }
//
// /**
// * @return the Y coordinate of the image rectangular
// */
// public int getY() {
// return y;
// }
//
// /**
// * @return the width of the image rectangular
// */
// public int getWidth() {
// return width;
// }
//
// /**
// * @return the height of the image rectangular
// */
// public int getHeight() {
// return height;
// }
//
// /**
// * Release the image buffer
// *
// * @return if successful
// */
// public boolean release() {
// return true;
// }
//
// @Override
// public String toString() {
// return "ImageRect [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
// }
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java
import org.jfxvnc.net.rfb.codec.decoder.ServerDecoderEvent;
import org.jfxvnc.net.rfb.codec.encoder.InputEventListener;
import org.jfxvnc.net.rfb.render.rect.ImageRect;
import org.jfxvnc.net.rfb.codec.ProtocolState;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render;
public interface RenderProtocol {
void render(ImageRect rect);
void renderComplete(RenderCallback callback);
void eventReceived(ServerDecoderEvent event);
void exceptionCaught(Throwable t);
| void stateChanged(ProtocolState state); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolState.java
// public enum ProtocolState {
//
// LISTENING, HANDSHAKE_STARTED, SECURITY_STARTED, SECURITY_FAILED, SECURITY_COMPLETE, HANDSHAKE_COMPLETE, FBU_REQUEST, CLOSED
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ServerDecoderEvent.java
// public interface ServerDecoderEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/InputEventListener.java
// public interface InputEventListener extends EventListener {
//
// void sendInputEvent(InputEvent event);
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
// public abstract class ImageRect {
//
// protected final int x;
// protected final int y;
// protected final int width;
// protected final int height;
//
// public ImageRect(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
// }
//
// /**
// * @return the image {@link Encoding} type
// */
// public abstract Encoding getEncoding();
//
//
// /**
// * @return the X coordinate of the image rectangular
// */
// public int getX() {
// return x;
// }
//
// /**
// * @return the Y coordinate of the image rectangular
// */
// public int getY() {
// return y;
// }
//
// /**
// * @return the width of the image rectangular
// */
// public int getWidth() {
// return width;
// }
//
// /**
// * @return the height of the image rectangular
// */
// public int getHeight() {
// return height;
// }
//
// /**
// * Release the image buffer
// *
// * @return if successful
// */
// public boolean release() {
// return true;
// }
//
// @Override
// public String toString() {
// return "ImageRect [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
// }
//
// }
| import org.jfxvnc.net.rfb.codec.decoder.ServerDecoderEvent;
import org.jfxvnc.net.rfb.codec.encoder.InputEventListener;
import org.jfxvnc.net.rfb.render.rect.ImageRect;
import org.jfxvnc.net.rfb.codec.ProtocolState; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render;
public interface RenderProtocol {
void render(ImageRect rect);
void renderComplete(RenderCallback callback);
void eventReceived(ServerDecoderEvent event);
void exceptionCaught(Throwable t);
void stateChanged(ProtocolState state);
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolState.java
// public enum ProtocolState {
//
// LISTENING, HANDSHAKE_STARTED, SECURITY_STARTED, SECURITY_FAILED, SECURITY_COMPLETE, HANDSHAKE_COMPLETE, FBU_REQUEST, CLOSED
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/decoder/ServerDecoderEvent.java
// public interface ServerDecoderEvent {
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/InputEventListener.java
// public interface InputEventListener extends EventListener {
//
// void sendInputEvent(InputEvent event);
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/rect/ImageRect.java
// public abstract class ImageRect {
//
// protected final int x;
// protected final int y;
// protected final int width;
// protected final int height;
//
// public ImageRect(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
// }
//
// /**
// * @return the image {@link Encoding} type
// */
// public abstract Encoding getEncoding();
//
//
// /**
// * @return the X coordinate of the image rectangular
// */
// public int getX() {
// return x;
// }
//
// /**
// * @return the Y coordinate of the image rectangular
// */
// public int getY() {
// return y;
// }
//
// /**
// * @return the width of the image rectangular
// */
// public int getWidth() {
// return width;
// }
//
// /**
// * @return the height of the image rectangular
// */
// public int getHeight() {
// return height;
// }
//
// /**
// * Release the image buffer
// *
// * @return if successful
// */
// public boolean release() {
// return true;
// }
//
// @Override
// public String toString() {
// return "ImageRect [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + "]";
// }
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java
import org.jfxvnc.net.rfb.codec.decoder.ServerDecoderEvent;
import org.jfxvnc.net.rfb.codec.encoder.InputEventListener;
import org.jfxvnc.net.rfb.render.rect.ImageRect;
import org.jfxvnc.net.rfb.codec.ProtocolState;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.render;
public interface RenderProtocol {
void render(ImageRect rect);
void renderComplete(RenderCallback callback);
void eventReceived(ServerDecoderEvent event);
void exceptionCaught(Throwable t);
void stateChanged(ProtocolState state);
| void registerInputEventListener(InputEventListener listener); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/ClientCutTextEncoder.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
| import java.nio.charset.StandardCharsets;
import java.util.List;
import org.jfxvnc.net.rfb.codec.ClientEventType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class ClientCutTextEncoder extends MessageToMessageEncoder<ClientCutText> {
@Override
protected void encode(ChannelHandlerContext ctx, ClientCutText msg, List<Object> out) throws Exception {
byte[] text = msg.getText().getBytes(StandardCharsets.ISO_8859_1);
ByteBuf buf = ctx.alloc().buffer(8 + text.length); | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ClientEventType.java
// public interface ClientEventType {
//
// int SET_PIXEL_FORMAT = 0;
// int SET_ENCODINGS = 2;
// int FRAMEBUFFER_UPDATE_REQUEST = 3;
// int KEY_EVENT = 4;
// int POINTER_EVENT = 5;
// int CLIENT_CUT_TEXT = 6;
//
// int AL = 255;
// int VMWare_A = 254;
// int VMWare_B = 127;
// int GII = 253;
// int TIGHT = 252;
// int PO_SET_DESKTOP_SIZE = 251;
// int CD_XVP = 250;
// int OLIVE_CALL_CONTROL = 249;
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/encoder/ClientCutTextEncoder.java
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.jfxvnc.net.rfb.codec.ClientEventType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.encoder;
public class ClientCutTextEncoder extends MessageToMessageEncoder<ClientCutText> {
@Override
protected void encode(ChannelHandlerContext ctx, ClientCutText msg, List<Object> out) throws Exception {
byte[] text = msg.getText().getBytes(StandardCharsets.ISO_8859_1);
ByteBuf buf = ctx.alloc().buffer(8 + text.length); | buf.writeByte(ClientEventType.CLIENT_CUT_TEXT); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientHandshakerFactory.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolVersion.java
// public class ProtocolVersion implements Comparable<ProtocolVersion> {
//
// public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);
// public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);
// public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);
//
// private final Pattern VERSION_PAT = Pattern.compile("RFB ([0-9]{3}).([0-9]{3})");
//
// private int majorVersion;
//
// private int minorVersion;
//
// /**
// * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))
// *
// * @param version String
// */
// public ProtocolVersion(String version) {
// if (version == null) {
// throw new IllegalArgumentException("null can not parsed to version");
// }
// Matcher versionMatcher = VERSION_PAT.matcher(version);
// if (versionMatcher.find()) {
// majorVersion = Integer.parseInt(versionMatcher.group(1));
// minorVersion = Integer.parseInt(versionMatcher.group(2));
// } else {
// throw new IllegalArgumentException("version: " + version + " not supported");
// }
// }
//
// public ProtocolVersion(int major, int minor) {
// majorVersion = major;
// minorVersion = minor;
// }
//
// public int getMajorVersion() {
// return majorVersion;
// }
//
// public int getMinorVersion() {
// return minorVersion;
// }
//
// public boolean isGreaterThan(ProtocolVersion o) {
// return compareTo(o) > 0;
// }
//
// public boolean isGreaterThan(String v) {
// return compareTo(new ProtocolVersion(v)) > 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof ProtocolVersion)) {
// return false;
// }
// return compareTo((ProtocolVersion) obj) == 0;
// }
//
// @Override
// public int compareTo(ProtocolVersion v) {
// if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {
// return 0;
// }
// if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {
// return 1;
// }
// return -1;
// }
//
// /**
// * encoded ASCII bytes include LF
// *
// * @return expected RFB version bytes
// */
// public byte[] getBytes() {
// return String.format("RFB %03d.%03d\n", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);
// }
//
// @Override
// public String toString() {
// return String.format("RFB %03d.%03d", majorVersion, minorVersion);
// }
// }
| import org.jfxvnc.net.rfb.codec.ProtocolVersion; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker;
public class RfbClientHandshakerFactory {
public RfbClientHandshakerFactory() {}
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolVersion.java
// public class ProtocolVersion implements Comparable<ProtocolVersion> {
//
// public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);
// public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);
// public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);
//
// private final Pattern VERSION_PAT = Pattern.compile("RFB ([0-9]{3}).([0-9]{3})");
//
// private int majorVersion;
//
// private int minorVersion;
//
// /**
// * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))
// *
// * @param version String
// */
// public ProtocolVersion(String version) {
// if (version == null) {
// throw new IllegalArgumentException("null can not parsed to version");
// }
// Matcher versionMatcher = VERSION_PAT.matcher(version);
// if (versionMatcher.find()) {
// majorVersion = Integer.parseInt(versionMatcher.group(1));
// minorVersion = Integer.parseInt(versionMatcher.group(2));
// } else {
// throw new IllegalArgumentException("version: " + version + " not supported");
// }
// }
//
// public ProtocolVersion(int major, int minor) {
// majorVersion = major;
// minorVersion = minor;
// }
//
// public int getMajorVersion() {
// return majorVersion;
// }
//
// public int getMinorVersion() {
// return minorVersion;
// }
//
// public boolean isGreaterThan(ProtocolVersion o) {
// return compareTo(o) > 0;
// }
//
// public boolean isGreaterThan(String v) {
// return compareTo(new ProtocolVersion(v)) > 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof ProtocolVersion)) {
// return false;
// }
// return compareTo((ProtocolVersion) obj) == 0;
// }
//
// @Override
// public int compareTo(ProtocolVersion v) {
// if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {
// return 0;
// }
// if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {
// return 1;
// }
// return -1;
// }
//
// /**
// * encoded ASCII bytes include LF
// *
// * @return expected RFB version bytes
// */
// public byte[] getBytes() {
// return String.format("RFB %03d.%03d\n", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);
// }
//
// @Override
// public String toString() {
// return String.format("RFB %03d.%03d", majorVersion, minorVersion);
// }
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/handshaker/RfbClientHandshakerFactory.java
import org.jfxvnc.net.rfb.codec.ProtocolVersion;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.handshaker;
public class RfbClientHandshakerFactory {
public RfbClientHandshakerFactory() {}
| public RfbClientHandshaker newRfbClientHandshaker(ProtocolVersion version) { |
comtel2000/jfxvnc | jfxvnc-net/src/test/java/org/jfxvnc/net/rfb/RfbVersionTest.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolVersion.java
// public class ProtocolVersion implements Comparable<ProtocolVersion> {
//
// public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);
// public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);
// public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);
//
// private final Pattern VERSION_PAT = Pattern.compile("RFB ([0-9]{3}).([0-9]{3})");
//
// private int majorVersion;
//
// private int minorVersion;
//
// /**
// * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))
// *
// * @param version String
// */
// public ProtocolVersion(String version) {
// if (version == null) {
// throw new IllegalArgumentException("null can not parsed to version");
// }
// Matcher versionMatcher = VERSION_PAT.matcher(version);
// if (versionMatcher.find()) {
// majorVersion = Integer.parseInt(versionMatcher.group(1));
// minorVersion = Integer.parseInt(versionMatcher.group(2));
// } else {
// throw new IllegalArgumentException("version: " + version + " not supported");
// }
// }
//
// public ProtocolVersion(int major, int minor) {
// majorVersion = major;
// minorVersion = minor;
// }
//
// public int getMajorVersion() {
// return majorVersion;
// }
//
// public int getMinorVersion() {
// return minorVersion;
// }
//
// public boolean isGreaterThan(ProtocolVersion o) {
// return compareTo(o) > 0;
// }
//
// public boolean isGreaterThan(String v) {
// return compareTo(new ProtocolVersion(v)) > 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof ProtocolVersion)) {
// return false;
// }
// return compareTo((ProtocolVersion) obj) == 0;
// }
//
// @Override
// public int compareTo(ProtocolVersion v) {
// if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {
// return 0;
// }
// if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {
// return 1;
// }
// return -1;
// }
//
// /**
// * encoded ASCII bytes include LF
// *
// * @return expected RFB version bytes
// */
// public byte[] getBytes() {
// return String.format("RFB %03d.%03d\n", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);
// }
//
// @Override
// public String toString() {
// return String.format("RFB %03d.%03d", majorVersion, minorVersion);
// }
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.jfxvnc.net.rfb.codec.ProtocolVersion;
import org.junit.Test; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb;
public class RfbVersionTest {
@Test
public void RfbVersionCompare() {
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolVersion.java
// public class ProtocolVersion implements Comparable<ProtocolVersion> {
//
// public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);
// public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);
// public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);
//
// private final Pattern VERSION_PAT = Pattern.compile("RFB ([0-9]{3}).([0-9]{3})");
//
// private int majorVersion;
//
// private int minorVersion;
//
// /**
// * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))
// *
// * @param version String
// */
// public ProtocolVersion(String version) {
// if (version == null) {
// throw new IllegalArgumentException("null can not parsed to version");
// }
// Matcher versionMatcher = VERSION_PAT.matcher(version);
// if (versionMatcher.find()) {
// majorVersion = Integer.parseInt(versionMatcher.group(1));
// minorVersion = Integer.parseInt(versionMatcher.group(2));
// } else {
// throw new IllegalArgumentException("version: " + version + " not supported");
// }
// }
//
// public ProtocolVersion(int major, int minor) {
// majorVersion = major;
// minorVersion = minor;
// }
//
// public int getMajorVersion() {
// return majorVersion;
// }
//
// public int getMinorVersion() {
// return minorVersion;
// }
//
// public boolean isGreaterThan(ProtocolVersion o) {
// return compareTo(o) > 0;
// }
//
// public boolean isGreaterThan(String v) {
// return compareTo(new ProtocolVersion(v)) > 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null || !(obj instanceof ProtocolVersion)) {
// return false;
// }
// return compareTo((ProtocolVersion) obj) == 0;
// }
//
// @Override
// public int compareTo(ProtocolVersion v) {
// if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {
// return 0;
// }
// if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {
// return 1;
// }
// return -1;
// }
//
// /**
// * encoded ASCII bytes include LF
// *
// * @return expected RFB version bytes
// */
// public byte[] getBytes() {
// return String.format("RFB %03d.%03d\n", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);
// }
//
// @Override
// public String toString() {
// return String.format("RFB %03d.%03d", majorVersion, minorVersion);
// }
// }
// Path: jfxvnc-net/src/test/java/org/jfxvnc/net/rfb/RfbVersionTest.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.jfxvnc.net.rfb.codec.ProtocolVersion;
import org.junit.Test;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb;
public class RfbVersionTest {
@Test
public void RfbVersionCompare() {
| ProtocolVersion v1 = new ProtocolVersion("RFB 003.003\n"); |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolInitializer.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java
// public interface RenderProtocol {
//
// void render(ImageRect rect);
//
// void renderComplete(RenderCallback callback);
//
// void eventReceived(ServerDecoderEvent event);
//
// void exceptionCaught(Throwable t);
//
// void stateChanged(ProtocolState state);
//
// void registerInputEventListener(InputEventListener listener);
// }
| import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
import org.jfxvnc.net.rfb.render.RenderProtocol;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec;
public class ProtocolInitializer extends ChannelInitializer<SocketChannel> {
private RenderProtocol render; | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
//
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/RenderProtocol.java
// public interface RenderProtocol {
//
// void render(ImageRect rect);
//
// void renderComplete(RenderCallback callback);
//
// void eventReceived(ServerDecoderEvent event);
//
// void exceptionCaught(Throwable t);
//
// void stateChanged(ProtocolState state);
//
// void registerInputEventListener(InputEventListener listener);
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/ProtocolInitializer.java
import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
import org.jfxvnc.net.rfb.render.RenderProtocol;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec;
public class ProtocolInitializer extends ChannelInitializer<SocketChannel> {
private RenderProtocol render; | private ProtocolConfiguration config; |
comtel2000/jfxvnc | jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityMessage.java | // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
| import org.jfxvnc.net.rfb.render.ProtocolConfiguration; | /*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public interface RfbSecurityMessage {
SecurityType getSecurityType();
| // Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/render/ProtocolConfiguration.java
// public interface ProtocolConfiguration {
//
// final int DEFAULT_PORT = 5900;
// final int DEFAULT_LISTENING_PORT = 5500;
//
// /**
// * VNC server name or IP address
// *
// * @return host
// */
// StringProperty hostProperty();
//
// /**
// * VNC server port (default: 5900)
// *
// * @return port
// */
// IntegerProperty portProperty();
//
// /**
// * listening mode to accept incoming connection requests (default: 5500)
// *
// * @return listening port
// */
// IntegerProperty listeningPortProperty();
//
// /**
// * VNC authentication password
// *
// * @return password
// */
// StringProperty passwordProperty();
//
// /**
// * Enable SSL/TLS transfer
// *
// * @return SSL/TLS enabled
// */
// BooleanProperty sslProperty();
//
// /**
// * Security Type {@link SecurityType}
// *
// * @return current {@link SecurityType}
// * @see org.jfxvnc.net.rfb.codec.security.SecurityType
// */
// ObjectProperty<SecurityType> securityProperty();
//
// /**
// * VNC connection shared by other clients
// *
// * @return shared
// */
// BooleanProperty sharedProperty();
//
// /**
// * Used Protocol Version {@link ProtocolVersion}
// *
// * @return current {@link ProtocolVersion}
// */
// ObjectProperty<ProtocolVersion> versionProperty();
//
// /**
// * Used PixelFormat {@link PixelFormat}
// *
// * @return current {@link PixelFormat}
// * @see org.jfxvnc.net.rfb.codec.PixelFormat
// */
// ObjectProperty<PixelFormat> clientPixelFormatProperty();
//
// /**
// * Activate RAW encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty rawEncProperty();
//
// /**
// * Activate COPY RECT encoding
// *
// * @return raw enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty copyRectEncProperty();
//
// /**
// * Activate Hextile encoding
// *
// * @return Hextile enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty hextileEncProperty();
//
// /**
// * Activate Cursor pseudo encoding
// *
// * @return Cursor enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty clientCursorProperty();
//
// /**
// * Activate Desktop Resize pseudo encoding
// *
// * @return Desktop Resize enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty desktopSizeProperty();
//
// /**
// * Activate Zlib pseudo encoding
// *
// * @return Zlib enabled
// * @see org.jfxvnc.net.rfb.codec.Encoding
// */
// BooleanProperty zlibEncProperty();
//
// }
// Path: jfxvnc-net/src/main/java/org/jfxvnc/net/rfb/codec/security/RfbSecurityMessage.java
import org.jfxvnc.net.rfb.render.ProtocolConfiguration;
/*******************************************************************************
* Copyright (c) 2016 comtel inc.
*
* Licensed under the Apache License, version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package org.jfxvnc.net.rfb.codec.security;
public interface RfbSecurityMessage {
SecurityType getSecurityType();
| void setCredentials(ProtocolConfiguration config); |
igd-geo/mongomvcc | src/main/java/de/fhg/igd/mongomvcc/impl/DefaultAccessStrategy.java | // Path: src/main/java/de/fhg/igd/mongomvcc/VException.java
// public class VException extends RuntimeException {
// private static final long serialVersionUID = 4131582095330835424L;
//
// /**
// * @see RuntimeException#RuntimeException()
// */
// public VException() {
// super();
// }
//
// /**
// * @see RuntimeException#RuntimeException(String)
// */
// public VException(String message) {
// super(message);
// }
//
// /**
// * @see RuntimeException#RuntimeException(Throwable)
// */
// public VException(Throwable cause) {
// super(cause);
// }
//
// /**
// * @see RuntimeException#RuntimeException(String, Throwable)
// */
// public VException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import de.fhg.igd.mongomvcc.VException; | for (Map.Entry<String, Object> e : obj.entrySet()) {
Object v = e.getValue();
long oid = _convert.convert(v);
if (oid != 0) {
e.setValue(oid);
binaryAttributes.add(e.getKey());
}
}
//save which attributes point to GridFS files
if (!binaryAttributes.isEmpty()) {
obj.put(BINARY_ATTRIBUTES, binaryAttributes);
}
}
@Override
public void onResolve(Map<String, Object> obj) {
@SuppressWarnings("unchecked")
List<String> binaryAttributes = (List<String>)obj.get(BINARY_ATTRIBUTES);
if (binaryAttributes == null) {
//nothing to do
return;
}
try {
for (String attr : binaryAttributes) {
long gridId = (Long)obj.get(attr);
obj.put(attr, _convert.convert(gridId));
}
} catch (IOException e) { | // Path: src/main/java/de/fhg/igd/mongomvcc/VException.java
// public class VException extends RuntimeException {
// private static final long serialVersionUID = 4131582095330835424L;
//
// /**
// * @see RuntimeException#RuntimeException()
// */
// public VException() {
// super();
// }
//
// /**
// * @see RuntimeException#RuntimeException(String)
// */
// public VException(String message) {
// super(message);
// }
//
// /**
// * @see RuntimeException#RuntimeException(Throwable)
// */
// public VException(Throwable cause) {
// super(cause);
// }
//
// /**
// * @see RuntimeException#RuntimeException(String, Throwable)
// */
// public VException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/de/fhg/igd/mongomvcc/impl/DefaultAccessStrategy.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import de.fhg.igd.mongomvcc.VException;
for (Map.Entry<String, Object> e : obj.entrySet()) {
Object v = e.getValue();
long oid = _convert.convert(v);
if (oid != 0) {
e.setValue(oid);
binaryAttributes.add(e.getKey());
}
}
//save which attributes point to GridFS files
if (!binaryAttributes.isEmpty()) {
obj.put(BINARY_ATTRIBUTES, binaryAttributes);
}
}
@Override
public void onResolve(Map<String, Object> obj) {
@SuppressWarnings("unchecked")
List<String> binaryAttributes = (List<String>)obj.get(BINARY_ATTRIBUTES);
if (binaryAttributes == null) {
//nothing to do
return;
}
try {
for (String attr : binaryAttributes) {
long gridId = (Long)obj.get(attr);
obj.put(attr, _convert.convert(gridId));
}
} catch (IOException e) { | throw new VException("Could not read binary data", e); |
igd-geo/mongomvcc | src/main/java/de/fhg/igd/mongomvcc/impl/internal/Commit.java | // Path: src/main/java/de/fhg/igd/mongomvcc/helper/IdMap.java
// public interface IdMap extends IdCollection {
// /**
// * Puts a key-value pair into the map. This operation overwrites
// * the old value if the key is already in the map.
// * @param key the key to insert
// * @param value the value to insert
// * @return the old, overwritten value or 0 if there was no such key
// */
// long put(long key, long value);
//
// /**
// * Checks if the map contains a given key
// * @param key the key
// * @return true if the map contains the key, false otherwise
// */
// boolean containsKey(long key);
//
// /**
// * Removes a key-value pair from the map
// * @param key the key of the pair to remove
// * @return the removed value or 0 if the key was not in the map
// */
// long remove(long key);
//
// /**
// * Retrieves the value for a given key
// * @param key the key
// * @return the value or 0 if the value was not in the map
// */
// long get(long key);
//
// /**
// * @return the map's keys as an array
// */
// long[] keys();
//
// /**
// * @return the map's values as an array
// */
// long[] values();
//
// /**
// * @return an iterator for this map
// */
// IdMapIterator iterator();
// }
| import java.util.Map;
import de.fhg.igd.mongomvcc.helper.IdMap; | // This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl.internal;
/**
* A commit has a CID and stores references to added/changed database objects
* @author Michel Kraemer
*/
public class Commit {
/**
* The commit's ID
*/
private final long _cid;
/**
* The commit's timestamp (in milliseconds since epoch, UTC)
*/
private final long _timestamp;
/**
* The CID of this commit's parent. Can be 0 (zero) if there is no
* parent (can only happen for the root commit)
*/
private final long _parentCID;
/**
* The root CID of the branch this commit belongs to
*/
private final long _rootCID;
/**
* Objects added/changed in this commit. Maps collection names to maps of
* UIDs and OIDs.
*/ | // Path: src/main/java/de/fhg/igd/mongomvcc/helper/IdMap.java
// public interface IdMap extends IdCollection {
// /**
// * Puts a key-value pair into the map. This operation overwrites
// * the old value if the key is already in the map.
// * @param key the key to insert
// * @param value the value to insert
// * @return the old, overwritten value or 0 if there was no such key
// */
// long put(long key, long value);
//
// /**
// * Checks if the map contains a given key
// * @param key the key
// * @return true if the map contains the key, false otherwise
// */
// boolean containsKey(long key);
//
// /**
// * Removes a key-value pair from the map
// * @param key the key of the pair to remove
// * @return the removed value or 0 if the key was not in the map
// */
// long remove(long key);
//
// /**
// * Retrieves the value for a given key
// * @param key the key
// * @return the value or 0 if the value was not in the map
// */
// long get(long key);
//
// /**
// * @return the map's keys as an array
// */
// long[] keys();
//
// /**
// * @return the map's values as an array
// */
// long[] values();
//
// /**
// * @return an iterator for this map
// */
// IdMapIterator iterator();
// }
// Path: src/main/java/de/fhg/igd/mongomvcc/impl/internal/Commit.java
import java.util.Map;
import de.fhg.igd.mongomvcc.helper.IdMap;
// This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl.internal;
/**
* A commit has a CID and stores references to added/changed database objects
* @author Michel Kraemer
*/
public class Commit {
/**
* The commit's ID
*/
private final long _cid;
/**
* The commit's timestamp (in milliseconds since epoch, UTC)
*/
private final long _timestamp;
/**
* The CID of this commit's parent. Can be 0 (zero) if there is no
* parent (can only happen for the root commit)
*/
private final long _parentCID;
/**
* The root CID of the branch this commit belongs to
*/
private final long _rootCID;
/**
* Objects added/changed in this commit. Maps collection names to maps of
* UIDs and OIDs.
*/ | private final Map<String, IdMap> _objects; |
igd-geo/mongomvcc | src/main/java/de/fhg/igd/mongomvcc/impl/MongoDBVFactory.java | // Path: src/main/java/de/fhg/igd/mongomvcc/VDatabase.java
// public interface VDatabase {
// /**
// * Connect to a database
// * @param name the database name
// * @throws VException if connection failed
// */
// void connect(String name);
//
// /**
// * Connect to a database
// * @param name the database name
// * @param port the port the database listens to
// * @throws VException if connection failed
// */
// void connect(String name, int port);
//
// /**
// * Connect to a database running on a given host and port
// * @param name the database name
// * @param host the host the database is running on
// * @param port the port the database listens to
// * @throws VException if connection failed
// */
// void connect(String name, String host, int port);
//
// /**
// * Checks out a named branch from the database
// * @param name the branch's name
// * @return the branch
// * @throws VException if the branch does not exist yet
// */
// VBranch checkout(String name);
//
// /**
// * Checks out an unnamed branch from the database
// * @param cid the CID of the commit which should be the branch's root
// * @return the branch
// * @throws VException if there is not commit with the given CID
// */
// VBranch checkout(long cid);
//
// /**
// * Creates a new named branch whose head is set to the given CID
// * @param name the branch's name
// * @param headCID the branch's head CID
// * @return the branch
// * @throws VException if there already is a branch with the given name or
// * if the given head CID could not be resolved to an existing commit
// */
// VBranch createBranch(String name, long headCID);
//
// /**
// * Deletes the whole database. Be very careful with this method!
// */
// void drop();
//
// /**
// * @return a counter which generates unique IDs for the database
// */
// VCounter getCounter();
//
// /**
// * @return the database's history
// */
// VHistory getHistory();
//
// /**
// * @return a maintenance object
// */
// VMaintenance getMaintenance();
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/VFactory.java
// public interface VFactory {
// /**
// * @return a new MVCC database
// */
// VDatabase createDatabase();
//
// /**
// * @return a new empty document
// */
// Map<String, Object> createDocument();
//
// /**
// * Convenience method to create a new document with exactly one element
// * @param key the element's key
// * @param value the element's value
// * @return the new document
// */
// Map<String, Object> createDocument(String key, Object value);
//
// /**
// * @return a new list
// */
// List<Object> createList();
// }
| import java.util.List;
import java.util.Map;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import de.fhg.igd.mongomvcc.VDatabase;
import de.fhg.igd.mongomvcc.VFactory; | // This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl;
/**
* Creates MongoDB implementation-specific objects of the MVCC model
* @author Michel Kraemer
*/
public class MongoDBVFactory implements VFactory {
@Override | // Path: src/main/java/de/fhg/igd/mongomvcc/VDatabase.java
// public interface VDatabase {
// /**
// * Connect to a database
// * @param name the database name
// * @throws VException if connection failed
// */
// void connect(String name);
//
// /**
// * Connect to a database
// * @param name the database name
// * @param port the port the database listens to
// * @throws VException if connection failed
// */
// void connect(String name, int port);
//
// /**
// * Connect to a database running on a given host and port
// * @param name the database name
// * @param host the host the database is running on
// * @param port the port the database listens to
// * @throws VException if connection failed
// */
// void connect(String name, String host, int port);
//
// /**
// * Checks out a named branch from the database
// * @param name the branch's name
// * @return the branch
// * @throws VException if the branch does not exist yet
// */
// VBranch checkout(String name);
//
// /**
// * Checks out an unnamed branch from the database
// * @param cid the CID of the commit which should be the branch's root
// * @return the branch
// * @throws VException if there is not commit with the given CID
// */
// VBranch checkout(long cid);
//
// /**
// * Creates a new named branch whose head is set to the given CID
// * @param name the branch's name
// * @param headCID the branch's head CID
// * @return the branch
// * @throws VException if there already is a branch with the given name or
// * if the given head CID could not be resolved to an existing commit
// */
// VBranch createBranch(String name, long headCID);
//
// /**
// * Deletes the whole database. Be very careful with this method!
// */
// void drop();
//
// /**
// * @return a counter which generates unique IDs for the database
// */
// VCounter getCounter();
//
// /**
// * @return the database's history
// */
// VHistory getHistory();
//
// /**
// * @return a maintenance object
// */
// VMaintenance getMaintenance();
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/VFactory.java
// public interface VFactory {
// /**
// * @return a new MVCC database
// */
// VDatabase createDatabase();
//
// /**
// * @return a new empty document
// */
// Map<String, Object> createDocument();
//
// /**
// * Convenience method to create a new document with exactly one element
// * @param key the element's key
// * @param value the element's value
// * @return the new document
// */
// Map<String, Object> createDocument(String key, Object value);
//
// /**
// * @return a new list
// */
// List<Object> createList();
// }
// Path: src/main/java/de/fhg/igd/mongomvcc/impl/MongoDBVFactory.java
import java.util.List;
import java.util.Map;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import de.fhg.igd.mongomvcc.VDatabase;
import de.fhg.igd.mongomvcc.VFactory;
// This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl;
/**
* Creates MongoDB implementation-specific objects of the MVCC model
* @author Michel Kraemer
*/
public class MongoDBVFactory implements VFactory {
@Override | public VDatabase createDatabase() { |
igd-geo/mongomvcc | src/main/java/de/fhg/igd/mongomvcc/impl/MongoDBVLargeCollection.java | // Path: src/main/java/de/fhg/igd/mongomvcc/VCounter.java
// public interface VCounter {
// /**
// * A thread safe method to get the next unique id
// * @return a unique id
// */
// public long getNextId();
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/VCursor.java
// public interface VCursor extends Iterable<Map<String, Object>> {
// /**
// * @return the number of database objects this cursor points to
// */
// int size();
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/VLargeCollection.java
// public interface VLargeCollection extends VCollection {
// //nothing to add yet
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/helper/Filter.java
// public interface Filter<T> {
// /**
// * Checks if the given element passes the filter
// * @param t the element
// * @return true if the element passes the filter, false otherwise
// */
// boolean filter(T t);
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/helper/TransformingIterator.java
// public abstract class TransformingIterator<I, O> implements Iterator<O> {
// /**
// * The wrapped iterator
// */
// private final Iterator<I> _delegate;
//
// /**
// * Constructs a new transforming iterator
// * @param delegate the iterator to wrap
// */
// public TransformingIterator(Iterator<I> delegate) {
// _delegate = delegate;
// }
//
// @Override
// public boolean hasNext() {
// return _delegate.hasNext();
// }
//
// @Override
// public O next() {
// return transform(_delegate.next());
// }
//
// /**
// * Transforms an element
// * @param input the element
// * @return the transformed element
// */
// abstract protected O transform(I input);
//
// @Override
// public void remove() {
// _delegate.remove();
// }
// }
| import de.fhg.igd.mongomvcc.helper.Filter;
import de.fhg.igd.mongomvcc.helper.TransformingIterator;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import de.fhg.igd.mongomvcc.VCounter;
import de.fhg.igd.mongomvcc.VCursor;
import de.fhg.igd.mongomvcc.VLargeCollection; | // This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl;
/**
* Saves primitive byte arrays and {@link InputStream}s in MongoDB's
* {@link GridFS}.
* @author Michel Kraemer
*/
public class MongoDBVLargeCollection extends MongoDBVCollection implements
VLargeCollection {
/**
* A cursor which calls {@link AccessStrategy#onResolve(Map)} for
* each object
*/
private class MongoDBVLargeCursor extends MongoDBVCursor {
/**
* @see MongoDBVCursor#MongoDBVCursor(DBCursor, Filter)
*/ | // Path: src/main/java/de/fhg/igd/mongomvcc/VCounter.java
// public interface VCounter {
// /**
// * A thread safe method to get the next unique id
// * @return a unique id
// */
// public long getNextId();
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/VCursor.java
// public interface VCursor extends Iterable<Map<String, Object>> {
// /**
// * @return the number of database objects this cursor points to
// */
// int size();
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/VLargeCollection.java
// public interface VLargeCollection extends VCollection {
// //nothing to add yet
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/helper/Filter.java
// public interface Filter<T> {
// /**
// * Checks if the given element passes the filter
// * @param t the element
// * @return true if the element passes the filter, false otherwise
// */
// boolean filter(T t);
// }
//
// Path: src/main/java/de/fhg/igd/mongomvcc/helper/TransformingIterator.java
// public abstract class TransformingIterator<I, O> implements Iterator<O> {
// /**
// * The wrapped iterator
// */
// private final Iterator<I> _delegate;
//
// /**
// * Constructs a new transforming iterator
// * @param delegate the iterator to wrap
// */
// public TransformingIterator(Iterator<I> delegate) {
// _delegate = delegate;
// }
//
// @Override
// public boolean hasNext() {
// return _delegate.hasNext();
// }
//
// @Override
// public O next() {
// return transform(_delegate.next());
// }
//
// /**
// * Transforms an element
// * @param input the element
// * @return the transformed element
// */
// abstract protected O transform(I input);
//
// @Override
// public void remove() {
// _delegate.remove();
// }
// }
// Path: src/main/java/de/fhg/igd/mongomvcc/impl/MongoDBVLargeCollection.java
import de.fhg.igd.mongomvcc.helper.Filter;
import de.fhg.igd.mongomvcc.helper.TransformingIterator;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import de.fhg.igd.mongomvcc.VCounter;
import de.fhg.igd.mongomvcc.VCursor;
import de.fhg.igd.mongomvcc.VLargeCollection;
// This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl;
/**
* Saves primitive byte arrays and {@link InputStream}s in MongoDB's
* {@link GridFS}.
* @author Michel Kraemer
*/
public class MongoDBVLargeCollection extends MongoDBVCollection implements
VLargeCollection {
/**
* A cursor which calls {@link AccessStrategy#onResolve(Map)} for
* each object
*/
private class MongoDBVLargeCursor extends MongoDBVCursor {
/**
* @see MongoDBVCursor#MongoDBVCursor(DBCursor, Filter)
*/ | public MongoDBVLargeCursor(DBCursor delegate, Filter<DBObject> filter) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.