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
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // }
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set;
private static List<String> wrapStringRespectingAnsiCodeFormat( String string, int wrapLength, boolean concatenatePercent) { if (string == null) { throw new NullPointerException("String is null."); } List<String> wrappedString = new LinkedList<>(); double relativeWrapLength = (double) wrapLength / AnsiCodeColors.remove(string).length(); double accumulatedWrapLength = 0; if (wrapLength < 1) { wrappedString.add(string); } else { StringBuilder substring = new StringBuilder(wrapLength * 2); StringBuilder ansiCodeFormat = new StringBuilder(); int substringChars = 0; for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); if (ch == UNICODE_CTRL) { ansiCodeFormat = new StringBuilder();
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // } // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; private static List<String> wrapStringRespectingAnsiCodeFormat( String string, int wrapLength, boolean concatenatePercent) { if (string == null) { throw new NullPointerException("String is null."); } List<String> wrappedString = new LinkedList<>(); double relativeWrapLength = (double) wrapLength / AnsiCodeColors.remove(string).length(); double accumulatedWrapLength = 0; if (wrapLength < 1) { wrappedString.add(string); } else { StringBuilder substring = new StringBuilder(wrapLength * 2); StringBuilder ansiCodeFormat = new StringBuilder(); int substringChars = 0; for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); if (ch == UNICODE_CTRL) { ansiCodeFormat = new StringBuilder();
while (string.charAt(i) != ANSI_CODE_COLOR_END) {
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE;
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO;
package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class represents a Uniform Fuzzy Hash block. * * @author s3curitybug@gmail.com * */ public class UniformFuzzyHashBlock { /** * Block hash. */ private int blockHash; /** * Block starting byte position (0 based). */ private int blockStartingBytePosition; /** * Block ending byte position (0 based). */ private int blockEndingBytePosition; /** * Base constructor. */ private UniformFuzzyHashBlock() { this.blockHash = 0; this.blockStartingBytePosition = 0; this.blockEndingBytePosition = 0; } /** * Constructor with arguments. * * @param blockHash Block hash. * @param blockStartingBytePosition Block starting byte position (0 based). * @param blockEndingBytePosition Block ending byte position (0 based). */ protected UniformFuzzyHashBlock( int blockHash, int blockStartingBytePosition, int blockEndingBytePosition) { this.blockHash = blockHash; this.blockStartingBytePosition = blockStartingBytePosition; this.blockEndingBytePosition = blockEndingBytePosition; } /** * @return The string representation of this Uniform Fuzzy Hash Block. */ @Override public String toString() {
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE; // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO; package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class represents a Uniform Fuzzy Hash block. * * @author s3curitybug@gmail.com * */ public class UniformFuzzyHashBlock { /** * Block hash. */ private int blockHash; /** * Block starting byte position (0 based). */ private int blockStartingBytePosition; /** * Block ending byte position (0 based). */ private int blockEndingBytePosition; /** * Base constructor. */ private UniformFuzzyHashBlock() { this.blockHash = 0; this.blockStartingBytePosition = 0; this.blockEndingBytePosition = 0; } /** * Constructor with arguments. * * @param blockHash Block hash. * @param blockStartingBytePosition Block starting byte position (0 based). * @param blockEndingBytePosition Block ending byte position (0 based). */ protected UniformFuzzyHashBlock( int blockHash, int blockStartingBytePosition, int blockEndingBytePosition) { this.blockHash = blockHash; this.blockStartingBytePosition = blockStartingBytePosition; this.blockEndingBytePosition = blockEndingBytePosition; } /** * @return The string representation of this Uniform Fuzzy Hash Block. */ @Override public String toString() {
StringBuilder strB = new StringBuilder(BLOCK_MAX_CHARS);
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE;
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO;
package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class represents a Uniform Fuzzy Hash block. * * @author s3curitybug@gmail.com * */ public class UniformFuzzyHashBlock { /** * Block hash. */ private int blockHash; /** * Block starting byte position (0 based). */ private int blockStartingBytePosition; /** * Block ending byte position (0 based). */ private int blockEndingBytePosition; /** * Base constructor. */ private UniformFuzzyHashBlock() { this.blockHash = 0; this.blockStartingBytePosition = 0; this.blockEndingBytePosition = 0; } /** * Constructor with arguments. * * @param blockHash Block hash. * @param blockStartingBytePosition Block starting byte position (0 based). * @param blockEndingBytePosition Block ending byte position (0 based). */ protected UniformFuzzyHashBlock( int blockHash, int blockStartingBytePosition, int blockEndingBytePosition) { this.blockHash = blockHash; this.blockStartingBytePosition = blockStartingBytePosition; this.blockEndingBytePosition = blockEndingBytePosition; } /** * @return The string representation of this Uniform Fuzzy Hash Block. */ @Override public String toString() { StringBuilder strB = new StringBuilder(BLOCK_MAX_CHARS); toString(strB); return strB.toString(); } /** * Appends the string representation of this Uniform Fuzzy Hash Block to an existing * String Builder. * * @param strB String Builder to which the string representation of this Uniform Fuzzy Hash * Block will be appended. */ protected void toString( StringBuilder strB) {
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE; // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO; package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class represents a Uniform Fuzzy Hash block. * * @author s3curitybug@gmail.com * */ public class UniformFuzzyHashBlock { /** * Block hash. */ private int blockHash; /** * Block starting byte position (0 based). */ private int blockStartingBytePosition; /** * Block ending byte position (0 based). */ private int blockEndingBytePosition; /** * Base constructor. */ private UniformFuzzyHashBlock() { this.blockHash = 0; this.blockStartingBytePosition = 0; this.blockEndingBytePosition = 0; } /** * Constructor with arguments. * * @param blockHash Block hash. * @param blockStartingBytePosition Block starting byte position (0 based). * @param blockEndingBytePosition Block ending byte position (0 based). */ protected UniformFuzzyHashBlock( int blockHash, int blockStartingBytePosition, int blockEndingBytePosition) { this.blockHash = blockHash; this.blockStartingBytePosition = blockStartingBytePosition; this.blockEndingBytePosition = blockEndingBytePosition; } /** * @return The string representation of this Uniform Fuzzy Hash Block. */ @Override public String toString() { StringBuilder strB = new StringBuilder(BLOCK_MAX_CHARS); toString(strB); return strB.toString(); } /** * Appends the string representation of this Uniform Fuzzy Hash Block to an existing * String Builder. * * @param strB String Builder to which the string representation of this Uniform Fuzzy Hash * Block will be appended. */ protected void toString( StringBuilder strB) {
strB.append(Integer.toString(blockHash, BLOCK_BASE));
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE;
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO;
package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class represents a Uniform Fuzzy Hash block. * * @author s3curitybug@gmail.com * */ public class UniformFuzzyHashBlock { /** * Block hash. */ private int blockHash; /** * Block starting byte position (0 based). */ private int blockStartingBytePosition; /** * Block ending byte position (0 based). */ private int blockEndingBytePosition; /** * Base constructor. */ private UniformFuzzyHashBlock() { this.blockHash = 0; this.blockStartingBytePosition = 0; this.blockEndingBytePosition = 0; } /** * Constructor with arguments. * * @param blockHash Block hash. * @param blockStartingBytePosition Block starting byte position (0 based). * @param blockEndingBytePosition Block ending byte position (0 based). */ protected UniformFuzzyHashBlock( int blockHash, int blockStartingBytePosition, int blockEndingBytePosition) { this.blockHash = blockHash; this.blockStartingBytePosition = blockStartingBytePosition; this.blockEndingBytePosition = blockEndingBytePosition; } /** * @return The string representation of this Uniform Fuzzy Hash Block. */ @Override public String toString() { StringBuilder strB = new StringBuilder(BLOCK_MAX_CHARS); toString(strB); return strB.toString(); } /** * Appends the string representation of this Uniform Fuzzy Hash Block to an existing * String Builder. * * @param strB String Builder to which the string representation of this Uniform Fuzzy Hash * Block will be appended. */ protected void toString( StringBuilder strB) { strB.append(Integer.toString(blockHash, BLOCK_BASE));
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE; // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO; package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class represents a Uniform Fuzzy Hash block. * * @author s3curitybug@gmail.com * */ public class UniformFuzzyHashBlock { /** * Block hash. */ private int blockHash; /** * Block starting byte position (0 based). */ private int blockStartingBytePosition; /** * Block ending byte position (0 based). */ private int blockEndingBytePosition; /** * Base constructor. */ private UniformFuzzyHashBlock() { this.blockHash = 0; this.blockStartingBytePosition = 0; this.blockEndingBytePosition = 0; } /** * Constructor with arguments. * * @param blockHash Block hash. * @param blockStartingBytePosition Block starting byte position (0 based). * @param blockEndingBytePosition Block ending byte position (0 based). */ protected UniformFuzzyHashBlock( int blockHash, int blockStartingBytePosition, int blockEndingBytePosition) { this.blockHash = blockHash; this.blockStartingBytePosition = blockStartingBytePosition; this.blockEndingBytePosition = blockEndingBytePosition; } /** * @return The string representation of this Uniform Fuzzy Hash Block. */ @Override public String toString() { StringBuilder strB = new StringBuilder(BLOCK_MAX_CHARS); toString(strB); return strB.toString(); } /** * Appends the string representation of this Uniform Fuzzy Hash Block to an existing * String Builder. * * @param strB String Builder to which the string representation of this Uniform Fuzzy Hash * Block will be appended. */ protected void toString( StringBuilder strB) { strB.append(Integer.toString(blockHash, BLOCK_BASE));
strB.append(BLOCK_INNER_SEPARATOR);
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE;
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO;
// Uniform Fuzzy Hash Block. UniformFuzzyHashBlock block = new UniformFuzzyHashBlock(); // Split block hash from block size. int splitIndex = blockString.lastIndexOf(BLOCK_INNER_SEPARATOR); if (splitIndex < 0) { throw new IllegalArgumentException(String.format( "Block string does not fit the format blockHash%sblockSize.", BLOCK_INNER_SEPARATOR)); } // Block hash. String blockHashString = blockString.substring(0, splitIndex); if (blockHashString.isEmpty()) { throw new IllegalArgumentException(String.format( "Block string does not fit the format blockHash%sblockSize.", BLOCK_INNER_SEPARATOR)); } try { block.blockHash = Integer.parseInt(blockHashString, BLOCK_BASE); } catch (NumberFormatException numberFormatException) { throw new IllegalArgumentException(String.format( "Block hash (%s) is not parseable.", blockHashString)); }
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_BASE = 36; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCK_INNER_SEPARATOR = "/"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_MAX_CHARS = // 2 * BLOCK_INT_MAX_CHARS + BLOCK_INNER_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // protected static final int BLOCK_HASH_MODULO = Integer.MAX_VALUE; // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashBlock.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_BASE; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_INNER_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.BLOCK_HASH_MODULO; // Uniform Fuzzy Hash Block. UniformFuzzyHashBlock block = new UniformFuzzyHashBlock(); // Split block hash from block size. int splitIndex = blockString.lastIndexOf(BLOCK_INNER_SEPARATOR); if (splitIndex < 0) { throw new IllegalArgumentException(String.format( "Block string does not fit the format blockHash%sblockSize.", BLOCK_INNER_SEPARATOR)); } // Block hash. String blockHashString = blockString.substring(0, splitIndex); if (blockHashString.isEmpty()) { throw new IllegalArgumentException(String.format( "Block string does not fit the format blockHash%sblockSize.", BLOCK_INNER_SEPARATOR)); } try { block.blockHash = Integer.parseInt(blockHashString, BLOCK_BASE); } catch (NumberFormatException numberFormatException) { throw new IllegalArgumentException(String.format( "Block hash (%s) is not parseable.", blockHashString)); }
if (block.blockHash < 0 || block.blockHash >= BLOCK_HASH_MODULO) {
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length();
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
// Match is only checked if the initial window has already been computed. // Last data byte always produces a block. if ((windowHash == windowHashMatchValue && i >= windowSize - 1) || (i == data.length - 1)) { // New block addition. blocks.add(new UniformFuzzyHashBlock( (int) blockHash, blockStartingBytePosition, i)); // Block hash reset. blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder(
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length(); // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; // Match is only checked if the initial window has already been computed. // Last data byte always produces a block. if ((windowHash == windowHashMatchValue && i >= windowSize - 1) || (i == data.length - 1)) { // New block addition. blocks.add(new UniformFuzzyHashBlock( (int) blockHash, blockStartingBytePosition, i)); // Block hash reset. blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder(
FACTOR_WITH_SEP_MAX_CHARS + BLOCK_WITH_SEP_MAX_CHARS * blocks.size());
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length();
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
// Match is only checked if the initial window has already been computed. // Last data byte always produces a block. if ((windowHash == windowHashMatchValue && i >= windowSize - 1) || (i == data.length - 1)) { // New block addition. blocks.add(new UniformFuzzyHashBlock( (int) blockHash, blockStartingBytePosition, i)); // Block hash reset. blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder(
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length(); // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; // Match is only checked if the initial window has already been computed. // Last data byte always produces a block. if ((windowHash == windowHashMatchValue && i >= windowSize - 1) || (i == data.length - 1)) { // New block addition. blocks.add(new UniformFuzzyHashBlock( (int) blockHash, blockStartingBytePosition, i)); // Block hash reset. blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder(
FACTOR_WITH_SEP_MAX_CHARS + BLOCK_WITH_SEP_MAX_CHARS * blocks.size());
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length();
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
// New block addition. blocks.add(new UniformFuzzyHashBlock( (int) blockHash, blockStartingBytePosition, i)); // Block hash reset. blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder( FACTOR_WITH_SEP_MAX_CHARS + BLOCK_WITH_SEP_MAX_CHARS * blocks.size()); // Factor. strB.append(factor);
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length(); // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; // New block addition. blocks.add(new UniformFuzzyHashBlock( (int) blockHash, blockStartingBytePosition, i)); // Block hash reset. blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder( FACTOR_WITH_SEP_MAX_CHARS + BLOCK_WITH_SEP_MAX_CHARS * blocks.size()); // Factor. strB.append(factor);
strB.append(FACTOR_SEPARATOR);
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length();
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set;
blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder( FACTOR_WITH_SEP_MAX_CHARS + BLOCK_WITH_SEP_MAX_CHARS * blocks.size()); // Factor. strB.append(factor); strB.append(FACTOR_SEPARATOR); // Blocks. int i = 0; for (UniformFuzzyHashBlock block : blocks) { if (i++ != 0) {
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String BLOCKS_SEPARATOR = "-"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int BLOCK_WITH_SEP_MAX_CHARS = // BLOCK_MAX_CHARS + BLOCKS_SEPARATOR.length(); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final String FACTOR_SEPARATOR = ":"; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final int FACTOR_WITH_SEP_MAX_CHARS = // INT_MAX_CHARS + FACTOR_SEPARATOR.length(); // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCKS_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.BLOCK_WITH_SEP_MAX_CHARS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_SEPARATOR; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.FACTOR_WITH_SEP_MAX_CHARS; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; blockHash = 0; // Next block starting byte position. blockStartingBytePosition = i + 1; } } } /** * @return The string representation of this Uniform Fuzzy Hash. */ @Override public String toString() { // String builder. // Initial capacity enough to build the full hash string. StringBuilder strB = new StringBuilder( FACTOR_WITH_SEP_MAX_CHARS + BLOCK_WITH_SEP_MAX_CHARS * blocks.size()); // Factor. strB.append(factor); strB.append(FACTOR_SEPARATOR); // Blocks. int i = 0; for (UniformFuzzyHashBlock block : blocks) { if (i++ != 0) {
strB.append(BLOCKS_SEPARATOR);
s3curitybug/similarity-uniform-fuzzy-hash
src/test/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashesTest.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // public enum SimilarityTypes { // // /** // * Similarity of a hash to other hashes. // */ // SIMILARITY("Similarity"), // // /** // * Similarity of other hashes to a hash. // */ // REVERSE_SIMILARITY("Reverse"), // // /** // * Maximum similarity between Similarity and Reverse. // */ // MAXIMUM("Maximum"), // // /** // * Minimum similarity between Similarity and Reverse. // */ // MINIMUM("Minimum"), // // /** // * Arithmetic mean between Similarity and Reverse, (Similarity * Reverse) / 2. // */ // ARITHMETIC_MEAN("ArithMean"), // // /** // * Geometric mean between Similarity and Reverse, sqrt(Similarity * Reverse). // */ // GEOMETRIC_MEAN("GeomMean"); // // /** // * Similarity type name. // */ // private String name; // // /** // * Constructor. // * // * @param name Similarity type name. // */ // SimilarityTypes( // String name) { // // this.name = name; // // } // // /** // * @return The similarity type name. // */ // public String getName() { // // return name; // // } // // /** // * @return A list with all the similarity types names. // */ // public static List<String> names() { // // SimilarityTypes[] similarityTypes = SimilarityTypes.values(); // List<String> similarityTypesNames = new ArrayList<>(similarityTypes.length); // // for (SimilarityTypes similarityType : similarityTypes) { // similarityTypesNames.add(similarityType.name); // } // // return similarityTypesNames; // // } // // }
import org.junit.Assert; import org.junit.Test; import com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.SimilarityTypes; import java.io.File; import java.io.IOException; import java.util.Map;
Map<String, UniformFuzzyHash> hashes = UniformFuzzyHashes .computeHashesFromDirectoryFiles(directory, factor, true); UniformFuzzyHashes.saveHashesToTextFile(hashes, storageFile, false); Assert.assertTrue(storageFile.exists()); Map<String, UniformFuzzyHash> loadedHashes = UniformFuzzyHashes .loadHashesFromTextFile(storageFile); Assert.assertTrue(hashes.equals(loadedHashes)); } /** * Similarities between file and directory files test. * Tests the similarities between a file and the files of a test resources directory, sorting * them by similarity, printing them in a table and saving them as a target CSV file. * * @throws IOException In case an exception occurs reading a test resource file. */ @Test public void similaritiesBetweenFileAndDirectoryFilesTest() throws IOException { final int factor = 11; final File file = TestResourcesUtils.getTestResourceFile("LoremIpsum/ABCD.txt"); final File directory = TestResourcesUtils.getTestResourceFile("LoremIpsum"); final File csvFile = TestResourcesUtils.getTargetFile(directory.getName() + ".csv");
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // public enum SimilarityTypes { // // /** // * Similarity of a hash to other hashes. // */ // SIMILARITY("Similarity"), // // /** // * Similarity of other hashes to a hash. // */ // REVERSE_SIMILARITY("Reverse"), // // /** // * Maximum similarity between Similarity and Reverse. // */ // MAXIMUM("Maximum"), // // /** // * Minimum similarity between Similarity and Reverse. // */ // MINIMUM("Minimum"), // // /** // * Arithmetic mean between Similarity and Reverse, (Similarity * Reverse) / 2. // */ // ARITHMETIC_MEAN("ArithMean"), // // /** // * Geometric mean between Similarity and Reverse, sqrt(Similarity * Reverse). // */ // GEOMETRIC_MEAN("GeomMean"); // // /** // * Similarity type name. // */ // private String name; // // /** // * Constructor. // * // * @param name Similarity type name. // */ // SimilarityTypes( // String name) { // // this.name = name; // // } // // /** // * @return The similarity type name. // */ // public String getName() { // // return name; // // } // // /** // * @return A list with all the similarity types names. // */ // public static List<String> names() { // // SimilarityTypes[] similarityTypes = SimilarityTypes.values(); // List<String> similarityTypesNames = new ArrayList<>(similarityTypes.length); // // for (SimilarityTypes similarityType : similarityTypes) { // similarityTypesNames.add(similarityType.name); // } // // return similarityTypesNames; // // } // // } // Path: src/test/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashesTest.java import org.junit.Assert; import org.junit.Test; import com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.SimilarityTypes; import java.io.File; import java.io.IOException; import java.util.Map; Map<String, UniformFuzzyHash> hashes = UniformFuzzyHashes .computeHashesFromDirectoryFiles(directory, factor, true); UniformFuzzyHashes.saveHashesToTextFile(hashes, storageFile, false); Assert.assertTrue(storageFile.exists()); Map<String, UniformFuzzyHash> loadedHashes = UniformFuzzyHashes .loadHashesFromTextFile(storageFile); Assert.assertTrue(hashes.equals(loadedHashes)); } /** * Similarities between file and directory files test. * Tests the similarities between a file and the files of a test resources directory, sorting * them by similarity, printing them in a table and saving them as a target CSV file. * * @throws IOException In case an exception occurs reading a test resource file. */ @Test public void similaritiesBetweenFileAndDirectoryFilesTest() throws IOException { final int factor = 11; final File file = TestResourcesUtils.getTestResourceFile("LoremIpsum/ABCD.txt"); final File directory = TestResourcesUtils.getTestResourceFile("LoremIpsum"); final File csvFile = TestResourcesUtils.getTargetFile(directory.getName() + ".csv");
final SimilarityTypes sortCriterion = SimilarityTypes.SIMILARITY;
rodhilton/jasome
src/main/java/org/jasome/output/XMLOutputter.java
// Path: src/main/java/org/jasome/input/Package.java // public class Package extends Code { // private Map<String, Type> typeLookup; // // public Package(String name) { // super(name); // typeLookup = new HashMap<>(); // } // // @SuppressWarnings("unchecked") // public Set<Type> getTypes() { // return (Set<Type>)(Set<?>)getChildren(); // } // // public void addType(Type type) { // typeLookup.put(type.getName(), type); // addChild(type); // } // // public Project getParentProject() { // return (Project)getParent(); // } // // @Override // public String toString() { // return "Package("+this.getName()+")"; // } // // public Optional<Type> lookupTypeByName(String typeName) { // if(typeLookup.containsKey(typeName)) { // return Optional.of(typeLookup.get(typeName)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import org.jasome.input.*; import org.jasome.input.Package; import org.jasome.metrics.Metric; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.text.DecimalFormat; import java.util.*; import java.util.stream.Collectors;
package org.jasome.output; public class XMLOutputter implements Outputter<Document> { @Override public Document output(Project project) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element projectElement = doc.createElement("Project"); doc.appendChild(projectElement); addAttributes(project, projectElement); addMetricsForNode(doc, projectElement, project); Element packagesElement = doc.createElement("Packages"); projectElement.appendChild(packagesElement);
// Path: src/main/java/org/jasome/input/Package.java // public class Package extends Code { // private Map<String, Type> typeLookup; // // public Package(String name) { // super(name); // typeLookup = new HashMap<>(); // } // // @SuppressWarnings("unchecked") // public Set<Type> getTypes() { // return (Set<Type>)(Set<?>)getChildren(); // } // // public void addType(Type type) { // typeLookup.put(type.getName(), type); // addChild(type); // } // // public Project getParentProject() { // return (Project)getParent(); // } // // @Override // public String toString() { // return "Package("+this.getName()+")"; // } // // public Optional<Type> lookupTypeByName(String typeName) { // if(typeLookup.containsKey(typeName)) { // return Optional.of(typeLookup.get(typeName)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/output/XMLOutputter.java import org.jasome.input.*; import org.jasome.input.Package; import org.jasome.metrics.Metric; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.text.DecimalFormat; import java.util.*; import java.util.stream.Collectors; package org.jasome.output; public class XMLOutputter implements Outputter<Document> { @Override public Document output(Project project) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element projectElement = doc.createElement("Project"); doc.appendChild(projectElement); addAttributes(project, projectElement); addMetricsForNode(doc, projectElement, project); Element packagesElement = doc.createElement("Packages"); projectElement.appendChild(packagesElement);
for (Package packageNode : sortChildren(project.getPackages())) {
rodhilton/jasome
src/main/java/org/jasome/output/XMLOutputter.java
// Path: src/main/java/org/jasome/input/Package.java // public class Package extends Code { // private Map<String, Type> typeLookup; // // public Package(String name) { // super(name); // typeLookup = new HashMap<>(); // } // // @SuppressWarnings("unchecked") // public Set<Type> getTypes() { // return (Set<Type>)(Set<?>)getChildren(); // } // // public void addType(Type type) { // typeLookup.put(type.getName(), type); // addChild(type); // } // // public Project getParentProject() { // return (Project)getParent(); // } // // @Override // public String toString() { // return "Package("+this.getName()+")"; // } // // public Optional<Type> lookupTypeByName(String typeName) { // if(typeLookup.containsKey(typeName)) { // return Optional.of(typeLookup.get(typeName)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import org.jasome.input.*; import org.jasome.input.Package; import org.jasome.metrics.Metric; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.text.DecimalFormat; import java.util.*; import java.util.stream.Collectors;
} } return doc; } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } private <T extends Code> List<T> sortChildren(Collection<T> children) { return children.stream().sorted(new Comparator<Code>() { @Override public int compare(Code o1, Code o2) { return o1.getName().compareTo(o2.getName()); } }).collect(Collectors.toList()); } private void addAttributes(Code classNode, Element classElement) { for (Map.Entry<String, String> attribute : classNode.getAttributes().entrySet()) { classElement.setAttribute(attribute.getKey(), attribute.getValue()); } } private void addMetricsForNode(Document doc, Node parentElement, Code node) { Element metricsContainer = doc.createElement("Metrics");
// Path: src/main/java/org/jasome/input/Package.java // public class Package extends Code { // private Map<String, Type> typeLookup; // // public Package(String name) { // super(name); // typeLookup = new HashMap<>(); // } // // @SuppressWarnings("unchecked") // public Set<Type> getTypes() { // return (Set<Type>)(Set<?>)getChildren(); // } // // public void addType(Type type) { // typeLookup.put(type.getName(), type); // addChild(type); // } // // public Project getParentProject() { // return (Project)getParent(); // } // // @Override // public String toString() { // return "Package("+this.getName()+")"; // } // // public Optional<Type> lookupTypeByName(String typeName) { // if(typeLookup.containsKey(typeName)) { // return Optional.of(typeLookup.get(typeName)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/output/XMLOutputter.java import org.jasome.input.*; import org.jasome.input.Package; import org.jasome.metrics.Metric; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.text.DecimalFormat; import java.util.*; import java.util.stream.Collectors; } } return doc; } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } private <T extends Code> List<T> sortChildren(Collection<T> children) { return children.stream().sorted(new Comparator<Code>() { @Override public int compare(Code o1, Code o2) { return o1.getName().compareTo(o2.getName()); } }).collect(Collectors.toList()); } private void addAttributes(Code classNode, Element classElement) { for (Map.Entry<String, String> attribute : classNode.getAttributes().entrySet()) { classElement.setAttribute(attribute.getKey(), attribute.getValue()); } } private void addMetricsForNode(Document doc, Node parentElement, Code node) { Element metricsContainer = doc.createElement("Metrics");
Set<Metric> metrics = node.getMetrics();
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/LinkCalculator.java
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.google.common.collect.ImmutableSet; import com.google.common.graph.Graph; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set;
package org.jasome.metrics.calculators; public class LinkCalculator implements Calculator<Type> { @Override
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/LinkCalculator.java import com.google.common.collect.ImmutableSet; import com.google.common.graph.Graph; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set; package org.jasome.metrics.calculators; public class LinkCalculator implements Calculator<Type> { @Override
public Set<Metric> calculate(Type type) {
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/ClassInheritanceCalculator.java
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.google.common.collect.ImmutableSet; import com.google.common.graph.Graph; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.HashSet; import java.util.Set; import java.util.Stack;
package org.jasome.metrics.calculators; public class ClassInheritanceCalculator implements Calculator<Type> { @Override
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/ClassInheritanceCalculator.java import com.google.common.collect.ImmutableSet; import com.google.common.graph.Graph; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.HashSet; import java.util.Set; import java.util.Stack; package org.jasome.metrics.calculators; public class ClassInheritanceCalculator implements Calculator<Type> { @Override
public Set<Metric> calculate(Type type) {
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/NumberOfClassesCalculator.java
// Path: src/main/java/org/jasome/input/Package.java // public class Package extends Code { // private Map<String, Type> typeLookup; // // public Package(String name) { // super(name); // typeLookup = new HashMap<>(); // } // // @SuppressWarnings("unchecked") // public Set<Type> getTypes() { // return (Set<Type>)(Set<?>)getChildren(); // } // // public void addType(Type type) { // typeLookup.put(type.getName(), type); // addChild(type); // } // // public Project getParentProject() { // return (Project)getParent(); // } // // @Override // public String toString() { // return "Package("+this.getName()+")"; // } // // public Optional<Type> lookupTypeByName(String typeName) { // if(typeLookup.containsKey(typeName)) { // return Optional.of(typeLookup.get(typeName)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.google.common.collect.ImmutableSet; import org.jasome.input.Package; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set;
package org.jasome.metrics.calculators; /** * Simply counts the number of classes in a package. Only counts top-level classes, not inner or anonymous classes. * * @author Rod Hilton * @since 0.3 */ public class NumberOfClassesCalculator implements Calculator<Package> { @Override
// Path: src/main/java/org/jasome/input/Package.java // public class Package extends Code { // private Map<String, Type> typeLookup; // // public Package(String name) { // super(name); // typeLookup = new HashMap<>(); // } // // @SuppressWarnings("unchecked") // public Set<Type> getTypes() { // return (Set<Type>)(Set<?>)getChildren(); // } // // public void addType(Type type) { // typeLookup.put(type.getName(), type); // addChild(type); // } // // public Project getParentProject() { // return (Project)getParent(); // } // // @Override // public String toString() { // return "Package("+this.getName()+")"; // } // // public Optional<Type> lookupTypeByName(String typeName) { // if(typeLookup.containsKey(typeName)) { // return Optional.of(typeLookup.get(typeName)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/NumberOfClassesCalculator.java import com.google.common.collect.ImmutableSet; import org.jasome.input.Package; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set; package org.jasome.metrics.calculators; /** * Simply counts the number of classes in a package. Only counts top-level classes, not inner or anonymous classes. * * @author Rod Hilton * @since 0.3 */ public class NumberOfClassesCalculator implements Calculator<Package> { @Override
public Set<Metric> calculate(Package aPackage) {
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/McclureCalculator.java
// Path: src/main/java/org/jasome/input/Method.java // public class Method extends Code { // private final MethodDeclaration declaration; // // public final static Method UNKNOWN = new Method(); // // private Method() { // super("unknownMethod"); // this.declaration = null; // } // // public Method(MethodDeclaration declaration) { // super(declaration.getDeclarationAsString()); // this.declaration = declaration; // } // // public MethodDeclaration getSource() { // return declaration; // } // // public Type getParentType() { // return (Type) getParent(); // } // // @Override // public String toString() { // return "Method(" + this.getName() + ")"; // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.BinaryExpr; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.stmt.*; import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream;
package org.jasome.metrics.calculators; public class McclureCalculator implements Calculator<Method> { @Override
// Path: src/main/java/org/jasome/input/Method.java // public class Method extends Code { // private final MethodDeclaration declaration; // // public final static Method UNKNOWN = new Method(); // // private Method() { // super("unknownMethod"); // this.declaration = null; // } // // public Method(MethodDeclaration declaration) { // super(declaration.getDeclarationAsString()); // this.declaration = declaration; // } // // public MethodDeclaration getSource() { // return declaration; // } // // public Type getParentType() { // return (Type) getParent(); // } // // @Override // public String toString() { // return "Method(" + this.getName() + ")"; // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/McclureCalculator.java import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.BinaryExpr; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.stmt.*; import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; package org.jasome.metrics.calculators; public class McclureCalculator implements Calculator<Method> { @Override
public Set<Metric> calculate(Method method) {
rodhilton/jasome
src/main/java/org/jasome/input/Code.java
// Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.jasome.metrics.Metric; import java.util.*;
package org.jasome.input; public abstract class Code { private String name; protected Set<Code> children = new HashSet<Code>(); private Code parent = null;
// Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/input/Code.java import com.google.common.base.Objects; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.jasome.metrics.Metric; import java.util.*; package org.jasome.input; public abstract class Code { private String name; protected Set<Code> children = new HashSet<Code>(); private Code parent = null;
private final Map<String, Metric> metrics;
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/NumberOfFieldsCalculator.java
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.google.common.collect.ImmutableSet; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set;
package org.jasome.metrics.calculators; /** * Counts the number of fields and methods in a class. * * <ul> * <li>NF - Number of Attributes (fields)</li> * <li>NSF - Number of Static Attributes (fields)</li> * <li>NPF - Number of Public Attributes (fields)</li> * <li>NM - Number of Methods</li> * <li>NSM - Number of Static Methods</li> * <li>NPM - Number of Public Methods</li> * </ul> * * @author Rod Hilton * @since 0.2 */ public class NumberOfFieldsCalculator implements Calculator<Type> { @Override
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/NumberOfFieldsCalculator.java import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.google.common.collect.ImmutableSet; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set; package org.jasome.metrics.calculators; /** * Counts the number of fields and methods in a class. * * <ul> * <li>NF - Number of Attributes (fields)</li> * <li>NSF - Number of Static Attributes (fields)</li> * <li>NPF - Number of Public Attributes (fields)</li> * <li>NM - Number of Methods</li> * <li>NSM - Number of Static Methods</li> * <li>NPM - Number of Public Methods</li> * </ul> * * @author Rod Hilton * @since 0.2 */ public class NumberOfFieldsCalculator implements Calculator<Type> { @Override
public Set<Metric> calculate(Type type) {
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/NumberOfParametersCalculator.java
// Path: src/main/java/org/jasome/input/Method.java // public class Method extends Code { // private final MethodDeclaration declaration; // // public final static Method UNKNOWN = new Method(); // // private Method() { // super("unknownMethod"); // this.declaration = null; // } // // public Method(MethodDeclaration declaration) { // super(declaration.getDeclarationAsString()); // this.declaration = declaration; // } // // public MethodDeclaration getSource() { // return declaration; // } // // public Type getParentType() { // return (Type) getParent(); // } // // @Override // public String toString() { // return "Method(" + this.getName() + ")"; // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set;
package org.jasome.metrics.calculators; /** * Simply counts the number of parameters on a method * * @author Rod Hilton * @since 0.3 */ public class NumberOfParametersCalculator implements Calculator<Method> { @Override
// Path: src/main/java/org/jasome/input/Method.java // public class Method extends Code { // private final MethodDeclaration declaration; // // public final static Method UNKNOWN = new Method(); // // private Method() { // super("unknownMethod"); // this.declaration = null; // } // // public Method(MethodDeclaration declaration) { // super(declaration.getDeclarationAsString()); // this.declaration = declaration; // } // // public MethodDeclaration getSource() { // return declaration; // } // // public Type getParentType() { // return (Type) getParent(); // } // // @Override // public String toString() { // return "Method(" + this.getName() + ")"; // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/NumberOfParametersCalculator.java import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Set; package org.jasome.metrics.calculators; /** * Simply counts the number of parameters on a method * * @author Rod Hilton * @since 0.3 */ public class NumberOfParametersCalculator implements Calculator<Method> { @Override
public Set<Metric> calculate(Method method) {
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/NestedBlockDepthCalculator.java
// Path: src/main/java/org/jasome/input/Method.java // public class Method extends Code { // private final MethodDeclaration declaration; // // public final static Method UNKNOWN = new Method(); // // private Method() { // super("unknownMethod"); // this.declaration = null; // } // // public Method(MethodDeclaration declaration) { // super(declaration.getDeclarationAsString()); // this.declaration = declaration; // } // // public MethodDeclaration getSource() { // return declaration; // } // // public Type getParentType() { // return (Type) getParent(); // } // // @Override // public String toString() { // return "Method(" + this.getName() + ")"; // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.LambdaExpr; import com.github.javaparser.ast.stmt.*; import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.ArrayList; import java.util.List; import java.util.OptionalInt; import java.util.Set;
package org.jasome.metrics.calculators; public class NestedBlockDepthCalculator implements Calculator<Method> { @Override
// Path: src/main/java/org/jasome/input/Method.java // public class Method extends Code { // private final MethodDeclaration declaration; // // public final static Method UNKNOWN = new Method(); // // private Method() { // super("unknownMethod"); // this.declaration = null; // } // // public Method(MethodDeclaration declaration) { // super(declaration.getDeclarationAsString()); // this.declaration = declaration; // } // // public MethodDeclaration getSource() { // return declaration; // } // // public Type getParentType() { // return (Type) getParent(); // } // // @Override // public String toString() { // return "Method(" + this.getName() + ")"; // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/NestedBlockDepthCalculator.java import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.LambdaExpr; import com.github.javaparser.ast.stmt.*; import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.ArrayList; import java.util.List; import java.util.OptionalInt; import java.util.Set; package org.jasome.metrics.calculators; public class NestedBlockDepthCalculator implements Calculator<Method> { @Override
public Set<Metric> calculate(Method method) {
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/RawTotalLinesOfCodeCalculator.java
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // }
import com.github.javaparser.Position; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.google.common.collect.ImmutableSet; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Optional; import java.util.Set;
package org.jasome.metrics.calculators; /** * Counts the raw number of lines of code within a class (excludes package * declaration, import statements, and comments outside of a class). Within a * class declaration, will count whitespace, comments, multi-line statements, * and brackets. * * @author Rod Hilton * @since 0.1 */ public class RawTotalLinesOfCodeCalculator implements Calculator<Type> { @Override
// Path: src/main/java/org/jasome/input/Type.java // public class Type extends Code { // private final ClassOrInterfaceDeclaration declaration; // private Map<String, Method> methodLookup; // // public Type(ClassOrInterfaceDeclaration declaration) { // super(getClassNameFromDeclaration(declaration)); // this.declaration = declaration; // this.methodLookup = new HashMap<>(); // } // // public ClassOrInterfaceDeclaration getSource() { // return declaration; // } // // private static String getClassNameFromDeclaration(ClassOrInterfaceDeclaration classDefinition) { // String className = classDefinition.getNameAsString(); // // if (classDefinition.getParentNode().isPresent()) { // Node parentNode = classDefinition.getParentNode().get(); // if (parentNode instanceof ClassOrInterfaceDeclaration) { // className = ((ClassOrInterfaceDeclaration) parentNode).getNameAsString() + "." + // classDefinition.getNameAsString(); // } // } // return className; // } // // @SuppressWarnings("unchecked") // public Set<Method> getMethods() { // return (Set<Method>)(Set<?>)getChildren(); // } // // public void addMethod(Method method) { // methodLookup.put(method.getSource().getSignature().asString(), method); // addChild(method); // } // // public Package getParentPackage() { // return (Package)getParent(); // } // // @Override // public String toString() { // return "Type("+this.getName()+")"; // } // // public Optional<Method> lookupMethodBySignature(String methodSignature) { // if(methodLookup.containsKey(methodSignature)) { // return Optional.of(methodLookup.get(methodSignature)); // } else { // return Optional.empty(); // } // } // } // // Path: src/main/java/org/jasome/metrics/Calculator.java // public interface Calculator<T extends Code> { // // Set<Metric> calculate(T t); // // } // // Path: src/main/java/org/jasome/metrics/Metric.java // public class Metric { // private String name; // private String description; // private NumericValue value; // // protected Metric(String name, String description, NumericValue value) { // this.name = name; // this.description = description; // this.value = value; // } // // public static Metric of(String name, String description, NumericValue value) { // return new Metric(name, description, value); // } // // public static Metric of(String name, String description, long value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public static Metric of(String name, String description, double value) { // return new Metric(name, description, NumericValue.of(value)); // } // // public String getName() { // return name; // } // // public String getDescription() { // return description; // } // // public NumericValue getValue() { // return value; // } // // @Override // public String toString() { // return name + ": " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Metric)) return false; // Metric that = (Metric) o; // return Objects.equal(name, that.name) && // Objects.equal(description, that.description) && // Objects.equal(value, that.value); // } // // @Override // public int hashCode() { // return Objects.hashCode(name, description, value); // } // // public String getFormattedValue() { // return value.toString(); // } // } // Path: src/main/java/org/jasome/metrics/calculators/RawTotalLinesOfCodeCalculator.java import com.github.javaparser.Position; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.google.common.collect.ImmutableSet; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import java.util.Optional; import java.util.Set; package org.jasome.metrics.calculators; /** * Counts the raw number of lines of code within a class (excludes package * declaration, import statements, and comments outside of a class). Within a * class declaration, will count whitespace, comments, multi-line statements, * and brackets. * * @author Rod Hilton * @since 0.1 */ public class RawTotalLinesOfCodeCalculator implements Calculator<Type> { @Override
public Set<Metric> calculate(Type type) {
OpenSensing/funf-v4
funf_v4/src/main/java/edu/mit/media/funf/config/HttpConfigUpdater.java
// Path: funf_v4/src/main/java/edu/mit/media/funf/util/IOUtil.java // public class IOUtil { // // public static String inputStreamToString(InputStream is, String encoding) throws IOException { // final char[] buffer = new char[0x10000]; // StringBuilder out = new StringBuilder(); // Reader in = new InputStreamReader(is, encoding); // int read; // do { // read = in.read(buffer, 0, buffer.length); // if (read>0) { // out.append(buffer, 0, read); // } // } while (read>=0); // return out.toString(); // } // // public static String httpGet(String uri,HttpParams params){ // HttpResponse response=null; // HttpClient httpclient = new DefaultHttpClient(); // StringBuilder uriBuilder = new StringBuilder(uri); // HttpGet httpget = new HttpGet(uriBuilder.toString()); // if (params != null) { // httpget.setParams(params); // } // try { // response = httpclient.execute(httpget); // if (response.getStatusLine().getStatusCode() == 401) { // FunfManager.funfManager.authError(); // response = null; // } // } catch (ClientProtocolException e) { // Log.e(TAG, "HttpGet Error: ", e); // response=null; // } catch (IOException e) { // Log.e(TAG, "HttpGet Error: ", e); // response=null; // } finally{ // httpclient.getConnectionManager().shutdown(); // } // if (response != null) { // try { // StringBuilder sb = new StringBuilder(); // HttpEntity entity = response.getEntity(); // BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()), 65728); // String line; // while ((line = reader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (IOException e) {e.printStackTrace();} // catch (Exception e) {e.printStackTrace();} // } // return null; // } // // /** // * Closes a stream, and swallows null cases our IOExceptions. // * @param stream // */ // public static boolean close(Closeable stream) { // if(stream != null) { // try { // stream.close(); // return true; // } catch (IOException e) { // Log.e(LogUtil.TAG, "Error closing stream", e); // } // } // return false; // } // // public static boolean isValidUrl(String url) { // Log.d(LogUtil.TAG, "Validating url"); // boolean isValidUrl = Patterns.WEB_URL.matcher(url).matches(); // Log.d(LogUtil.TAG, "Valid url? " + isValidUrl); // return isValidUrl; // } // // public static String formatServerUrl(String uploadurl, String filename) { // // URI uri = null; // String accessToken = ""; // try { // uri = new URI(uploadurl); // accessToken = FunfManager.context.getSharedPreferences("funf_auth", Context.MODE_PRIVATE).getString(md5(uri.getHost()), ""); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // String formattedUploadUrl = uploadurl; // formattedUploadUrl = formattedUploadUrl.replace("$FILENAME$", filename); // formattedUploadUrl = formattedUploadUrl.replace("$ACCESS_TOKEN$", accessToken); // // return formattedUploadUrl; // } // // public static final String md5(final String s) { // try { // // Create MD5 Hash // MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // // // Create Hex String // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) // h = "0" + h; // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } catch (NullPointerException e) { // e.printStackTrace(); // } // return ""; // } // }
import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import edu.mit.media.funf.util.IOUtil;
package edu.mit.media.funf.config; /** * ConfigUpdater which does an Http get to the given url. * */ public class HttpConfigUpdater extends ConfigUpdater { @Configurable private String url; @Override public JsonObject getConfig() throws ConfigUpdateException { try { String content = null;
// Path: funf_v4/src/main/java/edu/mit/media/funf/util/IOUtil.java // public class IOUtil { // // public static String inputStreamToString(InputStream is, String encoding) throws IOException { // final char[] buffer = new char[0x10000]; // StringBuilder out = new StringBuilder(); // Reader in = new InputStreamReader(is, encoding); // int read; // do { // read = in.read(buffer, 0, buffer.length); // if (read>0) { // out.append(buffer, 0, read); // } // } while (read>=0); // return out.toString(); // } // // public static String httpGet(String uri,HttpParams params){ // HttpResponse response=null; // HttpClient httpclient = new DefaultHttpClient(); // StringBuilder uriBuilder = new StringBuilder(uri); // HttpGet httpget = new HttpGet(uriBuilder.toString()); // if (params != null) { // httpget.setParams(params); // } // try { // response = httpclient.execute(httpget); // if (response.getStatusLine().getStatusCode() == 401) { // FunfManager.funfManager.authError(); // response = null; // } // } catch (ClientProtocolException e) { // Log.e(TAG, "HttpGet Error: ", e); // response=null; // } catch (IOException e) { // Log.e(TAG, "HttpGet Error: ", e); // response=null; // } finally{ // httpclient.getConnectionManager().shutdown(); // } // if (response != null) { // try { // StringBuilder sb = new StringBuilder(); // HttpEntity entity = response.getEntity(); // BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()), 65728); // String line; // while ((line = reader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (IOException e) {e.printStackTrace();} // catch (Exception e) {e.printStackTrace();} // } // return null; // } // // /** // * Closes a stream, and swallows null cases our IOExceptions. // * @param stream // */ // public static boolean close(Closeable stream) { // if(stream != null) { // try { // stream.close(); // return true; // } catch (IOException e) { // Log.e(LogUtil.TAG, "Error closing stream", e); // } // } // return false; // } // // public static boolean isValidUrl(String url) { // Log.d(LogUtil.TAG, "Validating url"); // boolean isValidUrl = Patterns.WEB_URL.matcher(url).matches(); // Log.d(LogUtil.TAG, "Valid url? " + isValidUrl); // return isValidUrl; // } // // public static String formatServerUrl(String uploadurl, String filename) { // // URI uri = null; // String accessToken = ""; // try { // uri = new URI(uploadurl); // accessToken = FunfManager.context.getSharedPreferences("funf_auth", Context.MODE_PRIVATE).getString(md5(uri.getHost()), ""); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // String formattedUploadUrl = uploadurl; // formattedUploadUrl = formattedUploadUrl.replace("$FILENAME$", filename); // formattedUploadUrl = formattedUploadUrl.replace("$ACCESS_TOKEN$", accessToken); // // return formattedUploadUrl; // } // // public static final String md5(final String s) { // try { // // Create MD5 Hash // MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // // // Create Hex String // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) // h = "0" + h; // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } catch (NullPointerException e) { // e.printStackTrace(); // } // return ""; // } // } // Path: funf_v4/src/main/java/edu/mit/media/funf/config/HttpConfigUpdater.java import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import edu.mit.media.funf.util.IOUtil; package edu.mit.media.funf.config; /** * ConfigUpdater which does an Http get to the given url. * */ public class HttpConfigUpdater extends ConfigUpdater { @Configurable private String url; @Override public JsonObject getConfig() throws ConfigUpdateException { try { String content = null;
String currentUrl = IOUtil.formatServerUrl(url, "");
andyiac/githot
app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java
// Path: app/src/main/java/com/knight/arch/api/FirService.java // public interface FirService { // @GET("/apps/latest/{id}") // Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token); // } // // Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.Toast; import com.knight.arch.BuildConfig; import com.knight.arch.R; import com.knight.arch.api.FirService; import com.knight.arch.model.FirVersion; import com.knight.arch.module.Injector; import com.umeng.analytics.MobclickAgent; import javax.inject.Inject; import de.psdev.licensesdialog.LicensesDialog; import rx.Subscriber; import rx.android.app.AppObservable;
package com.knight.arch.ui.fragment; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class SettingsFragment extends PreferenceFragment { private boolean injected = false; @Inject
// Path: app/src/main/java/com/knight/arch/api/FirService.java // public interface FirService { // @GET("/apps/latest/{id}") // Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token); // } // // Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.Toast; import com.knight.arch.BuildConfig; import com.knight.arch.R; import com.knight.arch.api.FirService; import com.knight.arch.model.FirVersion; import com.knight.arch.module.Injector; import com.umeng.analytics.MobclickAgent; import javax.inject.Inject; import de.psdev.licensesdialog.LicensesDialog; import rx.Subscriber; import rx.android.app.AppObservable; package com.knight.arch.ui.fragment; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class SettingsFragment extends PreferenceFragment { private boolean injected = false; @Inject
FirService firService;
andyiac/githot
app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java
// Path: app/src/main/java/com/knight/arch/api/FirService.java // public interface FirService { // @GET("/apps/latest/{id}") // Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token); // } // // Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.Toast; import com.knight.arch.BuildConfig; import com.knight.arch.R; import com.knight.arch.api.FirService; import com.knight.arch.model.FirVersion; import com.knight.arch.module.Injector; import com.umeng.analytics.MobclickAgent; import javax.inject.Inject; import de.psdev.licensesdialog.LicensesDialog; import rx.Subscriber; import rx.android.app.AppObservable;
Preference checkVersionPref = findPreference(getString(R.string.pref_check_version)); checkVersionPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { checkVersion(); return true; } }); checkVersionPref.setSummary(getString(R.string.s_check_version, BuildConfig.VERSION_NAME)); } public void onResume() { super.onResume(); MobclickAgent.onPageStart("SettingsFragment"); //统计页面 } public void onPause() { super.onPause(); MobclickAgent.onPageEnd("SettingsFragment"); } private void checkVersion() { final ProgressDialog dialog = new ProgressDialog(getActivity()); dialog.setMessage(getString(R.string.msg_checking_version)); dialog.show(); AppObservable.bindFragment(this, firService.checkVersion(BuildConfig.FIR_APPLICATION_ID, BuildConfig.FIR_API_TOKEN))
// Path: app/src/main/java/com/knight/arch/api/FirService.java // public interface FirService { // @GET("/apps/latest/{id}") // Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token); // } // // Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.Toast; import com.knight.arch.BuildConfig; import com.knight.arch.R; import com.knight.arch.api.FirService; import com.knight.arch.model.FirVersion; import com.knight.arch.module.Injector; import com.umeng.analytics.MobclickAgent; import javax.inject.Inject; import de.psdev.licensesdialog.LicensesDialog; import rx.Subscriber; import rx.android.app.AppObservable; Preference checkVersionPref = findPreference(getString(R.string.pref_check_version)); checkVersionPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { checkVersion(); return true; } }); checkVersionPref.setSummary(getString(R.string.s_check_version, BuildConfig.VERSION_NAME)); } public void onResume() { super.onResume(); MobclickAgent.onPageStart("SettingsFragment"); //统计页面 } public void onPause() { super.onPause(); MobclickAgent.onPageEnd("SettingsFragment"); } private void checkVersion() { final ProgressDialog dialog = new ProgressDialog(getActivity()); dialog.setMessage(getString(R.string.msg_checking_version)); dialog.show(); AppObservable.bindFragment(this, firService.checkVersion(BuildConfig.FIR_APPLICATION_ID, BuildConfig.FIR_API_TOKEN))
.subscribe(new Subscriber<FirVersion>() {
andyiac/githot
app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java
// Path: app/src/main/java/com/knight/arch/api/FirService.java // public interface FirService { // @GET("/apps/latest/{id}") // Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token); // } // // Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.Toast; import com.knight.arch.BuildConfig; import com.knight.arch.R; import com.knight.arch.api.FirService; import com.knight.arch.model.FirVersion; import com.knight.arch.module.Injector; import com.umeng.analytics.MobclickAgent; import javax.inject.Inject; import de.psdev.licensesdialog.LicensesDialog; import rx.Subscriber; import rx.android.app.AppObservable;
} else { Toast.makeText(getActivity(), R.string.msg_this_is_latest_version, Toast.LENGTH_SHORT).show(); dialog.dismiss(); } } }); } private void showNewVersionFoundDialog(final FirVersion newFirVersion) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_new_version_found) .setMessage(getString(R.string.msg_new_version_found, newFirVersion.getVersionShort(), newFirVersion.getVersion(), newFirVersion.getChangeLog())) .setPositiveButton(R.string.btn_dialog_update, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent downloadPageIntent = new Intent(Intent.ACTION_VIEW); downloadPageIntent.setData(Uri.parse(newFirVersion.getUpdateUrl())); getActivity().startActivity(downloadPageIntent); } }) .setNegativeButton(android.R.string.cancel, null) .create() .show(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!injected) { injected = true;
// Path: app/src/main/java/com/knight/arch/api/FirService.java // public interface FirService { // @GET("/apps/latest/{id}") // Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token); // } // // Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.Toast; import com.knight.arch.BuildConfig; import com.knight.arch.R; import com.knight.arch.api.FirService; import com.knight.arch.model.FirVersion; import com.knight.arch.module.Injector; import com.umeng.analytics.MobclickAgent; import javax.inject.Inject; import de.psdev.licensesdialog.LicensesDialog; import rx.Subscriber; import rx.android.app.AppObservable; } else { Toast.makeText(getActivity(), R.string.msg_this_is_latest_version, Toast.LENGTH_SHORT).show(); dialog.dismiss(); } } }); } private void showNewVersionFoundDialog(final FirVersion newFirVersion) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_new_version_found) .setMessage(getString(R.string.msg_new_version_found, newFirVersion.getVersionShort(), newFirVersion.getVersion(), newFirVersion.getChangeLog())) .setPositiveButton(R.string.btn_dialog_update, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent downloadPageIntent = new Intent(Intent.ACTION_VIEW); downloadPageIntent.setData(Uri.parse(newFirVersion.getUpdateUrl())); getActivity().startActivity(downloadPageIntent); } }) .setNegativeButton(android.R.string.cancel, null) .create() .show(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!injected) { injected = true;
Injector injector = (Injector) getActivity();
andyiac/githot
app/src/main/java/com/knight/arch/ui/SettingsActivity.java
// Path: app/src/main/java/com/knight/arch/module/SettingsModule.java // @Module( // complete = false, // overrides = true, // injects = { // SettingsActivity.class, // SettingsFragment.class // } // ) // public class SettingsModule { // } // // Path: app/src/main/java/com/knight/arch/ui/base/InjectableActivity.java // public abstract class InjectableActivity extends BaseActivity implements Injector { // protected ObjectGraph objectGraph; // // @Override // protected void onCreate(Bundle savedInstanceState) { // ClientApplication app = (ClientApplication) getApplication(); // objectGraph = app.plus(this); // objectGraph.inject(this); // super.onCreate(savedInstanceState); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // objectGraph = null; // } // // public void inject(Object target) { // objectGraph.inject(target); // } // // public ObjectGraph plus(Object[] modules) { // return objectGraph.plus(modules); // } // // } // // Path: app/src/main/java/com/knight/arch/utils/KeyBoardTools.java // public class KeyBoardTools { // /** // * 模拟键盘事件方法 // */ // public static void actionKey(final int keyCode) { // new Thread() { // public void run() { // try { // Instrumentation inst = new Instrumentation(); // inst.sendKeyDownUpSync(keyCode); // } catch (Exception e) { // e.printStackTrace(); // } // } // }.start(); // } // } // // Path: app/src/main/java/com/knight/arch/utils/L.java // public class L { // // public static boolean isDebuggable() { // return BuildConfig.DEBUG; // } // // public static void i(String msg) { // if (isDebuggable()) // Logger.i(msg); // } // // public static void d(String msg) { // if (isDebuggable()) // Logger.d(msg); // } // // public static void e(String msg) { // if (isDebuggable()) // Logger.e(msg); // } // // // public static void json(String json) { // if (isDebuggable()) // Logger.json(json); // // } // // public static void json(Object o) { // if (isDebuggable()) // Logger.json(JSON.toJSONString(o)); // } // // }
import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import com.knight.arch.R; import com.knight.arch.module.SettingsModule; import com.knight.arch.ui.base.InjectableActivity; import com.knight.arch.utils.KeyBoardTools; import com.knight.arch.utils.L; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List;
package com.knight.arch.ui; /** * @author andyiac * @date 15-8-15 * @web http://blog.andyiac.com/ */ public class SettingsActivity extends InjectableActivity { @Override public List<Object> getModules() {
// Path: app/src/main/java/com/knight/arch/module/SettingsModule.java // @Module( // complete = false, // overrides = true, // injects = { // SettingsActivity.class, // SettingsFragment.class // } // ) // public class SettingsModule { // } // // Path: app/src/main/java/com/knight/arch/ui/base/InjectableActivity.java // public abstract class InjectableActivity extends BaseActivity implements Injector { // protected ObjectGraph objectGraph; // // @Override // protected void onCreate(Bundle savedInstanceState) { // ClientApplication app = (ClientApplication) getApplication(); // objectGraph = app.plus(this); // objectGraph.inject(this); // super.onCreate(savedInstanceState); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // objectGraph = null; // } // // public void inject(Object target) { // objectGraph.inject(target); // } // // public ObjectGraph plus(Object[] modules) { // return objectGraph.plus(modules); // } // // } // // Path: app/src/main/java/com/knight/arch/utils/KeyBoardTools.java // public class KeyBoardTools { // /** // * 模拟键盘事件方法 // */ // public static void actionKey(final int keyCode) { // new Thread() { // public void run() { // try { // Instrumentation inst = new Instrumentation(); // inst.sendKeyDownUpSync(keyCode); // } catch (Exception e) { // e.printStackTrace(); // } // } // }.start(); // } // } // // Path: app/src/main/java/com/knight/arch/utils/L.java // public class L { // // public static boolean isDebuggable() { // return BuildConfig.DEBUG; // } // // public static void i(String msg) { // if (isDebuggable()) // Logger.i(msg); // } // // public static void d(String msg) { // if (isDebuggable()) // Logger.d(msg); // } // // public static void e(String msg) { // if (isDebuggable()) // Logger.e(msg); // } // // // public static void json(String json) { // if (isDebuggable()) // Logger.json(json); // // } // // public static void json(Object o) { // if (isDebuggable()) // Logger.json(JSON.toJSONString(o)); // } // // } // Path: app/src/main/java/com/knight/arch/ui/SettingsActivity.java import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import com.knight.arch.R; import com.knight.arch.module.SettingsModule; import com.knight.arch.ui.base.InjectableActivity; import com.knight.arch.utils.KeyBoardTools; import com.knight.arch.utils.L; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List; package com.knight.arch.ui; /** * @author andyiac * @date 15-8-15 * @web http://blog.andyiac.com/ */ public class SettingsActivity extends InjectableActivity { @Override public List<Object> getModules() {
return Arrays.<Object>asList(new SettingsModule());
andyiac/githot
app/src/main/java/com/knight/arch/ui/SettingsActivity.java
// Path: app/src/main/java/com/knight/arch/module/SettingsModule.java // @Module( // complete = false, // overrides = true, // injects = { // SettingsActivity.class, // SettingsFragment.class // } // ) // public class SettingsModule { // } // // Path: app/src/main/java/com/knight/arch/ui/base/InjectableActivity.java // public abstract class InjectableActivity extends BaseActivity implements Injector { // protected ObjectGraph objectGraph; // // @Override // protected void onCreate(Bundle savedInstanceState) { // ClientApplication app = (ClientApplication) getApplication(); // objectGraph = app.plus(this); // objectGraph.inject(this); // super.onCreate(savedInstanceState); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // objectGraph = null; // } // // public void inject(Object target) { // objectGraph.inject(target); // } // // public ObjectGraph plus(Object[] modules) { // return objectGraph.plus(modules); // } // // } // // Path: app/src/main/java/com/knight/arch/utils/KeyBoardTools.java // public class KeyBoardTools { // /** // * 模拟键盘事件方法 // */ // public static void actionKey(final int keyCode) { // new Thread() { // public void run() { // try { // Instrumentation inst = new Instrumentation(); // inst.sendKeyDownUpSync(keyCode); // } catch (Exception e) { // e.printStackTrace(); // } // } // }.start(); // } // } // // Path: app/src/main/java/com/knight/arch/utils/L.java // public class L { // // public static boolean isDebuggable() { // return BuildConfig.DEBUG; // } // // public static void i(String msg) { // if (isDebuggable()) // Logger.i(msg); // } // // public static void d(String msg) { // if (isDebuggable()) // Logger.d(msg); // } // // public static void e(String msg) { // if (isDebuggable()) // Logger.e(msg); // } // // // public static void json(String json) { // if (isDebuggable()) // Logger.json(json); // // } // // public static void json(Object o) { // if (isDebuggable()) // Logger.json(JSON.toJSONString(o)); // } // // }
import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import com.knight.arch.R; import com.knight.arch.module.SettingsModule; import com.knight.arch.ui.base.InjectableActivity; import com.knight.arch.utils.KeyBoardTools; import com.knight.arch.utils.L; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List;
MobclickAgent.onResume(this); } public void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); // setStatusColor(android.R.color.transparent); } private void initView() { Toolbar mToolbar = (Toolbar) findViewById(R.id.hot_repos_toolbar); setSupportActionBar(mToolbar); final ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setHomeAsUpIndicator(R.mipmap.ic_back_arrow); ab.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) {
// Path: app/src/main/java/com/knight/arch/module/SettingsModule.java // @Module( // complete = false, // overrides = true, // injects = { // SettingsActivity.class, // SettingsFragment.class // } // ) // public class SettingsModule { // } // // Path: app/src/main/java/com/knight/arch/ui/base/InjectableActivity.java // public abstract class InjectableActivity extends BaseActivity implements Injector { // protected ObjectGraph objectGraph; // // @Override // protected void onCreate(Bundle savedInstanceState) { // ClientApplication app = (ClientApplication) getApplication(); // objectGraph = app.plus(this); // objectGraph.inject(this); // super.onCreate(savedInstanceState); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // objectGraph = null; // } // // public void inject(Object target) { // objectGraph.inject(target); // } // // public ObjectGraph plus(Object[] modules) { // return objectGraph.plus(modules); // } // // } // // Path: app/src/main/java/com/knight/arch/utils/KeyBoardTools.java // public class KeyBoardTools { // /** // * 模拟键盘事件方法 // */ // public static void actionKey(final int keyCode) { // new Thread() { // public void run() { // try { // Instrumentation inst = new Instrumentation(); // inst.sendKeyDownUpSync(keyCode); // } catch (Exception e) { // e.printStackTrace(); // } // } // }.start(); // } // } // // Path: app/src/main/java/com/knight/arch/utils/L.java // public class L { // // public static boolean isDebuggable() { // return BuildConfig.DEBUG; // } // // public static void i(String msg) { // if (isDebuggable()) // Logger.i(msg); // } // // public static void d(String msg) { // if (isDebuggable()) // Logger.d(msg); // } // // public static void e(String msg) { // if (isDebuggable()) // Logger.e(msg); // } // // // public static void json(String json) { // if (isDebuggable()) // Logger.json(json); // // } // // public static void json(Object o) { // if (isDebuggable()) // Logger.json(JSON.toJSONString(o)); // } // // } // Path: app/src/main/java/com/knight/arch/ui/SettingsActivity.java import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import com.knight.arch.R; import com.knight.arch.module.SettingsModule; import com.knight.arch.ui.base.InjectableActivity; import com.knight.arch.utils.KeyBoardTools; import com.knight.arch.utils.L; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List; MobclickAgent.onResume(this); } public void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); // setStatusColor(android.R.color.transparent); } private void initView() { Toolbar mToolbar = (Toolbar) findViewById(R.id.hot_repos_toolbar); setSupportActionBar(mToolbar); final ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setHomeAsUpIndicator(R.mipmap.ic_back_arrow); ab.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) {
KeyBoardTools.actionKey(KeyEvent.KEYCODE_BACK);
andyiac/githot
app/src/main/java/com/knight/arch/ClientApplication.java
// Path: app/src/main/java/com/knight/arch/model/AccessTokenResponse.java // public class AccessTokenResponse { // // private String access_token; // private String scope; // private String token_type; // // public String getAccess_token() { // return access_token; // } // // public void setAccess_token(String access_token) { // this.access_token = access_token; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getToken_type() { // return token_type; // } // // public void setToken_type(String token_type) { // this.token_type = token_type; // } // } // // Path: app/src/main/java/com/knight/arch/module/AppModule.java // @Module( // injects = {ClientApplication.class}, // includes = {DataModule.class}, // library = true // ) // // public class AppModule { // Context ctx; // // public AppModule(Context context) { // this.ctx = context; // } // // @Provides // Context provideContexts() { // return this.ctx; // } // // @Provides // @Singleton // @Named("Root") // File provideCacheDir(Context ctx) { // return ctx.getCacheDir(); // } // // @Provides // @Singleton // @Named("Http") // File provideHttpCacheDir(@Named("Root") File root) { // return new File(root, "http"); // } // // @Provides // @Singleton // @Named("Data") // File provideDataCacheDir(@Named("Root") File data) { // return new File(data, "data"); // } // // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.app.Application; import com.facebook.stetho.Stetho; import com.knight.arch.model.AccessTokenResponse; import com.knight.arch.module.AppModule; import com.knight.arch.module.Injector; import com.orhanobut.logger.LogLevel; import com.orhanobut.logger.Logger; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List; import dagger.ObjectGraph;
package com.knight.arch; /** * @author andyiac * @date 15-8-4 * @web http://blog.andyiac.com/ */ public class ClientApplication extends Application implements Injector { private static final String LOGGER_TAG = "<<=TAG=>>";
// Path: app/src/main/java/com/knight/arch/model/AccessTokenResponse.java // public class AccessTokenResponse { // // private String access_token; // private String scope; // private String token_type; // // public String getAccess_token() { // return access_token; // } // // public void setAccess_token(String access_token) { // this.access_token = access_token; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getToken_type() { // return token_type; // } // // public void setToken_type(String token_type) { // this.token_type = token_type; // } // } // // Path: app/src/main/java/com/knight/arch/module/AppModule.java // @Module( // injects = {ClientApplication.class}, // includes = {DataModule.class}, // library = true // ) // // public class AppModule { // Context ctx; // // public AppModule(Context context) { // this.ctx = context; // } // // @Provides // Context provideContexts() { // return this.ctx; // } // // @Provides // @Singleton // @Named("Root") // File provideCacheDir(Context ctx) { // return ctx.getCacheDir(); // } // // @Provides // @Singleton // @Named("Http") // File provideHttpCacheDir(@Named("Root") File root) { // return new File(root, "http"); // } // // @Provides // @Singleton // @Named("Data") // File provideDataCacheDir(@Named("Root") File data) { // return new File(data, "data"); // } // // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ClientApplication.java import android.app.Application; import com.facebook.stetho.Stetho; import com.knight.arch.model.AccessTokenResponse; import com.knight.arch.module.AppModule; import com.knight.arch.module.Injector; import com.orhanobut.logger.LogLevel; import com.orhanobut.logger.Logger; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List; import dagger.ObjectGraph; package com.knight.arch; /** * @author andyiac * @date 15-8-4 * @web http://blog.andyiac.com/ */ public class ClientApplication extends Application implements Injector { private static final String LOGGER_TAG = "<<=TAG=>>";
private AccessTokenResponse accessTokenResponse;
andyiac/githot
app/src/main/java/com/knight/arch/ClientApplication.java
// Path: app/src/main/java/com/knight/arch/model/AccessTokenResponse.java // public class AccessTokenResponse { // // private String access_token; // private String scope; // private String token_type; // // public String getAccess_token() { // return access_token; // } // // public void setAccess_token(String access_token) { // this.access_token = access_token; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getToken_type() { // return token_type; // } // // public void setToken_type(String token_type) { // this.token_type = token_type; // } // } // // Path: app/src/main/java/com/knight/arch/module/AppModule.java // @Module( // injects = {ClientApplication.class}, // includes = {DataModule.class}, // library = true // ) // // public class AppModule { // Context ctx; // // public AppModule(Context context) { // this.ctx = context; // } // // @Provides // Context provideContexts() { // return this.ctx; // } // // @Provides // @Singleton // @Named("Root") // File provideCacheDir(Context ctx) { // return ctx.getCacheDir(); // } // // @Provides // @Singleton // @Named("Http") // File provideHttpCacheDir(@Named("Root") File root) { // return new File(root, "http"); // } // // @Provides // @Singleton // @Named("Data") // File provideDataCacheDir(@Named("Root") File data) { // return new File(data, "data"); // } // // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.app.Application; import com.facebook.stetho.Stetho; import com.knight.arch.model.AccessTokenResponse; import com.knight.arch.module.AppModule; import com.knight.arch.module.Injector; import com.orhanobut.logger.LogLevel; import com.orhanobut.logger.Logger; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List; import dagger.ObjectGraph;
initUmeng(); } private void initUmeng() { MobclickAgent.openActivityDurationTrack(false); } private void initDagger() { objectGraph = ObjectGraph.create(getModules().toArray()); objectGraph.inject(this); } private void initLogger() { Logger.init(LOGGER_TAG) // default PRETTYLOGGER or use just init() .setMethodCount(4) // default 2 .setLogLevel(LogLevel.FULL) // default LogLevel.FULL .setMethodOffset(2); // default 0 //.hideThreadInfo() // default shown } private void initStetho() { Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)) .build()); } public List<Object> getModules() {
// Path: app/src/main/java/com/knight/arch/model/AccessTokenResponse.java // public class AccessTokenResponse { // // private String access_token; // private String scope; // private String token_type; // // public String getAccess_token() { // return access_token; // } // // public void setAccess_token(String access_token) { // this.access_token = access_token; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getToken_type() { // return token_type; // } // // public void setToken_type(String token_type) { // this.token_type = token_type; // } // } // // Path: app/src/main/java/com/knight/arch/module/AppModule.java // @Module( // injects = {ClientApplication.class}, // includes = {DataModule.class}, // library = true // ) // // public class AppModule { // Context ctx; // // public AppModule(Context context) { // this.ctx = context; // } // // @Provides // Context provideContexts() { // return this.ctx; // } // // @Provides // @Singleton // @Named("Root") // File provideCacheDir(Context ctx) { // return ctx.getCacheDir(); // } // // @Provides // @Singleton // @Named("Http") // File provideHttpCacheDir(@Named("Root") File root) { // return new File(root, "http"); // } // // @Provides // @Singleton // @Named("Data") // File provideDataCacheDir(@Named("Root") File data) { // return new File(data, "data"); // } // // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ClientApplication.java import android.app.Application; import com.facebook.stetho.Stetho; import com.knight.arch.model.AccessTokenResponse; import com.knight.arch.module.AppModule; import com.knight.arch.module.Injector; import com.orhanobut.logger.LogLevel; import com.orhanobut.logger.Logger; import com.umeng.analytics.MobclickAgent; import java.util.Arrays; import java.util.List; import dagger.ObjectGraph; initUmeng(); } private void initUmeng() { MobclickAgent.openActivityDurationTrack(false); } private void initDagger() { objectGraph = ObjectGraph.create(getModules().toArray()); objectGraph.inject(this); } private void initLogger() { Logger.init(LOGGER_TAG) // default PRETTYLOGGER or use just init() .setMethodCount(4) // default 2 .setLogLevel(LogLevel.FULL) // default LogLevel.FULL .setMethodOffset(2); // default 0 //.hideThreadInfo() // default shown } private void initStetho() { Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)) .build()); } public List<Object> getModules() {
return Arrays.<Object>asList(new AppModule(this));
andyiac/githot
app/src/main/java/com/knight/arch/ui/fragment/LoginDialogFragment.java
// Path: app/src/main/java/com/knight/arch/events/LoginUriMsg.java // public class LoginUriMsg { // private Uri url; // // public Uri getUrl() { // return url; // } // // public void setUrl(Uri url) { // this.url = url; // } // } // // Path: app/src/main/java/com/knight/arch/utils/L.java // public class L { // // public static boolean isDebuggable() { // return BuildConfig.DEBUG; // } // // public static void i(String msg) { // if (isDebuggable()) // Logger.i(msg); // } // // public static void d(String msg) { // if (isDebuggable()) // Logger.d(msg); // } // // public static void e(String msg) { // if (isDebuggable()) // Logger.e(msg); // } // // // public static void json(String json) { // if (isDebuggable()) // Logger.json(json); // // } // // public static void json(Object o) { // if (isDebuggable()) // Logger.json(JSON.toJSONString(o)); // } // // }
import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import com.knight.arch.R; import com.knight.arch.events.LoginUriMsg; import com.knight.arch.utils.L; import de.greenrobot.event.EventBus;
@Override public boolean onCheckIsTextEditor() { return true; } }; webView.loadUrl(url); webView.setFocusable(true); webView.setFocusableInTouchMode(true); webView.requestFocus(View.FOCUS_DOWN); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (uri.getScheme().equals("http")) {
// Path: app/src/main/java/com/knight/arch/events/LoginUriMsg.java // public class LoginUriMsg { // private Uri url; // // public Uri getUrl() { // return url; // } // // public void setUrl(Uri url) { // this.url = url; // } // } // // Path: app/src/main/java/com/knight/arch/utils/L.java // public class L { // // public static boolean isDebuggable() { // return BuildConfig.DEBUG; // } // // public static void i(String msg) { // if (isDebuggable()) // Logger.i(msg); // } // // public static void d(String msg) { // if (isDebuggable()) // Logger.d(msg); // } // // public static void e(String msg) { // if (isDebuggable()) // Logger.e(msg); // } // // // public static void json(String json) { // if (isDebuggable()) // Logger.json(json); // // } // // public static void json(Object o) { // if (isDebuggable()) // Logger.json(JSON.toJSONString(o)); // } // // } // Path: app/src/main/java/com/knight/arch/ui/fragment/LoginDialogFragment.java import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import com.knight.arch.R; import com.knight.arch.events.LoginUriMsg; import com.knight.arch.utils.L; import de.greenrobot.event.EventBus; @Override public boolean onCheckIsTextEditor() { return true; } }; webView.loadUrl(url); webView.setFocusable(true); webView.setFocusableInTouchMode(true); webView.requestFocus(View.FOCUS_DOWN); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (uri.getScheme().equals("http")) {
LoginUriMsg msg = new LoginUriMsg();
andyiac/githot
app/src/main/java/com/knight/arch/api/FirService.java
// Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // }
import com.knight.arch.model.FirVersion; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable;
/* * * * Copyright (c) linroid 2015. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.knight.arch.api; public interface FirService { @GET("/apps/latest/{id}")
// Path: app/src/main/java/com/knight/arch/model/FirVersion.java // public class FirVersion { // // @Expose // private String name; // @Expose // private Integer version; // @SerializedName("changelog") // @Expose // private String changeLog; // @Expose // private String versionShort; // @Expose // private String installUrl; // @SerializedName("update_url") // @Expose // private String updateUrl; // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getVersion() { // return version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getChangeLog() { // return changeLog; // } // // public void setChangeLog(String changeLog) { // this.changeLog = changeLog; // } // // public String getVersionShort() { // return versionShort; // } // // public void setVersionShort(String versionShort) { // this.versionShort = versionShort; // } // // public String getInstallUrl() { // return installUrl; // } // // public void setInstallUrl(String installUrl) { // this.installUrl = installUrl; // } // // public String getUpdateUrl() { // return updateUrl; // } // // public void setUpdateUrl(String updateUrl) { // this.updateUrl = updateUrl; // } // } // Path: app/src/main/java/com/knight/arch/api/FirService.java import com.knight.arch.model.FirVersion; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.Query; import rx.Observable; /* * * * Copyright (c) linroid 2015. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.knight.arch.api; public interface FirService { @GET("/apps/latest/{id}")
Observable<FirVersion> checkVersion(@Path("id") String app_id, @Query(value = "api_token") String api_token);
andyiac/githot
app/src/main/java/com/knight/arch/ui/adapter/HotReposDetailsListAdapterHolder.java
// Path: app/src/main/java/com/knight/arch/data/ReposKV.java // public class ReposKV { // private String key; // private String value; // // public ReposKV(String key, String value) { // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // }
import android.support.v4.app.FragmentActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.knight.arch.R; import com.knight.arch.data.ReposKV; import java.util.List;
/* * Copyright (C) 2014 VenomVendor <info@VenomVendor.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.knight.arch.ui.adapter; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class HotReposDetailsListAdapterHolder extends RecyclerView.Adapter<HotReposDetailsListAdapterHolder.ViewHolder> { OnItemClickListener mItemClickListener; private FragmentActivity mActivity;
// Path: app/src/main/java/com/knight/arch/data/ReposKV.java // public class ReposKV { // private String key; // private String value; // // public ReposKV(String key, String value) { // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // Path: app/src/main/java/com/knight/arch/ui/adapter/HotReposDetailsListAdapterHolder.java import android.support.v4.app.FragmentActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.knight.arch.R; import com.knight.arch.data.ReposKV; import java.util.List; /* * Copyright (C) 2014 VenomVendor <info@VenomVendor.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.knight.arch.ui.adapter; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class HotReposDetailsListAdapterHolder extends RecyclerView.Adapter<HotReposDetailsListAdapterHolder.ViewHolder> { OnItemClickListener mItemClickListener; private FragmentActivity mActivity;
private List<ReposKV> mData;
andyiac/githot
app/src/main/java/com/knight/arch/api/OAuthGitHubWebFlow.java
// Path: app/src/main/java/com/knight/arch/model/AccessTokenResponse.java // public class AccessTokenResponse { // // private String access_token; // private String scope; // private String token_type; // // public String getAccess_token() { // return access_token; // } // // public void setAccess_token(String access_token) { // this.access_token = access_token; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getToken_type() { // return token_type; // } // // public void setToken_type(String token_type) { // this.token_type = token_type; // } // }
import com.knight.arch.model.AccessTokenResponse; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.Headers; import retrofit.http.POST; import rx.Observable;
package com.knight.arch.api; /** * @author andyiac * @date 6/11/23 * @web http://blog.andyiac.com * @github https://github.com/andyiac * GitHub Auth Web Application Flow */ public interface OAuthGitHubWebFlow { //POST https://github.com/login/oauth/access_token @Headers({ "Accept: application/json" }) @FormUrlEncoded @POST("/login/oauth/access_token")
// Path: app/src/main/java/com/knight/arch/model/AccessTokenResponse.java // public class AccessTokenResponse { // // private String access_token; // private String scope; // private String token_type; // // public String getAccess_token() { // return access_token; // } // // public void setAccess_token(String access_token) { // this.access_token = access_token; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getToken_type() { // return token_type; // } // // public void setToken_type(String token_type) { // this.token_type = token_type; // } // } // Path: app/src/main/java/com/knight/arch/api/OAuthGitHubWebFlow.java import com.knight.arch.model.AccessTokenResponse; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.Headers; import retrofit.http.POST; import rx.Observable; package com.knight.arch.api; /** * @author andyiac * @date 6/11/23 * @web http://blog.andyiac.com * @github https://github.com/andyiac * GitHub Auth Web Application Flow */ public interface OAuthGitHubWebFlow { //POST https://github.com/login/oauth/access_token @Headers({ "Accept: application/json" }) @FormUrlEncoded @POST("/login/oauth/access_token")
Observable<AccessTokenResponse> getOAuthToken(@Field("client_id") String client_id,
andyiac/githot
app/src/main/java/com/knight/arch/api/ApiClient.java
// Path: app/src/main/java/com/knight/arch/data/AllPersonlInfos.java // public class AllPersonlInfos { // public List<PersonInfo> data; // // public List<PersonInfo> getData() { // return data; // } // // public void setData(List<PersonInfo> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/data/Pagination.java // public class Pagination<T extends Parcelable> { // // @Expose // private List<T> data; // // // public List<T> getData() { // return data; // } // // public void setData(List<T> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/model/PersonInfo.java // public class PersonInfo implements Parcelable { // // public static final Creator<PersonInfo> CREATOR = new Creator<PersonInfo>() { // @Override // public PersonInfo createFromParcel(Parcel in) { // return new PersonInfo(in); // } // // @Override // public PersonInfo[] newArray(int size) { // return new PersonInfo[size]; // } // }; // @SerializedName("rank") // private String Rank; // @SerializedName("gravatar") // private String Gravatar; // private String username; // private String name; // private String location; // private String language; // private String repos; // private String followers; // private String created; // // protected PersonInfo(Parcel in) { // Rank = in.readString(); // Gravatar = in.readString(); // username = in.readString(); // name = in.readString(); // location = in.readString(); // language = in.readString(); // repos = in.readString(); // followers = in.readString(); // created = in.readString(); // } // // public String getGravatar() { // return Gravatar; // } // // public void setGravatar(String gravatar) { // Gravatar = gravatar; // } // // public String getRank() { // return Rank; // } // // public void setRank(String rank) { // Rank = rank; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public String getRepos() { // return repos; // } // // public void setRepos(String repos) { // this.repos = repos; // } // // public String getFollowers() { // return followers; // } // // public void setFollowers(String followers) { // this.followers = followers; // } // // public String getCreated() { // return created; // } // // public void setCreated(String created) { // this.created = created; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(Rank); // dest.writeString(Gravatar); // dest.writeString(username); // dest.writeString(name); // dest.writeString(location); // dest.writeString(language); // dest.writeString(repos); // dest.writeString(followers); // dest.writeString(created); // } // }
import com.facebook.stetho.okhttp.StethoInterceptor; import com.knight.arch.data.AllPersonlInfos; import com.knight.arch.data.Pagination; import com.knight.arch.model.PersonInfo; import com.squareup.okhttp.OkHttpClient; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable;
package com.knight.arch.api; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class ApiClient { static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s private static final String BASE_URL = "http://mock-api.com/TyTabSFqXNyqMpNw.mock"; private static TestDemoApiInterface testDemoApiInterface; /** * 用于Stethoscope调试的ttpClient */ public static OkClient getOkClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new StethoInterceptor()); return new OkClient(client); } public static TestDemoApiInterface getTestDemoApiClient() { if (testDemoApiInterface == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setClient(getOkClient()) .setEndpoint(BASE_URL) .build(); testDemoApiInterface = restAdapter.create(TestDemoApiInterface.class); } return testDemoApiInterface; } public interface TestDemoApiInterface { @GET("/getdata")
// Path: app/src/main/java/com/knight/arch/data/AllPersonlInfos.java // public class AllPersonlInfos { // public List<PersonInfo> data; // // public List<PersonInfo> getData() { // return data; // } // // public void setData(List<PersonInfo> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/data/Pagination.java // public class Pagination<T extends Parcelable> { // // @Expose // private List<T> data; // // // public List<T> getData() { // return data; // } // // public void setData(List<T> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/model/PersonInfo.java // public class PersonInfo implements Parcelable { // // public static final Creator<PersonInfo> CREATOR = new Creator<PersonInfo>() { // @Override // public PersonInfo createFromParcel(Parcel in) { // return new PersonInfo(in); // } // // @Override // public PersonInfo[] newArray(int size) { // return new PersonInfo[size]; // } // }; // @SerializedName("rank") // private String Rank; // @SerializedName("gravatar") // private String Gravatar; // private String username; // private String name; // private String location; // private String language; // private String repos; // private String followers; // private String created; // // protected PersonInfo(Parcel in) { // Rank = in.readString(); // Gravatar = in.readString(); // username = in.readString(); // name = in.readString(); // location = in.readString(); // language = in.readString(); // repos = in.readString(); // followers = in.readString(); // created = in.readString(); // } // // public String getGravatar() { // return Gravatar; // } // // public void setGravatar(String gravatar) { // Gravatar = gravatar; // } // // public String getRank() { // return Rank; // } // // public void setRank(String rank) { // Rank = rank; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public String getRepos() { // return repos; // } // // public void setRepos(String repos) { // this.repos = repos; // } // // public String getFollowers() { // return followers; // } // // public void setFollowers(String followers) { // this.followers = followers; // } // // public String getCreated() { // return created; // } // // public void setCreated(String created) { // this.created = created; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(Rank); // dest.writeString(Gravatar); // dest.writeString(username); // dest.writeString(name); // dest.writeString(location); // dest.writeString(language); // dest.writeString(repos); // dest.writeString(followers); // dest.writeString(created); // } // } // Path: app/src/main/java/com/knight/arch/api/ApiClient.java import com.facebook.stetho.okhttp.StethoInterceptor; import com.knight.arch.data.AllPersonlInfos; import com.knight.arch.data.Pagination; import com.knight.arch.model.PersonInfo; import com.squareup.okhttp.OkHttpClient; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable; package com.knight.arch.api; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class ApiClient { static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s private static final String BASE_URL = "http://mock-api.com/TyTabSFqXNyqMpNw.mock"; private static TestDemoApiInterface testDemoApiInterface; /** * 用于Stethoscope调试的ttpClient */ public static OkClient getOkClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new StethoInterceptor()); return new OkClient(client); } public static TestDemoApiInterface getTestDemoApiClient() { if (testDemoApiInterface == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setClient(getOkClient()) .setEndpoint(BASE_URL) .build(); testDemoApiInterface = restAdapter.create(TestDemoApiInterface.class); } return testDemoApiInterface; } public interface TestDemoApiInterface { @GET("/getdata")
void getStreams(@Query("limit") int limit, @Query("offset") int offset, Callback<List<AllPersonlInfos>> callback);
andyiac/githot
app/src/main/java/com/knight/arch/api/ApiClient.java
// Path: app/src/main/java/com/knight/arch/data/AllPersonlInfos.java // public class AllPersonlInfos { // public List<PersonInfo> data; // // public List<PersonInfo> getData() { // return data; // } // // public void setData(List<PersonInfo> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/data/Pagination.java // public class Pagination<T extends Parcelable> { // // @Expose // private List<T> data; // // // public List<T> getData() { // return data; // } // // public void setData(List<T> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/model/PersonInfo.java // public class PersonInfo implements Parcelable { // // public static final Creator<PersonInfo> CREATOR = new Creator<PersonInfo>() { // @Override // public PersonInfo createFromParcel(Parcel in) { // return new PersonInfo(in); // } // // @Override // public PersonInfo[] newArray(int size) { // return new PersonInfo[size]; // } // }; // @SerializedName("rank") // private String Rank; // @SerializedName("gravatar") // private String Gravatar; // private String username; // private String name; // private String location; // private String language; // private String repos; // private String followers; // private String created; // // protected PersonInfo(Parcel in) { // Rank = in.readString(); // Gravatar = in.readString(); // username = in.readString(); // name = in.readString(); // location = in.readString(); // language = in.readString(); // repos = in.readString(); // followers = in.readString(); // created = in.readString(); // } // // public String getGravatar() { // return Gravatar; // } // // public void setGravatar(String gravatar) { // Gravatar = gravatar; // } // // public String getRank() { // return Rank; // } // // public void setRank(String rank) { // Rank = rank; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public String getRepos() { // return repos; // } // // public void setRepos(String repos) { // this.repos = repos; // } // // public String getFollowers() { // return followers; // } // // public void setFollowers(String followers) { // this.followers = followers; // } // // public String getCreated() { // return created; // } // // public void setCreated(String created) { // this.created = created; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(Rank); // dest.writeString(Gravatar); // dest.writeString(username); // dest.writeString(name); // dest.writeString(location); // dest.writeString(language); // dest.writeString(repos); // dest.writeString(followers); // dest.writeString(created); // } // }
import com.facebook.stetho.okhttp.StethoInterceptor; import com.knight.arch.data.AllPersonlInfos; import com.knight.arch.data.Pagination; import com.knight.arch.model.PersonInfo; import com.squareup.okhttp.OkHttpClient; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable;
package com.knight.arch.api; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class ApiClient { static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s private static final String BASE_URL = "http://mock-api.com/TyTabSFqXNyqMpNw.mock"; private static TestDemoApiInterface testDemoApiInterface; /** * 用于Stethoscope调试的ttpClient */ public static OkClient getOkClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new StethoInterceptor()); return new OkClient(client); } public static TestDemoApiInterface getTestDemoApiClient() { if (testDemoApiInterface == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setClient(getOkClient()) .setEndpoint(BASE_URL) .build(); testDemoApiInterface = restAdapter.create(TestDemoApiInterface.class); } return testDemoApiInterface; } public interface TestDemoApiInterface { @GET("/getdata") void getStreams(@Query("limit") int limit, @Query("offset") int offset, Callback<List<AllPersonlInfos>> callback); @GET("/getdata") void getData2(Callback<AllPersonlInfos> callback); @GET("/getdata")
// Path: app/src/main/java/com/knight/arch/data/AllPersonlInfos.java // public class AllPersonlInfos { // public List<PersonInfo> data; // // public List<PersonInfo> getData() { // return data; // } // // public void setData(List<PersonInfo> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/data/Pagination.java // public class Pagination<T extends Parcelable> { // // @Expose // private List<T> data; // // // public List<T> getData() { // return data; // } // // public void setData(List<T> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/model/PersonInfo.java // public class PersonInfo implements Parcelable { // // public static final Creator<PersonInfo> CREATOR = new Creator<PersonInfo>() { // @Override // public PersonInfo createFromParcel(Parcel in) { // return new PersonInfo(in); // } // // @Override // public PersonInfo[] newArray(int size) { // return new PersonInfo[size]; // } // }; // @SerializedName("rank") // private String Rank; // @SerializedName("gravatar") // private String Gravatar; // private String username; // private String name; // private String location; // private String language; // private String repos; // private String followers; // private String created; // // protected PersonInfo(Parcel in) { // Rank = in.readString(); // Gravatar = in.readString(); // username = in.readString(); // name = in.readString(); // location = in.readString(); // language = in.readString(); // repos = in.readString(); // followers = in.readString(); // created = in.readString(); // } // // public String getGravatar() { // return Gravatar; // } // // public void setGravatar(String gravatar) { // Gravatar = gravatar; // } // // public String getRank() { // return Rank; // } // // public void setRank(String rank) { // Rank = rank; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public String getRepos() { // return repos; // } // // public void setRepos(String repos) { // this.repos = repos; // } // // public String getFollowers() { // return followers; // } // // public void setFollowers(String followers) { // this.followers = followers; // } // // public String getCreated() { // return created; // } // // public void setCreated(String created) { // this.created = created; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(Rank); // dest.writeString(Gravatar); // dest.writeString(username); // dest.writeString(name); // dest.writeString(location); // dest.writeString(language); // dest.writeString(repos); // dest.writeString(followers); // dest.writeString(created); // } // } // Path: app/src/main/java/com/knight/arch/api/ApiClient.java import com.facebook.stetho.okhttp.StethoInterceptor; import com.knight.arch.data.AllPersonlInfos; import com.knight.arch.data.Pagination; import com.knight.arch.model.PersonInfo; import com.squareup.okhttp.OkHttpClient; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable; package com.knight.arch.api; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class ApiClient { static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s private static final String BASE_URL = "http://mock-api.com/TyTabSFqXNyqMpNw.mock"; private static TestDemoApiInterface testDemoApiInterface; /** * 用于Stethoscope调试的ttpClient */ public static OkClient getOkClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new StethoInterceptor()); return new OkClient(client); } public static TestDemoApiInterface getTestDemoApiClient() { if (testDemoApiInterface == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setClient(getOkClient()) .setEndpoint(BASE_URL) .build(); testDemoApiInterface = restAdapter.create(TestDemoApiInterface.class); } return testDemoApiInterface; } public interface TestDemoApiInterface { @GET("/getdata") void getStreams(@Query("limit") int limit, @Query("offset") int offset, Callback<List<AllPersonlInfos>> callback); @GET("/getdata") void getData2(Callback<AllPersonlInfos> callback); @GET("/getdata")
Observable<Pagination<PersonInfo>> getDataRxJava();
andyiac/githot
app/src/main/java/com/knight/arch/api/ApiClient.java
// Path: app/src/main/java/com/knight/arch/data/AllPersonlInfos.java // public class AllPersonlInfos { // public List<PersonInfo> data; // // public List<PersonInfo> getData() { // return data; // } // // public void setData(List<PersonInfo> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/data/Pagination.java // public class Pagination<T extends Parcelable> { // // @Expose // private List<T> data; // // // public List<T> getData() { // return data; // } // // public void setData(List<T> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/model/PersonInfo.java // public class PersonInfo implements Parcelable { // // public static final Creator<PersonInfo> CREATOR = new Creator<PersonInfo>() { // @Override // public PersonInfo createFromParcel(Parcel in) { // return new PersonInfo(in); // } // // @Override // public PersonInfo[] newArray(int size) { // return new PersonInfo[size]; // } // }; // @SerializedName("rank") // private String Rank; // @SerializedName("gravatar") // private String Gravatar; // private String username; // private String name; // private String location; // private String language; // private String repos; // private String followers; // private String created; // // protected PersonInfo(Parcel in) { // Rank = in.readString(); // Gravatar = in.readString(); // username = in.readString(); // name = in.readString(); // location = in.readString(); // language = in.readString(); // repos = in.readString(); // followers = in.readString(); // created = in.readString(); // } // // public String getGravatar() { // return Gravatar; // } // // public void setGravatar(String gravatar) { // Gravatar = gravatar; // } // // public String getRank() { // return Rank; // } // // public void setRank(String rank) { // Rank = rank; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public String getRepos() { // return repos; // } // // public void setRepos(String repos) { // this.repos = repos; // } // // public String getFollowers() { // return followers; // } // // public void setFollowers(String followers) { // this.followers = followers; // } // // public String getCreated() { // return created; // } // // public void setCreated(String created) { // this.created = created; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(Rank); // dest.writeString(Gravatar); // dest.writeString(username); // dest.writeString(name); // dest.writeString(location); // dest.writeString(language); // dest.writeString(repos); // dest.writeString(followers); // dest.writeString(created); // } // }
import com.facebook.stetho.okhttp.StethoInterceptor; import com.knight.arch.data.AllPersonlInfos; import com.knight.arch.data.Pagination; import com.knight.arch.model.PersonInfo; import com.squareup.okhttp.OkHttpClient; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable;
package com.knight.arch.api; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class ApiClient { static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s private static final String BASE_URL = "http://mock-api.com/TyTabSFqXNyqMpNw.mock"; private static TestDemoApiInterface testDemoApiInterface; /** * 用于Stethoscope调试的ttpClient */ public static OkClient getOkClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new StethoInterceptor()); return new OkClient(client); } public static TestDemoApiInterface getTestDemoApiClient() { if (testDemoApiInterface == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setClient(getOkClient()) .setEndpoint(BASE_URL) .build(); testDemoApiInterface = restAdapter.create(TestDemoApiInterface.class); } return testDemoApiInterface; } public interface TestDemoApiInterface { @GET("/getdata") void getStreams(@Query("limit") int limit, @Query("offset") int offset, Callback<List<AllPersonlInfos>> callback); @GET("/getdata") void getData2(Callback<AllPersonlInfos> callback); @GET("/getdata")
// Path: app/src/main/java/com/knight/arch/data/AllPersonlInfos.java // public class AllPersonlInfos { // public List<PersonInfo> data; // // public List<PersonInfo> getData() { // return data; // } // // public void setData(List<PersonInfo> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/data/Pagination.java // public class Pagination<T extends Parcelable> { // // @Expose // private List<T> data; // // // public List<T> getData() { // return data; // } // // public void setData(List<T> data) { // this.data = data; // } // } // // Path: app/src/main/java/com/knight/arch/model/PersonInfo.java // public class PersonInfo implements Parcelable { // // public static final Creator<PersonInfo> CREATOR = new Creator<PersonInfo>() { // @Override // public PersonInfo createFromParcel(Parcel in) { // return new PersonInfo(in); // } // // @Override // public PersonInfo[] newArray(int size) { // return new PersonInfo[size]; // } // }; // @SerializedName("rank") // private String Rank; // @SerializedName("gravatar") // private String Gravatar; // private String username; // private String name; // private String location; // private String language; // private String repos; // private String followers; // private String created; // // protected PersonInfo(Parcel in) { // Rank = in.readString(); // Gravatar = in.readString(); // username = in.readString(); // name = in.readString(); // location = in.readString(); // language = in.readString(); // repos = in.readString(); // followers = in.readString(); // created = in.readString(); // } // // public String getGravatar() { // return Gravatar; // } // // public void setGravatar(String gravatar) { // Gravatar = gravatar; // } // // public String getRank() { // return Rank; // } // // public void setRank(String rank) { // Rank = rank; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public String getRepos() { // return repos; // } // // public void setRepos(String repos) { // this.repos = repos; // } // // public String getFollowers() { // return followers; // } // // public void setFollowers(String followers) { // this.followers = followers; // } // // public String getCreated() { // return created; // } // // public void setCreated(String created) { // this.created = created; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(Rank); // dest.writeString(Gravatar); // dest.writeString(username); // dest.writeString(name); // dest.writeString(location); // dest.writeString(language); // dest.writeString(repos); // dest.writeString(followers); // dest.writeString(created); // } // } // Path: app/src/main/java/com/knight/arch/api/ApiClient.java import com.facebook.stetho.okhttp.StethoInterceptor; import com.knight.arch.data.AllPersonlInfos; import com.knight.arch.data.Pagination; import com.knight.arch.model.PersonInfo; import com.squareup.okhttp.OkHttpClient; import java.util.List; import java.util.concurrent.TimeUnit; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable; package com.knight.arch.api; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class ApiClient { static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s private static final String BASE_URL = "http://mock-api.com/TyTabSFqXNyqMpNw.mock"; private static TestDemoApiInterface testDemoApiInterface; /** * 用于Stethoscope调试的ttpClient */ public static OkClient getOkClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new StethoInterceptor()); return new OkClient(client); } public static TestDemoApiInterface getTestDemoApiClient() { if (testDemoApiInterface == null) { RestAdapter restAdapter = new RestAdapter.Builder() .setClient(getOkClient()) .setEndpoint(BASE_URL) .build(); testDemoApiInterface = restAdapter.create(TestDemoApiInterface.class); } return testDemoApiInterface; } public interface TestDemoApiInterface { @GET("/getdata") void getStreams(@Query("limit") int limit, @Query("offset") int offset, Callback<List<AllPersonlInfos>> callback); @GET("/getdata") void getData2(Callback<AllPersonlInfos> callback); @GET("/getdata")
Observable<Pagination<PersonInfo>> getDataRxJava();
andyiac/githot
app/src/main/java/com/knight/arch/ui/base/InjectableActivity.java
// Path: app/src/main/java/com/knight/arch/ClientApplication.java // public class ClientApplication extends Application implements Injector { // private static final String LOGGER_TAG = "<<=TAG=>>"; // // private AccessTokenResponse accessTokenResponse; // // private ObjectGraph objectGraph; // // public void onCreate() { // super.onCreate(); // initStetho(); // initLogger(); // initDagger(); // initUmeng(); // } // // private void initUmeng() { // MobclickAgent.openActivityDurationTrack(false); // } // // // private void initDagger() { // objectGraph = ObjectGraph.create(getModules().toArray()); // objectGraph.inject(this); // } // // private void initLogger() { // Logger.init(LOGGER_TAG) // default PRETTYLOGGER or use just init() // .setMethodCount(4) // default 2 // .setLogLevel(LogLevel.FULL) // default LogLevel.FULL // .setMethodOffset(2); // default 0 // //.hideThreadInfo() // default shown // } // // private void initStetho() { // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)) // .build()); // } // // public List<Object> getModules() { // return Arrays.<Object>asList(new AppModule(this)); // } // // @Override // public void inject(Object target) { // this.objectGraph.inject(target); // } // // @Override // public ObjectGraph plus(Object[] modules) { // return objectGraph.plus(modules); // } // // public ObjectGraph plus(Injector injector) { // return this.objectGraph.plus(injector.getModules().toArray()); // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.os.Bundle; import com.knight.arch.ClientApplication; import com.knight.arch.module.Injector; import dagger.ObjectGraph;
package com.knight.arch.ui.base; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public abstract class InjectableActivity extends BaseActivity implements Injector { protected ObjectGraph objectGraph; @Override protected void onCreate(Bundle savedInstanceState) {
// Path: app/src/main/java/com/knight/arch/ClientApplication.java // public class ClientApplication extends Application implements Injector { // private static final String LOGGER_TAG = "<<=TAG=>>"; // // private AccessTokenResponse accessTokenResponse; // // private ObjectGraph objectGraph; // // public void onCreate() { // super.onCreate(); // initStetho(); // initLogger(); // initDagger(); // initUmeng(); // } // // private void initUmeng() { // MobclickAgent.openActivityDurationTrack(false); // } // // // private void initDagger() { // objectGraph = ObjectGraph.create(getModules().toArray()); // objectGraph.inject(this); // } // // private void initLogger() { // Logger.init(LOGGER_TAG) // default PRETTYLOGGER or use just init() // .setMethodCount(4) // default 2 // .setLogLevel(LogLevel.FULL) // default LogLevel.FULL // .setMethodOffset(2); // default 0 // //.hideThreadInfo() // default shown // } // // private void initStetho() { // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)) // .build()); // } // // public List<Object> getModules() { // return Arrays.<Object>asList(new AppModule(this)); // } // // @Override // public void inject(Object target) { // this.objectGraph.inject(target); // } // // @Override // public ObjectGraph plus(Object[] modules) { // return objectGraph.plus(modules); // } // // public ObjectGraph plus(Injector injector) { // return this.objectGraph.plus(injector.getModules().toArray()); // } // } // // Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ui/base/InjectableActivity.java import android.os.Bundle; import com.knight.arch.ClientApplication; import com.knight.arch.module.Injector; import dagger.ObjectGraph; package com.knight.arch.ui.base; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public abstract class InjectableActivity extends BaseActivity implements Injector { protected ObjectGraph objectGraph; @Override protected void onCreate(Bundle savedInstanceState) {
ClientApplication app = (ClientApplication) getApplication();
andyiac/githot
app/src/main/java/com/knight/arch/module/SettingsModule.java
// Path: app/src/main/java/com/knight/arch/ui/SettingsActivity.java // public class SettingsActivity extends InjectableActivity { // // @Override // public List<Object> getModules() { // return Arrays.<Object>asList(new SettingsModule()); // } // // @Override // protected int provideContentViewId() { // return R.layout.activity_setting; // } // // public void onResume() { // super.onResume(); // MobclickAgent.onResume(this); // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPause(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // // super.onCreate(savedInstanceState); // initView(); // // setStatusColor(android.R.color.transparent); // } // // private void initView() { // Toolbar mToolbar = (Toolbar) findViewById(R.id.hot_repos_toolbar); // setSupportActionBar(mToolbar); // // final ActionBar ab = getSupportActionBar(); // if (ab != null) { // ab.setHomeAsUpIndicator(R.mipmap.ic_back_arrow); // ab.setDisplayHomeAsUpEnabled(true); // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // if (item.getItemId() == android.R.id.home) { // KeyBoardTools.actionKey(KeyEvent.KEYCODE_BACK); // return true; // } // return super.onOptionsItemSelected(item); // } // // } // // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment { // // private boolean injected = false; // // // @Inject // FirService firService; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getActivity(); // addPreferencesFromResource(R.xml.preference); // // findPreference(getString(R.string.pref_build_time)) // .setSummary(BuildConfig.BUILD_TIME); // // findPreference(getString(R.string.open_source_licence)) // .setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // new LicensesDialog.Builder(getActivity()) // .setNotices(R.raw.notices) // .setIncludeOwnLicense(true) // .setThemeResourceId(R.style.custom_theme) // .build() // .show(); // return false; // } // }); // // Preference checkVersionPref = findPreference(getString(R.string.pref_check_version)); // // checkVersionPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // checkVersion(); // return true; // } // }); // // checkVersionPref.setSummary(getString(R.string.s_check_version, BuildConfig.VERSION_NAME)); // // } // // public void onResume() { // super.onResume(); // MobclickAgent.onPageStart("SettingsFragment"); //统计页面 // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPageEnd("SettingsFragment"); // } // // private void checkVersion() { // final ProgressDialog dialog = new ProgressDialog(getActivity()); // dialog.setMessage(getString(R.string.msg_checking_version)); // dialog.show(); // AppObservable.bindFragment(this, firService.checkVersion(BuildConfig.FIR_APPLICATION_ID, BuildConfig.FIR_API_TOKEN)) // .subscribe(new Subscriber<FirVersion>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // // @Override // public void onNext(FirVersion firVersion) { // if (firVersion.getVersion() > BuildConfig.VERSION_CODE) { // dialog.dismiss(); // showNewVersionFoundDialog(firVersion); // } else { // Toast.makeText(getActivity(), R.string.msg_this_is_latest_version, Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // } // }); // } // // private void showNewVersionFoundDialog(final FirVersion newFirVersion) { // new AlertDialog.Builder(getActivity()) // .setTitle(R.string.title_new_version_found) // .setMessage(getString(R.string.msg_new_version_found, newFirVersion.getVersionShort(), newFirVersion.getVersion(), newFirVersion.getChangeLog())) // .setPositiveButton(R.string.btn_dialog_update, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Intent downloadPageIntent = new Intent(Intent.ACTION_VIEW); // downloadPageIntent.setData(Uri.parse(newFirVersion.getUpdateUrl())); // getActivity().startActivity(downloadPageIntent); // } // }) // .setNegativeButton(android.R.string.cancel, null) // .create() // .show(); // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (!injected) { // injected = true; // Injector injector = (Injector) getActivity(); // injector.inject(this); // } // } // }
import com.knight.arch.ui.SettingsActivity; import com.knight.arch.ui.fragment.SettingsFragment; import dagger.Module;
package com.knight.arch.module; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ @Module( complete = false, overrides = true, injects = {
// Path: app/src/main/java/com/knight/arch/ui/SettingsActivity.java // public class SettingsActivity extends InjectableActivity { // // @Override // public List<Object> getModules() { // return Arrays.<Object>asList(new SettingsModule()); // } // // @Override // protected int provideContentViewId() { // return R.layout.activity_setting; // } // // public void onResume() { // super.onResume(); // MobclickAgent.onResume(this); // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPause(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // // super.onCreate(savedInstanceState); // initView(); // // setStatusColor(android.R.color.transparent); // } // // private void initView() { // Toolbar mToolbar = (Toolbar) findViewById(R.id.hot_repos_toolbar); // setSupportActionBar(mToolbar); // // final ActionBar ab = getSupportActionBar(); // if (ab != null) { // ab.setHomeAsUpIndicator(R.mipmap.ic_back_arrow); // ab.setDisplayHomeAsUpEnabled(true); // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // if (item.getItemId() == android.R.id.home) { // KeyBoardTools.actionKey(KeyEvent.KEYCODE_BACK); // return true; // } // return super.onOptionsItemSelected(item); // } // // } // // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment { // // private boolean injected = false; // // // @Inject // FirService firService; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getActivity(); // addPreferencesFromResource(R.xml.preference); // // findPreference(getString(R.string.pref_build_time)) // .setSummary(BuildConfig.BUILD_TIME); // // findPreference(getString(R.string.open_source_licence)) // .setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // new LicensesDialog.Builder(getActivity()) // .setNotices(R.raw.notices) // .setIncludeOwnLicense(true) // .setThemeResourceId(R.style.custom_theme) // .build() // .show(); // return false; // } // }); // // Preference checkVersionPref = findPreference(getString(R.string.pref_check_version)); // // checkVersionPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // checkVersion(); // return true; // } // }); // // checkVersionPref.setSummary(getString(R.string.s_check_version, BuildConfig.VERSION_NAME)); // // } // // public void onResume() { // super.onResume(); // MobclickAgent.onPageStart("SettingsFragment"); //统计页面 // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPageEnd("SettingsFragment"); // } // // private void checkVersion() { // final ProgressDialog dialog = new ProgressDialog(getActivity()); // dialog.setMessage(getString(R.string.msg_checking_version)); // dialog.show(); // AppObservable.bindFragment(this, firService.checkVersion(BuildConfig.FIR_APPLICATION_ID, BuildConfig.FIR_API_TOKEN)) // .subscribe(new Subscriber<FirVersion>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // // @Override // public void onNext(FirVersion firVersion) { // if (firVersion.getVersion() > BuildConfig.VERSION_CODE) { // dialog.dismiss(); // showNewVersionFoundDialog(firVersion); // } else { // Toast.makeText(getActivity(), R.string.msg_this_is_latest_version, Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // } // }); // } // // private void showNewVersionFoundDialog(final FirVersion newFirVersion) { // new AlertDialog.Builder(getActivity()) // .setTitle(R.string.title_new_version_found) // .setMessage(getString(R.string.msg_new_version_found, newFirVersion.getVersionShort(), newFirVersion.getVersion(), newFirVersion.getChangeLog())) // .setPositiveButton(R.string.btn_dialog_update, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Intent downloadPageIntent = new Intent(Intent.ACTION_VIEW); // downloadPageIntent.setData(Uri.parse(newFirVersion.getUpdateUrl())); // getActivity().startActivity(downloadPageIntent); // } // }) // .setNegativeButton(android.R.string.cancel, null) // .create() // .show(); // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (!injected) { // injected = true; // Injector injector = (Injector) getActivity(); // injector.inject(this); // } // } // } // Path: app/src/main/java/com/knight/arch/module/SettingsModule.java import com.knight.arch.ui.SettingsActivity; import com.knight.arch.ui.fragment.SettingsFragment; import dagger.Module; package com.knight.arch.module; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ @Module( complete = false, overrides = true, injects = {
SettingsActivity.class,
andyiac/githot
app/src/main/java/com/knight/arch/module/SettingsModule.java
// Path: app/src/main/java/com/knight/arch/ui/SettingsActivity.java // public class SettingsActivity extends InjectableActivity { // // @Override // public List<Object> getModules() { // return Arrays.<Object>asList(new SettingsModule()); // } // // @Override // protected int provideContentViewId() { // return R.layout.activity_setting; // } // // public void onResume() { // super.onResume(); // MobclickAgent.onResume(this); // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPause(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // // super.onCreate(savedInstanceState); // initView(); // // setStatusColor(android.R.color.transparent); // } // // private void initView() { // Toolbar mToolbar = (Toolbar) findViewById(R.id.hot_repos_toolbar); // setSupportActionBar(mToolbar); // // final ActionBar ab = getSupportActionBar(); // if (ab != null) { // ab.setHomeAsUpIndicator(R.mipmap.ic_back_arrow); // ab.setDisplayHomeAsUpEnabled(true); // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // if (item.getItemId() == android.R.id.home) { // KeyBoardTools.actionKey(KeyEvent.KEYCODE_BACK); // return true; // } // return super.onOptionsItemSelected(item); // } // // } // // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment { // // private boolean injected = false; // // // @Inject // FirService firService; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getActivity(); // addPreferencesFromResource(R.xml.preference); // // findPreference(getString(R.string.pref_build_time)) // .setSummary(BuildConfig.BUILD_TIME); // // findPreference(getString(R.string.open_source_licence)) // .setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // new LicensesDialog.Builder(getActivity()) // .setNotices(R.raw.notices) // .setIncludeOwnLicense(true) // .setThemeResourceId(R.style.custom_theme) // .build() // .show(); // return false; // } // }); // // Preference checkVersionPref = findPreference(getString(R.string.pref_check_version)); // // checkVersionPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // checkVersion(); // return true; // } // }); // // checkVersionPref.setSummary(getString(R.string.s_check_version, BuildConfig.VERSION_NAME)); // // } // // public void onResume() { // super.onResume(); // MobclickAgent.onPageStart("SettingsFragment"); //统计页面 // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPageEnd("SettingsFragment"); // } // // private void checkVersion() { // final ProgressDialog dialog = new ProgressDialog(getActivity()); // dialog.setMessage(getString(R.string.msg_checking_version)); // dialog.show(); // AppObservable.bindFragment(this, firService.checkVersion(BuildConfig.FIR_APPLICATION_ID, BuildConfig.FIR_API_TOKEN)) // .subscribe(new Subscriber<FirVersion>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // // @Override // public void onNext(FirVersion firVersion) { // if (firVersion.getVersion() > BuildConfig.VERSION_CODE) { // dialog.dismiss(); // showNewVersionFoundDialog(firVersion); // } else { // Toast.makeText(getActivity(), R.string.msg_this_is_latest_version, Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // } // }); // } // // private void showNewVersionFoundDialog(final FirVersion newFirVersion) { // new AlertDialog.Builder(getActivity()) // .setTitle(R.string.title_new_version_found) // .setMessage(getString(R.string.msg_new_version_found, newFirVersion.getVersionShort(), newFirVersion.getVersion(), newFirVersion.getChangeLog())) // .setPositiveButton(R.string.btn_dialog_update, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Intent downloadPageIntent = new Intent(Intent.ACTION_VIEW); // downloadPageIntent.setData(Uri.parse(newFirVersion.getUpdateUrl())); // getActivity().startActivity(downloadPageIntent); // } // }) // .setNegativeButton(android.R.string.cancel, null) // .create() // .show(); // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (!injected) { // injected = true; // Injector injector = (Injector) getActivity(); // injector.inject(this); // } // } // }
import com.knight.arch.ui.SettingsActivity; import com.knight.arch.ui.fragment.SettingsFragment; import dagger.Module;
package com.knight.arch.module; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ @Module( complete = false, overrides = true, injects = { SettingsActivity.class,
// Path: app/src/main/java/com/knight/arch/ui/SettingsActivity.java // public class SettingsActivity extends InjectableActivity { // // @Override // public List<Object> getModules() { // return Arrays.<Object>asList(new SettingsModule()); // } // // @Override // protected int provideContentViewId() { // return R.layout.activity_setting; // } // // public void onResume() { // super.onResume(); // MobclickAgent.onResume(this); // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPause(this); // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // // super.onCreate(savedInstanceState); // initView(); // // setStatusColor(android.R.color.transparent); // } // // private void initView() { // Toolbar mToolbar = (Toolbar) findViewById(R.id.hot_repos_toolbar); // setSupportActionBar(mToolbar); // // final ActionBar ab = getSupportActionBar(); // if (ab != null) { // ab.setHomeAsUpIndicator(R.mipmap.ic_back_arrow); // ab.setDisplayHomeAsUpEnabled(true); // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // if (item.getItemId() == android.R.id.home) { // KeyBoardTools.actionKey(KeyEvent.KEYCODE_BACK); // return true; // } // return super.onOptionsItemSelected(item); // } // // } // // Path: app/src/main/java/com/knight/arch/ui/fragment/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment { // // private boolean injected = false; // // // @Inject // FirService firService; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getActivity(); // addPreferencesFromResource(R.xml.preference); // // findPreference(getString(R.string.pref_build_time)) // .setSummary(BuildConfig.BUILD_TIME); // // findPreference(getString(R.string.open_source_licence)) // .setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // new LicensesDialog.Builder(getActivity()) // .setNotices(R.raw.notices) // .setIncludeOwnLicense(true) // .setThemeResourceId(R.style.custom_theme) // .build() // .show(); // return false; // } // }); // // Preference checkVersionPref = findPreference(getString(R.string.pref_check_version)); // // checkVersionPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // checkVersion(); // return true; // } // }); // // checkVersionPref.setSummary(getString(R.string.s_check_version, BuildConfig.VERSION_NAME)); // // } // // public void onResume() { // super.onResume(); // MobclickAgent.onPageStart("SettingsFragment"); //统计页面 // } // // public void onPause() { // super.onPause(); // MobclickAgent.onPageEnd("SettingsFragment"); // } // // private void checkVersion() { // final ProgressDialog dialog = new ProgressDialog(getActivity()); // dialog.setMessage(getString(R.string.msg_checking_version)); // dialog.show(); // AppObservable.bindFragment(this, firService.checkVersion(BuildConfig.FIR_APPLICATION_ID, BuildConfig.FIR_API_TOKEN)) // .subscribe(new Subscriber<FirVersion>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // // @Override // public void onNext(FirVersion firVersion) { // if (firVersion.getVersion() > BuildConfig.VERSION_CODE) { // dialog.dismiss(); // showNewVersionFoundDialog(firVersion); // } else { // Toast.makeText(getActivity(), R.string.msg_this_is_latest_version, Toast.LENGTH_SHORT).show(); // dialog.dismiss(); // } // } // }); // } // // private void showNewVersionFoundDialog(final FirVersion newFirVersion) { // new AlertDialog.Builder(getActivity()) // .setTitle(R.string.title_new_version_found) // .setMessage(getString(R.string.msg_new_version_found, newFirVersion.getVersionShort(), newFirVersion.getVersion(), newFirVersion.getChangeLog())) // .setPositiveButton(R.string.btn_dialog_update, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Intent downloadPageIntent = new Intent(Intent.ACTION_VIEW); // downloadPageIntent.setData(Uri.parse(newFirVersion.getUpdateUrl())); // getActivity().startActivity(downloadPageIntent); // } // }) // .setNegativeButton(android.R.string.cancel, null) // .create() // .show(); // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (!injected) { // injected = true; // Injector injector = (Injector) getActivity(); // injector.inject(this); // } // } // } // Path: app/src/main/java/com/knight/arch/module/SettingsModule.java import com.knight.arch.ui.SettingsActivity; import com.knight.arch.ui.fragment.SettingsFragment; import dagger.Module; package com.knight.arch.module; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ @Module( complete = false, overrides = true, injects = { SettingsActivity.class,
SettingsFragment.class
andyiac/githot
app/src/main/java/com/knight/arch/ui/base/InjectableFragment.java
// Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // }
import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.knight.arch.module.Injector;
package com.knight.arch.ui.base; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class InjectableFragment extends BaseFragment { boolean injected = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!injected) { injected = true;
// Path: app/src/main/java/com/knight/arch/module/Injector.java // public abstract interface Injector { // public abstract List<Object> getModules(); // // public abstract void inject(Object target); // // public abstract ObjectGraph plus(Object[] modules); // } // Path: app/src/main/java/com/knight/arch/ui/base/InjectableFragment.java import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.knight.arch.module.Injector; package com.knight.arch.ui.base; /** * @author andyiac * @date 15-9-16 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class InjectableFragment extends BaseFragment { boolean injected = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!injected) { injected = true;
Injector injector = (Injector) getActivity();
bbyars/httpmock
clients/java/test/org/httpmock/matchers/WasCalledTest.java
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // // Path: clients/java/src/org/httpmock/StubServer.java // public class StubServer { // private final HttpMock httpMock; // final String serverURL; // final String requestsURL; // final String stubURL; // // StubServer(HttpMock httpMock, String serverURL, String requestsURL, String stubURL) { // this.httpMock = httpMock; // this.serverURL = serverURL; // this.requestsURL = requestsURL; // this.stubURL = stubURL; // } // // public List<StubRequest> getRequests() { // HttpResponse response = httpMock.get(requestsURL); // response.assertStatusIs(200); // return collectRequests(response.getBodyAsJSONArray()); // } // // public Stubber on(String method, String url) { // Stubber stubber = new Stubber(httpMock, stubURL, url); // stubber.setRequestMethod(method); // return stubber; // } // // public void close() { // HttpResponse response = httpMock.delete(serverURL); // response.assertStatusIs(204); // } // // private List<StubRequest> collectRequests(JSONArray requests) { // List<StubRequest> result = new ArrayList<StubRequest>(); // for (Object request : requests) { // result.add(new StubRequest((JSONObject)request)); // } // return result; // } // } // // Path: clients/java/test/org/httpmock/matchers/TestStubRequest.java // public static TestStubRequest request(String requestMethod, String path) { // return new TestStubRequest(requestMethod, path); // }
import org.hamcrest.StringDescription; import org.httpmock.StubRequest; import org.httpmock.StubServer; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.*; import static org.httpmock.matchers.TestStubRequest.request; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.httpmock.matchers; public class WasCalledTest { private final StubServer stub = mock(StubServer.class); @Test public void shouldNotMatchIfNoRequests() {
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // // Path: clients/java/src/org/httpmock/StubServer.java // public class StubServer { // private final HttpMock httpMock; // final String serverURL; // final String requestsURL; // final String stubURL; // // StubServer(HttpMock httpMock, String serverURL, String requestsURL, String stubURL) { // this.httpMock = httpMock; // this.serverURL = serverURL; // this.requestsURL = requestsURL; // this.stubURL = stubURL; // } // // public List<StubRequest> getRequests() { // HttpResponse response = httpMock.get(requestsURL); // response.assertStatusIs(200); // return collectRequests(response.getBodyAsJSONArray()); // } // // public Stubber on(String method, String url) { // Stubber stubber = new Stubber(httpMock, stubURL, url); // stubber.setRequestMethod(method); // return stubber; // } // // public void close() { // HttpResponse response = httpMock.delete(serverURL); // response.assertStatusIs(204); // } // // private List<StubRequest> collectRequests(JSONArray requests) { // List<StubRequest> result = new ArrayList<StubRequest>(); // for (Object request : requests) { // result.add(new StubRequest((JSONObject)request)); // } // return result; // } // } // // Path: clients/java/test/org/httpmock/matchers/TestStubRequest.java // public static TestStubRequest request(String requestMethod, String path) { // return new TestStubRequest(requestMethod, path); // } // Path: clients/java/test/org/httpmock/matchers/WasCalledTest.java import org.hamcrest.StringDescription; import org.httpmock.StubRequest; import org.httpmock.StubServer; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.*; import static org.httpmock.matchers.TestStubRequest.request; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.httpmock.matchers; public class WasCalledTest { private final StubServer stub = mock(StubServer.class); @Test public void shouldNotMatchIfNoRequests() {
when(stub.getRequests()).thenReturn(new ArrayList<StubRequest>());
bbyars/httpmock
clients/java/test/org/httpmock/matchers/WasCalledTest.java
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // // Path: clients/java/src/org/httpmock/StubServer.java // public class StubServer { // private final HttpMock httpMock; // final String serverURL; // final String requestsURL; // final String stubURL; // // StubServer(HttpMock httpMock, String serverURL, String requestsURL, String stubURL) { // this.httpMock = httpMock; // this.serverURL = serverURL; // this.requestsURL = requestsURL; // this.stubURL = stubURL; // } // // public List<StubRequest> getRequests() { // HttpResponse response = httpMock.get(requestsURL); // response.assertStatusIs(200); // return collectRequests(response.getBodyAsJSONArray()); // } // // public Stubber on(String method, String url) { // Stubber stubber = new Stubber(httpMock, stubURL, url); // stubber.setRequestMethod(method); // return stubber; // } // // public void close() { // HttpResponse response = httpMock.delete(serverURL); // response.assertStatusIs(204); // } // // private List<StubRequest> collectRequests(JSONArray requests) { // List<StubRequest> result = new ArrayList<StubRequest>(); // for (Object request : requests) { // result.add(new StubRequest((JSONObject)request)); // } // return result; // } // } // // Path: clients/java/test/org/httpmock/matchers/TestStubRequest.java // public static TestStubRequest request(String requestMethod, String path) { // return new TestStubRequest(requestMethod, path); // }
import org.hamcrest.StringDescription; import org.httpmock.StubRequest; import org.httpmock.StubServer; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.*; import static org.httpmock.matchers.TestStubRequest.request; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package org.httpmock.matchers; public class WasCalledTest { private final StubServer stub = mock(StubServer.class); @Test public void shouldNotMatchIfNoRequests() { when(stub.getRequests()).thenReturn(new ArrayList<StubRequest>()); WasCalled matcher = new WasCalled("GET", "/"); assertFalse(matcher.matchesSafely(stub)); } @Test public void shouldMatchWithMatchingRequest() {
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // // Path: clients/java/src/org/httpmock/StubServer.java // public class StubServer { // private final HttpMock httpMock; // final String serverURL; // final String requestsURL; // final String stubURL; // // StubServer(HttpMock httpMock, String serverURL, String requestsURL, String stubURL) { // this.httpMock = httpMock; // this.serverURL = serverURL; // this.requestsURL = requestsURL; // this.stubURL = stubURL; // } // // public List<StubRequest> getRequests() { // HttpResponse response = httpMock.get(requestsURL); // response.assertStatusIs(200); // return collectRequests(response.getBodyAsJSONArray()); // } // // public Stubber on(String method, String url) { // Stubber stubber = new Stubber(httpMock, stubURL, url); // stubber.setRequestMethod(method); // return stubber; // } // // public void close() { // HttpResponse response = httpMock.delete(serverURL); // response.assertStatusIs(204); // } // // private List<StubRequest> collectRequests(JSONArray requests) { // List<StubRequest> result = new ArrayList<StubRequest>(); // for (Object request : requests) { // result.add(new StubRequest((JSONObject)request)); // } // return result; // } // } // // Path: clients/java/test/org/httpmock/matchers/TestStubRequest.java // public static TestStubRequest request(String requestMethod, String path) { // return new TestStubRequest(requestMethod, path); // } // Path: clients/java/test/org/httpmock/matchers/WasCalledTest.java import org.hamcrest.StringDescription; import org.httpmock.StubRequest; import org.httpmock.StubServer; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.*; import static org.httpmock.matchers.TestStubRequest.request; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package org.httpmock.matchers; public class WasCalledTest { private final StubServer stub = mock(StubServer.class); @Test public void shouldNotMatchIfNoRequests() { when(stub.getRequests()).thenReturn(new ArrayList<StubRequest>()); WasCalled matcher = new WasCalled("GET", "/"); assertFalse(matcher.matchesSafely(stub)); } @Test public void shouldMatchWithMatchingRequest() {
when(stub.getRequests()).thenReturn(listOf(request("GET", "/test")));
bbyars/httpmock
clients/java/src/org/httpmock/matchers/Expectation.java
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // }
import org.httpmock.StubRequest; import java.util.HashMap; import java.util.Map;
package org.httpmock.matchers; public class Expectation { private final String requestMethod; private final String path; private final Map<String, String> expectedHeaders = new HashMap<String, String>(); private String body; private String bodySubstring; public Expectation(String requestMethod, String path) { this.requestMethod = requestMethod; this.path = path; } public void addHeader(String key, String value) { expectedHeaders.put(key, value); } public void matchBody(String body) { this.body = body; } public void matchBodySubstring(String text) { bodySubstring = text; } public String getRequestMethod() { return requestMethod; } public String getPath() { return path; } public Map<String, String> getHeaders() { return expectedHeaders; }
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // Path: clients/java/src/org/httpmock/matchers/Expectation.java import org.httpmock.StubRequest; import java.util.HashMap; import java.util.Map; package org.httpmock.matchers; public class Expectation { private final String requestMethod; private final String path; private final Map<String, String> expectedHeaders = new HashMap<String, String>(); private String body; private String bodySubstring; public Expectation(String requestMethod, String path) { this.requestMethod = requestMethod; this.path = path; } public void addHeader(String key, String value) { expectedHeaders.put(key, value); } public void matchBody(String body) { this.body = body; } public void matchBodySubstring(String text) { bodySubstring = text; } public String getRequestMethod() { return requestMethod; } public String getPath() { return path; } public Map<String, String> getHeaders() { return expectedHeaders; }
public boolean matches(StubRequest request) {
bbyars/httpmock
clients/java/test/org/httpmock/matchers/ExpectationTest.java
// Path: clients/java/test/org/httpmock/matchers/TestStubRequest.java // public static TestStubRequest request(String requestMethod, String path) { // return new TestStubRequest(requestMethod, path); // }
import org.junit.Test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.httpmock.matchers.TestStubRequest.request;
package org.httpmock.matchers; public class ExpectationTest { @Test public void shouldMatchWithMatchingRequest() { Expectation expectation = new Expectation("GET", "/test");
// Path: clients/java/test/org/httpmock/matchers/TestStubRequest.java // public static TestStubRequest request(String requestMethod, String path) { // return new TestStubRequest(requestMethod, path); // } // Path: clients/java/test/org/httpmock/matchers/ExpectationTest.java import org.junit.Test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.httpmock.matchers.TestStubRequest.request; package org.httpmock.matchers; public class ExpectationTest { @Test public void shouldMatchWithMatchingRequest() { Expectation expectation = new Expectation("GET", "/test");
assertTrue(expectation.matches(request("GET", "/test")));
bbyars/httpmock
clients/java/src/org/httpmock/matchers/WasCalled.java
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // // Path: clients/java/src/org/httpmock/StubServer.java // public class StubServer { // private final HttpMock httpMock; // final String serverURL; // final String requestsURL; // final String stubURL; // // StubServer(HttpMock httpMock, String serverURL, String requestsURL, String stubURL) { // this.httpMock = httpMock; // this.serverURL = serverURL; // this.requestsURL = requestsURL; // this.stubURL = stubURL; // } // // public List<StubRequest> getRequests() { // HttpResponse response = httpMock.get(requestsURL); // response.assertStatusIs(200); // return collectRequests(response.getBodyAsJSONArray()); // } // // public Stubber on(String method, String url) { // Stubber stubber = new Stubber(httpMock, stubURL, url); // stubber.setRequestMethod(method); // return stubber; // } // // public void close() { // HttpResponse response = httpMock.delete(serverURL); // response.assertStatusIs(204); // } // // private List<StubRequest> collectRequests(JSONArray requests) { // List<StubRequest> result = new ArrayList<StubRequest>(); // for (Object request : requests) { // result.add(new StubRequest((JSONObject)request)); // } // return result; // } // }
import org.hamcrest.Description; import org.httpmock.StubRequest; import org.httpmock.StubServer; import org.junit.internal.matchers.TypeSafeMatcher; import java.util.List; import java.util.Map;
package org.httpmock.matchers; public class WasCalled extends TypeSafeMatcher<StubServer> { private final Expectation expectation;
// Path: clients/java/src/org/httpmock/StubRequest.java // public class StubRequest { // private final JSONObject data; // // public StubRequest(JSONObject data) { // this.data = data; // } // // public String getRequestMethod() { // return data.getString("method"); // } // // public String getPath() { // return data.getString("path"); // } // // public Map<String, String> getHeaders() { // Map<String, String> result = new HashMap<String, String>(); // JSONObject headers = data.getJSONObject("headers"); // Iterator iterator = headers.keys(); // while (iterator.hasNext()) { // String header = (String) iterator.next(); // result.put(header, headers.getString(header)); // } // return result; // } // // public String getBody() { // return data.getString("body"); // } // } // // Path: clients/java/src/org/httpmock/StubServer.java // public class StubServer { // private final HttpMock httpMock; // final String serverURL; // final String requestsURL; // final String stubURL; // // StubServer(HttpMock httpMock, String serverURL, String requestsURL, String stubURL) { // this.httpMock = httpMock; // this.serverURL = serverURL; // this.requestsURL = requestsURL; // this.stubURL = stubURL; // } // // public List<StubRequest> getRequests() { // HttpResponse response = httpMock.get(requestsURL); // response.assertStatusIs(200); // return collectRequests(response.getBodyAsJSONArray()); // } // // public Stubber on(String method, String url) { // Stubber stubber = new Stubber(httpMock, stubURL, url); // stubber.setRequestMethod(method); // return stubber; // } // // public void close() { // HttpResponse response = httpMock.delete(serverURL); // response.assertStatusIs(204); // } // // private List<StubRequest> collectRequests(JSONArray requests) { // List<StubRequest> result = new ArrayList<StubRequest>(); // for (Object request : requests) { // result.add(new StubRequest((JSONObject)request)); // } // return result; // } // } // Path: clients/java/src/org/httpmock/matchers/WasCalled.java import org.hamcrest.Description; import org.httpmock.StubRequest; import org.httpmock.StubServer; import org.junit.internal.matchers.TypeSafeMatcher; import java.util.List; import java.util.Map; package org.httpmock.matchers; public class WasCalled extends TypeSafeMatcher<StubServer> { private final Expectation expectation;
private List<StubRequest> stubRequests;
bbyars/httpmock
clients/java/functional-test/org/httpmock/WasCalledAtFunctionalTest.java
// Path: clients/java/src/org/httpmock/matchers/WasCalled.java // public static WasCalled wasCalled(String requestMethod, String endpoint) { // return new WasCalled(requestMethod, endpoint); // }
import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import static junit.framework.Assert.assertEquals; import static org.hamcrest.CoreMatchers.not; import static org.httpmock.matchers.WasCalled.wasCalled; import static org.junit.Assert.assertThat;
@Before public void connectToServer() { stub = ControlServer.at(controlServerURL).setupPort(3001); } @After public void shutdownServer() { stub.close(); } @Test public void shouldReturnAllRequestsToStub() { new HttpRequest("GET", "http://localhost:3001/first").send(); new HttpRequest("POST", "http://localhost:3001/second?with=query").withBody("TEST").send(); List<StubRequest> requests = stub.getRequests(); assertEquals(2, requests.size()); assertEquals("/first", requests.get(0).getPath()); assertEquals("GET", requests.get(0).getRequestMethod()); assertEquals("/second?with=query", requests.get(1).getPath()); assertEquals("TEST", requests.get(1).getBody()); assertEquals("POST", requests.get(1).getRequestMethod()); } @Test public void wasCalledShouldMatchPath() { new HttpRequest("GET", "http://localhost:3001/first").send();
// Path: clients/java/src/org/httpmock/matchers/WasCalled.java // public static WasCalled wasCalled(String requestMethod, String endpoint) { // return new WasCalled(requestMethod, endpoint); // } // Path: clients/java/functional-test/org/httpmock/WasCalledAtFunctionalTest.java import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import static junit.framework.Assert.assertEquals; import static org.hamcrest.CoreMatchers.not; import static org.httpmock.matchers.WasCalled.wasCalled; import static org.junit.Assert.assertThat; @Before public void connectToServer() { stub = ControlServer.at(controlServerURL).setupPort(3001); } @After public void shutdownServer() { stub.close(); } @Test public void shouldReturnAllRequestsToStub() { new HttpRequest("GET", "http://localhost:3001/first").send(); new HttpRequest("POST", "http://localhost:3001/second?with=query").withBody("TEST").send(); List<StubRequest> requests = stub.getRequests(); assertEquals(2, requests.size()); assertEquals("/first", requests.get(0).getPath()); assertEquals("GET", requests.get(0).getRequestMethod()); assertEquals("/second?with=query", requests.get(1).getPath()); assertEquals("TEST", requests.get(1).getBody()); assertEquals("POST", requests.get(1).getRequestMethod()); } @Test public void wasCalledShouldMatchPath() { new HttpRequest("GET", "http://localhost:3001/first").send();
assertThat(stub, wasCalled("GET", "/first"));
timofeevda/gwt-rxjs-jsinterop
gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/observable/OnSubscribe.java
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/subscription/TearDownSubscription.java // @JsType(isNative = true) // public interface TearDownSubscription { // void unsubscribe(); // }
import com.github.timofeevda.gwt.rxjs.interop.subscription.TearDownSubscription; import jsinterop.annotations.JsFunction;
/* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.observable; /** * @author dtimofeev since 20.12.2016. * @param <T> */ @JsFunction public interface OnSubscribe<T> {
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/subscription/TearDownSubscription.java // @JsType(isNative = true) // public interface TearDownSubscription { // void unsubscribe(); // } // Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/observable/OnSubscribe.java import com.github.timofeevda.gwt.rxjs.interop.subscription.TearDownSubscription; import jsinterop.annotations.JsFunction; /* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.observable; /** * @author dtimofeev since 20.12.2016. * @param <T> */ @JsFunction public interface OnSubscribe<T> {
TearDownSubscription call(Subscriber<T> subscriber);
timofeevda/gwt-rxjs-jsinterop
gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/observable/ObservableEx.java
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/event/KeyboardEvent.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") // public class KeyboardEvent extends Event { // public boolean altKey; // public int key; // public int code; // public boolean ctrlKey; // public boolean isComposing; // public int location; // public boolean metaKey; // public boolean repeat; // public boolean shiftKey; // public native boolean getModifierState(String modifier); // } // // Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/event/MouseEvent.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") // public class MouseEvent extends Event { // public boolean altKey; // public int button; // public int buttons; // public int clientX; // public int clientY; // public boolean ctrlKey; // public boolean metaKey; // public int movementX; // public int movementY; // public Element relatedTarget; // public int screenX; // public int screenY; // public boolean shiftKey; // public int x; // public int y; // public native boolean getModifierState(String modifier); // }
import com.github.timofeevda.gwt.rxjs.interop.event.MouseEvent; import com.google.gwt.dom.client.Element; import com.github.timofeevda.gwt.rxjs.interop.event.KeyboardEvent;
/* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.observable; /** * {@link Observable} extensions for type friendly signatures * * @author timofeevda since 12/01/2017 */ public class ObservableEx { public static Observable<MouseEvent> fromMouseEvent(Element element, String mouseEvent, boolean useCapture) { return Observable.fromEvent(element, mouseEvent, useCapture); } public static Observable<MouseEvent> fromMouseEvent(Element element, String mouseEvent) { return Observable.fromEvent(element, mouseEvent); }
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/event/KeyboardEvent.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") // public class KeyboardEvent extends Event { // public boolean altKey; // public int key; // public int code; // public boolean ctrlKey; // public boolean isComposing; // public int location; // public boolean metaKey; // public boolean repeat; // public boolean shiftKey; // public native boolean getModifierState(String modifier); // } // // Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/event/MouseEvent.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object") // public class MouseEvent extends Event { // public boolean altKey; // public int button; // public int buttons; // public int clientX; // public int clientY; // public boolean ctrlKey; // public boolean metaKey; // public int movementX; // public int movementY; // public Element relatedTarget; // public int screenX; // public int screenY; // public boolean shiftKey; // public int x; // public int y; // public native boolean getModifierState(String modifier); // } // Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/observable/ObservableEx.java import com.github.timofeevda.gwt.rxjs.interop.event.MouseEvent; import com.google.gwt.dom.client.Element; import com.github.timofeevda.gwt.rxjs.interop.event.KeyboardEvent; /* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.observable; /** * {@link Observable} extensions for type friendly signatures * * @author timofeevda since 12/01/2017 */ public class ObservableEx { public static Observable<MouseEvent> fromMouseEvent(Element element, String mouseEvent, boolean useCapture) { return Observable.fromEvent(element, mouseEvent, useCapture); } public static Observable<MouseEvent> fromMouseEvent(Element element, String mouseEvent) { return Observable.fromEvent(element, mouseEvent); }
public static Observable<KeyboardEvent> fromKeyboardEvent(Element element, String keyboardEvent) {
timofeevda/gwt-rxjs-jsinterop
gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/subscription/Subscription.java
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/functions/Action0.java // @JsFunction // @FunctionalInterface // public interface Action0 { // void call(); // }
import jsinterop.annotations.JsConstructor; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import com.github.timofeevda.gwt.rxjs.interop.functions.Action0;
/* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.subscription; /** * @author dtimofeev since 20.12.2016. */ @JsType(isNative = true, namespace = "Rx") public class Subscription implements ISubscription { @JsConstructor
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/functions/Action0.java // @JsFunction // @FunctionalInterface // public interface Action0 { // void call(); // } // Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/subscription/Subscription.java import jsinterop.annotations.JsConstructor; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import com.github.timofeevda.gwt.rxjs.interop.functions.Action0; /* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.subscription; /** * @author dtimofeev since 20.12.2016. */ @JsType(isNative = true, namespace = "Rx") public class Subscription implements ISubscription { @JsConstructor
public Subscription(Action0 unsubscribe) {
timofeevda/gwt-rxjs-jsinterop
gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/observable/ConnectableObservable.java
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/subscription/Subscription.java // @JsType(isNative = true, namespace = "Rx") // public class Subscription implements ISubscription { // // @JsConstructor // public Subscription(Action0 unsubscribe) { // // } // // @JsConstructor // public Subscription() { // // } // // @JsProperty(name = "closed") // @Override // public native boolean isClosed(); // // @Override // public native void unsubscribe(); // // public native Subscription add(TearDownSubscription tearDownLogic); // // public native void remove(Subscription subscription); // }
import com.github.timofeevda.gwt.rxjs.interop.subscription.Subscription; import jsinterop.annotations.JsType;
/* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.observable; /** * * @author dtimofeev since 21.12.2016. */ @JsType(namespace = "Rx", isNative = true) public class ConnectableObservable<T> extends Observable<T> {
// Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/subscription/Subscription.java // @JsType(isNative = true, namespace = "Rx") // public class Subscription implements ISubscription { // // @JsConstructor // public Subscription(Action0 unsubscribe) { // // } // // @JsConstructor // public Subscription() { // // } // // @JsProperty(name = "closed") // @Override // public native boolean isClosed(); // // @Override // public native void unsubscribe(); // // public native Subscription add(TearDownSubscription tearDownLogic); // // public native void remove(Subscription subscription); // } // Path: gwt-rxjs-jsinterop/src/main/java/com/github/timofeevda/gwt/rxjs/interop/observable/ConnectableObservable.java import com.github.timofeevda.gwt.rxjs.interop.subscription.Subscription; import jsinterop.annotations.JsType; /* * The MIT License (MIT) * * Copyright (c) 2018 Denis Timofeev <timofeevda@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN */ package com.github.timofeevda.gwt.rxjs.interop.observable; /** * * @author dtimofeev since 21.12.2016. */ @JsType(namespace = "Rx", isNative = true) public class ConnectableObservable<T> extends Observable<T> {
public native Subscription connect();
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/InheritedAnnotationsTest.java
// Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/City.java // @Type("city") // public class City extends BaseModel { // // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/Engineer.java // @Type("engineer") // public class Engineer extends Person { // // @Relationship("field") // private EngineeringField field; // // public EngineeringField getField() { // return field; // } // // public void setField(EngineeringField field) { // this.field = field; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/EngineeringField.java // @Type("engineering_field") // public class EngineeringField extends BaseModel { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.github.jasminb.jsonapi.models.inheritance.City; import com.github.jasminb.jsonapi.models.inheritance.Engineer; import com.github.jasminb.jsonapi.models.inheritance.EngineeringField; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets;
package com.github.jasminb.jsonapi; /** * Covering testing of resource classes with inherited annotations. * * @author jbegic */ public class InheritedAnnotationsTest { private ResourceConverter resourceConverter; @Before public void setup() {
// Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/City.java // @Type("city") // public class City extends BaseModel { // // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/Engineer.java // @Type("engineer") // public class Engineer extends Person { // // @Relationship("field") // private EngineeringField field; // // public EngineeringField getField() { // return field; // } // // public void setField(EngineeringField field) { // this.field = field; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/EngineeringField.java // @Type("engineering_field") // public class EngineeringField extends BaseModel { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/InheritedAnnotationsTest.java import com.github.jasminb.jsonapi.models.inheritance.City; import com.github.jasminb.jsonapi.models.inheritance.Engineer; import com.github.jasminb.jsonapi.models.inheritance.EngineeringField; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; package com.github.jasminb.jsonapi; /** * Covering testing of resource classes with inherited annotations. * * @author jbegic */ public class InheritedAnnotationsTest { private ResourceConverter resourceConverter; @Before public void setup() {
resourceConverter = new ResourceConverter(Engineer.class, EngineeringField.class, City.class);
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/InheritedAnnotationsTest.java
// Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/City.java // @Type("city") // public class City extends BaseModel { // // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/Engineer.java // @Type("engineer") // public class Engineer extends Person { // // @Relationship("field") // private EngineeringField field; // // public EngineeringField getField() { // return field; // } // // public void setField(EngineeringField field) { // this.field = field; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/EngineeringField.java // @Type("engineering_field") // public class EngineeringField extends BaseModel { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.github.jasminb.jsonapi.models.inheritance.City; import com.github.jasminb.jsonapi.models.inheritance.Engineer; import com.github.jasminb.jsonapi.models.inheritance.EngineeringField; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets;
package com.github.jasminb.jsonapi; /** * Covering testing of resource classes with inherited annotations. * * @author jbegic */ public class InheritedAnnotationsTest { private ResourceConverter resourceConverter; @Before public void setup() {
// Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/City.java // @Type("city") // public class City extends BaseModel { // // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/Engineer.java // @Type("engineer") // public class Engineer extends Person { // // @Relationship("field") // private EngineeringField field; // // public EngineeringField getField() { // return field; // } // // public void setField(EngineeringField field) { // this.field = field; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/EngineeringField.java // @Type("engineering_field") // public class EngineeringField extends BaseModel { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/InheritedAnnotationsTest.java import com.github.jasminb.jsonapi.models.inheritance.City; import com.github.jasminb.jsonapi.models.inheritance.Engineer; import com.github.jasminb.jsonapi.models.inheritance.EngineeringField; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; package com.github.jasminb.jsonapi; /** * Covering testing of resource classes with inherited annotations. * * @author jbegic */ public class InheritedAnnotationsTest { private ResourceConverter resourceConverter; @Before public void setup() {
resourceConverter = new ResourceConverter(Engineer.class, EngineeringField.class, City.class);
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/InheritedAnnotationsTest.java
// Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/City.java // @Type("city") // public class City extends BaseModel { // // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/Engineer.java // @Type("engineer") // public class Engineer extends Person { // // @Relationship("field") // private EngineeringField field; // // public EngineeringField getField() { // return field; // } // // public void setField(EngineeringField field) { // this.field = field; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/EngineeringField.java // @Type("engineering_field") // public class EngineeringField extends BaseModel { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.github.jasminb.jsonapi.models.inheritance.City; import com.github.jasminb.jsonapi.models.inheritance.Engineer; import com.github.jasminb.jsonapi.models.inheritance.EngineeringField; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets;
package com.github.jasminb.jsonapi; /** * Covering testing of resource classes with inherited annotations. * * @author jbegic */ public class InheritedAnnotationsTest { private ResourceConverter resourceConverter; @Before public void setup() {
// Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/City.java // @Type("city") // public class City extends BaseModel { // // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/Engineer.java // @Type("engineer") // public class Engineer extends Person { // // @Relationship("field") // private EngineeringField field; // // public EngineeringField getField() { // return field; // } // // public void setField(EngineeringField field) { // this.field = field; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/inheritance/EngineeringField.java // @Type("engineering_field") // public class EngineeringField extends BaseModel { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/InheritedAnnotationsTest.java import com.github.jasminb.jsonapi.models.inheritance.City; import com.github.jasminb.jsonapi.models.inheritance.Engineer; import com.github.jasminb.jsonapi.models.inheritance.EngineeringField; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; package com.github.jasminb.jsonapi; /** * Covering testing of resource classes with inherited annotations. * * @author jbegic */ public class InheritedAnnotationsTest { private ResourceConverter resourceConverter; @Before public void setup() {
resourceConverter = new ResourceConverter(Engineer.class, EngineeringField.class, City.class);
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/ValidationUtils.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import com.github.jasminb.jsonapi.models.errors.Errors;
package com.github.jasminb.jsonapi; /** * Utility methods for validating segments of JSON API resource object. * * @author jbegic */ public class ValidationUtils { private ValidationUtils() { // Private CTOR } /** * Ensures document has at least one of 'DATA', 'ERRORS' or 'META' attributes. * * @param resourceNode resource node * @throws ResourceParseException Maps error attribute into ResourceParseException if present. * @throws InvalidJsonApiResourceException is thrown when node has none of the required attributes. */ public static void ensureValidDocument(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode == null || resourceNode.isNull()) {
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/ValidationUtils.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import com.github.jasminb.jsonapi.models.errors.Errors; package com.github.jasminb.jsonapi; /** * Utility methods for validating segments of JSON API resource object. * * @author jbegic */ public class ValidationUtils { private ValidationUtils() { // Private CTOR } /** * Ensures document has at least one of 'DATA', 'ERRORS' or 'META' attributes. * * @param resourceNode resource node * @throws ResourceParseException Maps error attribute into ResourceParseException if present. * @throws InvalidJsonApiResourceException is thrown when node has none of the required attributes. */ public static void ensureValidDocument(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode == null || resourceNode.isNull()) {
throw new InvalidJsonApiResourceException();
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/ValidationUtils.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import com.github.jasminb.jsonapi.models.errors.Errors;
package com.github.jasminb.jsonapi; /** * Utility methods for validating segments of JSON API resource object. * * @author jbegic */ public class ValidationUtils { private ValidationUtils() { // Private CTOR } /** * Ensures document has at least one of 'DATA', 'ERRORS' or 'META' attributes. * * @param resourceNode resource node * @throws ResourceParseException Maps error attribute into ResourceParseException if present. * @throws InvalidJsonApiResourceException is thrown when node has none of the required attributes. */ public static void ensureValidDocument(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode == null || resourceNode.isNull()) { throw new InvalidJsonApiResourceException(); } boolean hasErrors = resourceNode.hasNonNull(JSONAPISpecConstants.ERRORS); boolean hasData = resourceNode.has(JSONAPISpecConstants.DATA); boolean hasMeta = resourceNode.has(JSONAPISpecConstants.META); if (hasErrors) { try {
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/ValidationUtils.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import com.github.jasminb.jsonapi.models.errors.Errors; package com.github.jasminb.jsonapi; /** * Utility methods for validating segments of JSON API resource object. * * @author jbegic */ public class ValidationUtils { private ValidationUtils() { // Private CTOR } /** * Ensures document has at least one of 'DATA', 'ERRORS' or 'META' attributes. * * @param resourceNode resource node * @throws ResourceParseException Maps error attribute into ResourceParseException if present. * @throws InvalidJsonApiResourceException is thrown when node has none of the required attributes. */ public static void ensureValidDocument(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode == null || resourceNode.isNull()) { throw new InvalidJsonApiResourceException(); } boolean hasErrors = resourceNode.hasNonNull(JSONAPISpecConstants.ERRORS); boolean hasData = resourceNode.has(JSONAPISpecConstants.DATA); boolean hasMeta = resourceNode.has(JSONAPISpecConstants.META); if (hasErrors) { try {
throw new ResourceParseException(ErrorUtils.parseError(mapper, resourceNode, Errors.class));
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/ValidationUtils.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import com.github.jasminb.jsonapi.models.errors.Errors;
package com.github.jasminb.jsonapi; /** * Utility methods for validating segments of JSON API resource object. * * @author jbegic */ public class ValidationUtils { private ValidationUtils() { // Private CTOR } /** * Ensures document has at least one of 'DATA', 'ERRORS' or 'META' attributes. * * @param resourceNode resource node * @throws ResourceParseException Maps error attribute into ResourceParseException if present. * @throws InvalidJsonApiResourceException is thrown when node has none of the required attributes. */ public static void ensureValidDocument(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode == null || resourceNode.isNull()) { throw new InvalidJsonApiResourceException(); } boolean hasErrors = resourceNode.hasNonNull(JSONAPISpecConstants.ERRORS); boolean hasData = resourceNode.has(JSONAPISpecConstants.DATA); boolean hasMeta = resourceNode.has(JSONAPISpecConstants.META); if (hasErrors) { try {
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/ValidationUtils.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import com.github.jasminb.jsonapi.models.errors.Errors; package com.github.jasminb.jsonapi; /** * Utility methods for validating segments of JSON API resource object. * * @author jbegic */ public class ValidationUtils { private ValidationUtils() { // Private CTOR } /** * Ensures document has at least one of 'DATA', 'ERRORS' or 'META' attributes. * * @param resourceNode resource node * @throws ResourceParseException Maps error attribute into ResourceParseException if present. * @throws InvalidJsonApiResourceException is thrown when node has none of the required attributes. */ public static void ensureValidDocument(ObjectMapper mapper, JsonNode resourceNode) { if (resourceNode == null || resourceNode.isNull()) { throw new InvalidJsonApiResourceException(); } boolean hasErrors = resourceNode.hasNonNull(JSONAPISpecConstants.ERRORS); boolean hasData = resourceNode.has(JSONAPISpecConstants.DATA); boolean hasMeta = resourceNode.has(JSONAPISpecConstants.META); if (hasErrors) { try {
throw new ResourceParseException(ErrorUtils.parseError(mapper, resourceNode, Errors.class));
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/DeserializationTest.java
// Path: src/test/java/com/github/jasminb/jsonapi/models/Article.java // @Type("articles") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Article { // @Id // private String id; // // private String title; // // @Relationship(value = "author", resolve = true, relType = RelType.RELATED) // private Author author; // // @Relationship(value = "comments", resolve = true) // private List<Comment> comments; // // @Relationship(value = "users", serialiseData = false) // private List<User> users; // // @RelationshipLinks(value = "users") // private Links userRelationshipLinks; // // public Article() { // users = Collections.emptyList(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public List<Comment> getComments() { // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public List<User> getUsers() { // return users; // } // // public void setUsers(List<User> users) { // this.users = users; // } // // public Links getUserRelationshipLinks() { // return userRelationshipLinks; // } // // public void setUserRelationshipLinks(Links userRelationshipLinks) { // this.userRelationshipLinks = userRelationshipLinks; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/Author.java // @Type("people") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Author { // @Id // private String id; // private String firstName; // private String lastName; // private String twitter; // // @Relationship("articles") // private Collection<Article> articles; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getTwitter() { // return twitter; // } // // public void setTwitter(String twitter) { // this.twitter = twitter; // } // // public Collection<Article> getArticles() { // return articles; // } // // public void setArticles(Collection<Article> articles) { // this.articles = articles; // } // }
import com.github.jasminb.jsonapi.models.Article; import com.github.jasminb.jsonapi.models.Author; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream;
package com.github.jasminb.jsonapi; public class DeserializationTest { private ResourceConverter converter; @Before public void setup() {
// Path: src/test/java/com/github/jasminb/jsonapi/models/Article.java // @Type("articles") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Article { // @Id // private String id; // // private String title; // // @Relationship(value = "author", resolve = true, relType = RelType.RELATED) // private Author author; // // @Relationship(value = "comments", resolve = true) // private List<Comment> comments; // // @Relationship(value = "users", serialiseData = false) // private List<User> users; // // @RelationshipLinks(value = "users") // private Links userRelationshipLinks; // // public Article() { // users = Collections.emptyList(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public List<Comment> getComments() { // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public List<User> getUsers() { // return users; // } // // public void setUsers(List<User> users) { // this.users = users; // } // // public Links getUserRelationshipLinks() { // return userRelationshipLinks; // } // // public void setUserRelationshipLinks(Links userRelationshipLinks) { // this.userRelationshipLinks = userRelationshipLinks; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/Author.java // @Type("people") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Author { // @Id // private String id; // private String firstName; // private String lastName; // private String twitter; // // @Relationship("articles") // private Collection<Article> articles; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getTwitter() { // return twitter; // } // // public void setTwitter(String twitter) { // this.twitter = twitter; // } // // public Collection<Article> getArticles() { // return articles; // } // // public void setArticles(Collection<Article> articles) { // this.articles = articles; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/DeserializationTest.java import com.github.jasminb.jsonapi.models.Article; import com.github.jasminb.jsonapi.models.Author; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; package com.github.jasminb.jsonapi; public class DeserializationTest { private ResourceConverter converter; @Before public void setup() {
converter = new ResourceConverter(Article.class, Author.class);
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/DeserializationTest.java
// Path: src/test/java/com/github/jasminb/jsonapi/models/Article.java // @Type("articles") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Article { // @Id // private String id; // // private String title; // // @Relationship(value = "author", resolve = true, relType = RelType.RELATED) // private Author author; // // @Relationship(value = "comments", resolve = true) // private List<Comment> comments; // // @Relationship(value = "users", serialiseData = false) // private List<User> users; // // @RelationshipLinks(value = "users") // private Links userRelationshipLinks; // // public Article() { // users = Collections.emptyList(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public List<Comment> getComments() { // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public List<User> getUsers() { // return users; // } // // public void setUsers(List<User> users) { // this.users = users; // } // // public Links getUserRelationshipLinks() { // return userRelationshipLinks; // } // // public void setUserRelationshipLinks(Links userRelationshipLinks) { // this.userRelationshipLinks = userRelationshipLinks; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/Author.java // @Type("people") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Author { // @Id // private String id; // private String firstName; // private String lastName; // private String twitter; // // @Relationship("articles") // private Collection<Article> articles; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getTwitter() { // return twitter; // } // // public void setTwitter(String twitter) { // this.twitter = twitter; // } // // public Collection<Article> getArticles() { // return articles; // } // // public void setArticles(Collection<Article> articles) { // this.articles = articles; // } // }
import com.github.jasminb.jsonapi.models.Article; import com.github.jasminb.jsonapi.models.Author; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream;
package com.github.jasminb.jsonapi; public class DeserializationTest { private ResourceConverter converter; @Before public void setup() {
// Path: src/test/java/com/github/jasminb/jsonapi/models/Article.java // @Type("articles") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Article { // @Id // private String id; // // private String title; // // @Relationship(value = "author", resolve = true, relType = RelType.RELATED) // private Author author; // // @Relationship(value = "comments", resolve = true) // private List<Comment> comments; // // @Relationship(value = "users", serialiseData = false) // private List<User> users; // // @RelationshipLinks(value = "users") // private Links userRelationshipLinks; // // public Article() { // users = Collections.emptyList(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public List<Comment> getComments() { // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public List<User> getUsers() { // return users; // } // // public void setUsers(List<User> users) { // this.users = users; // } // // public Links getUserRelationshipLinks() { // return userRelationshipLinks; // } // // public void setUserRelationshipLinks(Links userRelationshipLinks) { // this.userRelationshipLinks = userRelationshipLinks; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/Author.java // @Type("people") // @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") // public class Author { // @Id // private String id; // private String firstName; // private String lastName; // private String twitter; // // @Relationship("articles") // private Collection<Article> articles; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public String getTwitter() { // return twitter; // } // // public void setTwitter(String twitter) { // this.twitter = twitter; // } // // public Collection<Article> getArticles() { // return articles; // } // // public void setArticles(Collection<Article> articles) { // this.articles = articles; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/DeserializationTest.java import com.github.jasminb.jsonapi.models.Article; import com.github.jasminb.jsonapi.models.Author; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; package com.github.jasminb.jsonapi; public class DeserializationTest { private ResourceConverter converter; @Before public void setup() {
converter = new ResourceConverter(Article.class, Author.class);
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/NonStringIdsTest.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/DocumentSerializationException.java // public class DocumentSerializationException extends Exception { // // /** // * Creates new DocumentSerializationException. // * @param cause {@link Throwable} exception cause // */ // public DocumentSerializationException(Throwable cause) { // super(cause); // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java // @Type("integer-id-type") // public class IntegerIdResource { // // @Id(IntegerIdHandler.class) // private Integer id; // // private String value; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java // @Type("long-id-type") // public class LongIdResource { // // @Id(LongIdHandler.class) // private Long id; // // private String value; // // @Relationship("integer-id-relationship") // private IntegerIdResource integerIdResource; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public IntegerIdResource getIntegerIdResource() { // return integerIdResource; // } // // public void setIntegerIdResource(IntegerIdResource integerIdResource) { // this.integerIdResource = integerIdResource; // } // }
import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; import com.github.jasminb.jsonapi.models.IntegerIdResource; import com.github.jasminb.jsonapi.models.LongIdResource; import org.junit.Assert; import org.junit.Test;
package com.github.jasminb.jsonapi; /** * Covers functionality of using types other than {@link String} as resource identifier. * * @author jbegic */ public class NonStringIdsTest { @Test
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/DocumentSerializationException.java // public class DocumentSerializationException extends Exception { // // /** // * Creates new DocumentSerializationException. // * @param cause {@link Throwable} exception cause // */ // public DocumentSerializationException(Throwable cause) { // super(cause); // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java // @Type("integer-id-type") // public class IntegerIdResource { // // @Id(IntegerIdHandler.class) // private Integer id; // // private String value; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java // @Type("long-id-type") // public class LongIdResource { // // @Id(LongIdHandler.class) // private Long id; // // private String value; // // @Relationship("integer-id-relationship") // private IntegerIdResource integerIdResource; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public IntegerIdResource getIntegerIdResource() { // return integerIdResource; // } // // public void setIntegerIdResource(IntegerIdResource integerIdResource) { // this.integerIdResource = integerIdResource; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/NonStringIdsTest.java import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; import com.github.jasminb.jsonapi.models.IntegerIdResource; import com.github.jasminb.jsonapi.models.LongIdResource; import org.junit.Assert; import org.junit.Test; package com.github.jasminb.jsonapi; /** * Covers functionality of using types other than {@link String} as resource identifier. * * @author jbegic */ public class NonStringIdsTest { @Test
public void test() throws DocumentSerializationException {
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/NonStringIdsTest.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/DocumentSerializationException.java // public class DocumentSerializationException extends Exception { // // /** // * Creates new DocumentSerializationException. // * @param cause {@link Throwable} exception cause // */ // public DocumentSerializationException(Throwable cause) { // super(cause); // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java // @Type("integer-id-type") // public class IntegerIdResource { // // @Id(IntegerIdHandler.class) // private Integer id; // // private String value; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java // @Type("long-id-type") // public class LongIdResource { // // @Id(LongIdHandler.class) // private Long id; // // private String value; // // @Relationship("integer-id-relationship") // private IntegerIdResource integerIdResource; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public IntegerIdResource getIntegerIdResource() { // return integerIdResource; // } // // public void setIntegerIdResource(IntegerIdResource integerIdResource) { // this.integerIdResource = integerIdResource; // } // }
import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; import com.github.jasminb.jsonapi.models.IntegerIdResource; import com.github.jasminb.jsonapi.models.LongIdResource; import org.junit.Assert; import org.junit.Test;
package com.github.jasminb.jsonapi; /** * Covers functionality of using types other than {@link String} as resource identifier. * * @author jbegic */ public class NonStringIdsTest { @Test public void test() throws DocumentSerializationException {
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/DocumentSerializationException.java // public class DocumentSerializationException extends Exception { // // /** // * Creates new DocumentSerializationException. // * @param cause {@link Throwable} exception cause // */ // public DocumentSerializationException(Throwable cause) { // super(cause); // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java // @Type("integer-id-type") // public class IntegerIdResource { // // @Id(IntegerIdHandler.class) // private Integer id; // // private String value; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java // @Type("long-id-type") // public class LongIdResource { // // @Id(LongIdHandler.class) // private Long id; // // private String value; // // @Relationship("integer-id-relationship") // private IntegerIdResource integerIdResource; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public IntegerIdResource getIntegerIdResource() { // return integerIdResource; // } // // public void setIntegerIdResource(IntegerIdResource integerIdResource) { // this.integerIdResource = integerIdResource; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/NonStringIdsTest.java import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; import com.github.jasminb.jsonapi.models.IntegerIdResource; import com.github.jasminb.jsonapi.models.LongIdResource; import org.junit.Assert; import org.junit.Test; package com.github.jasminb.jsonapi; /** * Covers functionality of using types other than {@link String} as resource identifier. * * @author jbegic */ public class NonStringIdsTest { @Test public void test() throws DocumentSerializationException {
LongIdResource resource = new LongIdResource();
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/NonStringIdsTest.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/DocumentSerializationException.java // public class DocumentSerializationException extends Exception { // // /** // * Creates new DocumentSerializationException. // * @param cause {@link Throwable} exception cause // */ // public DocumentSerializationException(Throwable cause) { // super(cause); // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java // @Type("integer-id-type") // public class IntegerIdResource { // // @Id(IntegerIdHandler.class) // private Integer id; // // private String value; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java // @Type("long-id-type") // public class LongIdResource { // // @Id(LongIdHandler.class) // private Long id; // // private String value; // // @Relationship("integer-id-relationship") // private IntegerIdResource integerIdResource; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public IntegerIdResource getIntegerIdResource() { // return integerIdResource; // } // // public void setIntegerIdResource(IntegerIdResource integerIdResource) { // this.integerIdResource = integerIdResource; // } // }
import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; import com.github.jasminb.jsonapi.models.IntegerIdResource; import com.github.jasminb.jsonapi.models.LongIdResource; import org.junit.Assert; import org.junit.Test;
package com.github.jasminb.jsonapi; /** * Covers functionality of using types other than {@link String} as resource identifier. * * @author jbegic */ public class NonStringIdsTest { @Test public void test() throws DocumentSerializationException { LongIdResource resource = new LongIdResource(); resource.setId(Long.MAX_VALUE); resource.setValue("long-resource-value");
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/DocumentSerializationException.java // public class DocumentSerializationException extends Exception { // // /** // * Creates new DocumentSerializationException. // * @param cause {@link Throwable} exception cause // */ // public DocumentSerializationException(Throwable cause) { // super(cause); // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java // @Type("integer-id-type") // public class IntegerIdResource { // // @Id(IntegerIdHandler.class) // private Integer id; // // private String value; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java // @Type("long-id-type") // public class LongIdResource { // // @Id(LongIdHandler.class) // private Long id; // // private String value; // // @Relationship("integer-id-relationship") // private IntegerIdResource integerIdResource; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public IntegerIdResource getIntegerIdResource() { // return integerIdResource; // } // // public void setIntegerIdResource(IntegerIdResource integerIdResource) { // this.integerIdResource = integerIdResource; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/NonStringIdsTest.java import com.github.jasminb.jsonapi.exceptions.DocumentSerializationException; import com.github.jasminb.jsonapi.models.IntegerIdResource; import com.github.jasminb.jsonapi.models.LongIdResource; import org.junit.Assert; import org.junit.Test; package com.github.jasminb.jsonapi; /** * Covers functionality of using types other than {@link String} as resource identifier. * * @author jbegic */ public class NonStringIdsTest { @Test public void test() throws DocumentSerializationException { LongIdResource resource = new LongIdResource(); resource.setId(Long.MAX_VALUE); resource.setValue("long-resource-value");
IntegerIdResource integerIdResource = new IntegerIdResource();
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/JSONAPIDocument.java
// Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Error.java // public class Error { // private String id; // private Links links; // private String status; // private String code; // private String title; // private String detail; // private Source source; // private JsonNode meta; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Links getLinks() { // return links; // } // // public void setLinks(Links links) { // this.links = links; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public Source getSource() { // return source; // } // // public void setSource(Source source) { // this.source = source; // } // // public JsonNode getMeta() { // return meta; // } // // public void setMeta(JsonNode meta) { // this.meta = meta; // } // // @Override // public String toString() { // return "Error{" + // "id='" + id + '\'' + // ", links=" + links + // ", status='" + status + '\'' + // ", code='" + code + '\'' + // ", title='" + title + '\'' + // ", detail='" + detail + '\'' + // ", source=" + source + // ", meta=" + meta + // '}'; // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.models.errors.Error; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.Map;
package com.github.jasminb.jsonapi; /** * JSON API Document wrapper. * * @param <T> the type parameter * @author jbegic */ public class JSONAPIDocument<T> { private T data; private ObjectMapper deserializer;
// Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Error.java // public class Error { // private String id; // private Links links; // private String status; // private String code; // private String title; // private String detail; // private Source source; // private JsonNode meta; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Links getLinks() { // return links; // } // // public void setLinks(Links links) { // this.links = links; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDetail() { // return detail; // } // // public void setDetail(String detail) { // this.detail = detail; // } // // public Source getSource() { // return source; // } // // public void setSource(Source source) { // this.source = source; // } // // public JsonNode getMeta() { // return meta; // } // // public void setMeta(JsonNode meta) { // this.meta = meta; // } // // @Override // public String toString() { // return "Error{" + // "id='" + id + '\'' + // ", links=" + links + // ", status='" + status + '\'' + // ", code='" + code + '\'' + // ", title='" + title + '\'' + // ", detail='" + detail + '\'' + // ", source=" + source + // ", meta=" + meta + // '}'; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/JSONAPIDocument.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.models.errors.Error; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; package com.github.jasminb.jsonapi; /** * JSON API Document wrapper. * * @param <T> the type parameter * @author jbegic */ public class JSONAPIDocument<T> { private T data; private ObjectMapper deserializer;
private Iterable<? extends Error> errors;
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/annotations/Relationship.java
// Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // }
import com.github.jasminb.jsonapi.RelType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package com.github.jasminb.jsonapi.annotations; /** * Annotation used to configure relationship field in JSON API resources. * * @author jbegic */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Relationship { String value(); boolean resolve() default false; boolean serialise() default true; boolean serialiseData() default true;
// Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/annotations/Relationship.java import com.github.jasminb.jsonapi.RelType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package com.github.jasminb.jsonapi.annotations; /** * Annotation used to configure relationship field in JSON API resources. * * @author jbegic */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Relationship { String value(); boolean resolve() default false; boolean serialise() default true; boolean serialiseData() default true;
RelType relType() default RelType.SELF;
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/ErrorUtils.java
// Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.models.errors.Errors; import java.io.IOException; import java.io.InputStream; import okhttp3.ResponseBody;
package com.github.jasminb.jsonapi; /** * Utility class providing methods needed for parsing JSON API Spec errors. * * @author jbegic */ public class ErrorUtils { private ErrorUtils() { // Private constructor } /** * Parses provided ResponseBody and returns it as T. * * @param mapper Jackson Object mapper instance * @param errorResponse error response body * @return T collection * @throws IOException */
// Path: src/main/java/com/github/jasminb/jsonapi/models/errors/Errors.java // public class Errors { // private List<Error> errors; // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // @Override // public String toString() { // return "Errors{" + // "errors=" + (errors != null ? errors : "Undefined") + // '}'; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/ErrorUtils.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.jasminb.jsonapi.models.errors.Errors; import java.io.IOException; import java.io.InputStream; import okhttp3.ResponseBody; package com.github.jasminb.jsonapi; /** * Utility class providing methods needed for parsing JSON API Spec errors. * * @author jbegic */ public class ErrorUtils { private ErrorUtils() { // Private constructor } /** * Parses provided ResponseBody and returns it as T. * * @param mapper Jackson Object mapper instance * @param errorResponse error response body * @return T collection * @throws IOException */
public static <T extends Errors> T parseErrorResponse(ObjectMapper mapper, ResponseBody errorResponse, Class<T> cls) throws IOException {
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/models/Status.java
// Path: src/main/java/com/github/jasminb/jsonapi/Links.java // public class Links implements Serializable { // private static final long serialVersionUID = 1305238708279094084L; // // /** // * A map of link objects keyed by link name. // */ // private Map<String, Link> links; // // /** // * Create new Links. // */ // public Links() { // this.links = new LinkedHashMap<>(); // } // // /** // * Create new Links. // * @param linkMap {@link Map} link data // */ // public Links(Map<String, Link> linkMap) { // this.links = new LinkedHashMap<>(linkMap); // } // // /** // * Convenience method for returning named link. // * @param linkName name of the link to return // * @return the link object, or {@code null} if the named link does not exist // */ // public Link getLink(String linkName) { // return links.get(linkName); // } // // /** // * Convenience method for returning the {@code prev} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getPrevious() { // return getLink(JSONAPISpecConstants.PREV); // } // // /** // * Convenience method for returning the {@code first} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getFirst() { // return getLink(JSONAPISpecConstants.FIRST); // } // // /** // * Convenience method for returning the {@code next} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getNext() { // return getLink(JSONAPISpecConstants.NEXT); // } // // /** // * Convenience method for returning the {@code last} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getLast() { // return getLink(JSONAPISpecConstants.LAST); // } // // /** // * Convenience method for returning the {@code self} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getSelf() { // return getLink(JSONAPISpecConstants.SELF); // } // // /** // * Convenience method for returning the {@code related} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getRelated() { // return getLink(JSONAPISpecConstants.RELATED); // } // // /** // * Gets all registered links. // * @return {@link Map} link data // */ // public Map<String, Link> getLinks() { // return new LinkedHashMap<>(links); // } // // /** // * Adds a named link. // * // * @param linkName name of the link to add // * @param link the link to add // */ // public void addLink(String linkName, Link link) { // links.put(linkName, link); // } // }
import com.github.jasminb.jsonapi.Links; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.RelationshipLinks; import com.github.jasminb.jsonapi.annotations.RelationshipMeta; import com.github.jasminb.jsonapi.annotations.Type;
package com.github.jasminb.jsonapi.models; @Type(value = "statuses", path = "/statuses/{id}") public class Status { @Id private String id; private String content; private Integer commentCount; private Integer likeCount;
// Path: src/main/java/com/github/jasminb/jsonapi/Links.java // public class Links implements Serializable { // private static final long serialVersionUID = 1305238708279094084L; // // /** // * A map of link objects keyed by link name. // */ // private Map<String, Link> links; // // /** // * Create new Links. // */ // public Links() { // this.links = new LinkedHashMap<>(); // } // // /** // * Create new Links. // * @param linkMap {@link Map} link data // */ // public Links(Map<String, Link> linkMap) { // this.links = new LinkedHashMap<>(linkMap); // } // // /** // * Convenience method for returning named link. // * @param linkName name of the link to return // * @return the link object, or {@code null} if the named link does not exist // */ // public Link getLink(String linkName) { // return links.get(linkName); // } // // /** // * Convenience method for returning the {@code prev} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getPrevious() { // return getLink(JSONAPISpecConstants.PREV); // } // // /** // * Convenience method for returning the {@code first} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getFirst() { // return getLink(JSONAPISpecConstants.FIRST); // } // // /** // * Convenience method for returning the {@code next} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getNext() { // return getLink(JSONAPISpecConstants.NEXT); // } // // /** // * Convenience method for returning the {@code last} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getLast() { // return getLink(JSONAPISpecConstants.LAST); // } // // /** // * Convenience method for returning the {@code self} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getSelf() { // return getLink(JSONAPISpecConstants.SELF); // } // // /** // * Convenience method for returning the {@code related} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getRelated() { // return getLink(JSONAPISpecConstants.RELATED); // } // // /** // * Gets all registered links. // * @return {@link Map} link data // */ // public Map<String, Link> getLinks() { // return new LinkedHashMap<>(links); // } // // /** // * Adds a named link. // * // * @param linkName name of the link to add // * @param link the link to add // */ // public void addLink(String linkName, Link link) { // links.put(linkName, link); // } // } // Path: src/test/java/com/github/jasminb/jsonapi/models/Status.java import com.github.jasminb.jsonapi.Links; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.RelationshipLinks; import com.github.jasminb.jsonapi.annotations.RelationshipMeta; import com.github.jasminb.jsonapi.annotations.Type; package com.github.jasminb.jsonapi.models; @Type(value = "statuses", path = "/statuses/{id}") public class Status { @Id private String id; private String content; private Integer commentCount; private Integer likeCount;
@com.github.jasminb.jsonapi.annotations.Links
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java
// Path: src/main/java/com/github/jasminb/jsonapi/IntegerIdHandler.java // public class IntegerIdHandler implements ResourceIdHandler { // // /** // * Creates new IntegerIdHandler. // * // */ // public IntegerIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public Integer fromString(String source) { // if (source != null) { // return Integer.valueOf(source); // } // return null; // } // }
import com.github.jasminb.jsonapi.IntegerIdHandler; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Type;
package com.github.jasminb.jsonapi.models; /** * Model class used to test {@link Integer} as resource identifier. * * @author jbegic */ @Type("integer-id-type") public class IntegerIdResource {
// Path: src/main/java/com/github/jasminb/jsonapi/IntegerIdHandler.java // public class IntegerIdHandler implements ResourceIdHandler { // // /** // * Creates new IntegerIdHandler. // * // */ // public IntegerIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public Integer fromString(String source) { // if (source != null) { // return Integer.valueOf(source); // } // return null; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/models/IntegerIdResource.java import com.github.jasminb.jsonapi.IntegerIdHandler; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Type; package com.github.jasminb.jsonapi.models; /** * Model class used to test {@link Integer} as resource identifier. * * @author jbegic */ @Type("integer-id-type") public class IntegerIdResource {
@Id(IntegerIdHandler.class)
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/models/Article.java
// Path: src/main/java/com/github/jasminb/jsonapi/Links.java // public class Links implements Serializable { // private static final long serialVersionUID = 1305238708279094084L; // // /** // * A map of link objects keyed by link name. // */ // private Map<String, Link> links; // // /** // * Create new Links. // */ // public Links() { // this.links = new LinkedHashMap<>(); // } // // /** // * Create new Links. // * @param linkMap {@link Map} link data // */ // public Links(Map<String, Link> linkMap) { // this.links = new LinkedHashMap<>(linkMap); // } // // /** // * Convenience method for returning named link. // * @param linkName name of the link to return // * @return the link object, or {@code null} if the named link does not exist // */ // public Link getLink(String linkName) { // return links.get(linkName); // } // // /** // * Convenience method for returning the {@code prev} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getPrevious() { // return getLink(JSONAPISpecConstants.PREV); // } // // /** // * Convenience method for returning the {@code first} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getFirst() { // return getLink(JSONAPISpecConstants.FIRST); // } // // /** // * Convenience method for returning the {@code next} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getNext() { // return getLink(JSONAPISpecConstants.NEXT); // } // // /** // * Convenience method for returning the {@code last} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getLast() { // return getLink(JSONAPISpecConstants.LAST); // } // // /** // * Convenience method for returning the {@code self} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getSelf() { // return getLink(JSONAPISpecConstants.SELF); // } // // /** // * Convenience method for returning the {@code related} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getRelated() { // return getLink(JSONAPISpecConstants.RELATED); // } // // /** // * Gets all registered links. // * @return {@link Map} link data // */ // public Map<String, Link> getLinks() { // return new LinkedHashMap<>(links); // } // // /** // * Adds a named link. // * // * @param linkName name of the link to add // * @param link the link to add // */ // public void addLink(String linkName, Link link) { // links.put(linkName, link); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // }
import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.github.jasminb.jsonapi.Links; import com.github.jasminb.jsonapi.RelType; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.RelationshipLinks; import com.github.jasminb.jsonapi.annotations.Type; import java.util.Collections; import java.util.List;
package com.github.jasminb.jsonapi.models; @Type("articles") @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") public class Article { @Id private String id; private String title;
// Path: src/main/java/com/github/jasminb/jsonapi/Links.java // public class Links implements Serializable { // private static final long serialVersionUID = 1305238708279094084L; // // /** // * A map of link objects keyed by link name. // */ // private Map<String, Link> links; // // /** // * Create new Links. // */ // public Links() { // this.links = new LinkedHashMap<>(); // } // // /** // * Create new Links. // * @param linkMap {@link Map} link data // */ // public Links(Map<String, Link> linkMap) { // this.links = new LinkedHashMap<>(linkMap); // } // // /** // * Convenience method for returning named link. // * @param linkName name of the link to return // * @return the link object, or {@code null} if the named link does not exist // */ // public Link getLink(String linkName) { // return links.get(linkName); // } // // /** // * Convenience method for returning the {@code prev} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getPrevious() { // return getLink(JSONAPISpecConstants.PREV); // } // // /** // * Convenience method for returning the {@code first} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getFirst() { // return getLink(JSONAPISpecConstants.FIRST); // } // // /** // * Convenience method for returning the {@code next} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getNext() { // return getLink(JSONAPISpecConstants.NEXT); // } // // /** // * Convenience method for returning the {@code last} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getLast() { // return getLink(JSONAPISpecConstants.LAST); // } // // /** // * Convenience method for returning the {@code self} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getSelf() { // return getLink(JSONAPISpecConstants.SELF); // } // // /** // * Convenience method for returning the {@code related} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getRelated() { // return getLink(JSONAPISpecConstants.RELATED); // } // // /** // * Gets all registered links. // * @return {@link Map} link data // */ // public Map<String, Link> getLinks() { // return new LinkedHashMap<>(links); // } // // /** // * Adds a named link. // * // * @param linkName name of the link to add // * @param link the link to add // */ // public void addLink(String linkName, Link link) { // links.put(linkName, link); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/models/Article.java import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.github.jasminb.jsonapi.Links; import com.github.jasminb.jsonapi.RelType; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.RelationshipLinks; import com.github.jasminb.jsonapi.annotations.Type; import java.util.Collections; import java.util.List; package com.github.jasminb.jsonapi.models; @Type("articles") @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") public class Article { @Id private String id; private String title;
@Relationship(value = "author", resolve = true, relType = RelType.RELATED)
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/models/Article.java
// Path: src/main/java/com/github/jasminb/jsonapi/Links.java // public class Links implements Serializable { // private static final long serialVersionUID = 1305238708279094084L; // // /** // * A map of link objects keyed by link name. // */ // private Map<String, Link> links; // // /** // * Create new Links. // */ // public Links() { // this.links = new LinkedHashMap<>(); // } // // /** // * Create new Links. // * @param linkMap {@link Map} link data // */ // public Links(Map<String, Link> linkMap) { // this.links = new LinkedHashMap<>(linkMap); // } // // /** // * Convenience method for returning named link. // * @param linkName name of the link to return // * @return the link object, or {@code null} if the named link does not exist // */ // public Link getLink(String linkName) { // return links.get(linkName); // } // // /** // * Convenience method for returning the {@code prev} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getPrevious() { // return getLink(JSONAPISpecConstants.PREV); // } // // /** // * Convenience method for returning the {@code first} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getFirst() { // return getLink(JSONAPISpecConstants.FIRST); // } // // /** // * Convenience method for returning the {@code next} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getNext() { // return getLink(JSONAPISpecConstants.NEXT); // } // // /** // * Convenience method for returning the {@code last} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getLast() { // return getLink(JSONAPISpecConstants.LAST); // } // // /** // * Convenience method for returning the {@code self} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getSelf() { // return getLink(JSONAPISpecConstants.SELF); // } // // /** // * Convenience method for returning the {@code related} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getRelated() { // return getLink(JSONAPISpecConstants.RELATED); // } // // /** // * Gets all registered links. // * @return {@link Map} link data // */ // public Map<String, Link> getLinks() { // return new LinkedHashMap<>(links); // } // // /** // * Adds a named link. // * // * @param linkName name of the link to add // * @param link the link to add // */ // public void addLink(String linkName, Link link) { // links.put(linkName, link); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // }
import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.github.jasminb.jsonapi.Links; import com.github.jasminb.jsonapi.RelType; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.RelationshipLinks; import com.github.jasminb.jsonapi.annotations.Type; import java.util.Collections; import java.util.List;
package com.github.jasminb.jsonapi.models; @Type("articles") @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") public class Article { @Id private String id; private String title; @Relationship(value = "author", resolve = true, relType = RelType.RELATED) private Author author; @Relationship(value = "comments", resolve = true) private List<Comment> comments; @Relationship(value = "users", serialiseData = false) private List<User> users; @RelationshipLinks(value = "users")
// Path: src/main/java/com/github/jasminb/jsonapi/Links.java // public class Links implements Serializable { // private static final long serialVersionUID = 1305238708279094084L; // // /** // * A map of link objects keyed by link name. // */ // private Map<String, Link> links; // // /** // * Create new Links. // */ // public Links() { // this.links = new LinkedHashMap<>(); // } // // /** // * Create new Links. // * @param linkMap {@link Map} link data // */ // public Links(Map<String, Link> linkMap) { // this.links = new LinkedHashMap<>(linkMap); // } // // /** // * Convenience method for returning named link. // * @param linkName name of the link to return // * @return the link object, or {@code null} if the named link does not exist // */ // public Link getLink(String linkName) { // return links.get(linkName); // } // // /** // * Convenience method for returning the {@code prev} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getPrevious() { // return getLink(JSONAPISpecConstants.PREV); // } // // /** // * Convenience method for returning the {@code first} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getFirst() { // return getLink(JSONAPISpecConstants.FIRST); // } // // /** // * Convenience method for returning the {@code next} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getNext() { // return getLink(JSONAPISpecConstants.NEXT); // } // // /** // * Convenience method for returning the {@code last} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getLast() { // return getLink(JSONAPISpecConstants.LAST); // } // // /** // * Convenience method for returning the {@code self} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getSelf() { // return getLink(JSONAPISpecConstants.SELF); // } // // /** // * Convenience method for returning the {@code related} link. // * // * @return the link, or {@code null} if the named link does not exist // */ // @JsonIgnore // public Link getRelated() { // return getLink(JSONAPISpecConstants.RELATED); // } // // /** // * Gets all registered links. // * @return {@link Map} link data // */ // public Map<String, Link> getLinks() { // return new LinkedHashMap<>(links); // } // // /** // * Adds a named link. // * // * @param linkName name of the link to add // * @param link the link to add // */ // public void addLink(String linkName, Link link) { // links.put(linkName, link); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/models/Article.java import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.github.jasminb.jsonapi.Links; import com.github.jasminb.jsonapi.RelType; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.RelationshipLinks; import com.github.jasminb.jsonapi.annotations.Type; import java.util.Collections; import java.util.List; package com.github.jasminb.jsonapi.models; @Type("articles") @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "id") public class Article { @Id private String id; private String title; @Relationship(value = "author", resolve = true, relType = RelType.RELATED) private Author author; @Relationship(value = "comments", resolve = true) private List<Comment> comments; @Relationship(value = "users", serialiseData = false) private List<User> users; @RelationshipLinks(value = "users")
private Links userRelationshipLinks;
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java
// Path: src/main/java/com/github/jasminb/jsonapi/LongIdHandler.java // public class LongIdHandler implements ResourceIdHandler { // // /** // * Creates new LongIdHandler. // * // */ // public LongIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public Long fromString(String source) { // if (source != null) { // return Long.valueOf(source); // } // return null; // } // }
import com.github.jasminb.jsonapi.LongIdHandler; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Type;
package com.github.jasminb.jsonapi.models; /** * Model class used to test {@link Long} as resource identifier. * * @author jbegic */ @Type("long-id-type") public class LongIdResource {
// Path: src/main/java/com/github/jasminb/jsonapi/LongIdHandler.java // public class LongIdHandler implements ResourceIdHandler { // // /** // * Creates new LongIdHandler. // * // */ // public LongIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public Long fromString(String source) { // if (source != null) { // return Long.valueOf(source); // } // return null; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/models/LongIdResource.java import com.github.jasminb.jsonapi.LongIdHandler; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Type; package com.github.jasminb.jsonapi.models; /** * Model class used to test {@link Long} as resource identifier. * * @author jbegic */ @Type("long-id-type") public class LongIdResource {
@Id(LongIdHandler.class)
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/annotations/Id.java
// Path: src/main/java/com/github/jasminb/jsonapi/ResourceIdHandler.java // public interface ResourceIdHandler { // // /** // * Convert identifier to {@link String}. // * // * @param identifier to convert // * @return {@link String} identifier string representation // */ // String asString(Object identifier); // // /** // * Create identifier object by consuming its string representation. // * // * @param source {@link String} identifier // * @return target object // */ // Object fromString(String source); // } // // Path: src/main/java/com/github/jasminb/jsonapi/StringIdHandler.java // public class StringIdHandler implements ResourceIdHandler { // // /** // * Creates new StringIdHandler. // * // */ // public StringIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public String fromString(String source) { // return source; // } // }
import com.github.jasminb.jsonapi.ResourceIdHandler; import com.github.jasminb.jsonapi.StringIdHandler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package com.github.jasminb.jsonapi.annotations; /** * Annotation used to mark resource field as an id in JSON API resource class. * * @author jbegic */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Id {
// Path: src/main/java/com/github/jasminb/jsonapi/ResourceIdHandler.java // public interface ResourceIdHandler { // // /** // * Convert identifier to {@link String}. // * // * @param identifier to convert // * @return {@link String} identifier string representation // */ // String asString(Object identifier); // // /** // * Create identifier object by consuming its string representation. // * // * @param source {@link String} identifier // * @return target object // */ // Object fromString(String source); // } // // Path: src/main/java/com/github/jasminb/jsonapi/StringIdHandler.java // public class StringIdHandler implements ResourceIdHandler { // // /** // * Creates new StringIdHandler. // * // */ // public StringIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public String fromString(String source) { // return source; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/annotations/Id.java import com.github.jasminb.jsonapi.ResourceIdHandler; import com.github.jasminb.jsonapi.StringIdHandler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package com.github.jasminb.jsonapi.annotations; /** * Annotation used to mark resource field as an id in JSON API resource class. * * @author jbegic */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Id {
Class<? extends ResourceIdHandler> value() default StringIdHandler.class;
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/annotations/Id.java
// Path: src/main/java/com/github/jasminb/jsonapi/ResourceIdHandler.java // public interface ResourceIdHandler { // // /** // * Convert identifier to {@link String}. // * // * @param identifier to convert // * @return {@link String} identifier string representation // */ // String asString(Object identifier); // // /** // * Create identifier object by consuming its string representation. // * // * @param source {@link String} identifier // * @return target object // */ // Object fromString(String source); // } // // Path: src/main/java/com/github/jasminb/jsonapi/StringIdHandler.java // public class StringIdHandler implements ResourceIdHandler { // // /** // * Creates new StringIdHandler. // * // */ // public StringIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public String fromString(String source) { // return source; // } // }
import com.github.jasminb.jsonapi.ResourceIdHandler; import com.github.jasminb.jsonapi.StringIdHandler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package com.github.jasminb.jsonapi.annotations; /** * Annotation used to mark resource field as an id in JSON API resource class. * * @author jbegic */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Id {
// Path: src/main/java/com/github/jasminb/jsonapi/ResourceIdHandler.java // public interface ResourceIdHandler { // // /** // * Convert identifier to {@link String}. // * // * @param identifier to convert // * @return {@link String} identifier string representation // */ // String asString(Object identifier); // // /** // * Create identifier object by consuming its string representation. // * // * @param source {@link String} identifier // * @return target object // */ // Object fromString(String source); // } // // Path: src/main/java/com/github/jasminb/jsonapi/StringIdHandler.java // public class StringIdHandler implements ResourceIdHandler { // // /** // * Creates new StringIdHandler. // * // */ // public StringIdHandler() { // // Default constructor // } // // @Override // public String asString(Object identifier) { // if (identifier != null) { // return String.valueOf(identifier); // } // return null; // } // // @Override // public String fromString(String source) { // return source; // } // } // Path: src/main/java/com/github/jasminb/jsonapi/annotations/Id.java import com.github.jasminb.jsonapi.ResourceIdHandler; import com.github.jasminb.jsonapi.StringIdHandler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package com.github.jasminb.jsonapi.annotations; /** * Annotation used to mark resource field as an id in JSON API resource class. * * @author jbegic */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Id {
Class<? extends ResourceIdHandler> value() default StringIdHandler.class;
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/ValidationUtilsTest.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException;
package com.github.jasminb.jsonapi; /** * Covering cases for validation utility class. * * @author jbegic */ public class ValidationUtilsTest { private ObjectMapper mapper; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setup() { mapper = new ObjectMapper(); } //ensureValidDocument
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/ValidationUtilsTest.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; package com.github.jasminb.jsonapi; /** * Covering cases for validation utility class. * * @author jbegic */ public class ValidationUtilsTest { private ObjectMapper mapper; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setup() { mapper = new ObjectMapper(); } //ensureValidDocument
@Test(expected = InvalidJsonApiResourceException.class)
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/ValidationUtilsTest.java
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException;
package com.github.jasminb.jsonapi; /** * Covering cases for validation utility class. * * @author jbegic */ public class ValidationUtilsTest { private ObjectMapper mapper; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setup() { mapper = new ObjectMapper(); } //ensureValidDocument @Test(expected = InvalidJsonApiResourceException.class) public void testExpectData() throws IOException { JsonNode node = mapper.readTree("{}"); ValidationUtils.ensureValidDocument(mapper, node); }
// Path: src/main/java/com/github/jasminb/jsonapi/exceptions/InvalidJsonApiResourceException.java // public class InvalidJsonApiResourceException extends RuntimeException { // // /** // * Creates a new InvalidJsonApiResourceException. // */ // public InvalidJsonApiResourceException() { // super("Resource must contain at least one of 'data', 'error' or 'meta' nodes."); // } // // /** // * Creates a new InvalidJsonApiResourceException. // * // * @param errorMessage detail message containing spec for resource that was invalid. // */ // public InvalidJsonApiResourceException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/github/jasminb/jsonapi/exceptions/ResourceParseException.java // public class ResourceParseException extends RuntimeException { // private final Errors errors; // // public ResourceParseException(Errors errors) { // super(errors.toString()); // this.errors = errors; // } // // /** // * Returns Errors or <code>null</code> // * @return {@link Errors} // */ // public Errors getErrors() { // return errors; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/ValidationUtilsTest.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; import com.github.jasminb.jsonapi.exceptions.InvalidJsonApiResourceException; import com.github.jasminb.jsonapi.exceptions.ResourceParseException; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; package com.github.jasminb.jsonapi; /** * Covering cases for validation utility class. * * @author jbegic */ public class ValidationUtilsTest { private ObjectMapper mapper; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setup() { mapper = new ObjectMapper(); } //ensureValidDocument @Test(expected = InvalidJsonApiResourceException.class) public void testExpectData() throws IOException { JsonNode node = mapper.readTree("{}"); ValidationUtils.ensureValidDocument(mapper, node); }
@Test(expected = ResourceParseException.class)
jasminb/jsonapi-converter
src/test/java/com/github/jasminb/jsonapi/models/RecursingNode.java
// Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // }
import com.github.jasminb.jsonapi.RelType; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Type;
package com.github.jasminb.jsonapi.models; /** * A test class that has a parent. */ @Type("node") public class RecursingNode { @Id private String id; private String name; private String url;
// Path: src/main/java/com/github/jasminb/jsonapi/RelType.java // public enum RelType { // // SELF (JSONAPISpecConstants.SELF), // // RELATED (JSONAPISpecConstants.RELATED); // // private String relName; // // RelType(String relName) { // this.relName = relName; // } // // /** // * Obtains the name of the relationship, suitable for use in serialized JSON. // * // * @return the relationship name // */ // public String getRelName() { // return relName; // } // } // Path: src/test/java/com/github/jasminb/jsonapi/models/RecursingNode.java import com.github.jasminb.jsonapi.RelType; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Relationship; import com.github.jasminb.jsonapi.annotations.Type; package com.github.jasminb.jsonapi.models; /** * A test class that has a parent. */ @Type("node") public class RecursingNode { @Id private String id; private String name; private String url;
@Relationship(value = "parent", resolve = true, relType = RelType.RELATED)
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/util/SituationCast.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java // public interface SituationType extends Type { // public String getName(); // public List<? extends Part> getParts(); // //public List<Bind> getBinds(); // public List<? extends Snapshot> getSnapshots(); // // }
import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import br.ufes.inf.lprm.situation.model.SituationType; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.spi.Activation; import java.util.*;
package br.ufes.inf.lprm.scene.util; @SuppressWarnings("serial") public class SituationCast extends HashMap<String, Object> { private int hash = 17;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java // public interface SituationType extends Type { // public String getName(); // public List<? extends Part> getParts(); // //public List<Bind> getBinds(); // public List<? extends Snapshot> getSnapshots(); // // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/SituationCast.java import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import br.ufes.inf.lprm.situation.model.SituationType; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.spi.Activation; import java.util.*; package br.ufes.inf.lprm.scene.util; @SuppressWarnings("serial") public class SituationCast extends HashMap<String, Object> { private int hash = 17;
public SituationCast(Activation activation, SituationType type) throws Exception {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/util/SituationCast.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java // public interface SituationType extends Type { // public String getName(); // public List<? extends Part> getParts(); // //public List<Bind> getBinds(); // public List<? extends Snapshot> getSnapshots(); // // }
import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import br.ufes.inf.lprm.situation.model.SituationType; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.spi.Activation; import java.util.*;
package br.ufes.inf.lprm.scene.util; @SuppressWarnings("serial") public class SituationCast extends HashMap<String, Object> { private int hash = 17; public SituationCast(Activation activation, SituationType type) throws Exception { int counter; String roleLabel; Object obj; RuleImpl rule = activation.getRule(); //List<Part> parts = type.getParts();
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java // public interface SituationType extends Type { // public String getName(); // public List<? extends Part> getParts(); // //public List<Bind> getBinds(); // public List<? extends Snapshot> getSnapshots(); // // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/SituationCast.java import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import br.ufes.inf.lprm.situation.model.SituationType; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.spi.Activation; import java.util.*; package br.ufes.inf.lprm.scene.util; @SuppressWarnings("serial") public class SituationCast extends HashMap<String, Object> { private int hash = 17; public SituationCast(Activation activation, SituationType type) throws Exception { int counter; String roleLabel; Object obj; RuleImpl rule = activation.getRule(); //List<Part> parts = type.getParts();
for(Part p: type.getParts()) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/util/SituationCast.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java // public interface SituationType extends Type { // public String getName(); // public List<? extends Part> getParts(); // //public List<Bind> getBinds(); // public List<? extends Snapshot> getSnapshots(); // // }
import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import br.ufes.inf.lprm.situation.model.SituationType; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.spi.Activation; import java.util.*;
package br.ufes.inf.lprm.scene.util; @SuppressWarnings("serial") public class SituationCast extends HashMap<String, Object> { private int hash = 17; public SituationCast(Activation activation, SituationType type) throws Exception { int counter; String roleLabel; Object obj; RuleImpl rule = activation.getRule(); //List<Part> parts = type.getParts(); for(Part p: type.getParts()) { put(p.getLabel(), activation.getDeclarationValue(p.getLabel()), p.isKey()); }
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java // public interface SituationType extends Type { // public String getName(); // public List<? extends Part> getParts(); // //public List<Bind> getBinds(); // public List<? extends Snapshot> getSnapshots(); // // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/SituationCast.java import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import br.ufes.inf.lprm.situation.model.SituationType; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.spi.Activation; import java.util.*; package br.ufes.inf.lprm.scene.util; @SuppressWarnings("serial") public class SituationCast extends HashMap<String, Object> { private int hash = 17; public SituationCast(Activation activation, SituationType type) throws Exception { int counter; String roleLabel; Object obj; RuleImpl rule = activation.getRule(); //List<Part> parts = type.getParts(); for(Part p: type.getParts()) { put(p.getLabel(), activation.getDeclarationValue(p.getLabel()), p.isKey()); }
for(Snapshot s: type.getSnapshots()) {
pextralabs/scene-platform
scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/event/Event.java
// Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/TemporalEntity.java // public interface TemporalEntity { // public String getId(); // public boolean isFinished(); // public long getStart(); // public long getEnd(); // public Type getTemporalType(); // // public enum Type { // EVENT, SITUATION // } // // }
import br.ufes.inf.lprm.scene.test.temporal.model.TemporalEntity; import org.kie.api.definition.type.Duration; import org.kie.api.definition.type.Role; import org.kie.api.definition.type.Timestamp; import java.io.Serializable;
package br.ufes.inf.lprm.scene.test.temporal.model.event; @Role(Role.Type.EVENT) @Timestamp("start") @Duration("duration")
// Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/TemporalEntity.java // public interface TemporalEntity { // public String getId(); // public boolean isFinished(); // public long getStart(); // public long getEnd(); // public Type getTemporalType(); // // public enum Type { // EVENT, SITUATION // } // // } // Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/event/Event.java import br.ufes.inf.lprm.scene.test.temporal.model.TemporalEntity; import org.kie.api.definition.type.Duration; import org.kie.api.definition.type.Role; import org.kie.api.definition.type.Timestamp; import java.io.Serializable; package br.ufes.inf.lprm.scene.test.temporal.model.event; @Role(Role.Type.EVENT) @Timestamp("start") @Duration("duration")
public class Event implements Serializable, TemporalEntity {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/listeners/SCENESessionListener.java
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java // public class OnGoingSituation { // // private int currentId; // private SituationCast cast; // private br.ufes.inf.lprm.situation.model.SituationType type; // private String typename; // private Situation situation; // private long timestamp; // private int hashcode; // // public OnGoingSituation(br.ufes.inf.lprm.situation.model.SituationType type, long timestamp, SituationCast cast) { // this.currentId = ((SituationType) type).getTypeClass().hashCode() + cast.hashCode(); // this.hashcode = cast.hashCode(); // this.cast = cast; // this.type = type; // this.typename = type.getName(); // this.timestamp = timestamp; // } // // public SituationCast getCast() { // return cast; // } // public br.ufes.inf.lprm.situation.model.SituationType getType() { // return type; // } // // public void setSituation(Situation situation) { // this.situation = situation; // } // public Situation getSituation() { // return situation; // } // // @Override // public boolean equals(Object obj) { // // if (obj == null) { // return false; // } // else { // if ( !(obj instanceof OnGoingSituation) ) { // return false; // } // else { // return this.type.equals(((OnGoingSituation) obj).getType()) && this.cast.equals(((OnGoingSituation) obj).getCast()); // // } // } // } // @Override // public int hashCode() { // return this.currentId; // } // // public long getTimestamp() { // return timestamp; // } // // public int getHashcode() { // return hashcode; // } // // public void setHashcode(int hashcode) { // this.hashcode = hashcode; // } // // public String getTypename() { // return typename; // } // // public void setTypename(String typename) { // this.typename = typename; // } // // public String toString() { // // StringBuilder str = new StringBuilder(); // str.append("TYPE: "); // str.append(typename); // str.append("\t"); // str.append("ID: "); // str.append(currentId); // str.append("\t"); // str.append("CAST: "); // str.append(this.cast.toString()); // // return str.toString(); // // } // // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/logging/SCENELogger.java // public class SCENELogger { // // public static Logger logger = LoggerFactory.getLogger(SCENELogger.class); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/events/SituationEvent.java // public interface SituationEvent { // // public long getTimestamp(); // public Situation getSituation(); // // }
import br.ufes.inf.lprm.scene.util.OnGoingSituation; import br.ufes.inf.lprm.scene.base.logging.SCENELogger; import br.ufes.inf.lprm.situation.model.events.SituationEvent; import org.kie.api.event.rule.DefaultRuleRuntimeEventListener; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; import org.slf4j.Logger;
package br.ufes.inf.lprm.scene.base.listeners; public class SCENESessionListener extends DefaultRuleRuntimeEventListener { Logger logger = SCENELogger.logger; public SCENESessionListener() { this.logger = SCENELogger.logger; } public SCENESessionListener(Logger logger) { this.logger = logger; } @Override public void objectInserted(ObjectInsertedEvent event) { Object in = event.getObject();
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java // public class OnGoingSituation { // // private int currentId; // private SituationCast cast; // private br.ufes.inf.lprm.situation.model.SituationType type; // private String typename; // private Situation situation; // private long timestamp; // private int hashcode; // // public OnGoingSituation(br.ufes.inf.lprm.situation.model.SituationType type, long timestamp, SituationCast cast) { // this.currentId = ((SituationType) type).getTypeClass().hashCode() + cast.hashCode(); // this.hashcode = cast.hashCode(); // this.cast = cast; // this.type = type; // this.typename = type.getName(); // this.timestamp = timestamp; // } // // public SituationCast getCast() { // return cast; // } // public br.ufes.inf.lprm.situation.model.SituationType getType() { // return type; // } // // public void setSituation(Situation situation) { // this.situation = situation; // } // public Situation getSituation() { // return situation; // } // // @Override // public boolean equals(Object obj) { // // if (obj == null) { // return false; // } // else { // if ( !(obj instanceof OnGoingSituation) ) { // return false; // } // else { // return this.type.equals(((OnGoingSituation) obj).getType()) && this.cast.equals(((OnGoingSituation) obj).getCast()); // // } // } // } // @Override // public int hashCode() { // return this.currentId; // } // // public long getTimestamp() { // return timestamp; // } // // public int getHashcode() { // return hashcode; // } // // public void setHashcode(int hashcode) { // this.hashcode = hashcode; // } // // public String getTypename() { // return typename; // } // // public void setTypename(String typename) { // this.typename = typename; // } // // public String toString() { // // StringBuilder str = new StringBuilder(); // str.append("TYPE: "); // str.append(typename); // str.append("\t"); // str.append("ID: "); // str.append(currentId); // str.append("\t"); // str.append("CAST: "); // str.append(this.cast.toString()); // // return str.toString(); // // } // // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/logging/SCENELogger.java // public class SCENELogger { // // public static Logger logger = LoggerFactory.getLogger(SCENELogger.class); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/events/SituationEvent.java // public interface SituationEvent { // // public long getTimestamp(); // public Situation getSituation(); // // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/listeners/SCENESessionListener.java import br.ufes.inf.lprm.scene.util.OnGoingSituation; import br.ufes.inf.lprm.scene.base.logging.SCENELogger; import br.ufes.inf.lprm.situation.model.events.SituationEvent; import org.kie.api.event.rule.DefaultRuleRuntimeEventListener; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; import org.slf4j.Logger; package br.ufes.inf.lprm.scene.base.listeners; public class SCENESessionListener extends DefaultRuleRuntimeEventListener { Logger logger = SCENELogger.logger; public SCENESessionListener() { this.logger = SCENELogger.logger; } public SCENESessionListener(Logger logger) { this.logger = logger; } @Override public void objectInserted(ObjectInsertedEvent event) { Object in = event.getObject();
if (in instanceof OnGoingSituation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/listeners/SCENESessionListener.java
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java // public class OnGoingSituation { // // private int currentId; // private SituationCast cast; // private br.ufes.inf.lprm.situation.model.SituationType type; // private String typename; // private Situation situation; // private long timestamp; // private int hashcode; // // public OnGoingSituation(br.ufes.inf.lprm.situation.model.SituationType type, long timestamp, SituationCast cast) { // this.currentId = ((SituationType) type).getTypeClass().hashCode() + cast.hashCode(); // this.hashcode = cast.hashCode(); // this.cast = cast; // this.type = type; // this.typename = type.getName(); // this.timestamp = timestamp; // } // // public SituationCast getCast() { // return cast; // } // public br.ufes.inf.lprm.situation.model.SituationType getType() { // return type; // } // // public void setSituation(Situation situation) { // this.situation = situation; // } // public Situation getSituation() { // return situation; // } // // @Override // public boolean equals(Object obj) { // // if (obj == null) { // return false; // } // else { // if ( !(obj instanceof OnGoingSituation) ) { // return false; // } // else { // return this.type.equals(((OnGoingSituation) obj).getType()) && this.cast.equals(((OnGoingSituation) obj).getCast()); // // } // } // } // @Override // public int hashCode() { // return this.currentId; // } // // public long getTimestamp() { // return timestamp; // } // // public int getHashcode() { // return hashcode; // } // // public void setHashcode(int hashcode) { // this.hashcode = hashcode; // } // // public String getTypename() { // return typename; // } // // public void setTypename(String typename) { // this.typename = typename; // } // // public String toString() { // // StringBuilder str = new StringBuilder(); // str.append("TYPE: "); // str.append(typename); // str.append("\t"); // str.append("ID: "); // str.append(currentId); // str.append("\t"); // str.append("CAST: "); // str.append(this.cast.toString()); // // return str.toString(); // // } // // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/logging/SCENELogger.java // public class SCENELogger { // // public static Logger logger = LoggerFactory.getLogger(SCENELogger.class); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/events/SituationEvent.java // public interface SituationEvent { // // public long getTimestamp(); // public Situation getSituation(); // // }
import br.ufes.inf.lprm.scene.util.OnGoingSituation; import br.ufes.inf.lprm.scene.base.logging.SCENELogger; import br.ufes.inf.lprm.situation.model.events.SituationEvent; import org.kie.api.event.rule.DefaultRuleRuntimeEventListener; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; import org.slf4j.Logger;
package br.ufes.inf.lprm.scene.base.listeners; public class SCENESessionListener extends DefaultRuleRuntimeEventListener { Logger logger = SCENELogger.logger; public SCENESessionListener() { this.logger = SCENELogger.logger; } public SCENESessionListener(Logger logger) { this.logger = logger; } @Override public void objectInserted(ObjectInsertedEvent event) { Object in = event.getObject(); if (in instanceof OnGoingSituation) { logger.debug("SITUATION ACTIVATION - " + in.toString());
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java // public class OnGoingSituation { // // private int currentId; // private SituationCast cast; // private br.ufes.inf.lprm.situation.model.SituationType type; // private String typename; // private Situation situation; // private long timestamp; // private int hashcode; // // public OnGoingSituation(br.ufes.inf.lprm.situation.model.SituationType type, long timestamp, SituationCast cast) { // this.currentId = ((SituationType) type).getTypeClass().hashCode() + cast.hashCode(); // this.hashcode = cast.hashCode(); // this.cast = cast; // this.type = type; // this.typename = type.getName(); // this.timestamp = timestamp; // } // // public SituationCast getCast() { // return cast; // } // public br.ufes.inf.lprm.situation.model.SituationType getType() { // return type; // } // // public void setSituation(Situation situation) { // this.situation = situation; // } // public Situation getSituation() { // return situation; // } // // @Override // public boolean equals(Object obj) { // // if (obj == null) { // return false; // } // else { // if ( !(obj instanceof OnGoingSituation) ) { // return false; // } // else { // return this.type.equals(((OnGoingSituation) obj).getType()) && this.cast.equals(((OnGoingSituation) obj).getCast()); // // } // } // } // @Override // public int hashCode() { // return this.currentId; // } // // public long getTimestamp() { // return timestamp; // } // // public int getHashcode() { // return hashcode; // } // // public void setHashcode(int hashcode) { // this.hashcode = hashcode; // } // // public String getTypename() { // return typename; // } // // public void setTypename(String typename) { // this.typename = typename; // } // // public String toString() { // // StringBuilder str = new StringBuilder(); // str.append("TYPE: "); // str.append(typename); // str.append("\t"); // str.append("ID: "); // str.append(currentId); // str.append("\t"); // str.append("CAST: "); // str.append(this.cast.toString()); // // return str.toString(); // // } // // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/logging/SCENELogger.java // public class SCENELogger { // // public static Logger logger = LoggerFactory.getLogger(SCENELogger.class); // // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/events/SituationEvent.java // public interface SituationEvent { // // public long getTimestamp(); // public Situation getSituation(); // // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/listeners/SCENESessionListener.java import br.ufes.inf.lprm.scene.util.OnGoingSituation; import br.ufes.inf.lprm.scene.base.logging.SCENELogger; import br.ufes.inf.lprm.situation.model.events.SituationEvent; import org.kie.api.event.rule.DefaultRuleRuntimeEventListener; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; import org.slf4j.Logger; package br.ufes.inf.lprm.scene.base.listeners; public class SCENESessionListener extends DefaultRuleRuntimeEventListener { Logger logger = SCENELogger.logger; public SCENESessionListener() { this.logger = SCENELogger.logger; } public SCENESessionListener(Logger logger) { this.logger = logger; } @Override public void objectInserted(ObjectInsertedEvent event) { Object in = event.getObject(); if (in instanceof OnGoingSituation) { logger.debug("SITUATION ACTIVATION - " + in.toString());
} else if (in instanceof SituationEvent) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/SituationType.java // public class SituationType implements br.ufes.inf.lprm.situation.model.SituationType { // // private Class clazz; // private List<Part> parts; // private List<Snapshot> snapshots; // private Map<String, Part> mappedParts; // private Map<String, Snapshot> mappedSnapshots; // // public SituationType(Class<?> clazz, List<Part> parts, List<Snapshot> snapshots) { // this.clazz = clazz; // this.parts = parts; // this.snapshots = snapshots; // mappedParts = new HashMap<String, Part>(); // for (Part part: this.parts) { // mappedParts.put(part.getLabel(), part); // } // mappedSnapshots = new HashMap<String, Snapshot>(); // for (Snapshot snapshot: this.snapshots) { // mappedSnapshots.put(snapshot.getLabel(), snapshot); // } // } // // @Override // public String getName() { // return clazz.getName(); // } // // public Class getTypeClass() { // return clazz; // } // // @Override // public List<Part> getParts() { // return parts; // } // // @Override // public List<Snapshot> getSnapshots() { // return snapshots; // } // // public Part getPart(String label) { // return mappedParts.get(label); // } // // public Situation newInstance(Activation activation, SituationCast cast) { // try { // //Field fInternalKey = Situation.class.getDeclaredField("internalKey"); // Field fRunningId = Situation.class.getDeclaredField("runningId"); // Field fActivation = Situation.class.getDeclaredField("activation"); // Field fType = Situation.class.getDeclaredField("type"); // Field fParticipations = Situation.class.getDeclaredField("participations"); // Field fActive = Situation.class.getDeclaredField("active"); // // //fInternalKey.setAccessible(true); // fRunningId.setAccessible(true); // fActivation.setAccessible(true); // fType.setAccessible(true); // fParticipations.setAccessible(true); // fActive.setAccessible(true); // // Situation situation = (Situation) clazz.newInstance(); // // //fInternalKey.set(situation, UUID.randomUUID().toString()); // fRunningId.setInt(situation, this.getTypeClass().hashCode() + cast.hashCode()); // fType.set(situation, this); // fActivation.set(situation, activation); // fActive.set(situation, true); // // List<br.ufes.inf.lprm.situation.model.Participation> participations = new ArrayList<br.ufes.inf.lprm.situation.model.Participation>(); // // for(Part part: getParts()) { // Object participant = cast.get(part.getLabel()); // if (participant != null) { // br.ufes.inf.lprm.situation.model.Participation participation = new Participation(situation, part, participant); // participations.add(participation); // } // } // fParticipations.set(situation, participations); // // for(Snapshot snapshot: getSnapshots()) { // Object obj = cast.get(snapshot.getLabel()); // ((br.ufes.inf.lprm.scene.model.Snapshot) snapshot).set(situation, obj); // } // // //fInternalKey.setAccessible(false); // fRunningId.setAccessible(false); // fActivation.setAccessible(false); // fType.setAccessible(false); // fParticipations.setAccessible(false); // fActive.setAccessible(false); // // return situation; // // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // return null; // } // // public String toString() { // return clazz.getSimpleName(); // } // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.scene.model.SituationType; import br.ufes.inf.lprm.situation.model.Situation;
package br.ufes.inf.lprm.scene.util; public class OnGoingSituation { private int currentId; private SituationCast cast;
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/SituationType.java // public class SituationType implements br.ufes.inf.lprm.situation.model.SituationType { // // private Class clazz; // private List<Part> parts; // private List<Snapshot> snapshots; // private Map<String, Part> mappedParts; // private Map<String, Snapshot> mappedSnapshots; // // public SituationType(Class<?> clazz, List<Part> parts, List<Snapshot> snapshots) { // this.clazz = clazz; // this.parts = parts; // this.snapshots = snapshots; // mappedParts = new HashMap<String, Part>(); // for (Part part: this.parts) { // mappedParts.put(part.getLabel(), part); // } // mappedSnapshots = new HashMap<String, Snapshot>(); // for (Snapshot snapshot: this.snapshots) { // mappedSnapshots.put(snapshot.getLabel(), snapshot); // } // } // // @Override // public String getName() { // return clazz.getName(); // } // // public Class getTypeClass() { // return clazz; // } // // @Override // public List<Part> getParts() { // return parts; // } // // @Override // public List<Snapshot> getSnapshots() { // return snapshots; // } // // public Part getPart(String label) { // return mappedParts.get(label); // } // // public Situation newInstance(Activation activation, SituationCast cast) { // try { // //Field fInternalKey = Situation.class.getDeclaredField("internalKey"); // Field fRunningId = Situation.class.getDeclaredField("runningId"); // Field fActivation = Situation.class.getDeclaredField("activation"); // Field fType = Situation.class.getDeclaredField("type"); // Field fParticipations = Situation.class.getDeclaredField("participations"); // Field fActive = Situation.class.getDeclaredField("active"); // // //fInternalKey.setAccessible(true); // fRunningId.setAccessible(true); // fActivation.setAccessible(true); // fType.setAccessible(true); // fParticipations.setAccessible(true); // fActive.setAccessible(true); // // Situation situation = (Situation) clazz.newInstance(); // // //fInternalKey.set(situation, UUID.randomUUID().toString()); // fRunningId.setInt(situation, this.getTypeClass().hashCode() + cast.hashCode()); // fType.set(situation, this); // fActivation.set(situation, activation); // fActive.set(situation, true); // // List<br.ufes.inf.lprm.situation.model.Participation> participations = new ArrayList<br.ufes.inf.lprm.situation.model.Participation>(); // // for(Part part: getParts()) { // Object participant = cast.get(part.getLabel()); // if (participant != null) { // br.ufes.inf.lprm.situation.model.Participation participation = new Participation(situation, part, participant); // participations.add(participation); // } // } // fParticipations.set(situation, participations); // // for(Snapshot snapshot: getSnapshots()) { // Object obj = cast.get(snapshot.getLabel()); // ((br.ufes.inf.lprm.scene.model.Snapshot) snapshot).set(situation, obj); // } // // //fInternalKey.setAccessible(false); // fRunningId.setAccessible(false); // fActivation.setAccessible(false); // fType.setAccessible(false); // fParticipations.setAccessible(false); // fActive.setAccessible(false); // // return situation; // // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // return null; // } // // public String toString() { // return clazz.getSimpleName(); // } // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java import br.ufes.inf.lprm.scene.model.SituationType; import br.ufes.inf.lprm.situation.model.Situation; package br.ufes.inf.lprm.scene.util; public class OnGoingSituation { private int currentId; private SituationCast cast;
private br.ufes.inf.lprm.situation.model.SituationType type;
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/SituationType.java // public class SituationType implements br.ufes.inf.lprm.situation.model.SituationType { // // private Class clazz; // private List<Part> parts; // private List<Snapshot> snapshots; // private Map<String, Part> mappedParts; // private Map<String, Snapshot> mappedSnapshots; // // public SituationType(Class<?> clazz, List<Part> parts, List<Snapshot> snapshots) { // this.clazz = clazz; // this.parts = parts; // this.snapshots = snapshots; // mappedParts = new HashMap<String, Part>(); // for (Part part: this.parts) { // mappedParts.put(part.getLabel(), part); // } // mappedSnapshots = new HashMap<String, Snapshot>(); // for (Snapshot snapshot: this.snapshots) { // mappedSnapshots.put(snapshot.getLabel(), snapshot); // } // } // // @Override // public String getName() { // return clazz.getName(); // } // // public Class getTypeClass() { // return clazz; // } // // @Override // public List<Part> getParts() { // return parts; // } // // @Override // public List<Snapshot> getSnapshots() { // return snapshots; // } // // public Part getPart(String label) { // return mappedParts.get(label); // } // // public Situation newInstance(Activation activation, SituationCast cast) { // try { // //Field fInternalKey = Situation.class.getDeclaredField("internalKey"); // Field fRunningId = Situation.class.getDeclaredField("runningId"); // Field fActivation = Situation.class.getDeclaredField("activation"); // Field fType = Situation.class.getDeclaredField("type"); // Field fParticipations = Situation.class.getDeclaredField("participations"); // Field fActive = Situation.class.getDeclaredField("active"); // // //fInternalKey.setAccessible(true); // fRunningId.setAccessible(true); // fActivation.setAccessible(true); // fType.setAccessible(true); // fParticipations.setAccessible(true); // fActive.setAccessible(true); // // Situation situation = (Situation) clazz.newInstance(); // // //fInternalKey.set(situation, UUID.randomUUID().toString()); // fRunningId.setInt(situation, this.getTypeClass().hashCode() + cast.hashCode()); // fType.set(situation, this); // fActivation.set(situation, activation); // fActive.set(situation, true); // // List<br.ufes.inf.lprm.situation.model.Participation> participations = new ArrayList<br.ufes.inf.lprm.situation.model.Participation>(); // // for(Part part: getParts()) { // Object participant = cast.get(part.getLabel()); // if (participant != null) { // br.ufes.inf.lprm.situation.model.Participation participation = new Participation(situation, part, participant); // participations.add(participation); // } // } // fParticipations.set(situation, participations); // // for(Snapshot snapshot: getSnapshots()) { // Object obj = cast.get(snapshot.getLabel()); // ((br.ufes.inf.lprm.scene.model.Snapshot) snapshot).set(situation, obj); // } // // //fInternalKey.setAccessible(false); // fRunningId.setAccessible(false); // fActivation.setAccessible(false); // fType.setAccessible(false); // fParticipations.setAccessible(false); // fActive.setAccessible(false); // // return situation; // // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // return null; // } // // public String toString() { // return clazz.getSimpleName(); // } // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.scene.model.SituationType; import br.ufes.inf.lprm.situation.model.Situation;
package br.ufes.inf.lprm.scene.util; public class OnGoingSituation { private int currentId; private SituationCast cast; private br.ufes.inf.lprm.situation.model.SituationType type; private String typename;
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/SituationType.java // public class SituationType implements br.ufes.inf.lprm.situation.model.SituationType { // // private Class clazz; // private List<Part> parts; // private List<Snapshot> snapshots; // private Map<String, Part> mappedParts; // private Map<String, Snapshot> mappedSnapshots; // // public SituationType(Class<?> clazz, List<Part> parts, List<Snapshot> snapshots) { // this.clazz = clazz; // this.parts = parts; // this.snapshots = snapshots; // mappedParts = new HashMap<String, Part>(); // for (Part part: this.parts) { // mappedParts.put(part.getLabel(), part); // } // mappedSnapshots = new HashMap<String, Snapshot>(); // for (Snapshot snapshot: this.snapshots) { // mappedSnapshots.put(snapshot.getLabel(), snapshot); // } // } // // @Override // public String getName() { // return clazz.getName(); // } // // public Class getTypeClass() { // return clazz; // } // // @Override // public List<Part> getParts() { // return parts; // } // // @Override // public List<Snapshot> getSnapshots() { // return snapshots; // } // // public Part getPart(String label) { // return mappedParts.get(label); // } // // public Situation newInstance(Activation activation, SituationCast cast) { // try { // //Field fInternalKey = Situation.class.getDeclaredField("internalKey"); // Field fRunningId = Situation.class.getDeclaredField("runningId"); // Field fActivation = Situation.class.getDeclaredField("activation"); // Field fType = Situation.class.getDeclaredField("type"); // Field fParticipations = Situation.class.getDeclaredField("participations"); // Field fActive = Situation.class.getDeclaredField("active"); // // //fInternalKey.setAccessible(true); // fRunningId.setAccessible(true); // fActivation.setAccessible(true); // fType.setAccessible(true); // fParticipations.setAccessible(true); // fActive.setAccessible(true); // // Situation situation = (Situation) clazz.newInstance(); // // //fInternalKey.set(situation, UUID.randomUUID().toString()); // fRunningId.setInt(situation, this.getTypeClass().hashCode() + cast.hashCode()); // fType.set(situation, this); // fActivation.set(situation, activation); // fActive.set(situation, true); // // List<br.ufes.inf.lprm.situation.model.Participation> participations = new ArrayList<br.ufes.inf.lprm.situation.model.Participation>(); // // for(Part part: getParts()) { // Object participant = cast.get(part.getLabel()); // if (participant != null) { // br.ufes.inf.lprm.situation.model.Participation participation = new Participation(situation, part, participant); // participations.add(participation); // } // } // fParticipations.set(situation, participations); // // for(Snapshot snapshot: getSnapshots()) { // Object obj = cast.get(snapshot.getLabel()); // ((br.ufes.inf.lprm.scene.model.Snapshot) snapshot).set(situation, obj); // } // // //fInternalKey.setAccessible(false); // fRunningId.setAccessible(false); // fActivation.setAccessible(false); // fType.setAccessible(false); // fParticipations.setAccessible(false); // fActive.setAccessible(false); // // return situation; // // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // return null; // } // // public String toString() { // return clazz.getSimpleName(); // } // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/util/OnGoingSituation.java import br.ufes.inf.lprm.scene.model.SituationType; import br.ufes.inf.lprm.situation.model.Situation; package br.ufes.inf.lprm.scene.util; public class OnGoingSituation { private int currentId; private SituationCast cast; private br.ufes.inf.lprm.situation.model.SituationType type; private String typename;
private Situation situation;
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/MetByEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.MetByEvaluatorDefinition; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction.LeftEndRightStartContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
try { Field finalRange = this.getClass().getSuperclass().getDeclaredField("finalRange"); finalRange.setAccessible(true); this.finalRange = finalRange.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, final InternalReadAccessor extractor, final InternalFactHandle object1, final FieldValue object2) { throw new RuntimeException( "The 'metby' operator can only be used to compare one event or situation event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftEndTS, rightStartTS; rightStartTS = ((LeftEndRightStartContextEntry)context).timestamp;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/MetByEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.MetByEvaluatorDefinition; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction.LeftEndRightStartContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; try { Field finalRange = this.getClass().getSuperclass().getDeclaredField("finalRange"); finalRange.setAccessible(true); this.finalRange = finalRange.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, final InternalReadAccessor extractor, final InternalFactHandle object1, final FieldValue object2) { throw new RuntimeException( "The 'metby' operator can only be used to compare one event or situation event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, final VariableContextEntry context, final InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftEndTS, rightStartTS; rightStartTS = ((LeftEndRightStartContextEntry)context).timestamp;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/situation/Situation.java
// Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/TemporalEntity.java // public interface TemporalEntity { // public String getId(); // public boolean isFinished(); // public long getStart(); // public long getEnd(); // public Type getTemporalType(); // // public enum Type { // EVENT, SITUATION // } // // } // // Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/event/Event.java // @Role(Role.Type.EVENT) // @Timestamp("start") // @Duration("duration") // public class Event implements Serializable, TemporalEntity { // // private static final long serialVersionUID = 1L; // private long start; // private long duration; // private boolean finished; // private String id; // // public Event(String id, long start, long duration) { // this.id = id; // this.start = start; // this.duration = duration; // } // // public long getStart() { // return start; // } // // public long getDuration() { // return duration; // } // // public String getId() { // return id; // } // // public boolean isFinished() { // return finished; // } // // public Event setFinished(boolean finished) { // this.finished = finished; // return this; // } // // public long getEnd() { // return start + duration; // } // // @Override // public TemporalEntity.Type getTemporalType() { // return Type.EVENT; // } // }
import br.ufes.inf.lprm.scene.test.temporal.model.TemporalEntity; import br.ufes.inf.lprm.scene.test.temporal.model.event.Event; import br.ufes.inf.lprm.situation.bindings.part; import org.kie.api.definition.type.Key;
package br.ufes.inf.lprm.scene.test.temporal.model.situation; public class Situation extends br.ufes.inf.lprm.scene.model.Situation implements TemporalEntity { @part @Key
// Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/TemporalEntity.java // public interface TemporalEntity { // public String getId(); // public boolean isFinished(); // public long getStart(); // public long getEnd(); // public Type getTemporalType(); // // public enum Type { // EVENT, SITUATION // } // // } // // Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/event/Event.java // @Role(Role.Type.EVENT) // @Timestamp("start") // @Duration("duration") // public class Event implements Serializable, TemporalEntity { // // private static final long serialVersionUID = 1L; // private long start; // private long duration; // private boolean finished; // private String id; // // public Event(String id, long start, long duration) { // this.id = id; // this.start = start; // this.duration = duration; // } // // public long getStart() { // return start; // } // // public long getDuration() { // return duration; // } // // public String getId() { // return id; // } // // public boolean isFinished() { // return finished; // } // // public Event setFinished(boolean finished) { // this.finished = finished; // return this; // } // // public long getEnd() { // return start + duration; // } // // @Override // public TemporalEntity.Type getTemporalType() { // return Type.EVENT; // } // } // Path: scene-core/src/test/java/br/ufes/inf/lprm/scene/test/temporal/model/situation/Situation.java import br.ufes.inf.lprm.scene.test.temporal.model.TemporalEntity; import br.ufes.inf.lprm.scene.test.temporal.model.event.Event; import br.ufes.inf.lprm.situation.bindings.part; import org.kie.api.definition.type.Key; package br.ufes.inf.lprm.scene.test.temporal.model.situation; public class Situation extends br.ufes.inf.lprm.scene.model.Situation implements TemporalEntity { @part @Key
private Event event;
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/StartsEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.StartsEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
} private void extractParams() { try { Field startDev = this.getClass().getSuperclass().getDeclaredField("startDev"); startDev.setAccessible(true); this.startDev = startDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'starts' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS; rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/StartsEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.StartsEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; } private void extractParams() { try { Field startDev = this.getClass().getSuperclass().getDeclaredField("startDev"); startDev.setAccessible(true); this.startDev = startDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'starts' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS; rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/StartedByEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.StartedByEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
} private void extractParams() { try { Field startDev = this.getClass().getSuperclass().getDeclaredField("startDev"); startDev.setAccessible(true); this.startDev = startDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'startedby' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS; rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/StartedByEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.StartedByEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; } private void extractParams() { try { Field startDev = this.getClass().getSuperclass().getDeclaredField("startDev"); startDev.setAccessible(true); this.startDev = startDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'startedby' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS; rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/IncludesEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.IncludesEvaluatorDefinition; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
startMaxDev.setAccessible(true); endMinDev.setAccessible(true); endMaxDev.setAccessible(true); this.startMinDev = startMinDev.getLong(this); this.startMaxDev = startMaxDev.getLong(this); this.endMinDev = 0;//endMinDev.getLong(this); this.endMaxDev = endMaxDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'includes' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/IncludesEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.IncludesEvaluatorDefinition; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; startMaxDev.setAccessible(true); endMinDev.setAccessible(true); endMaxDev.setAccessible(true); this.startMinDev = startMinDev.getLong(this); this.startMaxDev = startMaxDev.getLong(this); this.endMinDev = 0;//endMinDev.getLong(this); this.endMaxDev = endMaxDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'includes' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-examples/src/main/java/br/ufes/inf/lprm/scene/examples/fever/situations/NoFever.java
// Path: scene-examples/src/main/java/br/ufes/inf/lprm/scene/examples/fever/entities/Person.java // public class Person { // // private int id; // private String name; // private Temperature temperature; // // public int getId() { // return id; // } // // public Person setId(int id) { // this.id = id; // temperature = new Temperature(); // return this; // } // // public String getName() { // return name; // } // // public Person setName(String name) { // this.name = name; // return this; // } // // public Temperature getTemperature() { // return temperature; // } // // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Situation.java // public class Situation implements br.ufes.inf.lprm.situation.model.Situation { // @Key // private String internalKey; // private int runningId; // private Activation activation; // private Deactivation deactivation; // private Boolean active; // private SituationType type; // private List<br.ufes.inf.lprm.situation.model.Participation> participations; // // public Situation(SituationType type, Activation activation, SituationCast cast, boolean active) { // // this.runningId = ((br.ufes.inf.lprm.scene.model.SituationType) type).getTypeClass().hashCode() + cast.hashCode(); // this.type = type; // this.activation = activation; // this.active = active; // // participations = new ArrayList<>(); // // for(Part part: type.getParts()) { // Object participant = cast.get(part.getLabel()); // if (participant != null) { // br.ufes.inf.lprm.situation.model.Participation participation = new Participation(this, part, participant); // participations.add(participation); // } // } // } // // public Situation() { // this.active = true; // this.internalKey = UUID.randomUUID().toString(); // } // // public Situation(SituationType type, SituationCast cast, Activation activation) { // this(type, activation, cast, true); // } // // @Override // public long getUID() { // return runningId; // } // // @Override // public SituationEvent getActivation() { // return activation; // } // // @Override // public SituationEvent getDeactivation() { // return deactivation; // } // // public void setDeactivation(SituationEvent deactivation) { // this.deactivation = (Deactivation) deactivation; // this.active = false; // } // // @Override // public boolean isActive() { // return active; // } // // @Override // public List<br.ufes.inf.lprm.situation.model.Participation> getParticipations() { // return participations; // } // // @Override // public SituationType getType() { // return type; // } // // public String getInternalKey() { // return internalKey; // } // }
import org.kie.api.definition.type.Key; import br.ufes.inf.lprm.scene.examples.fever.entities.Person; import br.ufes.inf.lprm.scene.model.Situation; import br.ufes.inf.lprm.situation.bindings.part;
package br.ufes.inf.lprm.scene.examples.fever.situations; public class NoFever extends Situation { @Key @part(label = "f1")
// Path: scene-examples/src/main/java/br/ufes/inf/lprm/scene/examples/fever/entities/Person.java // public class Person { // // private int id; // private String name; // private Temperature temperature; // // public int getId() { // return id; // } // // public Person setId(int id) { // this.id = id; // temperature = new Temperature(); // return this; // } // // public String getName() { // return name; // } // // public Person setName(String name) { // this.name = name; // return this; // } // // public Temperature getTemperature() { // return temperature; // } // // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Situation.java // public class Situation implements br.ufes.inf.lprm.situation.model.Situation { // @Key // private String internalKey; // private int runningId; // private Activation activation; // private Deactivation deactivation; // private Boolean active; // private SituationType type; // private List<br.ufes.inf.lprm.situation.model.Participation> participations; // // public Situation(SituationType type, Activation activation, SituationCast cast, boolean active) { // // this.runningId = ((br.ufes.inf.lprm.scene.model.SituationType) type).getTypeClass().hashCode() + cast.hashCode(); // this.type = type; // this.activation = activation; // this.active = active; // // participations = new ArrayList<>(); // // for(Part part: type.getParts()) { // Object participant = cast.get(part.getLabel()); // if (participant != null) { // br.ufes.inf.lprm.situation.model.Participation participation = new Participation(this, part, participant); // participations.add(participation); // } // } // } // // public Situation() { // this.active = true; // this.internalKey = UUID.randomUUID().toString(); // } // // public Situation(SituationType type, SituationCast cast, Activation activation) { // this(type, activation, cast, true); // } // // @Override // public long getUID() { // return runningId; // } // // @Override // public SituationEvent getActivation() { // return activation; // } // // @Override // public SituationEvent getDeactivation() { // return deactivation; // } // // public void setDeactivation(SituationEvent deactivation) { // this.deactivation = (Deactivation) deactivation; // this.active = false; // } // // @Override // public boolean isActive() { // return active; // } // // @Override // public List<br.ufes.inf.lprm.situation.model.Participation> getParticipations() { // return participations; // } // // @Override // public SituationType getType() { // return type; // } // // public String getInternalKey() { // return internalKey; // } // } // Path: scene-examples/src/main/java/br/ufes/inf/lprm/scene/examples/fever/situations/NoFever.java import org.kie.api.definition.type.Key; import br.ufes.inf.lprm.scene.examples.fever.entities.Person; import br.ufes.inf.lprm.scene.model.Situation; import br.ufes.inf.lprm.situation.bindings.part; package br.ufes.inf.lprm.scene.examples.fever.situations; public class NoFever extends Situation { @Key @part(label = "f1")
private Person nonFebrile;
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/FinishesEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.FinishesEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
parameters, paramText ); extractParams(); } private void extractParams() { try { Field endDev = this.getClass().getSuperclass().getDeclaredField("endDev"); endDev.setAccessible(true); this.endDev = endDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'finishes' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/FinishesEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.FinishesEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; parameters, paramText ); extractParams(); } private void extractParams() { try { Field endDev = this.getClass().getSuperclass().getDeclaredField("endDev"); endDev.setAccessible(true); this.endDev = endDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'finishes' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Participation.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation;
package br.ufes.inf.lprm.scene.model; public class Participation implements br.ufes.inf.lprm.situation.model.Participation { private Object actor; private br.ufes.inf.lprm.situation.model.bindings.Part part;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Participation.java import br.ufes.inf.lprm.situation.model.Situation; package br.ufes.inf.lprm.scene.model; public class Participation implements br.ufes.inf.lprm.situation.model.Participation { private Object actor; private br.ufes.inf.lprm.situation.model.bindings.Part part;
private Situation situation;
pextralabs/scene-platform
situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // }
import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import java.lang.reflect.Type; import java.util.List;
package br.ufes.inf.lprm.situation.model; public interface SituationType extends Type { public String getName();
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import java.lang.reflect.Type; import java.util.List; package br.ufes.inf.lprm.situation.model; public interface SituationType extends Type { public String getName();
public List<? extends Part> getParts();
pextralabs/scene-platform
situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // }
import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import java.lang.reflect.Type; import java.util.List;
package br.ufes.inf.lprm.situation.model; public interface SituationType extends Type { public String getName(); public List<? extends Part> getParts(); //public List<Bind> getBinds();
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Snapshot.java // public interface Snapshot extends Bind { // // public SnapshotPolicy getPolicy(); // // } // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/SituationType.java import br.ufes.inf.lprm.situation.model.bindings.Part; import br.ufes.inf.lprm.situation.model.bindings.Snapshot; import java.lang.reflect.Type; import java.util.List; package br.ufes.inf.lprm.situation.model; public interface SituationType extends Type { public String getName(); public List<? extends Part> getParts(); //public List<Bind> getBinds();
public List<? extends Snapshot> getSnapshots();
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/serialization/JsonContext.java
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotCompatibleException.java // public class NotCompatibleException extends Exception { // // public NotCompatibleException(String message) { // super(message); // } // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotInstantiatedException.java // public class NotInstantiatedException extends Exception { // // public NotInstantiatedException(String message) { // super(message); // } // }
import br.ufes.inf.lprm.scene.exceptions.NotCompatibleException; import br.ufes.inf.lprm.scene.exceptions.NotInstantiatedException; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.ClockType; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieModule; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.model.KieSessionModel; import org.kie.api.definition.type.FactField; import org.kie.api.definition.type.FactType; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.conf.ClockTypeOption; import org.kie.api.runtime.rule.FactHandle; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*;
package br.ufes.inf.lprm.scene.serialization; /** * Created by hborjaille on 10/24/16. */ public class JsonContext { private Map<String, Map<Integer, FactHandle>> factHandleMap; private Map<String, Map<Integer, Object>> objectMap; private ArrayList<String> packages; private KieSession kSession; private String appname; private String description; public JsonContext() { factHandleMap = new HashMap<>(); objectMap = new HashMap<>(); packages = new ArrayList<>(); }
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotCompatibleException.java // public class NotCompatibleException extends Exception { // // public NotCompatibleException(String message) { // super(message); // } // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotInstantiatedException.java // public class NotInstantiatedException extends Exception { // // public NotInstantiatedException(String message) { // super(message); // } // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/serialization/JsonContext.java import br.ufes.inf.lprm.scene.exceptions.NotCompatibleException; import br.ufes.inf.lprm.scene.exceptions.NotInstantiatedException; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.ClockType; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieModule; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.model.KieSessionModel; import org.kie.api.definition.type.FactField; import org.kie.api.definition.type.FactType; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.conf.ClockTypeOption; import org.kie.api.runtime.rule.FactHandle; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; package br.ufes.inf.lprm.scene.serialization; /** * Created by hborjaille on 10/24/16. */ public class JsonContext { private Map<String, Map<Integer, FactHandle>> factHandleMap; private Map<String, Map<Integer, Object>> objectMap; private ArrayList<String> packages; private KieSession kSession; private String appname; private String description; public JsonContext() { factHandleMap = new HashMap<>(); objectMap = new HashMap<>(); packages = new ArrayList<>(); }
public void compileCodeJson(String content) throws NotCompatibleException {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/serialization/JsonContext.java
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotCompatibleException.java // public class NotCompatibleException extends Exception { // // public NotCompatibleException(String message) { // super(message); // } // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotInstantiatedException.java // public class NotInstantiatedException extends Exception { // // public NotInstantiatedException(String message) { // super(message); // } // }
import br.ufes.inf.lprm.scene.exceptions.NotCompatibleException; import br.ufes.inf.lprm.scene.exceptions.NotInstantiatedException; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.ClockType; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieModule; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.model.KieSessionModel; import org.kie.api.definition.type.FactField; import org.kie.api.definition.type.FactType; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.conf.ClockTypeOption; import org.kie.api.runtime.rule.FactHandle; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*;
Enumeration<URL> e = JsonContext.class.getClassLoader().getResources(KieModuleModelImpl.KMODULE_JAR_PATH); while ( e.hasMoreElements() ) { URL url = e.nextElement(); String path; if (url.getPath().contains(".jar!")) { path = url.getPath().replace("!/" + KieModuleModelImpl.KMODULE_JAR_PATH, ""); dependencies.add(kServices.getResources().newUrlResource(path)); } else { path = url.getPath().replace(KieModuleModelImpl.KMODULE_JAR_PATH, ""); dependencies.add(kServices.getResources().newFileSystemResource(path)); } } } catch (IOException e1) { e1.printStackTrace(); } kbuilder.setDependencies(dependencies.toArray(new Resource[0])); kbuilder.buildAll(); if (kbuilder.getResults().hasMessages()) { throw new IllegalArgumentException("Couldn't build knowledge module " + kbuilder.getResults()); } KieModule kModule = kbuilder.getKieModule(); KieContainer kContainer = kServices.newKieContainer(kModule.getReleaseId()); kSession = kContainer.newKieSession(appname + ".session"); }
// Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotCompatibleException.java // public class NotCompatibleException extends Exception { // // public NotCompatibleException(String message) { // super(message); // } // } // // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/exceptions/NotInstantiatedException.java // public class NotInstantiatedException extends Exception { // // public NotInstantiatedException(String message) { // super(message); // } // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/serialization/JsonContext.java import br.ufes.inf.lprm.scene.exceptions.NotCompatibleException; import br.ufes.inf.lprm.scene.exceptions.NotInstantiatedException; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.ClockType; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieModule; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.model.KieSessionModel; import org.kie.api.definition.type.FactField; import org.kie.api.definition.type.FactType; import org.kie.api.io.Resource; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.conf.ClockTypeOption; import org.kie.api.runtime.rule.FactHandle; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; Enumeration<URL> e = JsonContext.class.getClassLoader().getResources(KieModuleModelImpl.KMODULE_JAR_PATH); while ( e.hasMoreElements() ) { URL url = e.nextElement(); String path; if (url.getPath().contains(".jar!")) { path = url.getPath().replace("!/" + KieModuleModelImpl.KMODULE_JAR_PATH, ""); dependencies.add(kServices.getResources().newUrlResource(path)); } else { path = url.getPath().replace(KieModuleModelImpl.KMODULE_JAR_PATH, ""); dependencies.add(kServices.getResources().newFileSystemResource(path)); } } } catch (IOException e1) { e1.printStackTrace(); } kbuilder.setDependencies(dependencies.toArray(new Resource[0])); kbuilder.buildAll(); if (kbuilder.getResults().hasMessages()) { throw new IllegalArgumentException("Couldn't build knowledge module " + kbuilder.getResults()); } KieModule kModule = kbuilder.getKieModule(); KieContainer kContainer = kServices.newKieContainer(kModule.getReleaseId()); kSession = kContainer.newKieSession(appname + ".session"); }
public void compileDataJson(String content, JsonType type) throws NotInstantiatedException {
pextralabs/scene-platform
situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Participation.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // }
import br.ufes.inf.lprm.situation.model.bindings.Part;
package br.ufes.inf.lprm.situation.model; public interface Participation { public Object getActor();
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/Part.java // public interface Part extends Bind { // public boolean isKey(); // } // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Participation.java import br.ufes.inf.lprm.situation.model.bindings.Part; package br.ufes.inf.lprm.situation.model; public interface Participation { public Object getActor();
public Part getPart();
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/CoincidesEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.CoincidesEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor;
final String paramText, final boolean unwrapLeft, final boolean unwrapRight) { super( type, isNegated, parameters, paramText, unwrapLeft, unwrapRight); } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'coincides' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long rightStartTS, rightEndTS; long leftStartTS, leftEndTS; rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS; if ( context.declaration.getExtractor().isSelfReference() ) {
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/CoincidesEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.CoincidesEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; final String paramText, final boolean unwrapLeft, final boolean unwrapRight) { super( type, isNegated, parameters, paramText, unwrapLeft, unwrapRight); } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'coincides' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long rightStartTS, rightEndTS; long leftStartTS, leftEndTS; rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS; if ( context.declaration.getExtractor().isSelfReference() ) {
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/FinishedByEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.FinishedByEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
isNegated, parameters, paramText ); extractParams(); } private void extractParams() { try { Field endDev = this.getClass().getSuperclass().getDeclaredField("endDev"); endDev.setAccessible(true); this.endDev = endDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'finishedby' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/FinishedByEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.FinishedByEvaluatorDefinition; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; isNegated, parameters, paramText ); extractParams(); } private void extractParams() { try { Field endDev = this.getClass().getSuperclass().getDeclaredField("endDev"); endDev.setAccessible(true); this.endDev = endDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'finishedby' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/DuringEvaluator.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // }
import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field;
startMaxDev.setAccessible(true); endMinDev.setAccessible(true); endMaxDev.setAccessible(true); this.startMinDev = startMinDev.getLong(this); this.startMaxDev = startMaxDev.getLong(this); this.endMinDev = 0;//endMinDev.getLong(this); this.endMaxDev = endMaxDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'during' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/DuringEvaluator.java import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; startMaxDev.setAccessible(true); endMinDev.setAccessible(true); endMaxDev.setAccessible(true); this.startMinDev = startMinDev.getLong(this); this.startMaxDev = startMaxDev.getLong(this); this.endMinDev = 0;//endMinDev.getLong(this); this.endMaxDev = endMaxDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'during' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS;
if (left.getObject() instanceof Situation) {
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Snapshot.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/SnapshotPolicy.java // public enum SnapshotPolicy { // Shallow, // Deep // }
import br.ufes.inf.lprm.situation.model.Situation; import br.ufes.inf.lprm.situation.model.bindings.SnapshotPolicy; import java.lang.reflect.Field; import java.util.*;
Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(boolean.class); ret.add(char.class); ret.add(byte.class); ret.add(short.class); ret.add(int.class); ret.add(long.class); ret.add(float.class); ret.add(double.class); ret.add(void.class); return ret; } private static Set<Class<?>> getWrapperTypes() { Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(Boolean.class); ret.add(Character.class); ret.add(Byte.class); ret.add(Short.class); ret.add(Integer.class); ret.add(Long.class); ret.add(Float.class); ret.add(Double.class); ret.add(Void.class); return ret; } private String label; private Field field;
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/SnapshotPolicy.java // public enum SnapshotPolicy { // Shallow, // Deep // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Snapshot.java import br.ufes.inf.lprm.situation.model.Situation; import br.ufes.inf.lprm.situation.model.bindings.SnapshotPolicy; import java.lang.reflect.Field; import java.util.*; Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(boolean.class); ret.add(char.class); ret.add(byte.class); ret.add(short.class); ret.add(int.class); ret.add(long.class); ret.add(float.class); ret.add(double.class); ret.add(void.class); return ret; } private static Set<Class<?>> getWrapperTypes() { Set<Class<?>> ret = new HashSet<Class<?>>(); ret.add(Boolean.class); ret.add(Character.class); ret.add(Byte.class); ret.add(Short.class); ret.add(Integer.class); ret.add(Long.class); ret.add(Float.class); ret.add(Double.class); ret.add(Void.class); return ret; } private String label; private Field field;
private SnapshotPolicy policy;
pextralabs/scene-platform
scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Snapshot.java
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/SnapshotPolicy.java // public enum SnapshotPolicy { // Shallow, // Deep // }
import br.ufes.inf.lprm.situation.model.Situation; import br.ufes.inf.lprm.situation.model.bindings.SnapshotPolicy; import java.lang.reflect.Field; import java.util.*;
public Snapshot(String label, Field field, SnapshotPolicy policy) { this.label = label; this.field = field; this.policy = policy; } @Override public String getLabel() { return label; } public Field getField() { return field; } @Override public SnapshotPolicy getPolicy() { return policy; } private List<Field> fieldsFromClass(Class clazz) { List<Field> fields = new ArrayList<Field>(); Class superclazz = clazz.getSuperclass(); if (superclazz != null) { fields.addAll(fieldsFromClass(superclazz)); } for (Field field: clazz.getDeclaredFields()) fields.add(field); return fields; }
// Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/Situation.java // public interface Situation { // // public long getUID(); // public SituationEvent getActivation(); // public SituationEvent getDeactivation(); // public void setDeactivation(SituationEvent deactivation); // public boolean isActive(); // public List<? extends Participation> getParticipations(); // public SituationType getType(); // } // // Path: situation-model/src/main/java/br/ufes/inf/lprm/situation/model/bindings/SnapshotPolicy.java // public enum SnapshotPolicy { // Shallow, // Deep // } // Path: scene-core/src/main/java/br/ufes/inf/lprm/scene/model/Snapshot.java import br.ufes.inf.lprm.situation.model.Situation; import br.ufes.inf.lprm.situation.model.bindings.SnapshotPolicy; import java.lang.reflect.Field; import java.util.*; public Snapshot(String label, Field field, SnapshotPolicy policy) { this.label = label; this.field = field; this.policy = policy; } @Override public String getLabel() { return label; } public Field getField() { return field; } @Override public SnapshotPolicy getPolicy() { return policy; } private List<Field> fieldsFromClass(Class clazz) { List<Field> fields = new ArrayList<Field>(); Class superclazz = clazz.getSuperclass(); if (superclazz != null) { fields.addAll(fieldsFromClass(superclazz)); } for (Field field: clazz.getDeclaredFields()) fields.add(field); return fields; }
public void set(Situation situation, Object src) throws IllegalAccessException, InstantiationException {