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
|
---|---|---|---|---|---|---|
MX-Futhark/hook-any-text
|
src/main/java/hextostring/convert/Converter.java
|
// Path: src/main/java/hextostring/debug/DebuggableStrings.java
// public interface DebuggableStrings {
//
// /**
// * Formats the lines depending on the debugging flags.
// *
// * @param debuggingFlags
// * The debugging flags used to format these lines.
// * @param converterStrictness
// * The validity value below which a converted string is eliminated.
// * @return A string representing these lines, with or without debug traces.
// */
// String toString(long debuggingFlags, int converterStrictness);
//
// /**
// * Provides a list of lines that can be formatted.
// *
// * @return A list of lines that can be formatted.
// */
// DecorableList getDecorableList();
//
// }
//
// Path: src/main/java/hextostring/replacement/Replacements.java
// public class Replacements
// implements TableData<Replacement>, Serializable {
//
// /**
// * Backward-compatible with 0.7.0
// */
// private static final long serialVersionUID = 00000000007000000L;
//
// private List<Replacement> orderedReplacements;
// private Map<ReplacementType, List<Replacement>> replacementsByType;
//
// public Replacements() {
// orderedReplacements = new ArrayList<>();
// replacementsByType = new HashMap<>();
// for (ReplacementType type : ReplacementType.values()) {
// replacementsByType.put(type, new LinkedList<Replacement>());
// }
// }
//
// /**
// * Getter on a replacement by its index.
// *
// * @param index
// * The index of the replacement.
// * @return The replacement at the specified index.
// */
// @Override
// public Replacement get(int index) {
// return orderedReplacements.get(index);
// }
//
// /**
// * Getter on the replacements.
// *
// * @return The replacements.
// */
// @Override
// public List<Replacement> getAll() {
// return new ArrayList<Replacement>(orderedReplacements);
// }
//
// /**
// * Adds a replacement at the end of the list.
// *
// * @param r
// * The replacement to add.
// */
// @Override
// public void add(Replacement r) {
// orderedReplacements.add(r);
// replacementsByType.get(r.getType()).add(r);
// }
//
// /**
// * Removes a replacement at the specified index.
// *
// * @param index
// * The index of the replacement to remove.
// */
// @Override
// public void remove(int index) {
// Replacement deleted = orderedReplacements.remove(index);
// replacementsByType.get(deleted.getType()).remove(deleted);
// }
//
// /**
// * Empties the list.
// */
// public void clear() {
// orderedReplacements.clear();
// for (ReplacementType type : replacementsByType.keySet()) {
// replacementsByType.get(type).clear();
// }
// }
//
// /**
// * Get all replacements of a specified type.
// *
// * @param type
// * The type of the replacements.
// * @return All replacements of a specified type.
// */
// public List<Replacement> getByType(ReplacementType type) {
// return replacementsByType.get(type);
// }
//
// /**
// * Setter on the type of a replacement.
// *
// * @param r
// * The replacement to modify.
// * @param type
// * The new type of the replacement.
// */
// public void setType(Replacement r, ReplacementType type) {
// for (ReplacementType previoustType : replacementsByType.keySet()) {
// replacementsByType.get(previoustType).remove(r);
// }
// replacementsByType.get(type).add(r);
// r.setType(type);
// }
//
// /**
// * Applies all the replacements of a given type.
// *
// * @param s
// * The string to which replacements are applied.
// * @param type
// * The type of the replacements to use.
// * @return The string to which replacements were applied.
// */
// public String apply(String s, ReplacementType type) {
// String res = new String(s);
// for (Replacement r : replacementsByType.get(type)) {
// res = r.apply(res);
// }
// return res;
// }
//
// }
|
import hextostring.debug.DebuggableStrings;
import hextostring.replacement.Replacements;
|
package hextostring.convert;
/**
* Converters transform a hexadecimal string into a readable string.
*
* @author Maxime PIA
*/
public interface Converter {
DebuggableStrings convert(String hex);
|
// Path: src/main/java/hextostring/debug/DebuggableStrings.java
// public interface DebuggableStrings {
//
// /**
// * Formats the lines depending on the debugging flags.
// *
// * @param debuggingFlags
// * The debugging flags used to format these lines.
// * @param converterStrictness
// * The validity value below which a converted string is eliminated.
// * @return A string representing these lines, with or without debug traces.
// */
// String toString(long debuggingFlags, int converterStrictness);
//
// /**
// * Provides a list of lines that can be formatted.
// *
// * @return A list of lines that can be formatted.
// */
// DecorableList getDecorableList();
//
// }
//
// Path: src/main/java/hextostring/replacement/Replacements.java
// public class Replacements
// implements TableData<Replacement>, Serializable {
//
// /**
// * Backward-compatible with 0.7.0
// */
// private static final long serialVersionUID = 00000000007000000L;
//
// private List<Replacement> orderedReplacements;
// private Map<ReplacementType, List<Replacement>> replacementsByType;
//
// public Replacements() {
// orderedReplacements = new ArrayList<>();
// replacementsByType = new HashMap<>();
// for (ReplacementType type : ReplacementType.values()) {
// replacementsByType.put(type, new LinkedList<Replacement>());
// }
// }
//
// /**
// * Getter on a replacement by its index.
// *
// * @param index
// * The index of the replacement.
// * @return The replacement at the specified index.
// */
// @Override
// public Replacement get(int index) {
// return orderedReplacements.get(index);
// }
//
// /**
// * Getter on the replacements.
// *
// * @return The replacements.
// */
// @Override
// public List<Replacement> getAll() {
// return new ArrayList<Replacement>(orderedReplacements);
// }
//
// /**
// * Adds a replacement at the end of the list.
// *
// * @param r
// * The replacement to add.
// */
// @Override
// public void add(Replacement r) {
// orderedReplacements.add(r);
// replacementsByType.get(r.getType()).add(r);
// }
//
// /**
// * Removes a replacement at the specified index.
// *
// * @param index
// * The index of the replacement to remove.
// */
// @Override
// public void remove(int index) {
// Replacement deleted = orderedReplacements.remove(index);
// replacementsByType.get(deleted.getType()).remove(deleted);
// }
//
// /**
// * Empties the list.
// */
// public void clear() {
// orderedReplacements.clear();
// for (ReplacementType type : replacementsByType.keySet()) {
// replacementsByType.get(type).clear();
// }
// }
//
// /**
// * Get all replacements of a specified type.
// *
// * @param type
// * The type of the replacements.
// * @return All replacements of a specified type.
// */
// public List<Replacement> getByType(ReplacementType type) {
// return replacementsByType.get(type);
// }
//
// /**
// * Setter on the type of a replacement.
// *
// * @param r
// * The replacement to modify.
// * @param type
// * The new type of the replacement.
// */
// public void setType(Replacement r, ReplacementType type) {
// for (ReplacementType previoustType : replacementsByType.keySet()) {
// replacementsByType.get(previoustType).remove(r);
// }
// replacementsByType.get(type).add(r);
// r.setType(type);
// }
//
// /**
// * Applies all the replacements of a given type.
// *
// * @param s
// * The string to which replacements are applied.
// * @param type
// * The type of the replacements to use.
// * @return The string to which replacements were applied.
// */
// public String apply(String s, ReplacementType type) {
// String res = new String(s);
// for (Replacement r : replacementsByType.get(type)) {
// res = r.apply(res);
// }
// return res;
// }
//
// }
// Path: src/main/java/hextostring/convert/Converter.java
import hextostring.debug.DebuggableStrings;
import hextostring.replacement.Replacements;
package hextostring.convert;
/**
* Converters transform a hexadecimal string into a readable string.
*
* @author Maxime PIA
*/
public interface Converter {
DebuggableStrings convert(String hex);
|
void setReplacements(Replacements r);
|
MX-Futhark/hook-any-text
|
src/main/java/hextostring/history/History.java
|
// Path: src/main/java/hexcapture/HexSelectionsContentSnapshot.java
// public class HexSelectionsContentSnapshot {
//
// private static final String STRING_REPRESENTATION_SEPARATOR = "|";
//
// protected HexSelections selections;
// protected Map<HexSelection, String> selectionValues;
//
// protected HexSelectionsContentSnapshot() {}
//
// /**
// * Getter on the value of a selection by its index
// * @param index
// * @return
// */
// public String getValueAt(int index) {
// return selectionValues.get(selections.get(index));
// }
//
// /**
// * Getter on the id of a selection by its index
// * @param index
// * @return
// */
// public int getSelectionIdAt(int index) {
// return selections.get(index).getId();
// }
//
// /**
// * Getter on the start index of a selection by its index
// * @param index
// * @return
// */
// public long getSelectionStartAt(int index) {
// return selections.get(index).getStart();
// }
//
// /**
// * Getter on the end index of a selection by its index
// * @param index
// * @return
// */
// public long getSelectionEndAt(int index) {
// return selections.get(index).getEnd();
// }
//
// /**
// * Getter on the index of the active selection
// * @return
// */
// public int getActiveSelectionIndex() {
// return selections.getActiveSelectionIndex();
// }
//
// /**
// * Getter on the size of the selection collection
// * @return
// */
// public int getSize() {
// return selections.getAll().size();
// }
//
// @Override
// public String toString() {
// StringBuilder res = new StringBuilder();
// for (HexSelection s : selections.getAll()) {
// res.append(selectionValues.get(s));
// if (s != selections.getAll().get(getSize() - 1)) {
// res.append(STRING_REPRESENTATION_SEPARATOR);
// }
// }
// return res.toString();
// }
//
// }
|
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import hexcapture.HexSelectionsContentSnapshot;
|
package hextostring.history;
public class History extends Observable {
public static final int HISTORY_MAX_SIZE = 100;
private Deque<InputOutputPair> content = new LinkedList<InputOutputPair>();
public synchronized InputOutputPair getLast() {
return content.peek();
}
|
// Path: src/main/java/hexcapture/HexSelectionsContentSnapshot.java
// public class HexSelectionsContentSnapshot {
//
// private static final String STRING_REPRESENTATION_SEPARATOR = "|";
//
// protected HexSelections selections;
// protected Map<HexSelection, String> selectionValues;
//
// protected HexSelectionsContentSnapshot() {}
//
// /**
// * Getter on the value of a selection by its index
// * @param index
// * @return
// */
// public String getValueAt(int index) {
// return selectionValues.get(selections.get(index));
// }
//
// /**
// * Getter on the id of a selection by its index
// * @param index
// * @return
// */
// public int getSelectionIdAt(int index) {
// return selections.get(index).getId();
// }
//
// /**
// * Getter on the start index of a selection by its index
// * @param index
// * @return
// */
// public long getSelectionStartAt(int index) {
// return selections.get(index).getStart();
// }
//
// /**
// * Getter on the end index of a selection by its index
// * @param index
// * @return
// */
// public long getSelectionEndAt(int index) {
// return selections.get(index).getEnd();
// }
//
// /**
// * Getter on the index of the active selection
// * @return
// */
// public int getActiveSelectionIndex() {
// return selections.getActiveSelectionIndex();
// }
//
// /**
// * Getter on the size of the selection collection
// * @return
// */
// public int getSize() {
// return selections.getAll().size();
// }
//
// @Override
// public String toString() {
// StringBuilder res = new StringBuilder();
// for (HexSelection s : selections.getAll()) {
// res.append(selectionValues.get(s));
// if (s != selections.getAll().get(getSize() - 1)) {
// res.append(STRING_REPRESENTATION_SEPARATOR);
// }
// }
// return res.toString();
// }
//
// }
// Path: src/main/java/hextostring/history/History.java
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import hexcapture.HexSelectionsContentSnapshot;
package hextostring.history;
public class History extends Observable {
public static final int HISTORY_MAX_SIZE = 100;
private Deque<InputOutputPair> content = new LinkedList<InputOutputPair>();
public synchronized InputOutputPair getLast() {
return content.peek();
}
|
public synchronized void add(HexSelectionsContentSnapshot input,
|
MX-Futhark/hook-any-text
|
src/main/java/gui/views/components/renderers/ReorderColumnRenderer.java
|
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
|
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import gui.utils.Images;
|
package gui.views.components.renderers;
/**
* Renderer for table columns that reorders rows
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class ReorderColumnRenderer extends DefaultTableCellRenderer {
private static final JButton UP_BUTTON =
|
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
// Path: src/main/java/gui/views/components/renderers/ReorderColumnRenderer.java
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import gui.utils.Images;
package gui.views.components.renderers;
/**
* Renderer for table columns that reorders rows
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class ReorderColumnRenderer extends DefaultTableCellRenderer {
private static final JButton UP_BUTTON =
|
new JButton(Images.resize(Images.TRIANGLE, 10, 10));
|
MX-Futhark/hook-any-text
|
src/main/java/gui/views/components/AboutPanel.java
|
// Path: src/main/java/gui/utils/GUIErrorHandler.java
// public class GUIErrorHandler {
//
// public GUIErrorHandler(Exception e) {
// // TODO
// e.printStackTrace();
// }
//
// }
//
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
//
// Path: src/main/java/main/utils/ProjectProperties.java
// public class ProjectProperties {
//
// public static final String PATH = "/about.prop";
//
// public static final String KEY_VERSION = "version";
// public static final String KEY_WEBSITE = "website";
// public static final String KEY_MAIL = "mail";
//
// private static Properties props = new Properties();
// private static boolean propsLoaded = false;
//
// private static void loadProperties() throws IOException {
// if (propsLoaded) return;
//
// InputStream versionStream =
// ProjectProperties.class.getResourceAsStream("/about.prop");
// props.load(versionStream);
// versionStream.close();
// propsLoaded = true;
// }
//
// /**
// * Finds and returns a property.
// *
// * @param key
// * The key for this property.
// * @return The property corresponding to the key.
// * @throws IOException
// */
// public static String get(String key) throws IOException {
// loadProperties();
// return props.getProperty(key);
// }
//
// }
|
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import main.utils.ProjectProperties;
|
package gui.views.components;
/**
* Content of the "about" dialog.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class AboutPanel extends JPanel {
public AboutPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
|
// Path: src/main/java/gui/utils/GUIErrorHandler.java
// public class GUIErrorHandler {
//
// public GUIErrorHandler(Exception e) {
// // TODO
// e.printStackTrace();
// }
//
// }
//
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
//
// Path: src/main/java/main/utils/ProjectProperties.java
// public class ProjectProperties {
//
// public static final String PATH = "/about.prop";
//
// public static final String KEY_VERSION = "version";
// public static final String KEY_WEBSITE = "website";
// public static final String KEY_MAIL = "mail";
//
// private static Properties props = new Properties();
// private static boolean propsLoaded = false;
//
// private static void loadProperties() throws IOException {
// if (propsLoaded) return;
//
// InputStream versionStream =
// ProjectProperties.class.getResourceAsStream("/about.prop");
// props.load(versionStream);
// versionStream.close();
// propsLoaded = true;
// }
//
// /**
// * Finds and returns a property.
// *
// * @param key
// * The key for this property.
// * @return The property corresponding to the key.
// * @throws IOException
// */
// public static String get(String key) throws IOException {
// loadProperties();
// return props.getProperty(key);
// }
//
// }
// Path: src/main/java/gui/views/components/AboutPanel.java
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import main.utils.ProjectProperties;
package gui.views.components;
/**
* Content of the "about" dialog.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class AboutPanel extends JPanel {
public AboutPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
|
JLabel logo = new JLabel(Images.DEFAULT_LOGO);
|
MX-Futhark/hook-any-text
|
src/main/java/gui/views/components/AboutPanel.java
|
// Path: src/main/java/gui/utils/GUIErrorHandler.java
// public class GUIErrorHandler {
//
// public GUIErrorHandler(Exception e) {
// // TODO
// e.printStackTrace();
// }
//
// }
//
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
//
// Path: src/main/java/main/utils/ProjectProperties.java
// public class ProjectProperties {
//
// public static final String PATH = "/about.prop";
//
// public static final String KEY_VERSION = "version";
// public static final String KEY_WEBSITE = "website";
// public static final String KEY_MAIL = "mail";
//
// private static Properties props = new Properties();
// private static boolean propsLoaded = false;
//
// private static void loadProperties() throws IOException {
// if (propsLoaded) return;
//
// InputStream versionStream =
// ProjectProperties.class.getResourceAsStream("/about.prop");
// props.load(versionStream);
// versionStream.close();
// propsLoaded = true;
// }
//
// /**
// * Finds and returns a property.
// *
// * @param key
// * The key for this property.
// * @return The property corresponding to the key.
// * @throws IOException
// */
// public static String get(String key) throws IOException {
// loadProperties();
// return props.getProperty(key);
// }
//
// }
|
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import main.utils.ProjectProperties;
|
package gui.views.components;
/**
* Content of the "about" dialog.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class AboutPanel extends JPanel {
public AboutPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel logo = new JLabel(Images.DEFAULT_LOGO);
try {
JLabel version = new JLabel(
"Hook Any Text version "
|
// Path: src/main/java/gui/utils/GUIErrorHandler.java
// public class GUIErrorHandler {
//
// public GUIErrorHandler(Exception e) {
// // TODO
// e.printStackTrace();
// }
//
// }
//
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
//
// Path: src/main/java/main/utils/ProjectProperties.java
// public class ProjectProperties {
//
// public static final String PATH = "/about.prop";
//
// public static final String KEY_VERSION = "version";
// public static final String KEY_WEBSITE = "website";
// public static final String KEY_MAIL = "mail";
//
// private static Properties props = new Properties();
// private static boolean propsLoaded = false;
//
// private static void loadProperties() throws IOException {
// if (propsLoaded) return;
//
// InputStream versionStream =
// ProjectProperties.class.getResourceAsStream("/about.prop");
// props.load(versionStream);
// versionStream.close();
// propsLoaded = true;
// }
//
// /**
// * Finds and returns a property.
// *
// * @param key
// * The key for this property.
// * @return The property corresponding to the key.
// * @throws IOException
// */
// public static String get(String key) throws IOException {
// loadProperties();
// return props.getProperty(key);
// }
//
// }
// Path: src/main/java/gui/views/components/AboutPanel.java
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import main.utils.ProjectProperties;
package gui.views.components;
/**
* Content of the "about" dialog.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class AboutPanel extends JPanel {
public AboutPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel logo = new JLabel(Images.DEFAULT_LOGO);
try {
JLabel version = new JLabel(
"Hook Any Text version "
|
+ ProjectProperties.get(ProjectProperties.KEY_VERSION)
|
MX-Futhark/hook-any-text
|
src/main/java/gui/views/components/AboutPanel.java
|
// Path: src/main/java/gui/utils/GUIErrorHandler.java
// public class GUIErrorHandler {
//
// public GUIErrorHandler(Exception e) {
// // TODO
// e.printStackTrace();
// }
//
// }
//
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
//
// Path: src/main/java/main/utils/ProjectProperties.java
// public class ProjectProperties {
//
// public static final String PATH = "/about.prop";
//
// public static final String KEY_VERSION = "version";
// public static final String KEY_WEBSITE = "website";
// public static final String KEY_MAIL = "mail";
//
// private static Properties props = new Properties();
// private static boolean propsLoaded = false;
//
// private static void loadProperties() throws IOException {
// if (propsLoaded) return;
//
// InputStream versionStream =
// ProjectProperties.class.getResourceAsStream("/about.prop");
// props.load(versionStream);
// versionStream.close();
// propsLoaded = true;
// }
//
// /**
// * Finds and returns a property.
// *
// * @param key
// * The key for this property.
// * @return The property corresponding to the key.
// * @throws IOException
// */
// public static String get(String key) throws IOException {
// loadProperties();
// return props.getProperty(key);
// }
//
// }
|
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import main.utils.ProjectProperties;
|
package gui.views.components;
/**
* Content of the "about" dialog.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class AboutPanel extends JPanel {
public AboutPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel logo = new JLabel(Images.DEFAULT_LOGO);
try {
JLabel version = new JLabel(
"Hook Any Text version "
+ ProjectProperties.get(ProjectProperties.KEY_VERSION)
);
ClickableURL urlButton = new ClickableURL(
ProjectProperties.get(ProjectProperties.KEY_WEBSITE),
"GitHub home page"
);
JLabel mail = new JLabel(
"Contact me at: "
+ ProjectProperties.get(ProjectProperties.KEY_MAIL)
);
add(logo);
add(version);
add(urlButton);
add(mail);
} catch (IOException er) {
|
// Path: src/main/java/gui/utils/GUIErrorHandler.java
// public class GUIErrorHandler {
//
// public GUIErrorHandler(Exception e) {
// // TODO
// e.printStackTrace();
// }
//
// }
//
// Path: src/main/java/gui/utils/Images.java
// public class Images {
//
// public static final ImageIcon DEFAULT_ICON =
// new ImageIcon(Images.class.getResource("/img/icon.png"));
// public static final ImageIcon DEFAULT_LOGO =
// new ImageIcon(Images.class.getResource("/img/logo.png"));
//
// public static final ImageIcon TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/triangle.png"));
// public static final ImageIcon INVERTED_TRIANGLE =
// new ImageIcon(Images.class.getResource("/img/inverted_triangle.png"));
//
// public static ImageIcon resize(ImageIcon icon, int width, int height) {
// return
// new ImageIcon(icon.getImage().getScaledInstance(width, height, 0));
// }
//
// }
//
// Path: src/main/java/main/utils/ProjectProperties.java
// public class ProjectProperties {
//
// public static final String PATH = "/about.prop";
//
// public static final String KEY_VERSION = "version";
// public static final String KEY_WEBSITE = "website";
// public static final String KEY_MAIL = "mail";
//
// private static Properties props = new Properties();
// private static boolean propsLoaded = false;
//
// private static void loadProperties() throws IOException {
// if (propsLoaded) return;
//
// InputStream versionStream =
// ProjectProperties.class.getResourceAsStream("/about.prop");
// props.load(versionStream);
// versionStream.close();
// propsLoaded = true;
// }
//
// /**
// * Finds and returns a property.
// *
// * @param key
// * The key for this property.
// * @return The property corresponding to the key.
// * @throws IOException
// */
// public static String get(String key) throws IOException {
// loadProperties();
// return props.getProperty(key);
// }
//
// }
// Path: src/main/java/gui/views/components/AboutPanel.java
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import main.utils.ProjectProperties;
package gui.views.components;
/**
* Content of the "about" dialog.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class AboutPanel extends JPanel {
public AboutPanel() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JLabel logo = new JLabel(Images.DEFAULT_LOGO);
try {
JLabel version = new JLabel(
"Hook Any Text version "
+ ProjectProperties.get(ProjectProperties.KEY_VERSION)
);
ClickableURL urlButton = new ClickableURL(
ProjectProperties.get(ProjectProperties.KEY_WEBSITE),
"GitHub home page"
);
JLabel mail = new JLabel(
"Contact me at: "
+ ProjectProperties.get(ProjectProperties.KEY_MAIL)
);
add(logo);
add(version);
add(urlButton);
add(mail);
} catch (IOException er) {
|
new GUIErrorHandler(er);
|
MX-Futhark/hook-any-text
|
src/main/java/hextostring/convert/UTF16Converter.java
|
// Path: src/main/java/hextostring/utils/Charsets.java
// public class Charsets implements ValueClass {
//
// // Charsets used in Japanese games
// @CommandLineValue(
// value = "sjis",
// shortcut = "j",
// description = "Shift JIS"
// )
// public static final Charset SHIFT_JIS = Charset.forName("Shift_JIS");
// @CommandLineValue(
// value = "utf16-le",
// shortcut = "l",
// description = "UTF16 Little Endian"
// )
// public static final Charset UTF16_LE = Charset.forName("UTF-16LE");
// @CommandLineValue(
// value = "utf16-be",
// shortcut = "b",
// description = "UTF16 Bid Endian"
// )
// public static final Charset UTF16_BE = Charset.forName("UTF-16BE");
// // also used for test files
// @CommandLineValue(
// value = "utf8",
// shortcut = "u",
// description = "UTF8"
// )
// public static final Charset UTF8 = Charset.forName("UTF-8");
//
// // not a charset, used for automatic recognition
// @CommandLineValue(
// value = "detect",
// shortcut = "d",
// description = "Detect the right encoding among the other ones"
// )
// public static final Charset DETECT = CharsetAutodetect.getInstance();
//
// public static final Charset[] ALL_CHARSETS = getAllCharsets();
//
// public static Charset getValidCharset(String charsetName) {
// for (Charset cs : ALL_CHARSETS) {
// if (cs.name().equals(charsetName)) {
// return cs;
// }
// }
// return null;
// }
//
// private static Charset[] getAllCharsets() {
//
// List<Field> charsetFields = ReflectionUtils.getAnnotatedFields(
// Charsets.class,
// CommandLineValue.class
// );
// Charset[] allCharsets = new Charset[charsetFields.size()];
// int eltCounter = 0;
// for (Field charsetField : charsetFields) {
// try {
// allCharsets[eltCounter++] = (Charset) charsetField.get(null);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// return allCharsets;
// }
//
// }
|
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hextostring.utils.Charsets;
|
package hextostring.convert;
/**
* Standard converter for UTF-16-encoded hexadecimal strings.
*
* @author Maxime PIA
*/
public class UTF16Converter extends AbstractConverter {
public UTF16Converter(boolean bigEndian) {
|
// Path: src/main/java/hextostring/utils/Charsets.java
// public class Charsets implements ValueClass {
//
// // Charsets used in Japanese games
// @CommandLineValue(
// value = "sjis",
// shortcut = "j",
// description = "Shift JIS"
// )
// public static final Charset SHIFT_JIS = Charset.forName("Shift_JIS");
// @CommandLineValue(
// value = "utf16-le",
// shortcut = "l",
// description = "UTF16 Little Endian"
// )
// public static final Charset UTF16_LE = Charset.forName("UTF-16LE");
// @CommandLineValue(
// value = "utf16-be",
// shortcut = "b",
// description = "UTF16 Bid Endian"
// )
// public static final Charset UTF16_BE = Charset.forName("UTF-16BE");
// // also used for test files
// @CommandLineValue(
// value = "utf8",
// shortcut = "u",
// description = "UTF8"
// )
// public static final Charset UTF8 = Charset.forName("UTF-8");
//
// // not a charset, used for automatic recognition
// @CommandLineValue(
// value = "detect",
// shortcut = "d",
// description = "Detect the right encoding among the other ones"
// )
// public static final Charset DETECT = CharsetAutodetect.getInstance();
//
// public static final Charset[] ALL_CHARSETS = getAllCharsets();
//
// public static Charset getValidCharset(String charsetName) {
// for (Charset cs : ALL_CHARSETS) {
// if (cs.name().equals(charsetName)) {
// return cs;
// }
// }
// return null;
// }
//
// private static Charset[] getAllCharsets() {
//
// List<Field> charsetFields = ReflectionUtils.getAnnotatedFields(
// Charsets.class,
// CommandLineValue.class
// );
// Charset[] allCharsets = new Charset[charsetFields.size()];
// int eltCounter = 0;
// for (Field charsetField : charsetFields) {
// try {
// allCharsets[eltCounter++] = (Charset) charsetField.get(null);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// return allCharsets;
// }
//
// }
// Path: src/main/java/hextostring/convert/UTF16Converter.java
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hextostring.utils.Charsets;
package hextostring.convert;
/**
* Standard converter for UTF-16-encoded hexadecimal strings.
*
* @author Maxime PIA
*/
public class UTF16Converter extends AbstractConverter {
public UTF16Converter(boolean bigEndian) {
|
super(bigEndian ? Charsets.UTF16_BE : Charsets.UTF16_LE);
|
MX-Futhark/hook-any-text
|
src/main/java/hextostring/debug/DebuggableStrings.java
|
// Path: src/main/java/hextostring/format/DecorableList.java
// public interface DecorableList {
//
// public void setDecorationBefore(String decoration);
//
// public void setDecorationBetween(String decoration);
//
// public void setDecorationAfter(String decoration);
//
// public void setLinesDecorations(String before, String after);
//
// }
|
import hextostring.format.DecorableList;
|
package hextostring.debug;
/**
* Wraps a hexadecimal input and the results of its conversion into an object
* containing all the necessary information to print debugging messages.
*
* @author Maxime PIA
*/
public interface DebuggableStrings {
/**
* Formats the lines depending on the debugging flags.
*
* @param debuggingFlags
* The debugging flags used to format these lines.
* @param converterStrictness
* The validity value below which a converted string is eliminated.
* @return A string representing these lines, with or without debug traces.
*/
String toString(long debuggingFlags, int converterStrictness);
/**
* Provides a list of lines that can be formatted.
*
* @return A list of lines that can be formatted.
*/
|
// Path: src/main/java/hextostring/format/DecorableList.java
// public interface DecorableList {
//
// public void setDecorationBefore(String decoration);
//
// public void setDecorationBetween(String decoration);
//
// public void setDecorationAfter(String decoration);
//
// public void setLinesDecorations(String before, String after);
//
// }
// Path: src/main/java/hextostring/debug/DebuggableStrings.java
import hextostring.format.DecorableList;
package hextostring.debug;
/**
* Wraps a hexadecimal input and the results of its conversion into an object
* containing all the necessary information to print debugging messages.
*
* @author Maxime PIA
*/
public interface DebuggableStrings {
/**
* Formats the lines depending on the debugging flags.
*
* @param debuggingFlags
* The debugging flags used to format these lines.
* @param converterStrictness
* The validity value below which a converted string is eliminated.
* @return A string representing these lines, with or without debug traces.
*/
String toString(long debuggingFlags, int converterStrictness);
/**
* Provides a list of lines that can be formatted.
*
* @return A list of lines that can be formatted.
*/
|
DecorableList getDecorableList();
|
MX-Futhark/hook-any-text
|
src/main/java/hextostring/convert/UTF8Converter.java
|
// Path: src/main/java/hextostring/utils/Charsets.java
// public class Charsets implements ValueClass {
//
// // Charsets used in Japanese games
// @CommandLineValue(
// value = "sjis",
// shortcut = "j",
// description = "Shift JIS"
// )
// public static final Charset SHIFT_JIS = Charset.forName("Shift_JIS");
// @CommandLineValue(
// value = "utf16-le",
// shortcut = "l",
// description = "UTF16 Little Endian"
// )
// public static final Charset UTF16_LE = Charset.forName("UTF-16LE");
// @CommandLineValue(
// value = "utf16-be",
// shortcut = "b",
// description = "UTF16 Bid Endian"
// )
// public static final Charset UTF16_BE = Charset.forName("UTF-16BE");
// // also used for test files
// @CommandLineValue(
// value = "utf8",
// shortcut = "u",
// description = "UTF8"
// )
// public static final Charset UTF8 = Charset.forName("UTF-8");
//
// // not a charset, used for automatic recognition
// @CommandLineValue(
// value = "detect",
// shortcut = "d",
// description = "Detect the right encoding among the other ones"
// )
// public static final Charset DETECT = CharsetAutodetect.getInstance();
//
// public static final Charset[] ALL_CHARSETS = getAllCharsets();
//
// public static Charset getValidCharset(String charsetName) {
// for (Charset cs : ALL_CHARSETS) {
// if (cs.name().equals(charsetName)) {
// return cs;
// }
// }
// return null;
// }
//
// private static Charset[] getAllCharsets() {
//
// List<Field> charsetFields = ReflectionUtils.getAnnotatedFields(
// Charsets.class,
// CommandLineValue.class
// );
// Charset[] allCharsets = new Charset[charsetFields.size()];
// int eltCounter = 0;
// for (Field charsetField : charsetFields) {
// try {
// allCharsets[eltCounter++] = (Charset) charsetField.get(null);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// return allCharsets;
// }
//
// }
|
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hextostring.utils.Charsets;
|
package hextostring.convert;
/**
* Standard converter for UTF-8-encoded hexadecimal strings.
*
* @author Maxime PIA
*/
public class UTF8Converter extends AbstractConverter {
public UTF8Converter() {
|
// Path: src/main/java/hextostring/utils/Charsets.java
// public class Charsets implements ValueClass {
//
// // Charsets used in Japanese games
// @CommandLineValue(
// value = "sjis",
// shortcut = "j",
// description = "Shift JIS"
// )
// public static final Charset SHIFT_JIS = Charset.forName("Shift_JIS");
// @CommandLineValue(
// value = "utf16-le",
// shortcut = "l",
// description = "UTF16 Little Endian"
// )
// public static final Charset UTF16_LE = Charset.forName("UTF-16LE");
// @CommandLineValue(
// value = "utf16-be",
// shortcut = "b",
// description = "UTF16 Bid Endian"
// )
// public static final Charset UTF16_BE = Charset.forName("UTF-16BE");
// // also used for test files
// @CommandLineValue(
// value = "utf8",
// shortcut = "u",
// description = "UTF8"
// )
// public static final Charset UTF8 = Charset.forName("UTF-8");
//
// // not a charset, used for automatic recognition
// @CommandLineValue(
// value = "detect",
// shortcut = "d",
// description = "Detect the right encoding among the other ones"
// )
// public static final Charset DETECT = CharsetAutodetect.getInstance();
//
// public static final Charset[] ALL_CHARSETS = getAllCharsets();
//
// public static Charset getValidCharset(String charsetName) {
// for (Charset cs : ALL_CHARSETS) {
// if (cs.name().equals(charsetName)) {
// return cs;
// }
// }
// return null;
// }
//
// private static Charset[] getAllCharsets() {
//
// List<Field> charsetFields = ReflectionUtils.getAnnotatedFields(
// Charsets.class,
// CommandLineValue.class
// );
// Charset[] allCharsets = new Charset[charsetFields.size()];
// int eltCounter = 0;
// for (Field charsetField : charsetFields) {
// try {
// allCharsets[eltCounter++] = (Charset) charsetField.get(null);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// return allCharsets;
// }
//
// }
// Path: src/main/java/hextostring/convert/UTF8Converter.java
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hextostring.utils.Charsets;
package hextostring.convert;
/**
* Standard converter for UTF-8-encoded hexadecimal strings.
*
* @author Maxime PIA
*/
public class UTF8Converter extends AbstractConverter {
public UTF8Converter() {
|
super(Charsets.UTF8);
|
Qinka/Java-Homework
|
pim-client/src/pro/qinka/pim/gui/ConnectionWindows.java
|
// Path: pim-client/src/pro/qinka/pim/collection/PIMBaseCollection.java
// public interface PIMBaseCollection extends Collection<PIMEntity>, List<PIMEntity>
// {
// /**
// * The method to get all the notes
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getNotes();
// /**
// * The method to get all the notes whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getNotes(String owner);
//
// /**
// * The method to get all the todos
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getTodos();
// /**
// * The method to get all the todos whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getTodos(String owner);
//
// /**
// * The method to get all the appointments
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAppointments();
// /**
// * The method to get all the appointments whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAppointments(String owner);
//
// /**
// * The method to get all the contacts
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getContacts();
// /**
// * The method to get all the contacts whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getContacts(String owner);
//
// /**
// * The method to get all the items whose date is same with what was given
// * @param d is the date
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getItemsForDate(Date d);
// /**
// * The method to get all the items whose date and owner is same with what was given
// * @param d is the date
// * @param owner is the owner of the item
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getItemsForDate(Date d, String owner);
//
// /**
// * The method to get all the items
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAll();
// /**
// * The method to get all the items whose owner is same with what was given
// * @param owner is the owner of the item
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAll(String owner);
//
// /**
// * The method to add an new item to colllection
// * @param item the item which will be added to collection
// * @return the return is about whether the action is success.
// */
// public boolean add(PIMEntity item);
// }
|
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import net.miginfocom.swing.*;
import pro.qinka.pim.collection.PIMBaseCollection;
|
package pro.qinka.pim.gui;
/**
* ConnectionWindows
*
* @author Qinka [email protected] [email protected] 李约瀚 14130140331
* @license GPL3
* @version 0.2.0.10
*
* The windows where we choose and connect the backend, database, or just open a file.
*/
public class ConnectionWindows extends JFrame {
/**
* The constructor of ConnectionWindows
*/
public ConnectionWindows() {
initComponents();
}
/**
* The method of button clicked.
*/
private void button1MouseClicked(MouseEvent e) {
Connector cr = null;
switch(comboBox1.getSelectedIndex()){
case 0: // file
cr = new ConnectSelect.FileConnect(connectionparam.getText());
break;
case 1: // http backend
cr = new ConnectSelect.BackendConnect(connectionparam.getText());
break;
case 2: //database
cr = new ConnectSelect.DatabaseConnect(connectionparam.getText(),
usernameI.getText(),
new String(passwordI.getPassword()));
break;
default: // PIMCollection
cr = new ConnectSelect();
break;
}
|
// Path: pim-client/src/pro/qinka/pim/collection/PIMBaseCollection.java
// public interface PIMBaseCollection extends Collection<PIMEntity>, List<PIMEntity>
// {
// /**
// * The method to get all the notes
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getNotes();
// /**
// * The method to get all the notes whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getNotes(String owner);
//
// /**
// * The method to get all the todos
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getTodos();
// /**
// * The method to get all the todos whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getTodos(String owner);
//
// /**
// * The method to get all the appointments
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAppointments();
// /**
// * The method to get all the appointments whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAppointments(String owner);
//
// /**
// * The method to get all the contacts
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getContacts();
// /**
// * The method to get all the contacts whose owner is someone
// * @param owner the owner of the items you want
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getContacts(String owner);
//
// /**
// * The method to get all the items whose date is same with what was given
// * @param d is the date
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getItemsForDate(Date d);
// /**
// * The method to get all the items whose date and owner is same with what was given
// * @param d is the date
// * @param owner is the owner of the item
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getItemsForDate(Date d, String owner);
//
// /**
// * The method to get all the items
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAll();
// /**
// * The method to get all the items whose owner is same with what was given
// * @param owner is the owner of the item
// * @return the collection of what were gotten
// */
// public PIMBaseCollection getAll(String owner);
//
// /**
// * The method to add an new item to colllection
// * @param item the item which will be added to collection
// * @return the return is about whether the action is success.
// */
// public boolean add(PIMEntity item);
// }
// Path: pim-client/src/pro/qinka/pim/gui/ConnectionWindows.java
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import net.miginfocom.swing.*;
import pro.qinka.pim.collection.PIMBaseCollection;
package pro.qinka.pim.gui;
/**
* ConnectionWindows
*
* @author Qinka [email protected] [email protected] 李约瀚 14130140331
* @license GPL3
* @version 0.2.0.10
*
* The windows where we choose and connect the backend, database, or just open a file.
*/
public class ConnectionWindows extends JFrame {
/**
* The constructor of ConnectionWindows
*/
public ConnectionWindows() {
initComponents();
}
/**
* The method of button clicked.
*/
private void button1MouseClicked(MouseEvent e) {
Connector cr = null;
switch(comboBox1.getSelectedIndex()){
case 0: // file
cr = new ConnectSelect.FileConnect(connectionparam.getText());
break;
case 1: // http backend
cr = new ConnectSelect.BackendConnect(connectionparam.getText());
break;
case 2: //database
cr = new ConnectSelect.DatabaseConnect(connectionparam.getText(),
usernameI.getText(),
new String(passwordI.getPassword()));
break;
default: // PIMCollection
cr = new ConnectSelect();
break;
}
|
PIMBaseCollection pimc = cr.getCollection();
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/net/NIOReactorPool.java
|
// Path: src/main/java/io/mycat/jcache/net/strategy/ReactorStrategy.java
// public interface ReactorStrategy {
//
// /**
// * 获取下一个reactor
// * @param reactors
// * @return
// */
// public int getNextReactor(NIOReactor[] reactors,int lastreactor);
//
// }
//
// Path: src/main/java/io/mycat/jcache/setting/Settings.java
// @SuppressWarnings("restriction")
// public class Settings {
// public static boolean useCas = true;
// public static String access = "0700";
// public static int port = 11211;
// public static int udpport = 11211;
// public static int redis_port=6378;
// public static String inter = null;
//
// public static long maxbytes = VM.maxDirectMemory()>0?VM.maxDirectMemory():64*1024*1024; //64M
// public static int maxConns = 1024;
// public static short verbose = 2;
// public static long oldestLive = 0;
// public static long oldestCas = 0;
// public static short evictToFree = 1; /* push old items out of cache when memory runs out */
// public static String socketPath = null;
// public static boolean prealloc = true;
// public static double factor = 1.25;
// public static int chunkSize = 48;
// public static int numThreads = 4; /* N workers */
// public static int numThreadsPerUdp = 0;
// public static String prefixDelimiter = ":";
// public static boolean detailEnabled = false;
// public static int reqsPerEvent = 20;
// public static int backLog = 1024;
// public static Protocol binding_protocol = Protocol.negotiating;
// public static int itemSizeMax = 1024*1024; /* The famous 1MB upper limit. */
// public static int slabPageSize = 1024 * 1024; /* chunks are split from 1MB pages. */
// public static int slabChunkSizeMax = slabPageSize;
// public static boolean sasl = false; /* SASL on/off */
// public static boolean maxConnsFast = false;
// public static boolean lruCrawler = false;
// public static int lruCrawlerSleep = 100;
// public static int lruCrawlerTocrawl = 0;
// public static boolean lruMaintainerThread = false; /* LRU maintainer background thread */
// public static int hotLruPct = 32;
// public static int warmLruPct = 32;
// public static boolean expireZeroDoesNotEvict = false;
// public static int idleTimeout = 0;
// public static int hashpower_default = 16; /* Initial power multiplier for the hash table */
// public static int hashPowerInit = hashpower_default;
// public static boolean slabReassign = false; /* Whether or not slab reassignment is allowed */
// public static short slabAutoMove = 0; /* Whether or not to automatically move slabs */
// public static boolean shutdownCommand = false; /* allow shutdown command */
// public static long tailRepairTime = JcacheGlobalConfig.TAIL_REPAIR_TIME_DEFAULT; /* LRU tail refcount leak repair time */
// public static boolean flushEnabled = true; /* flush_all enabled */
// public static int crawlsPerSleep = 1000; /* Number of seconds to let connections idle */
// public static int loggerWatcherBufSize = 1024; /* size of logger's per-watcher buffer */
// public static int loggerBufSize = 1024; /* size of per-thread logger buffer */
//
// public static boolean lru_crawler = false;
// public static int lru_crawler_sleep = 100;
// public static int lru_crawler_tocrawl = 0;
// public static boolean lru_maintainer_thread = false;
// public static long current_time = new Date().getTime();
//
// public static String hash_algorithm; //PigBrother hash algorithm
//
// /*
// * We only reposition items in the LRU queue if they haven't been repositioned
// * in this many seconds. That saves us from churning on frequently-accessed
// * items.
// */
// public static int ITEM_UPDATE_INTERVAL= 60 * 1000;
//
// public static int hashsize; //临时参数
//
// public static String mapfile; // MappedByteBuffer 内存映射文件地址
//
// public static long process_started = System.currentTimeMillis();
//
//
//
//
// public static final int MAX_NUMBER_OF_SLAB_CLASSES = 64;
// public static final int POWER_SMALLEST = 1;
// public static final int POWER_LARGEST = 256;
// public static final int CHUNK_ALIGN_BYTES = 8;
// public static final int SLAB_GLOBAL_PAGE_POOL = 0; /* magic slab class for storing pages for reassignment */
// public static final int ITEM_HEADER_LENGTH = 52; /* item header length */
// public static final int MAX_MAINTCRAWL_WAIT = 60 * 60;
// public static final int slab_automove = 0;
// public static final boolean expirezero_does_not_evict = false;
// }
|
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.mycat.jcache.net.strategy.ReactorStrategy;
import io.mycat.jcache.setting.Settings;
|
package io.mycat.jcache.net;
/**
* rector 线程池 也是acceptor线程分配 连接给 具体某一个rector 线程的策略上下文
* @author liyanjun
*/
public class NIOReactorPool {
private final NIOReactor[] reactors;
private final String rectorname = "rector";
|
// Path: src/main/java/io/mycat/jcache/net/strategy/ReactorStrategy.java
// public interface ReactorStrategy {
//
// /**
// * 获取下一个reactor
// * @param reactors
// * @return
// */
// public int getNextReactor(NIOReactor[] reactors,int lastreactor);
//
// }
//
// Path: src/main/java/io/mycat/jcache/setting/Settings.java
// @SuppressWarnings("restriction")
// public class Settings {
// public static boolean useCas = true;
// public static String access = "0700";
// public static int port = 11211;
// public static int udpport = 11211;
// public static int redis_port=6378;
// public static String inter = null;
//
// public static long maxbytes = VM.maxDirectMemory()>0?VM.maxDirectMemory():64*1024*1024; //64M
// public static int maxConns = 1024;
// public static short verbose = 2;
// public static long oldestLive = 0;
// public static long oldestCas = 0;
// public static short evictToFree = 1; /* push old items out of cache when memory runs out */
// public static String socketPath = null;
// public static boolean prealloc = true;
// public static double factor = 1.25;
// public static int chunkSize = 48;
// public static int numThreads = 4; /* N workers */
// public static int numThreadsPerUdp = 0;
// public static String prefixDelimiter = ":";
// public static boolean detailEnabled = false;
// public static int reqsPerEvent = 20;
// public static int backLog = 1024;
// public static Protocol binding_protocol = Protocol.negotiating;
// public static int itemSizeMax = 1024*1024; /* The famous 1MB upper limit. */
// public static int slabPageSize = 1024 * 1024; /* chunks are split from 1MB pages. */
// public static int slabChunkSizeMax = slabPageSize;
// public static boolean sasl = false; /* SASL on/off */
// public static boolean maxConnsFast = false;
// public static boolean lruCrawler = false;
// public static int lruCrawlerSleep = 100;
// public static int lruCrawlerTocrawl = 0;
// public static boolean lruMaintainerThread = false; /* LRU maintainer background thread */
// public static int hotLruPct = 32;
// public static int warmLruPct = 32;
// public static boolean expireZeroDoesNotEvict = false;
// public static int idleTimeout = 0;
// public static int hashpower_default = 16; /* Initial power multiplier for the hash table */
// public static int hashPowerInit = hashpower_default;
// public static boolean slabReassign = false; /* Whether or not slab reassignment is allowed */
// public static short slabAutoMove = 0; /* Whether or not to automatically move slabs */
// public static boolean shutdownCommand = false; /* allow shutdown command */
// public static long tailRepairTime = JcacheGlobalConfig.TAIL_REPAIR_TIME_DEFAULT; /* LRU tail refcount leak repair time */
// public static boolean flushEnabled = true; /* flush_all enabled */
// public static int crawlsPerSleep = 1000; /* Number of seconds to let connections idle */
// public static int loggerWatcherBufSize = 1024; /* size of logger's per-watcher buffer */
// public static int loggerBufSize = 1024; /* size of per-thread logger buffer */
//
// public static boolean lru_crawler = false;
// public static int lru_crawler_sleep = 100;
// public static int lru_crawler_tocrawl = 0;
// public static boolean lru_maintainer_thread = false;
// public static long current_time = new Date().getTime();
//
// public static String hash_algorithm; //PigBrother hash algorithm
//
// /*
// * We only reposition items in the LRU queue if they haven't been repositioned
// * in this many seconds. That saves us from churning on frequently-accessed
// * items.
// */
// public static int ITEM_UPDATE_INTERVAL= 60 * 1000;
//
// public static int hashsize; //临时参数
//
// public static String mapfile; // MappedByteBuffer 内存映射文件地址
//
// public static long process_started = System.currentTimeMillis();
//
//
//
//
// public static final int MAX_NUMBER_OF_SLAB_CLASSES = 64;
// public static final int POWER_SMALLEST = 1;
// public static final int POWER_LARGEST = 256;
// public static final int CHUNK_ALIGN_BYTES = 8;
// public static final int SLAB_GLOBAL_PAGE_POOL = 0; /* magic slab class for storing pages for reassignment */
// public static final int ITEM_HEADER_LENGTH = 52; /* item header length */
// public static final int MAX_MAINTCRAWL_WAIT = 60 * 60;
// public static final int slab_automove = 0;
// public static final boolean expirezero_does_not_evict = false;
// }
// Path: src/main/java/io/mycat/jcache/net/NIOReactorPool.java
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.mycat.jcache.net.strategy.ReactorStrategy;
import io.mycat.jcache.setting.Settings;
package io.mycat.jcache.net;
/**
* rector 线程池 也是acceptor线程分配 连接给 具体某一个rector 线程的策略上下文
* @author liyanjun
*/
public class NIOReactorPool {
private final NIOReactor[] reactors;
private final String rectorname = "rector";
|
private final ReactorStrategy startegy;
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/memory/Slabs.java
|
// Path: src/main/java/io/mycat/jcache/enums/memory/REASSIGN_RESULT_TYPE.java
// public enum REASSIGN_RESULT_TYPE {
// REASSIGN_OK,
// REASSIGN_RUNNING,
// REASSIGN_BADCLASS,
// REASSIGN_NOSPARE,
// REASSIGN_SRC_DST_SAME
// }
|
import io.mycat.jcache.enums.memory.REASSIGN_RESULT_TYPE;
|
package io.mycat.jcache.memory;
public interface Slabs {
/** Allocate object of given length. 0 on error */ /*@null@*/
public static final int SLABS_ALLOC_NO_NEWPAGE = 1; /* 不允许 slabclass 分配新的 page */
public static final int SLABS_ALLOC_NEWPAGE = 0; /* 允许 slabclass 分配新的 page */
/** Init the subsystem. 1st argument is the limit on no. of bytes to allocate,
0 if no limit. 2nd argument is the growth factor; each slab will use a chunk
size equal to the previous slab's chunk size times this factor.
3rd argument specifies if the slab allocator should allocate all memory
up front (if true), or allocate memory in chunks as it is needed (if false)
*/
public void slabs_init(long limit,double factor,boolean prealloc,int[] slab_sizes);
/**
* Figures out which slab class (chunk size) is required to store an item of
* a given size.
*
* Given object size, return id to use when allocating/freeing memory for object
* 0 means error: can't store such a large object
*/
public int slabs_clsid(int size);
/**
* 获取 slabclass 的内存首地址
* @param id
* @return
*/
public long getSlabClass(int id);
/** Allocate object of given length. 0 on error
* @param size
* @param id
* @param total_bytes 内存首地址
* @param flags
* @return
*/
public long slabs_alloc(int size,int id,long total_bytes,int flags);
/** Free previously allocated object */
public void slabs_free(long addr,int size,int id);
/** Adjust the stats for memory requested */
public void slabs_adjust_mem_requested(int id,int old,int ntotal);
/** Adjust global memory limit up or down */
public boolean slabs_adjust_mem_limit(int new_mem_limit);
/** Return a datum for stats in binary protocol */
// public boolean get_stats(long stat_type,int nkey,ADD_STAT add_stats,long c);
/** Fill buffer with stats */ /*@null@*/
// public void slabs_stats(ADD_STAT add_stats,long c);
/** Hints as to freespace in slab class
* @param id
* @param mem_flag
* @param total_bytes 内存首地址
* @param chunks_perslab 内存首地址
* @return
*/
public int slabs_available_chunks(int id,long mem_flag,long total_bytes,long chunks_perslab);
public int start_slab_maintenance_thread();
public void stop_slab_maintenance_thread();
|
// Path: src/main/java/io/mycat/jcache/enums/memory/REASSIGN_RESULT_TYPE.java
// public enum REASSIGN_RESULT_TYPE {
// REASSIGN_OK,
// REASSIGN_RUNNING,
// REASSIGN_BADCLASS,
// REASSIGN_NOSPARE,
// REASSIGN_SRC_DST_SAME
// }
// Path: src/main/java/io/mycat/jcache/memory/Slabs.java
import io.mycat.jcache.enums.memory.REASSIGN_RESULT_TYPE;
package io.mycat.jcache.memory;
public interface Slabs {
/** Allocate object of given length. 0 on error */ /*@null@*/
public static final int SLABS_ALLOC_NO_NEWPAGE = 1; /* 不允许 slabclass 分配新的 page */
public static final int SLABS_ALLOC_NEWPAGE = 0; /* 允许 slabclass 分配新的 page */
/** Init the subsystem. 1st argument is the limit on no. of bytes to allocate,
0 if no limit. 2nd argument is the growth factor; each slab will use a chunk
size equal to the previous slab's chunk size times this factor.
3rd argument specifies if the slab allocator should allocate all memory
up front (if true), or allocate memory in chunks as it is needed (if false)
*/
public void slabs_init(long limit,double factor,boolean prealloc,int[] slab_sizes);
/**
* Figures out which slab class (chunk size) is required to store an item of
* a given size.
*
* Given object size, return id to use when allocating/freeing memory for object
* 0 means error: can't store such a large object
*/
public int slabs_clsid(int size);
/**
* 获取 slabclass 的内存首地址
* @param id
* @return
*/
public long getSlabClass(int id);
/** Allocate object of given length. 0 on error
* @param size
* @param id
* @param total_bytes 内存首地址
* @param flags
* @return
*/
public long slabs_alloc(int size,int id,long total_bytes,int flags);
/** Free previously allocated object */
public void slabs_free(long addr,int size,int id);
/** Adjust the stats for memory requested */
public void slabs_adjust_mem_requested(int id,int old,int ntotal);
/** Adjust global memory limit up or down */
public boolean slabs_adjust_mem_limit(int new_mem_limit);
/** Return a datum for stats in binary protocol */
// public boolean get_stats(long stat_type,int nkey,ADD_STAT add_stats,long c);
/** Fill buffer with stats */ /*@null@*/
// public void slabs_stats(ADD_STAT add_stats,long c);
/** Hints as to freespace in slab class
* @param id
* @param mem_flag
* @param total_bytes 内存首地址
* @param chunks_perslab 内存首地址
* @return
*/
public int slabs_available_chunks(int id,long mem_flag,long total_bytes,long chunks_perslab);
public int start_slab_maintenance_thread();
public void stop_slab_maintenance_thread();
|
REASSIGN_RESULT_TYPE slabs_reassign(int src,int dst);
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/setting/Settings.java
|
// Path: src/main/java/io/mycat/jcache/enums/protocol/Protocol.java
// public enum Protocol {
// binary( 0 ),
// negotiating( 0 ), /* Discovering the protocol */
// ascii( 3 ), /* arbitrary value. */
// resp(4);/* redis protocol */
//
// private int value = 0;
//
// private Protocol(int value) {
// this.value = value;
// }
//
// public int getValue() {
// return value;
// }
//
// public void setValue( int value ) {
// this.value = value;
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/JcacheGlobalConfig.java
// public final class JcacheGlobalConfig {
//
// /**
// * 默认reactor pool 大小
// */
// public static int defaulePoolSize = Runtime.getRuntime().availableProcessors();
//
// /**
// * 默认 reactor pool 绑定地址
// */
// public static final String defaultPoolBindIp = "0.0.0.0";
//
// /**
// * 默认 reactor 选择策略
// */
// public static final String defaultReactorSelectStrategy = "ROUND_ROBIN";
//
// /**
// *
// */
// public static final int defaultMaxAcceptNum = 10000;
//
// /**
// * 默认字符编码
// */
// public static final String defaultCahrset = "UTF-8";
//
// /** Maximum length of a key */
// public static final int KEY_MAX_LENGTH = 250;
//
//
// /** Maximum length of a value */
// public static final long VALUE_MAX_LENGTH=1024*1024;
//
// /** current version */
// public static final String version = "0.5.0";
//
// /** How long an object can reasonably be assumed to be locked before
// harvesting it on a low memory condition. Default: disabled. */
// public static final int TAIL_REPAIR_TIME_DEFAULT = 0;
//
// /** Size of an incr buf. */
// public static final int INCR_MAX_STORAGE_LEN = 24;
//
// }
|
import java.util.Date;
import io.mycat.jcache.enums.protocol.Protocol;
import io.mycat.jcache.net.JcacheGlobalConfig;
import sun.misc.VM;
|
/*
* 文件创建时间: 2016年11月29日
* 文件创建者: tangww
* 所属工程: JCache
* CopyRights Received EMail Dev. Dept. 21CN
*
* 备注:
*/
package io.mycat.jcache.setting;
/**
*
* 类功能描述:TODO
* @author <a href="mailto:[email protected]">tangww</a>
* @version newEDM
* @since 2016年11月29日
*
*/
@SuppressWarnings("restriction")
public class Settings {
public static boolean useCas = true;
public static String access = "0700";
public static int port = 11211;
public static int udpport = 11211;
public static int redis_port=6378;
public static String inter = null;
public static long maxbytes = VM.maxDirectMemory()>0?VM.maxDirectMemory():64*1024*1024; //64M
public static int maxConns = 1024;
public static short verbose = 2;
public static long oldestLive = 0;
public static long oldestCas = 0;
public static short evictToFree = 1; /* push old items out of cache when memory runs out */
public static String socketPath = null;
public static boolean prealloc = true;
public static double factor = 1.25;
public static int chunkSize = 48;
public static int numThreads = 4; /* N workers */
public static int numThreadsPerUdp = 0;
public static String prefixDelimiter = ":";
public static boolean detailEnabled = false;
public static int reqsPerEvent = 20;
public static int backLog = 1024;
|
// Path: src/main/java/io/mycat/jcache/enums/protocol/Protocol.java
// public enum Protocol {
// binary( 0 ),
// negotiating( 0 ), /* Discovering the protocol */
// ascii( 3 ), /* arbitrary value. */
// resp(4);/* redis protocol */
//
// private int value = 0;
//
// private Protocol(int value) {
// this.value = value;
// }
//
// public int getValue() {
// return value;
// }
//
// public void setValue( int value ) {
// this.value = value;
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/JcacheGlobalConfig.java
// public final class JcacheGlobalConfig {
//
// /**
// * 默认reactor pool 大小
// */
// public static int defaulePoolSize = Runtime.getRuntime().availableProcessors();
//
// /**
// * 默认 reactor pool 绑定地址
// */
// public static final String defaultPoolBindIp = "0.0.0.0";
//
// /**
// * 默认 reactor 选择策略
// */
// public static final String defaultReactorSelectStrategy = "ROUND_ROBIN";
//
// /**
// *
// */
// public static final int defaultMaxAcceptNum = 10000;
//
// /**
// * 默认字符编码
// */
// public static final String defaultCahrset = "UTF-8";
//
// /** Maximum length of a key */
// public static final int KEY_MAX_LENGTH = 250;
//
//
// /** Maximum length of a value */
// public static final long VALUE_MAX_LENGTH=1024*1024;
//
// /** current version */
// public static final String version = "0.5.0";
//
// /** How long an object can reasonably be assumed to be locked before
// harvesting it on a low memory condition. Default: disabled. */
// public static final int TAIL_REPAIR_TIME_DEFAULT = 0;
//
// /** Size of an incr buf. */
// public static final int INCR_MAX_STORAGE_LEN = 24;
//
// }
// Path: src/main/java/io/mycat/jcache/setting/Settings.java
import java.util.Date;
import io.mycat.jcache.enums.protocol.Protocol;
import io.mycat.jcache.net.JcacheGlobalConfig;
import sun.misc.VM;
/*
* 文件创建时间: 2016年11月29日
* 文件创建者: tangww
* 所属工程: JCache
* CopyRights Received EMail Dev. Dept. 21CN
*
* 备注:
*/
package io.mycat.jcache.setting;
/**
*
* 类功能描述:TODO
* @author <a href="mailto:[email protected]">tangww</a>
* @version newEDM
* @since 2016年11月29日
*
*/
@SuppressWarnings("restriction")
public class Settings {
public static boolean useCas = true;
public static String access = "0700";
public static int port = 11211;
public static int udpport = 11211;
public static int redis_port=6378;
public static String inter = null;
public static long maxbytes = VM.maxDirectMemory()>0?VM.maxDirectMemory():64*1024*1024; //64M
public static int maxConns = 1024;
public static short verbose = 2;
public static long oldestLive = 0;
public static long oldestCas = 0;
public static short evictToFree = 1; /* push old items out of cache when memory runs out */
public static String socketPath = null;
public static boolean prealloc = true;
public static double factor = 1.25;
public static int chunkSize = 48;
public static int numThreads = 4; /* N workers */
public static int numThreadsPerUdp = 0;
public static String prefixDelimiter = ":";
public static boolean detailEnabled = false;
public static int reqsPerEvent = 20;
public static int backLog = 1024;
|
public static Protocol binding_protocol = Protocol.negotiating;
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/setting/Settings.java
|
// Path: src/main/java/io/mycat/jcache/enums/protocol/Protocol.java
// public enum Protocol {
// binary( 0 ),
// negotiating( 0 ), /* Discovering the protocol */
// ascii( 3 ), /* arbitrary value. */
// resp(4);/* redis protocol */
//
// private int value = 0;
//
// private Protocol(int value) {
// this.value = value;
// }
//
// public int getValue() {
// return value;
// }
//
// public void setValue( int value ) {
// this.value = value;
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/JcacheGlobalConfig.java
// public final class JcacheGlobalConfig {
//
// /**
// * 默认reactor pool 大小
// */
// public static int defaulePoolSize = Runtime.getRuntime().availableProcessors();
//
// /**
// * 默认 reactor pool 绑定地址
// */
// public static final String defaultPoolBindIp = "0.0.0.0";
//
// /**
// * 默认 reactor 选择策略
// */
// public static final String defaultReactorSelectStrategy = "ROUND_ROBIN";
//
// /**
// *
// */
// public static final int defaultMaxAcceptNum = 10000;
//
// /**
// * 默认字符编码
// */
// public static final String defaultCahrset = "UTF-8";
//
// /** Maximum length of a key */
// public static final int KEY_MAX_LENGTH = 250;
//
//
// /** Maximum length of a value */
// public static final long VALUE_MAX_LENGTH=1024*1024;
//
// /** current version */
// public static final String version = "0.5.0";
//
// /** How long an object can reasonably be assumed to be locked before
// harvesting it on a low memory condition. Default: disabled. */
// public static final int TAIL_REPAIR_TIME_DEFAULT = 0;
//
// /** Size of an incr buf. */
// public static final int INCR_MAX_STORAGE_LEN = 24;
//
// }
|
import java.util.Date;
import io.mycat.jcache.enums.protocol.Protocol;
import io.mycat.jcache.net.JcacheGlobalConfig;
import sun.misc.VM;
|
public static short evictToFree = 1; /* push old items out of cache when memory runs out */
public static String socketPath = null;
public static boolean prealloc = true;
public static double factor = 1.25;
public static int chunkSize = 48;
public static int numThreads = 4; /* N workers */
public static int numThreadsPerUdp = 0;
public static String prefixDelimiter = ":";
public static boolean detailEnabled = false;
public static int reqsPerEvent = 20;
public static int backLog = 1024;
public static Protocol binding_protocol = Protocol.negotiating;
public static int itemSizeMax = 1024*1024; /* The famous 1MB upper limit. */
public static int slabPageSize = 1024 * 1024; /* chunks are split from 1MB pages. */
public static int slabChunkSizeMax = slabPageSize;
public static boolean sasl = false; /* SASL on/off */
public static boolean maxConnsFast = false;
public static boolean lruCrawler = false;
public static int lruCrawlerSleep = 100;
public static int lruCrawlerTocrawl = 0;
public static boolean lruMaintainerThread = false; /* LRU maintainer background thread */
public static int hotLruPct = 32;
public static int warmLruPct = 32;
public static boolean expireZeroDoesNotEvict = false;
public static int idleTimeout = 0;
public static int hashpower_default = 16; /* Initial power multiplier for the hash table */
public static int hashPowerInit = hashpower_default;
public static boolean slabReassign = false; /* Whether or not slab reassignment is allowed */
public static short slabAutoMove = 0; /* Whether or not to automatically move slabs */
public static boolean shutdownCommand = false; /* allow shutdown command */
|
// Path: src/main/java/io/mycat/jcache/enums/protocol/Protocol.java
// public enum Protocol {
// binary( 0 ),
// negotiating( 0 ), /* Discovering the protocol */
// ascii( 3 ), /* arbitrary value. */
// resp(4);/* redis protocol */
//
// private int value = 0;
//
// private Protocol(int value) {
// this.value = value;
// }
//
// public int getValue() {
// return value;
// }
//
// public void setValue( int value ) {
// this.value = value;
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/JcacheGlobalConfig.java
// public final class JcacheGlobalConfig {
//
// /**
// * 默认reactor pool 大小
// */
// public static int defaulePoolSize = Runtime.getRuntime().availableProcessors();
//
// /**
// * 默认 reactor pool 绑定地址
// */
// public static final String defaultPoolBindIp = "0.0.0.0";
//
// /**
// * 默认 reactor 选择策略
// */
// public static final String defaultReactorSelectStrategy = "ROUND_ROBIN";
//
// /**
// *
// */
// public static final int defaultMaxAcceptNum = 10000;
//
// /**
// * 默认字符编码
// */
// public static final String defaultCahrset = "UTF-8";
//
// /** Maximum length of a key */
// public static final int KEY_MAX_LENGTH = 250;
//
//
// /** Maximum length of a value */
// public static final long VALUE_MAX_LENGTH=1024*1024;
//
// /** current version */
// public static final String version = "0.5.0";
//
// /** How long an object can reasonably be assumed to be locked before
// harvesting it on a low memory condition. Default: disabled. */
// public static final int TAIL_REPAIR_TIME_DEFAULT = 0;
//
// /** Size of an incr buf. */
// public static final int INCR_MAX_STORAGE_LEN = 24;
//
// }
// Path: src/main/java/io/mycat/jcache/setting/Settings.java
import java.util.Date;
import io.mycat.jcache.enums.protocol.Protocol;
import io.mycat.jcache.net.JcacheGlobalConfig;
import sun.misc.VM;
public static short evictToFree = 1; /* push old items out of cache when memory runs out */
public static String socketPath = null;
public static boolean prealloc = true;
public static double factor = 1.25;
public static int chunkSize = 48;
public static int numThreads = 4; /* N workers */
public static int numThreadsPerUdp = 0;
public static String prefixDelimiter = ":";
public static boolean detailEnabled = false;
public static int reqsPerEvent = 20;
public static int backLog = 1024;
public static Protocol binding_protocol = Protocol.negotiating;
public static int itemSizeMax = 1024*1024; /* The famous 1MB upper limit. */
public static int slabPageSize = 1024 * 1024; /* chunks are split from 1MB pages. */
public static int slabChunkSizeMax = slabPageSize;
public static boolean sasl = false; /* SASL on/off */
public static boolean maxConnsFast = false;
public static boolean lruCrawler = false;
public static int lruCrawlerSleep = 100;
public static int lruCrawlerTocrawl = 0;
public static boolean lruMaintainerThread = false; /* LRU maintainer background thread */
public static int hotLruPct = 32;
public static int warmLruPct = 32;
public static boolean expireZeroDoesNotEvict = false;
public static int idleTimeout = 0;
public static int hashpower_default = 16; /* Initial power multiplier for the hash table */
public static int hashPowerInit = hashpower_default;
public static boolean slabReassign = false; /* Whether or not slab reassignment is allowed */
public static short slabAutoMove = 0; /* Whether or not to automatically move slabs */
public static boolean shutdownCommand = false; /* allow shutdown command */
|
public static long tailRepairTime = JcacheGlobalConfig.TAIL_REPAIR_TIME_DEFAULT; /* LRU tail refcount leak repair time */
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/net/conn/handler/IOHandlerFactory.java
|
// Path: src/main/java/io/mycat/jcache/enums/protocol/Protocol.java
// public enum Protocol {
// binary( 0 ),
// negotiating( 0 ), /* Discovering the protocol */
// ascii( 3 ), /* arbitrary value. */
// resp(4);/* redis protocol */
//
// private int value = 0;
//
// private Protocol(int value) {
// this.value = value;
// }
//
// public int getValue() {
// return value;
// }
//
// public void setValue( int value ) {
// this.value = value;
// }
// }
|
import io.mycat.jcache.enums.protocol.Protocol;
|
package io.mycat.jcache.net.conn.handler;
/**
* @author dragonwu
* @date 17/1/20
**/
public class IOHandlerFactory {
private static final IOHandler ASCII_IO_HANDLER = new AsciiIOHanlder();
private static final IOHandler BINARY_IO_HANDLER = new BinaryIOHandler();
private static final IOHandler REDIS_IO_HANDLER = new RedisIOHandler();
private IOHandlerFactory() {
}
|
// Path: src/main/java/io/mycat/jcache/enums/protocol/Protocol.java
// public enum Protocol {
// binary( 0 ),
// negotiating( 0 ), /* Discovering the protocol */
// ascii( 3 ), /* arbitrary value. */
// resp(4);/* redis protocol */
//
// private int value = 0;
//
// private Protocol(int value) {
// this.value = value;
// }
//
// public int getValue() {
// return value;
// }
//
// public void setValue( int value ) {
// this.value = value;
// }
// }
// Path: src/main/java/io/mycat/jcache/net/conn/handler/IOHandlerFactory.java
import io.mycat.jcache.enums.protocol.Protocol;
package io.mycat.jcache.net.conn.handler;
/**
* @author dragonwu
* @date 17/1/20
**/
public class IOHandlerFactory {
private static final IOHandler ASCII_IO_HANDLER = new AsciiIOHanlder();
private static final IOHandler BINARY_IO_HANDLER = new BinaryIOHandler();
private static final IOHandler REDIS_IO_HANDLER = new RedisIOHandler();
private IOHandlerFactory() {
}
|
public static IOHandler getHandler(Protocol protocol) {
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/net/conn/handler/RedisCommandHandlerFactory.java
|
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisGetCommandHandler.java
// public class RedisGetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn,RedisMessage message) {
// logger.debug("handle get command....");
// String[] cmdParams = message.cmdParams();
// String params = cmdParams[1];
//
// ConcurrentMap<String, Object> strStorage = RedisStorage.getStringStorage();
// if(!strStorage.containsKey(params)){
// message.addNilReply(message);
// writeResponseToClient(conn,message);
// return;
// }
// String value = (String)strStorage.get(params);
// if(value==null || value.equals("")){
// message.addNilReply(message);
// }else {
// message.replay("$" + value.length() + "\r\n" + value + "\r\n");
// }
// writeResponseToClient(conn,message);
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisSetCommandHandler.java
// public class RedisSetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn, RedisMessage message) {
// logger.debug("set command handler....");
// String key = message.cmdParams()[1];
// Object value = message.cmdParams()[2];
//
// RedisStorage.getStringStorage().put(key,value);
//
// message.replay("OK\r\n");
// writeResponseToClient(conn,message);
// }
// }
|
import io.mycat.jcache.net.conn.handler.redis.strings.RedisGetCommandHandler;
import io.mycat.jcache.net.conn.handler.redis.strings.RedisSetCommandHandler;
|
package io.mycat.jcache.net.conn.handler;
/**
* command handler 工厂类
* @author yangll
* @create 2017-07-18 21:08
*/
public final class RedisCommandHandlerFactory {
/**
* 根据不同的cmd,返回不同的命令处理器
* @param cmd
* @return
*/
public static RedisCommandHandler getHandler(String cmd){
switch (cmd){
case "get":
|
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisGetCommandHandler.java
// public class RedisGetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn,RedisMessage message) {
// logger.debug("handle get command....");
// String[] cmdParams = message.cmdParams();
// String params = cmdParams[1];
//
// ConcurrentMap<String, Object> strStorage = RedisStorage.getStringStorage();
// if(!strStorage.containsKey(params)){
// message.addNilReply(message);
// writeResponseToClient(conn,message);
// return;
// }
// String value = (String)strStorage.get(params);
// if(value==null || value.equals("")){
// message.addNilReply(message);
// }else {
// message.replay("$" + value.length() + "\r\n" + value + "\r\n");
// }
// writeResponseToClient(conn,message);
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisSetCommandHandler.java
// public class RedisSetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn, RedisMessage message) {
// logger.debug("set command handler....");
// String key = message.cmdParams()[1];
// Object value = message.cmdParams()[2];
//
// RedisStorage.getStringStorage().put(key,value);
//
// message.replay("OK\r\n");
// writeResponseToClient(conn,message);
// }
// }
// Path: src/main/java/io/mycat/jcache/net/conn/handler/RedisCommandHandlerFactory.java
import io.mycat.jcache.net.conn.handler.redis.strings.RedisGetCommandHandler;
import io.mycat.jcache.net.conn.handler.redis.strings.RedisSetCommandHandler;
package io.mycat.jcache.net.conn.handler;
/**
* command handler 工厂类
* @author yangll
* @create 2017-07-18 21:08
*/
public final class RedisCommandHandlerFactory {
/**
* 根据不同的cmd,返回不同的命令处理器
* @param cmd
* @return
*/
public static RedisCommandHandler getHandler(String cmd){
switch (cmd){
case "get":
|
return new RedisGetCommandHandler();
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/net/conn/handler/RedisCommandHandlerFactory.java
|
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisGetCommandHandler.java
// public class RedisGetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn,RedisMessage message) {
// logger.debug("handle get command....");
// String[] cmdParams = message.cmdParams();
// String params = cmdParams[1];
//
// ConcurrentMap<String, Object> strStorage = RedisStorage.getStringStorage();
// if(!strStorage.containsKey(params)){
// message.addNilReply(message);
// writeResponseToClient(conn,message);
// return;
// }
// String value = (String)strStorage.get(params);
// if(value==null || value.equals("")){
// message.addNilReply(message);
// }else {
// message.replay("$" + value.length() + "\r\n" + value + "\r\n");
// }
// writeResponseToClient(conn,message);
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisSetCommandHandler.java
// public class RedisSetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn, RedisMessage message) {
// logger.debug("set command handler....");
// String key = message.cmdParams()[1];
// Object value = message.cmdParams()[2];
//
// RedisStorage.getStringStorage().put(key,value);
//
// message.replay("OK\r\n");
// writeResponseToClient(conn,message);
// }
// }
|
import io.mycat.jcache.net.conn.handler.redis.strings.RedisGetCommandHandler;
import io.mycat.jcache.net.conn.handler.redis.strings.RedisSetCommandHandler;
|
package io.mycat.jcache.net.conn.handler;
/**
* command handler 工厂类
* @author yangll
* @create 2017-07-18 21:08
*/
public final class RedisCommandHandlerFactory {
/**
* 根据不同的cmd,返回不同的命令处理器
* @param cmd
* @return
*/
public static RedisCommandHandler getHandler(String cmd){
switch (cmd){
case "get":
return new RedisGetCommandHandler();
case "set":
|
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisGetCommandHandler.java
// public class RedisGetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn,RedisMessage message) {
// logger.debug("handle get command....");
// String[] cmdParams = message.cmdParams();
// String params = cmdParams[1];
//
// ConcurrentMap<String, Object> strStorage = RedisStorage.getStringStorage();
// if(!strStorage.containsKey(params)){
// message.addNilReply(message);
// writeResponseToClient(conn,message);
// return;
// }
// String value = (String)strStorage.get(params);
// if(value==null || value.equals("")){
// message.addNilReply(message);
// }else {
// message.replay("$" + value.length() + "\r\n" + value + "\r\n");
// }
// writeResponseToClient(conn,message);
// }
// }
//
// Path: src/main/java/io/mycat/jcache/net/conn/handler/redis/strings/RedisSetCommandHandler.java
// public class RedisSetCommandHandler extends AbstractRedisComandHandler {
//
// private static final Logger logger = LoggerFactory.getLogger(RedisGetCommandHandler.class);
//
// @Override
// public void handle(Connection conn, RedisMessage message) {
// logger.debug("set command handler....");
// String key = message.cmdParams()[1];
// Object value = message.cmdParams()[2];
//
// RedisStorage.getStringStorage().put(key,value);
//
// message.replay("OK\r\n");
// writeResponseToClient(conn,message);
// }
// }
// Path: src/main/java/io/mycat/jcache/net/conn/handler/RedisCommandHandlerFactory.java
import io.mycat.jcache.net.conn.handler.redis.strings.RedisGetCommandHandler;
import io.mycat.jcache.net.conn.handler.redis.strings.RedisSetCommandHandler;
package io.mycat.jcache.net.conn.handler;
/**
* command handler 工厂类
* @author yangll
* @create 2017-07-18 21:08
*/
public final class RedisCommandHandlerFactory {
/**
* 根据不同的cmd,返回不同的命令处理器
* @param cmd
* @return
*/
public static RedisCommandHandler getHandler(String cmd){
switch (cmd){
case "get":
return new RedisGetCommandHandler();
case "set":
|
return new RedisSetCommandHandler();
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/net/strategy/RoundRobinStrategy.java
|
// Path: src/main/java/io/mycat/jcache/net/NIOReactor.java
// public final class NIOReactor extends Thread{
// private static final Logger logger = LoggerFactory.getLogger(NIOReactor.class);
//
// private final Selector selector;
//
// private final LinkedTransferQueue<Connection> registerQueue;
//
// public NIOReactor(String name) throws IOException {
// super.setName(name);
// this.selector = Selector.open();
// this.registerQueue = new LinkedTransferQueue<>(); // 这里不使用 ConcurrentLinkedQueue 的原因在于,可能acceptor 和reactor同时操作队列
// }
//
// /**
// * 将新的连接请求 放到 reactor 的请求队列中,同时唤醒 reactor selector
// * @param socketChannel
// */
// final void registerNewClient(Connection conn) {
// registerQueue.offer(conn);
// selector.wakeup();
// }
//
// @Override
// public void run() {
// final Selector selector = this.selector;
// Set<SelectionKey> keys = null;
// int readys=0;
// for (;;) {
// try {
// // 400/(readys+1)
// readys=selector.select(400); //借鉴mycat-core
// if(readys==0) // 没有需要处理的事件时,处理新连接请求 注册 read 事件
// {
// handlerEvents(selector);
// continue;
// }
// keys = selector.selectedKeys();
// for(SelectionKey key:keys)
// {
// Connection con = (Connection)key.attachment();
// logger.info("select-key-readyOps = {}, attachment = {}", key.readyOps(), con);
// // JcacheContext.getExecutor().execute(con);
// con.run();
// }
// } catch (Throwable e) {
// logger.warn(getName(), e);
// } finally {
// if (keys != null) {
// keys.clear();
// }
// }
// handlerEvents(selector); //处理完成事件后,处理新里连接请求 注册 read 事件
// }
// }
//
// // private void processEvents() {
// // TODO
// // if(events.isEmpty())
// // {
// // return;
// // }
// // Object[] objs=events.toArray();
// // if(objs.length>0)
// // {
// // for(Object obj:objs)
// // {
// // ((Runnable)obj).run();
// // }
// // events.removeAll(Arrays.asList(objs));
// // }
// // }
//
// private void handlerEvents(Selector selector)
// {
// try
// {
// register(selector); //注册 selector 读写事件
// }catch(Exception e)
// {
// logger.warn("caught user event err:",e);
// }
// }
//
// /**
// * 注册 io 读写事件
// * @param selector
// */
// private void register(Selector selector) {
// if (registerQueue.isEmpty()) {
// return;
// }
// Connection c = null;
// while ((c = registerQueue.poll()) != null) {
// try {
// c.register(selector);
// } catch (Throwable e) {
// logger.warn("register error ", e);
// c.close("register err");
// }
// }
// }
// }
|
import io.mycat.jcache.net.NIOReactor;
|
package io.mycat.jcache.net.strategy;
/**
* 轮询策略
* @author liyanjun
*
*/
public class RoundRobinStrategy implements ReactorStrategy{
@Override
|
// Path: src/main/java/io/mycat/jcache/net/NIOReactor.java
// public final class NIOReactor extends Thread{
// private static final Logger logger = LoggerFactory.getLogger(NIOReactor.class);
//
// private final Selector selector;
//
// private final LinkedTransferQueue<Connection> registerQueue;
//
// public NIOReactor(String name) throws IOException {
// super.setName(name);
// this.selector = Selector.open();
// this.registerQueue = new LinkedTransferQueue<>(); // 这里不使用 ConcurrentLinkedQueue 的原因在于,可能acceptor 和reactor同时操作队列
// }
//
// /**
// * 将新的连接请求 放到 reactor 的请求队列中,同时唤醒 reactor selector
// * @param socketChannel
// */
// final void registerNewClient(Connection conn) {
// registerQueue.offer(conn);
// selector.wakeup();
// }
//
// @Override
// public void run() {
// final Selector selector = this.selector;
// Set<SelectionKey> keys = null;
// int readys=0;
// for (;;) {
// try {
// // 400/(readys+1)
// readys=selector.select(400); //借鉴mycat-core
// if(readys==0) // 没有需要处理的事件时,处理新连接请求 注册 read 事件
// {
// handlerEvents(selector);
// continue;
// }
// keys = selector.selectedKeys();
// for(SelectionKey key:keys)
// {
// Connection con = (Connection)key.attachment();
// logger.info("select-key-readyOps = {}, attachment = {}", key.readyOps(), con);
// // JcacheContext.getExecutor().execute(con);
// con.run();
// }
// } catch (Throwable e) {
// logger.warn(getName(), e);
// } finally {
// if (keys != null) {
// keys.clear();
// }
// }
// handlerEvents(selector); //处理完成事件后,处理新里连接请求 注册 read 事件
// }
// }
//
// // private void processEvents() {
// // TODO
// // if(events.isEmpty())
// // {
// // return;
// // }
// // Object[] objs=events.toArray();
// // if(objs.length>0)
// // {
// // for(Object obj:objs)
// // {
// // ((Runnable)obj).run();
// // }
// // events.removeAll(Arrays.asList(objs));
// // }
// // }
//
// private void handlerEvents(Selector selector)
// {
// try
// {
// register(selector); //注册 selector 读写事件
// }catch(Exception e)
// {
// logger.warn("caught user event err:",e);
// }
// }
//
// /**
// * 注册 io 读写事件
// * @param selector
// */
// private void register(Selector selector) {
// if (registerQueue.isEmpty()) {
// return;
// }
// Connection c = null;
// while ((c = registerQueue.poll()) != null) {
// try {
// c.register(selector);
// } catch (Throwable e) {
// logger.warn("register error ", e);
// c.close("register err");
// }
// }
// }
// }
// Path: src/main/java/io/mycat/jcache/net/strategy/RoundRobinStrategy.java
import io.mycat.jcache.net.NIOReactor;
package io.mycat.jcache.net.strategy;
/**
* 轮询策略
* @author liyanjun
*
*/
public class RoundRobinStrategy implements ReactorStrategy{
@Override
|
public int getNextReactor(NIOReactor[] reactors,int lastreactor) {
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/hash/TestHashCode.java
|
// Path: src/main/java/io/mycat/jcache/enums/hash/Hash_func_type.java
// public enum Hash_func_type {
// JENKINS_HASH, MURMUR3_HASH, PIG_HASH
// }
//
// Path: src/main/java/io/mycat/jcache/hash/impl/HashImpl.java
// @Deprecated
// public class HashImpl implements Hash_init {
//
// private Hash hash;
//
// @Override
// public long hash(String key, long... length) {
// return hash.hash(key);
// }
//
// @Override
// public int hash_init(Hash_func_type type) {
// switch (type){
// case JENKINS_HASH:
// Settings.hash_algorithm="jenkins";
// hash = new Jenkins_hash();
// break;
// case MURMUR3_HASH:
// Settings.hash_algorithm="murmur3";
// break;
// case PIG_HASH:
// Settings.hash_algorithm="Pig_SDBM_hash";
// hash = new Pig_SDBM_hash();
// break;
// default:
// return -1;
// }
// return 0;
// }
// public HashImpl(){
// }
//
// public HashImpl(Hash_func_type hashfunc_type){
// hash_init(hashfunc_type);
// }
// }
|
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.UUID;
import io.mycat.jcache.enums.hash.Hash_func_type;
import io.mycat.jcache.hash.impl.HashImpl;
|
/*
* 文件创建时间: 2016年12月11日
* 文件创建者: PigBrother(LZY/LZS)二师兄
* 所属工程: JCache
* CopyRights
*
* 备注:
*/
package io.mycat.jcache.hash;
/**
* Created by PigBrother(LZS/LZY) on 2016/12/12 17:16.
*/
/**
* 类功能描述:test类 demo
* <p>
* 方法调用:
* Hash hash = new HashImpl(Hash_func_type.PIG_HASH);
* hash.hash(key); //此处返回 自定义 hashcode
* 新的hashcode 为 long 类型 冲突率 较 原生的hashcode 小一些
* 数据如下 若条件允许 可以 生成几乎不冲突的hashcode 条件是接受long[]类型的hashcode数组
* 数据量 :随机字符串不相同的个数:java自带hashcode的不相同个数:优化后的hashcode的不相同个数
* Tue Dec 13 08:27:41 CST 2016 :1 :1 :1 :1
* Tue Dec 13 08:27:41 CST 2016 :10 :10 :10 :10
* Tue Dec 13 08:27:41 CST 2016 :100 :100 :100 :100
* Tue Dec 13 08:27:42 CST 2016 :1000 :1000 :1000 :1000
* Tue Dec 13 08:27:42 CST 2016 :10000 :10000 :10000 :10000
* Tue Dec 13 08:27:42 CST 2016 :100000 :100000 :99995 :100000
* Tue Dec 13 08:27:47 CST 2016 :1000000 :1000000 :999892 :1000000
* Tue Dec 13 08:29:55 CST 2016 :10000000 :10000000 :9988403 :10000000
* <p>
* <p>
* <p>
* <p>
* <p> 版权所有:
* <p> 未经许可,不得以任何方式复制或使用本程序任何部分 <p>
*
* @author <a href="mailto:[email protected]">PigBrother</a>
* @version 0.0.1
* @since 2016年12月11日
*/
public class TestHashCode {
public static void main(String[] args) {
|
// Path: src/main/java/io/mycat/jcache/enums/hash/Hash_func_type.java
// public enum Hash_func_type {
// JENKINS_HASH, MURMUR3_HASH, PIG_HASH
// }
//
// Path: src/main/java/io/mycat/jcache/hash/impl/HashImpl.java
// @Deprecated
// public class HashImpl implements Hash_init {
//
// private Hash hash;
//
// @Override
// public long hash(String key, long... length) {
// return hash.hash(key);
// }
//
// @Override
// public int hash_init(Hash_func_type type) {
// switch (type){
// case JENKINS_HASH:
// Settings.hash_algorithm="jenkins";
// hash = new Jenkins_hash();
// break;
// case MURMUR3_HASH:
// Settings.hash_algorithm="murmur3";
// break;
// case PIG_HASH:
// Settings.hash_algorithm="Pig_SDBM_hash";
// hash = new Pig_SDBM_hash();
// break;
// default:
// return -1;
// }
// return 0;
// }
// public HashImpl(){
// }
//
// public HashImpl(Hash_func_type hashfunc_type){
// hash_init(hashfunc_type);
// }
// }
// Path: src/main/java/io/mycat/jcache/hash/TestHashCode.java
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.UUID;
import io.mycat.jcache.enums.hash.Hash_func_type;
import io.mycat.jcache.hash.impl.HashImpl;
/*
* 文件创建时间: 2016年12月11日
* 文件创建者: PigBrother(LZY/LZS)二师兄
* 所属工程: JCache
* CopyRights
*
* 备注:
*/
package io.mycat.jcache.hash;
/**
* Created by PigBrother(LZS/LZY) on 2016/12/12 17:16.
*/
/**
* 类功能描述:test类 demo
* <p>
* 方法调用:
* Hash hash = new HashImpl(Hash_func_type.PIG_HASH);
* hash.hash(key); //此处返回 自定义 hashcode
* 新的hashcode 为 long 类型 冲突率 较 原生的hashcode 小一些
* 数据如下 若条件允许 可以 生成几乎不冲突的hashcode 条件是接受long[]类型的hashcode数组
* 数据量 :随机字符串不相同的个数:java自带hashcode的不相同个数:优化后的hashcode的不相同个数
* Tue Dec 13 08:27:41 CST 2016 :1 :1 :1 :1
* Tue Dec 13 08:27:41 CST 2016 :10 :10 :10 :10
* Tue Dec 13 08:27:41 CST 2016 :100 :100 :100 :100
* Tue Dec 13 08:27:42 CST 2016 :1000 :1000 :1000 :1000
* Tue Dec 13 08:27:42 CST 2016 :10000 :10000 :10000 :10000
* Tue Dec 13 08:27:42 CST 2016 :100000 :100000 :99995 :100000
* Tue Dec 13 08:27:47 CST 2016 :1000000 :1000000 :999892 :1000000
* Tue Dec 13 08:29:55 CST 2016 :10000000 :10000000 :9988403 :10000000
* <p>
* <p>
* <p>
* <p>
* <p> 版权所有:
* <p> 未经许可,不得以任何方式复制或使用本程序任何部分 <p>
*
* @author <a href="mailto:[email protected]">PigBrother</a>
* @version 0.0.1
* @since 2016年12月11日
*/
public class TestHashCode {
public static void main(String[] args) {
|
Hash_init hash = new HashImpl();
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/hash/TestHashCode.java
|
// Path: src/main/java/io/mycat/jcache/enums/hash/Hash_func_type.java
// public enum Hash_func_type {
// JENKINS_HASH, MURMUR3_HASH, PIG_HASH
// }
//
// Path: src/main/java/io/mycat/jcache/hash/impl/HashImpl.java
// @Deprecated
// public class HashImpl implements Hash_init {
//
// private Hash hash;
//
// @Override
// public long hash(String key, long... length) {
// return hash.hash(key);
// }
//
// @Override
// public int hash_init(Hash_func_type type) {
// switch (type){
// case JENKINS_HASH:
// Settings.hash_algorithm="jenkins";
// hash = new Jenkins_hash();
// break;
// case MURMUR3_HASH:
// Settings.hash_algorithm="murmur3";
// break;
// case PIG_HASH:
// Settings.hash_algorithm="Pig_SDBM_hash";
// hash = new Pig_SDBM_hash();
// break;
// default:
// return -1;
// }
// return 0;
// }
// public HashImpl(){
// }
//
// public HashImpl(Hash_func_type hashfunc_type){
// hash_init(hashfunc_type);
// }
// }
|
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.UUID;
import io.mycat.jcache.enums.hash.Hash_func_type;
import io.mycat.jcache.hash.impl.HashImpl;
|
/*
* 文件创建时间: 2016年12月11日
* 文件创建者: PigBrother(LZY/LZS)二师兄
* 所属工程: JCache
* CopyRights
*
* 备注:
*/
package io.mycat.jcache.hash;
/**
* Created by PigBrother(LZS/LZY) on 2016/12/12 17:16.
*/
/**
* 类功能描述:test类 demo
* <p>
* 方法调用:
* Hash hash = new HashImpl(Hash_func_type.PIG_HASH);
* hash.hash(key); //此处返回 自定义 hashcode
* 新的hashcode 为 long 类型 冲突率 较 原生的hashcode 小一些
* 数据如下 若条件允许 可以 生成几乎不冲突的hashcode 条件是接受long[]类型的hashcode数组
* 数据量 :随机字符串不相同的个数:java自带hashcode的不相同个数:优化后的hashcode的不相同个数
* Tue Dec 13 08:27:41 CST 2016 :1 :1 :1 :1
* Tue Dec 13 08:27:41 CST 2016 :10 :10 :10 :10
* Tue Dec 13 08:27:41 CST 2016 :100 :100 :100 :100
* Tue Dec 13 08:27:42 CST 2016 :1000 :1000 :1000 :1000
* Tue Dec 13 08:27:42 CST 2016 :10000 :10000 :10000 :10000
* Tue Dec 13 08:27:42 CST 2016 :100000 :100000 :99995 :100000
* Tue Dec 13 08:27:47 CST 2016 :1000000 :1000000 :999892 :1000000
* Tue Dec 13 08:29:55 CST 2016 :10000000 :10000000 :9988403 :10000000
* <p>
* <p>
* <p>
* <p>
* <p> 版权所有:
* <p> 未经许可,不得以任何方式复制或使用本程序任何部分 <p>
*
* @author <a href="mailto:[email protected]">PigBrother</a>
* @version 0.0.1
* @since 2016年12月11日
*/
public class TestHashCode {
public static void main(String[] args) {
Hash_init hash = new HashImpl();
|
// Path: src/main/java/io/mycat/jcache/enums/hash/Hash_func_type.java
// public enum Hash_func_type {
// JENKINS_HASH, MURMUR3_HASH, PIG_HASH
// }
//
// Path: src/main/java/io/mycat/jcache/hash/impl/HashImpl.java
// @Deprecated
// public class HashImpl implements Hash_init {
//
// private Hash hash;
//
// @Override
// public long hash(String key, long... length) {
// return hash.hash(key);
// }
//
// @Override
// public int hash_init(Hash_func_type type) {
// switch (type){
// case JENKINS_HASH:
// Settings.hash_algorithm="jenkins";
// hash = new Jenkins_hash();
// break;
// case MURMUR3_HASH:
// Settings.hash_algorithm="murmur3";
// break;
// case PIG_HASH:
// Settings.hash_algorithm="Pig_SDBM_hash";
// hash = new Pig_SDBM_hash();
// break;
// default:
// return -1;
// }
// return 0;
// }
// public HashImpl(){
// }
//
// public HashImpl(Hash_func_type hashfunc_type){
// hash_init(hashfunc_type);
// }
// }
// Path: src/main/java/io/mycat/jcache/hash/TestHashCode.java
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.UUID;
import io.mycat.jcache.enums.hash.Hash_func_type;
import io.mycat.jcache.hash.impl.HashImpl;
/*
* 文件创建时间: 2016年12月11日
* 文件创建者: PigBrother(LZY/LZS)二师兄
* 所属工程: JCache
* CopyRights
*
* 备注:
*/
package io.mycat.jcache.hash;
/**
* Created by PigBrother(LZS/LZY) on 2016/12/12 17:16.
*/
/**
* 类功能描述:test类 demo
* <p>
* 方法调用:
* Hash hash = new HashImpl(Hash_func_type.PIG_HASH);
* hash.hash(key); //此处返回 自定义 hashcode
* 新的hashcode 为 long 类型 冲突率 较 原生的hashcode 小一些
* 数据如下 若条件允许 可以 生成几乎不冲突的hashcode 条件是接受long[]类型的hashcode数组
* 数据量 :随机字符串不相同的个数:java自带hashcode的不相同个数:优化后的hashcode的不相同个数
* Tue Dec 13 08:27:41 CST 2016 :1 :1 :1 :1
* Tue Dec 13 08:27:41 CST 2016 :10 :10 :10 :10
* Tue Dec 13 08:27:41 CST 2016 :100 :100 :100 :100
* Tue Dec 13 08:27:42 CST 2016 :1000 :1000 :1000 :1000
* Tue Dec 13 08:27:42 CST 2016 :10000 :10000 :10000 :10000
* Tue Dec 13 08:27:42 CST 2016 :100000 :100000 :99995 :100000
* Tue Dec 13 08:27:47 CST 2016 :1000000 :1000000 :999892 :1000000
* Tue Dec 13 08:29:55 CST 2016 :10000000 :10000000 :9988403 :10000000
* <p>
* <p>
* <p>
* <p>
* <p> 版权所有:
* <p> 未经许可,不得以任何方式复制或使用本程序任何部分 <p>
*
* @author <a href="mailto:[email protected]">PigBrother</a>
* @version 0.0.1
* @since 2016年12月11日
*/
public class TestHashCode {
public static void main(String[] args) {
Hash_init hash = new HashImpl();
|
hash.hash_init(Hash_func_type.PIG_HASH);
|
MyCATApache/Mycat-JCache
|
src/main/java/io/mycat/jcache/crawler/CrawlerExpiredData.java
|
// Path: src/main/java/io/mycat/jcache/setting/Settings.java
// @SuppressWarnings("restriction")
// public class Settings {
// public static boolean useCas = true;
// public static String access = "0700";
// public static int port = 11211;
// public static int udpport = 11211;
// public static int redis_port=6378;
// public static String inter = null;
//
// public static long maxbytes = VM.maxDirectMemory()>0?VM.maxDirectMemory():64*1024*1024; //64M
// public static int maxConns = 1024;
// public static short verbose = 2;
// public static long oldestLive = 0;
// public static long oldestCas = 0;
// public static short evictToFree = 1; /* push old items out of cache when memory runs out */
// public static String socketPath = null;
// public static boolean prealloc = true;
// public static double factor = 1.25;
// public static int chunkSize = 48;
// public static int numThreads = 4; /* N workers */
// public static int numThreadsPerUdp = 0;
// public static String prefixDelimiter = ":";
// public static boolean detailEnabled = false;
// public static int reqsPerEvent = 20;
// public static int backLog = 1024;
// public static Protocol binding_protocol = Protocol.negotiating;
// public static int itemSizeMax = 1024*1024; /* The famous 1MB upper limit. */
// public static int slabPageSize = 1024 * 1024; /* chunks are split from 1MB pages. */
// public static int slabChunkSizeMax = slabPageSize;
// public static boolean sasl = false; /* SASL on/off */
// public static boolean maxConnsFast = false;
// public static boolean lruCrawler = false;
// public static int lruCrawlerSleep = 100;
// public static int lruCrawlerTocrawl = 0;
// public static boolean lruMaintainerThread = false; /* LRU maintainer background thread */
// public static int hotLruPct = 32;
// public static int warmLruPct = 32;
// public static boolean expireZeroDoesNotEvict = false;
// public static int idleTimeout = 0;
// public static int hashpower_default = 16; /* Initial power multiplier for the hash table */
// public static int hashPowerInit = hashpower_default;
// public static boolean slabReassign = false; /* Whether or not slab reassignment is allowed */
// public static short slabAutoMove = 0; /* Whether or not to automatically move slabs */
// public static boolean shutdownCommand = false; /* allow shutdown command */
// public static long tailRepairTime = JcacheGlobalConfig.TAIL_REPAIR_TIME_DEFAULT; /* LRU tail refcount leak repair time */
// public static boolean flushEnabled = true; /* flush_all enabled */
// public static int crawlsPerSleep = 1000; /* Number of seconds to let connections idle */
// public static int loggerWatcherBufSize = 1024; /* size of logger's per-watcher buffer */
// public static int loggerBufSize = 1024; /* size of per-thread logger buffer */
//
// public static boolean lru_crawler = false;
// public static int lru_crawler_sleep = 100;
// public static int lru_crawler_tocrawl = 0;
// public static boolean lru_maintainer_thread = false;
// public static long current_time = new Date().getTime();
//
// public static String hash_algorithm; //PigBrother hash algorithm
//
// /*
// * We only reposition items in the LRU queue if they haven't been repositioned
// * in this many seconds. That saves us from churning on frequently-accessed
// * items.
// */
// public static int ITEM_UPDATE_INTERVAL= 60 * 1000;
//
// public static int hashsize; //临时参数
//
// public static String mapfile; // MappedByteBuffer 内存映射文件地址
//
// public static long process_started = System.currentTimeMillis();
//
//
//
//
// public static final int MAX_NUMBER_OF_SLAB_CLASSES = 64;
// public static final int POWER_SMALLEST = 1;
// public static final int POWER_LARGEST = 256;
// public static final int CHUNK_ALIGN_BYTES = 8;
// public static final int SLAB_GLOBAL_PAGE_POOL = 0; /* magic slab class for storing pages for reassignment */
// public static final int ITEM_HEADER_LENGTH = 52; /* item header length */
// public static final int MAX_MAINTCRAWL_WAIT = 60 * 60;
// public static final int slab_automove = 0;
// public static final boolean expirezero_does_not_evict = false;
// }
|
import java.util.concurrent.atomic.AtomicBoolean;
import io.mycat.jcache.setting.Settings;
|
package io.mycat.jcache.crawler;
/**
* item爬虫常量定义
* @author Tommy
*
*/
public class CrawlerExpiredData {
public static AtomicBoolean lock = new AtomicBoolean(false);
|
// Path: src/main/java/io/mycat/jcache/setting/Settings.java
// @SuppressWarnings("restriction")
// public class Settings {
// public static boolean useCas = true;
// public static String access = "0700";
// public static int port = 11211;
// public static int udpport = 11211;
// public static int redis_port=6378;
// public static String inter = null;
//
// public static long maxbytes = VM.maxDirectMemory()>0?VM.maxDirectMemory():64*1024*1024; //64M
// public static int maxConns = 1024;
// public static short verbose = 2;
// public static long oldestLive = 0;
// public static long oldestCas = 0;
// public static short evictToFree = 1; /* push old items out of cache when memory runs out */
// public static String socketPath = null;
// public static boolean prealloc = true;
// public static double factor = 1.25;
// public static int chunkSize = 48;
// public static int numThreads = 4; /* N workers */
// public static int numThreadsPerUdp = 0;
// public static String prefixDelimiter = ":";
// public static boolean detailEnabled = false;
// public static int reqsPerEvent = 20;
// public static int backLog = 1024;
// public static Protocol binding_protocol = Protocol.negotiating;
// public static int itemSizeMax = 1024*1024; /* The famous 1MB upper limit. */
// public static int slabPageSize = 1024 * 1024; /* chunks are split from 1MB pages. */
// public static int slabChunkSizeMax = slabPageSize;
// public static boolean sasl = false; /* SASL on/off */
// public static boolean maxConnsFast = false;
// public static boolean lruCrawler = false;
// public static int lruCrawlerSleep = 100;
// public static int lruCrawlerTocrawl = 0;
// public static boolean lruMaintainerThread = false; /* LRU maintainer background thread */
// public static int hotLruPct = 32;
// public static int warmLruPct = 32;
// public static boolean expireZeroDoesNotEvict = false;
// public static int idleTimeout = 0;
// public static int hashpower_default = 16; /* Initial power multiplier for the hash table */
// public static int hashPowerInit = hashpower_default;
// public static boolean slabReassign = false; /* Whether or not slab reassignment is allowed */
// public static short slabAutoMove = 0; /* Whether or not to automatically move slabs */
// public static boolean shutdownCommand = false; /* allow shutdown command */
// public static long tailRepairTime = JcacheGlobalConfig.TAIL_REPAIR_TIME_DEFAULT; /* LRU tail refcount leak repair time */
// public static boolean flushEnabled = true; /* flush_all enabled */
// public static int crawlsPerSleep = 1000; /* Number of seconds to let connections idle */
// public static int loggerWatcherBufSize = 1024; /* size of logger's per-watcher buffer */
// public static int loggerBufSize = 1024; /* size of per-thread logger buffer */
//
// public static boolean lru_crawler = false;
// public static int lru_crawler_sleep = 100;
// public static int lru_crawler_tocrawl = 0;
// public static boolean lru_maintainer_thread = false;
// public static long current_time = new Date().getTime();
//
// public static String hash_algorithm; //PigBrother hash algorithm
//
// /*
// * We only reposition items in the LRU queue if they haven't been repositioned
// * in this many seconds. That saves us from churning on frequently-accessed
// * items.
// */
// public static int ITEM_UPDATE_INTERVAL= 60 * 1000;
//
// public static int hashsize; //临时参数
//
// public static String mapfile; // MappedByteBuffer 内存映射文件地址
//
// public static long process_started = System.currentTimeMillis();
//
//
//
//
// public static final int MAX_NUMBER_OF_SLAB_CLASSES = 64;
// public static final int POWER_SMALLEST = 1;
// public static final int POWER_LARGEST = 256;
// public static final int CHUNK_ALIGN_BYTES = 8;
// public static final int SLAB_GLOBAL_PAGE_POOL = 0; /* magic slab class for storing pages for reassignment */
// public static final int ITEM_HEADER_LENGTH = 52; /* item header length */
// public static final int MAX_MAINTCRAWL_WAIT = 60 * 60;
// public static final int slab_automove = 0;
// public static final boolean expirezero_does_not_evict = false;
// }
// Path: src/main/java/io/mycat/jcache/crawler/CrawlerExpiredData.java
import java.util.concurrent.atomic.AtomicBoolean;
import io.mycat.jcache.setting.Settings;
package io.mycat.jcache.crawler;
/**
* item爬虫常量定义
* @author Tommy
*
*/
public class CrawlerExpiredData {
public static AtomicBoolean lock = new AtomicBoolean(false);
|
public CrawlerstatsT crawlerstats[] = new CrawlerstatsT[Settings.MAX_NUMBER_OF_SLAB_CLASSES];
|
j256/simplecsv
|
src/test/java/com/j256/simplecsv/processor/RowValidatorTest.java
|
// Path: src/main/java/com/j256/simplecsv/processor/ParseError.java
// public enum ErrorType {
// /** no error */
// NONE("none"),
// /** column is in an invalid format */
// INVALID_FORMAT("invalid format"),
// /** column seems to be truncated */
// TRUNCATED_COLUMN("truncated column"),
// /** no header line read */
// NO_HEADER("no header line"),
// /** header line seems to be invalid */
// INVALID_HEADER("no valid header line"),
// /** null value for this field is invalid */
// INVALID_NULL("null value is invalid"),
// /** field must not be blank and no data specified */
// MUST_NOT_BE_BLANK("field must not be blank"),
// /** internal error was encountered */
// INTERNAL_ERROR("internal error"),
// /** line seems to be truncated */
// TRUNCATED_LINE("line is truncated"),
// /** line seems to have extra columns */
// TOO_MANY_COLUMNS("too many columns"),
// /** entity validation failed */
// INVALID_ENTITY("entity validation failed"),
// // end
// ;
//
// private String typeString;
//
// private ErrorType(String typeString) {
// this.typeString = typeString;
// }
//
// public String getTypeMessage() {
// return typeString;
// }
// }
|
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import org.junit.Test;
import com.j256.simplecsv.common.CsvColumn;
import com.j256.simplecsv.processor.ParseError.ErrorType;
|
package com.j256.simplecsv.processor;
public class RowValidatorTest {
@Test
public void testBasic() throws ParseException {
CsvProcessor<Basic> processor = new CsvProcessor<Basic>(Basic.class);
processor.setRowValidator(new RowValidator<Basic>() {
@Override
public void validateRow(String line, int lineNumber, Basic entity, ParseError parseError) {
if (entity.intValue >= 100) {
|
// Path: src/main/java/com/j256/simplecsv/processor/ParseError.java
// public enum ErrorType {
// /** no error */
// NONE("none"),
// /** column is in an invalid format */
// INVALID_FORMAT("invalid format"),
// /** column seems to be truncated */
// TRUNCATED_COLUMN("truncated column"),
// /** no header line read */
// NO_HEADER("no header line"),
// /** header line seems to be invalid */
// INVALID_HEADER("no valid header line"),
// /** null value for this field is invalid */
// INVALID_NULL("null value is invalid"),
// /** field must not be blank and no data specified */
// MUST_NOT_BE_BLANK("field must not be blank"),
// /** internal error was encountered */
// INTERNAL_ERROR("internal error"),
// /** line seems to be truncated */
// TRUNCATED_LINE("line is truncated"),
// /** line seems to have extra columns */
// TOO_MANY_COLUMNS("too many columns"),
// /** entity validation failed */
// INVALID_ENTITY("entity validation failed"),
// // end
// ;
//
// private String typeString;
//
// private ErrorType(String typeString) {
// this.typeString = typeString;
// }
//
// public String getTypeMessage() {
// return typeString;
// }
// }
// Path: src/test/java/com/j256/simplecsv/processor/RowValidatorTest.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import org.junit.Test;
import com.j256.simplecsv.common.CsvColumn;
import com.j256.simplecsv.processor.ParseError.ErrorType;
package com.j256.simplecsv.processor;
public class RowValidatorTest {
@Test
public void testBasic() throws ParseException {
CsvProcessor<Basic> processor = new CsvProcessor<Basic>(Basic.class);
processor.setRowValidator(new RowValidator<Basic>() {
@Override
public void validateRow(String line, int lineNumber, Basic entity, ParseError parseError) {
if (entity.intValue >= 100) {
|
parseError.setErrorType(ErrorType.INVALID_ENTITY);
|
j256/simplecsv
|
src/test/java/com/j256/simplecsv/processor/ParseErrorTest.java
|
// Path: src/main/java/com/j256/simplecsv/processor/ParseError.java
// public enum ErrorType {
// /** no error */
// NONE("none"),
// /** column is in an invalid format */
// INVALID_FORMAT("invalid format"),
// /** column seems to be truncated */
// TRUNCATED_COLUMN("truncated column"),
// /** no header line read */
// NO_HEADER("no header line"),
// /** header line seems to be invalid */
// INVALID_HEADER("no valid header line"),
// /** null value for this field is invalid */
// INVALID_NULL("null value is invalid"),
// /** field must not be blank and no data specified */
// MUST_NOT_BE_BLANK("field must not be blank"),
// /** internal error was encountered */
// INTERNAL_ERROR("internal error"),
// /** line seems to be truncated */
// TRUNCATED_LINE("line is truncated"),
// /** line seems to have extra columns */
// TOO_MANY_COLUMNS("too many columns"),
// /** entity validation failed */
// INVALID_ENTITY("entity validation failed"),
// // end
// ;
//
// private String typeString;
//
// private ErrorType(String typeString) {
// this.typeString = typeString;
// }
//
// public String getTypeMessage() {
// return typeString;
// }
// }
|
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.j256.simplecsv.processor.ParseError.ErrorType;
|
package com.j256.simplecsv.processor;
public class ParseErrorTest {
@Test
public void testStuff() {
ParseError parseError = new ParseError();
|
// Path: src/main/java/com/j256/simplecsv/processor/ParseError.java
// public enum ErrorType {
// /** no error */
// NONE("none"),
// /** column is in an invalid format */
// INVALID_FORMAT("invalid format"),
// /** column seems to be truncated */
// TRUNCATED_COLUMN("truncated column"),
// /** no header line read */
// NO_HEADER("no header line"),
// /** header line seems to be invalid */
// INVALID_HEADER("no valid header line"),
// /** null value for this field is invalid */
// INVALID_NULL("null value is invalid"),
// /** field must not be blank and no data specified */
// MUST_NOT_BE_BLANK("field must not be blank"),
// /** internal error was encountered */
// INTERNAL_ERROR("internal error"),
// /** line seems to be truncated */
// TRUNCATED_LINE("line is truncated"),
// /** line seems to have extra columns */
// TOO_MANY_COLUMNS("too many columns"),
// /** entity validation failed */
// INVALID_ENTITY("entity validation failed"),
// // end
// ;
//
// private String typeString;
//
// private ErrorType(String typeString) {
// this.typeString = typeString;
// }
//
// public String getTypeMessage() {
// return typeString;
// }
// }
// Path: src/test/java/com/j256/simplecsv/processor/ParseErrorTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.j256.simplecsv.processor.ParseError.ErrorType;
package com.j256.simplecsv.processor;
public class ParseErrorTest {
@Test
public void testStuff() {
ParseError parseError = new ParseError();
|
ErrorType errorType = ErrorType.INVALID_FORMAT;
|
KaloyanBogoslovov/Virtual-Trading
|
src/accounts/LogIn.java
|
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import data.updating.LoggedUser;
import database.Database;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
|
e1.printStackTrace();
}
});
loginButton.setPrefWidth(110);
Button signButton = new Button("Create Account");
signButton.setOnAction(e -> {
new CreateAccount();
});
signButton.setPrefWidth(110);
HBox hbox = new HBox(10);
hbox.getChildren().addAll(signButton, loginButton);
GridPane.setConstraints(hbox, 1, 2);
error = new Label();
GridPane.setConstraints(error, 1, 3);
grid.getChildren().addAll(nameLabel, nameTF, passLabel, passTF, hbox, error);
Scene scene = new Scene(grid, 330, 160);
window.setScene(scene);
window.setResizable(false);
window.setOnCloseRequest(e -> {
System.exit(0);
});
window.getIcons().add(new Image("blue.png"));
window.show();
}
private void logging() throws ClassNotFoundException, SQLException {
|
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
// Path: src/accounts/LogIn.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import data.updating.LoggedUser;
import database.Database;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
e1.printStackTrace();
}
});
loginButton.setPrefWidth(110);
Button signButton = new Button("Create Account");
signButton.setOnAction(e -> {
new CreateAccount();
});
signButton.setPrefWidth(110);
HBox hbox = new HBox(10);
hbox.getChildren().addAll(signButton, loginButton);
GridPane.setConstraints(hbox, 1, 2);
error = new Label();
GridPane.setConstraints(error, 1, 3);
grid.getChildren().addAll(nameLabel, nameTF, passLabel, passTF, hbox, error);
Scene scene = new Scene(grid, 330, 160);
window.setScene(scene);
window.setResizable(false);
window.setOnCloseRequest(e -> {
System.exit(0);
});
window.getIcons().add(new Image("blue.png"));
window.show();
}
private void logging() throws ClassNotFoundException, SQLException {
|
Database.connectingToDB();
|
KaloyanBogoslovov/Virtual-Trading
|
src/accounts/LogIn.java
|
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import data.updating.LoggedUser;
import database.Database;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
|
signButton.setOnAction(e -> {
new CreateAccount();
});
signButton.setPrefWidth(110);
HBox hbox = new HBox(10);
hbox.getChildren().addAll(signButton, loginButton);
GridPane.setConstraints(hbox, 1, 2);
error = new Label();
GridPane.setConstraints(error, 1, 3);
grid.getChildren().addAll(nameLabel, nameTF, passLabel, passTF, hbox, error);
Scene scene = new Scene(grid, 330, 160);
window.setScene(scene);
window.setResizable(false);
window.setOnCloseRequest(e -> {
System.exit(0);
});
window.getIcons().add(new Image("blue.png"));
window.show();
}
private void logging() throws ClassNotFoundException, SQLException {
Database.connectingToDB();
String input = nameTF.getText() + " " + passTF.getText();
ResultSet result = Database.SelectDB("Select username,password,stockexchange from USERS");
while (result.next()) {
if (input.equals(result.getString(1) + " " + result.getString(2))) {
|
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
// Path: src/accounts/LogIn.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import data.updating.LoggedUser;
import database.Database;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
signButton.setOnAction(e -> {
new CreateAccount();
});
signButton.setPrefWidth(110);
HBox hbox = new HBox(10);
hbox.getChildren().addAll(signButton, loginButton);
GridPane.setConstraints(hbox, 1, 2);
error = new Label();
GridPane.setConstraints(error, 1, 3);
grid.getChildren().addAll(nameLabel, nameTF, passLabel, passTF, hbox, error);
Scene scene = new Scene(grid, 330, 160);
window.setScene(scene);
window.setResizable(false);
window.setOnCloseRequest(e -> {
System.exit(0);
});
window.getIcons().add(new Image("blue.png"));
window.show();
}
private void logging() throws ClassNotFoundException, SQLException {
Database.connectingToDB();
String input = nameTF.getText() + " " + passTF.getText();
ResultSet result = Database.SelectDB("Select username,password,stockexchange from USERS");
while (result.next()) {
if (input.equals(result.getString(1) + " " + result.getString(2))) {
|
LoggedUser.setLoggedUser(nameTF.getText());
|
KaloyanBogoslovov/Virtual-Trading
|
src/charts/Chart.java
|
// Path: src/yahoo/ChartData.java
// public class ChartData {
// private String date;
// private BigDecimal open;
// private BigDecimal low;
// private BigDecimal high;
// private BigDecimal close;
// private BigDecimal adjClose;
// private Long volume;
//
// public ChartData(String date, String open, String low, String high, String close, String adjClose,
// Long volume) {
//
// this.date = date;
// this.open = new BigDecimal(open);
// this.low = new BigDecimal(low);
// this.high = new BigDecimal(high);
// this.close = new BigDecimal(close);
// this.adjClose = new BigDecimal(adjClose);
// this.volume = volume;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public BigDecimal getOpen() {
// return open;
// }
//
// public void setOpen(BigDecimal open) {
// this.open = open;
// }
//
// public BigDecimal getLow() {
// return low;
// }
//
// public void setLow(BigDecimal low) {
// this.low = low;
// }
//
// public BigDecimal getHigh() {
// return high;
// }
//
// public void setHigh(BigDecimal high) {
// this.high = high;
// }
//
// public BigDecimal getClose() {
// return close;
// }
//
// public void setClose(BigDecimal close) {
// this.close = close;
// }
//
// public BigDecimal getAdjClose() {
// return adjClose;
// }
//
// public void setAdjClose(BigDecimal adjClose) {
// this.adjClose = adjClose;
// }
//
// public Long getVolume() {
// return volume;
// }
//
// public void setVolume(Long volume) {
// this.volume = volume;
// }
//
// }
//
// Path: src/yahoo/ChartDataFromYahoo.java
// public class ChartDataFromYahoo extends YahooFinance {
// private String company;
// private String from;
// private String to;
// private String interval;
// private List<ChartData> result;
//
// public ChartDataFromYahoo(String company, String from, String to, String interval) {
// this.company = company;
// this.from = from;
// this.to = to;
// this.interval = interval;
//
// }
//
// public Object getData() {
// String url = makeURL();
// URLConnection connection = setConnectionWithYahoo(url);
// getInformationFromYahoo(connection);
// return result;
// }
//
// public String makeURL() {
// int fr = Integer.parseInt(from.substring(0, 2)) - 1;
// int t = Integer.parseInt(to.substring(0, 2)) - 1;
//
// String fromTo = "&a=" + fr + "&b=" + from.charAt(3) + from.charAt(4) + "&c=" + from.charAt(6)
// + from.charAt(7) + from.charAt(8) + from.charAt(9) + "&d=" + t + "&e=" + to.charAt(3)
// + to.charAt(4) + "&f=" + to.charAt(6) + to.charAt(7) + to.charAt(8) + to.charAt(9) + "&g=";
//
// String url =
// "http://ichart.yahoo.com/table.csv?s=" + company + fromTo + interval + "&ignore=.csv";
// return url;
// }
//
// private void getInformationFromYahoo(URLConnection connection) {
// try {
// InputStreamReader is = new InputStreamReader(connection.getInputStream());
// BufferedReader br = new BufferedReader(is);
// br.readLine();
// String line = br.readLine();
// addChartDataObjectsToList(line, br);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// private void addChartDataObjectsToList(String line, BufferedReader br) throws IOException {
// result = new ArrayList<ChartData>();
// while (line != null) {
// System.out.println("Historical data parsing:" + line);
// ChartData quote = parseCSVAndSetChartData(line);
// result.add(quote);
// line = br.readLine();
// }
// br.close();
// }
//
// private ChartData parseCSVAndSetChartData(String line) {
// String[] data = line.split(",");
// return new ChartData(data[0], data[1], data[3], data[2], data[4], data[6],
// Long.parseLong(data[5]));
// }
//
//
//
// }
//
// Path: src/yahoo/YahooFinance.java
// public abstract class YahooFinance {
// public static final int CONNECTION_TIMEOUT =
// Integer.parseInt(System.getProperty("yahoofinance.connection.timeout", "10000"));
//
// public abstract Object getData();
//
// public URLConnection setConnectionWithYahoo(String url) {
// URLConnection connection = null;
// try {
// System.out.println("URL:" + url);
// URL request = new URL(url);
// connection = request.openConnection();
// connection.setConnectTimeout(CONNECTION_TIMEOUT);
// connection.setReadTimeout(CONNECTION_TIMEOUT);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return connection;
// }
//
//
//
// }
|
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import yahoo.ChartData;
import yahoo.ChartDataFromYahoo;
import yahoo.YahooFinance;
|
package charts;
public class Chart {
protected double startValue;
protected double endValue;
LineChart<String, Number> lineChart;
@SuppressWarnings({"unchecked", "rawtypes"})
protected void makeChart(String comp, String period, String periodCB, String interval) {
XYChart.Series series = new XYChart.Series();
|
// Path: src/yahoo/ChartData.java
// public class ChartData {
// private String date;
// private BigDecimal open;
// private BigDecimal low;
// private BigDecimal high;
// private BigDecimal close;
// private BigDecimal adjClose;
// private Long volume;
//
// public ChartData(String date, String open, String low, String high, String close, String adjClose,
// Long volume) {
//
// this.date = date;
// this.open = new BigDecimal(open);
// this.low = new BigDecimal(low);
// this.high = new BigDecimal(high);
// this.close = new BigDecimal(close);
// this.adjClose = new BigDecimal(adjClose);
// this.volume = volume;
// }
//
// public String getDate() {
// return date;
// }
//
// public void setDate(String date) {
// this.date = date;
// }
//
// public BigDecimal getOpen() {
// return open;
// }
//
// public void setOpen(BigDecimal open) {
// this.open = open;
// }
//
// public BigDecimal getLow() {
// return low;
// }
//
// public void setLow(BigDecimal low) {
// this.low = low;
// }
//
// public BigDecimal getHigh() {
// return high;
// }
//
// public void setHigh(BigDecimal high) {
// this.high = high;
// }
//
// public BigDecimal getClose() {
// return close;
// }
//
// public void setClose(BigDecimal close) {
// this.close = close;
// }
//
// public BigDecimal getAdjClose() {
// return adjClose;
// }
//
// public void setAdjClose(BigDecimal adjClose) {
// this.adjClose = adjClose;
// }
//
// public Long getVolume() {
// return volume;
// }
//
// public void setVolume(Long volume) {
// this.volume = volume;
// }
//
// }
//
// Path: src/yahoo/ChartDataFromYahoo.java
// public class ChartDataFromYahoo extends YahooFinance {
// private String company;
// private String from;
// private String to;
// private String interval;
// private List<ChartData> result;
//
// public ChartDataFromYahoo(String company, String from, String to, String interval) {
// this.company = company;
// this.from = from;
// this.to = to;
// this.interval = interval;
//
// }
//
// public Object getData() {
// String url = makeURL();
// URLConnection connection = setConnectionWithYahoo(url);
// getInformationFromYahoo(connection);
// return result;
// }
//
// public String makeURL() {
// int fr = Integer.parseInt(from.substring(0, 2)) - 1;
// int t = Integer.parseInt(to.substring(0, 2)) - 1;
//
// String fromTo = "&a=" + fr + "&b=" + from.charAt(3) + from.charAt(4) + "&c=" + from.charAt(6)
// + from.charAt(7) + from.charAt(8) + from.charAt(9) + "&d=" + t + "&e=" + to.charAt(3)
// + to.charAt(4) + "&f=" + to.charAt(6) + to.charAt(7) + to.charAt(8) + to.charAt(9) + "&g=";
//
// String url =
// "http://ichart.yahoo.com/table.csv?s=" + company + fromTo + interval + "&ignore=.csv";
// return url;
// }
//
// private void getInformationFromYahoo(URLConnection connection) {
// try {
// InputStreamReader is = new InputStreamReader(connection.getInputStream());
// BufferedReader br = new BufferedReader(is);
// br.readLine();
// String line = br.readLine();
// addChartDataObjectsToList(line, br);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// private void addChartDataObjectsToList(String line, BufferedReader br) throws IOException {
// result = new ArrayList<ChartData>();
// while (line != null) {
// System.out.println("Historical data parsing:" + line);
// ChartData quote = parseCSVAndSetChartData(line);
// result.add(quote);
// line = br.readLine();
// }
// br.close();
// }
//
// private ChartData parseCSVAndSetChartData(String line) {
// String[] data = line.split(",");
// return new ChartData(data[0], data[1], data[3], data[2], data[4], data[6],
// Long.parseLong(data[5]));
// }
//
//
//
// }
//
// Path: src/yahoo/YahooFinance.java
// public abstract class YahooFinance {
// public static final int CONNECTION_TIMEOUT =
// Integer.parseInt(System.getProperty("yahoofinance.connection.timeout", "10000"));
//
// public abstract Object getData();
//
// public URLConnection setConnectionWithYahoo(String url) {
// URLConnection connection = null;
// try {
// System.out.println("URL:" + url);
// URL request = new URL(url);
// connection = request.openConnection();
// connection.setConnectTimeout(CONNECTION_TIMEOUT);
// connection.setReadTimeout(CONNECTION_TIMEOUT);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return connection;
// }
//
//
//
// }
// Path: src/charts/Chart.java
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import yahoo.ChartData;
import yahoo.ChartDataFromYahoo;
import yahoo.YahooFinance;
package charts;
public class Chart {
protected double startValue;
protected double endValue;
LineChart<String, Number> lineChart;
@SuppressWarnings({"unchecked", "rawtypes"})
protected void makeChart(String comp, String period, String periodCB, String interval) {
XYChart.Series series = new XYChart.Series();
|
List<ChartData> stocks = getChartData(comp, period, periodCB, interval);
|
KaloyanBogoslovov/Virtual-Trading
|
src/tabs/bottom/BalanceTab.java
|
// Path: src/data/tables/BalanceData.java
// public class BalanceData {
// private SimpleStringProperty balance;
// private SimpleStringProperty equity;
// private SimpleStringProperty leverage;
// private SimpleStringProperty margin;
// private SimpleStringProperty freeMargin;
// private SimpleStringProperty profit;
//
// public BalanceData() {
//
// balance = new SimpleStringProperty();
// equity = new SimpleStringProperty();
// leverage = new SimpleStringProperty();
// margin = new SimpleStringProperty();
// freeMargin = new SimpleStringProperty();
// profit = new SimpleStringProperty();
// }
//
// public String getBalance() {
// return balance.get();
// }
//
// public void setBalance(String balancee) {
// balance.set(balancee);
// }
//
// public String getEquity() {
// return equity.get();
// }
//
// public void setEquity(String equityy) {
// equity.set(equityy);
// }
//
// public String getLeverage() {
// return leverage.get();
// }
//
// public void setLeverage(String leveragee) {
// leverage.set(leveragee);
// }
//
// public String getMargin() {
// return margin.get();
// }
//
// public void setMargin(String marginn) {
// margin.set(marginn);
// }
//
// public String getFreeMargin() {
// return freeMargin.get();
// }
//
// public void setFreeMargin(String freeMarginn) {
// freeMargin.set(freeMarginn);
// }
//
// public String getProfit() {
// return profit.get();
// }
//
// public void setProfit(String profitt) {
// profit.set(profitt);
// }
// }
//
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
//
// Path: src/tabs/Tabs.java
// public interface Tabs {
// public TableView<Object> getTable();
// public void initTableContent();
//
// }
|
import java.sql.ResultSet;
import java.sql.SQLException;
import data.tables.BalanceData;
import data.updating.LoggedUser;
import database.Database;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import tabs.Tabs;
|
marginColumn = new TableColumn<BalanceData, String>("Margin");
marginColumn.setCellValueFactory(new PropertyValueFactory("margin"));
freeMarginColumn = new TableColumn<BalanceData, String>("Free Margin");
freeMarginColumn.setCellValueFactory(new PropertyValueFactory("freeMargin"));
totalProfitColumn = new TableColumn<BalanceData, String>("Live Profit");
totalProfitColumn.setCellValueFactory(new PropertyValueFactory("profit"));
balanceTable = new TableView<BalanceData>();
balanceTable.getColumns().addAll(balanceColumn, equityColumn, leverageColumn, marginColumn,
freeMarginColumn, totalProfitColumn);
setColumnSizes();
}
private void setColumnSizes() {
balanceColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
equityColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
leverageColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
marginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
freeMarginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
totalProfitColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
}
public TableView getTable() {
return balanceTable;
}
public void initTableContent() {
try {
|
// Path: src/data/tables/BalanceData.java
// public class BalanceData {
// private SimpleStringProperty balance;
// private SimpleStringProperty equity;
// private SimpleStringProperty leverage;
// private SimpleStringProperty margin;
// private SimpleStringProperty freeMargin;
// private SimpleStringProperty profit;
//
// public BalanceData() {
//
// balance = new SimpleStringProperty();
// equity = new SimpleStringProperty();
// leverage = new SimpleStringProperty();
// margin = new SimpleStringProperty();
// freeMargin = new SimpleStringProperty();
// profit = new SimpleStringProperty();
// }
//
// public String getBalance() {
// return balance.get();
// }
//
// public void setBalance(String balancee) {
// balance.set(balancee);
// }
//
// public String getEquity() {
// return equity.get();
// }
//
// public void setEquity(String equityy) {
// equity.set(equityy);
// }
//
// public String getLeverage() {
// return leverage.get();
// }
//
// public void setLeverage(String leveragee) {
// leverage.set(leveragee);
// }
//
// public String getMargin() {
// return margin.get();
// }
//
// public void setMargin(String marginn) {
// margin.set(marginn);
// }
//
// public String getFreeMargin() {
// return freeMargin.get();
// }
//
// public void setFreeMargin(String freeMarginn) {
// freeMargin.set(freeMarginn);
// }
//
// public String getProfit() {
// return profit.get();
// }
//
// public void setProfit(String profitt) {
// profit.set(profitt);
// }
// }
//
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
//
// Path: src/tabs/Tabs.java
// public interface Tabs {
// public TableView<Object> getTable();
// public void initTableContent();
//
// }
// Path: src/tabs/bottom/BalanceTab.java
import java.sql.ResultSet;
import java.sql.SQLException;
import data.tables.BalanceData;
import data.updating.LoggedUser;
import database.Database;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import tabs.Tabs;
marginColumn = new TableColumn<BalanceData, String>("Margin");
marginColumn.setCellValueFactory(new PropertyValueFactory("margin"));
freeMarginColumn = new TableColumn<BalanceData, String>("Free Margin");
freeMarginColumn.setCellValueFactory(new PropertyValueFactory("freeMargin"));
totalProfitColumn = new TableColumn<BalanceData, String>("Live Profit");
totalProfitColumn.setCellValueFactory(new PropertyValueFactory("profit"));
balanceTable = new TableView<BalanceData>();
balanceTable.getColumns().addAll(balanceColumn, equityColumn, leverageColumn, marginColumn,
freeMarginColumn, totalProfitColumn);
setColumnSizes();
}
private void setColumnSizes() {
balanceColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
equityColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
leverageColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
marginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
freeMarginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
totalProfitColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
}
public TableView getTable() {
return balanceTable;
}
public void initTableContent() {
try {
|
Database.connectingToDB();
|
KaloyanBogoslovov/Virtual-Trading
|
src/tabs/bottom/BalanceTab.java
|
// Path: src/data/tables/BalanceData.java
// public class BalanceData {
// private SimpleStringProperty balance;
// private SimpleStringProperty equity;
// private SimpleStringProperty leverage;
// private SimpleStringProperty margin;
// private SimpleStringProperty freeMargin;
// private SimpleStringProperty profit;
//
// public BalanceData() {
//
// balance = new SimpleStringProperty();
// equity = new SimpleStringProperty();
// leverage = new SimpleStringProperty();
// margin = new SimpleStringProperty();
// freeMargin = new SimpleStringProperty();
// profit = new SimpleStringProperty();
// }
//
// public String getBalance() {
// return balance.get();
// }
//
// public void setBalance(String balancee) {
// balance.set(balancee);
// }
//
// public String getEquity() {
// return equity.get();
// }
//
// public void setEquity(String equityy) {
// equity.set(equityy);
// }
//
// public String getLeverage() {
// return leverage.get();
// }
//
// public void setLeverage(String leveragee) {
// leverage.set(leveragee);
// }
//
// public String getMargin() {
// return margin.get();
// }
//
// public void setMargin(String marginn) {
// margin.set(marginn);
// }
//
// public String getFreeMargin() {
// return freeMargin.get();
// }
//
// public void setFreeMargin(String freeMarginn) {
// freeMargin.set(freeMarginn);
// }
//
// public String getProfit() {
// return profit.get();
// }
//
// public void setProfit(String profitt) {
// profit.set(profitt);
// }
// }
//
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
//
// Path: src/tabs/Tabs.java
// public interface Tabs {
// public TableView<Object> getTable();
// public void initTableContent();
//
// }
|
import java.sql.ResultSet;
import java.sql.SQLException;
import data.tables.BalanceData;
import data.updating.LoggedUser;
import database.Database;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import tabs.Tabs;
|
freeMarginColumn.setCellValueFactory(new PropertyValueFactory("freeMargin"));
totalProfitColumn = new TableColumn<BalanceData, String>("Live Profit");
totalProfitColumn.setCellValueFactory(new PropertyValueFactory("profit"));
balanceTable = new TableView<BalanceData>();
balanceTable.getColumns().addAll(balanceColumn, equityColumn, leverageColumn, marginColumn,
freeMarginColumn, totalProfitColumn);
setColumnSizes();
}
private void setColumnSizes() {
balanceColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
equityColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
leverageColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
marginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
freeMarginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
totalProfitColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
}
public TableView getTable() {
return balanceTable;
}
public void initTableContent() {
try {
Database.connectingToDB();
ResultSet result = Database.SelectDB(
"select balance, equity,leverage,margin,freemargin,totalprofit from users where username='"
|
// Path: src/data/tables/BalanceData.java
// public class BalanceData {
// private SimpleStringProperty balance;
// private SimpleStringProperty equity;
// private SimpleStringProperty leverage;
// private SimpleStringProperty margin;
// private SimpleStringProperty freeMargin;
// private SimpleStringProperty profit;
//
// public BalanceData() {
//
// balance = new SimpleStringProperty();
// equity = new SimpleStringProperty();
// leverage = new SimpleStringProperty();
// margin = new SimpleStringProperty();
// freeMargin = new SimpleStringProperty();
// profit = new SimpleStringProperty();
// }
//
// public String getBalance() {
// return balance.get();
// }
//
// public void setBalance(String balancee) {
// balance.set(balancee);
// }
//
// public String getEquity() {
// return equity.get();
// }
//
// public void setEquity(String equityy) {
// equity.set(equityy);
// }
//
// public String getLeverage() {
// return leverage.get();
// }
//
// public void setLeverage(String leveragee) {
// leverage.set(leveragee);
// }
//
// public String getMargin() {
// return margin.get();
// }
//
// public void setMargin(String marginn) {
// margin.set(marginn);
// }
//
// public String getFreeMargin() {
// return freeMargin.get();
// }
//
// public void setFreeMargin(String freeMarginn) {
// freeMargin.set(freeMarginn);
// }
//
// public String getProfit() {
// return profit.get();
// }
//
// public void setProfit(String profitt) {
// profit.set(profitt);
// }
// }
//
// Path: src/data/updating/LoggedUser.java
// public class LoggedUser {
//
// private static StringProperty loggedUser = new SimpleStringProperty("");
//
// public static StringProperty loggedUserProperty() {
// return loggedUser;
// }
//
// public static String getLoggedUser() {
// return loggedUser.get();
// }
//
//
// public static void setLoggedUser(String currentLoggedUser) {
// loggedUser.set(currentLoggedUser);
// }
//
// }
//
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
//
// Path: src/tabs/Tabs.java
// public interface Tabs {
// public TableView<Object> getTable();
// public void initTableContent();
//
// }
// Path: src/tabs/bottom/BalanceTab.java
import java.sql.ResultSet;
import java.sql.SQLException;
import data.tables.BalanceData;
import data.updating.LoggedUser;
import database.Database;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import tabs.Tabs;
freeMarginColumn.setCellValueFactory(new PropertyValueFactory("freeMargin"));
totalProfitColumn = new TableColumn<BalanceData, String>("Live Profit");
totalProfitColumn.setCellValueFactory(new PropertyValueFactory("profit"));
balanceTable = new TableView<BalanceData>();
balanceTable.getColumns().addAll(balanceColumn, equityColumn, leverageColumn, marginColumn,
freeMarginColumn, totalProfitColumn);
setColumnSizes();
}
private void setColumnSizes() {
balanceColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
equityColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
leverageColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
marginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
freeMarginColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
totalProfitColumn.prefWidthProperty().bind(balanceTable.widthProperty().multiply(0.1666));
}
public TableView getTable() {
return balanceTable;
}
public void initTableContent() {
try {
Database.connectingToDB();
ResultSet result = Database.SelectDB(
"select balance, equity,leverage,margin,freemargin,totalprofit from users where username='"
|
+ LoggedUser.getLoggedUser() + "'");
|
KaloyanBogoslovov/Virtual-Trading
|
src/accounts/CreateAccount.java
|
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
|
import java.sql.ResultSet;
import java.sql.SQLException;
import database.Database;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
|
try {
addNewAccToDB();
} catch (Exception e1) {
e1.printStackTrace();
}
});
HBox hbox = new HBox(10);
hbox.getChildren().addAll(cancelButton, signButton);
GridPane.setConstraints(hbox, 1, 7);
emptyField = new Label();
GridPane.setConstraints(emptyField, 1, 8);
grid.getChildren().addAll(firstNameLabel, firstNameTF, lastNameLabel, lastNameTF, userNameLabel,
userNameTF, passLabel, passTF, balanceLabel, balanceTF, leverageLabel, leverageCB,
exchangeLabel, exchangeCB, hbox, emptyField);
Scene scene = new Scene(grid, 300, 320);
window.setScene(scene);
window.setResizable(false);
window.getIcons().add(new Image("blue.png"));
window.show();
}
private void addNewAccToDB() throws SQLException, ClassNotFoundException {
boolean run = checkData();
if (run) {
|
// Path: src/database/Database.java
// public class Database {
//
// private static final String DBURL = "jdbc:h2:~/test";
// private static final String DBUSER = "Kaloyan_Bogoslovov";
// private static final String DBPASS = "qwerty";
// private static Connection connection;
//
// public static void connectingToDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
// }
//
// public static void createDB() throws ClassNotFoundException, SQLException {
// Class.forName("org.h2.Driver");
// Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
// Statement st = con.createStatement();
// String createUsersTable =
// "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
// String createTradesTable =
// "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
// st.executeUpdate(createUsersTable);
// st.executeUpdate(createTradesTable);
// con.close();
// }
//
// public static ResultSet SelectDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// ResultSet rs = st.executeQuery(data);
// return rs;
// }
//
// public static void insertDB(String data) throws SQLException {
// Statement st = connection.createStatement();
// st.executeUpdate(data);
// }
//
// public static void closeConnectionToDB() throws SQLException {
// connection.close();
// }
//
// }
// Path: src/accounts/CreateAccount.java
import java.sql.ResultSet;
import java.sql.SQLException;
import database.Database;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
try {
addNewAccToDB();
} catch (Exception e1) {
e1.printStackTrace();
}
});
HBox hbox = new HBox(10);
hbox.getChildren().addAll(cancelButton, signButton);
GridPane.setConstraints(hbox, 1, 7);
emptyField = new Label();
GridPane.setConstraints(emptyField, 1, 8);
grid.getChildren().addAll(firstNameLabel, firstNameTF, lastNameLabel, lastNameTF, userNameLabel,
userNameTF, passLabel, passTF, balanceLabel, balanceTF, leverageLabel, leverageCB,
exchangeLabel, exchangeCB, hbox, emptyField);
Scene scene = new Scene(grid, 300, 320);
window.setScene(scene);
window.setResizable(false);
window.getIcons().add(new Image("blue.png"));
window.show();
}
private void addNewAccToDB() throws SQLException, ClassNotFoundException {
boolean run = checkData();
if (run) {
|
Database.connectingToDB();
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorMySQL.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import java.util.Arrays;
import java.util.Iterator;
import liquibase.database.Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorMySQL</code> generates the SQL for creating a spatial index in
* MySQL.
*/
public class CreateSpatialIndexGeneratorMySQL extends AbstractCreateSpatialIndexGenerator {
@Override
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorMySQL.java
import java.util.Arrays;
import java.util.Iterator;
import liquibase.database.Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorMySQL</code> generates the SQL for creating a spatial index in
* MySQL.
*/
public class CreateSpatialIndexGeneratorMySQL extends AbstractCreateSpatialIndexGenerator {
@Override
|
public boolean supports(final CreateSpatialIndexStatement statement, final Database database) {
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/change/CreateSpatialIndexChange.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
|
import java.util.ArrayList;
import java.util.List;
import liquibase.change.AbstractChange;
import liquibase.change.Change;
import liquibase.change.ChangeMetaData;
import liquibase.change.ChangeWithColumns;
import liquibase.change.ColumnConfig;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.util.StringUtils;
|
return validationErrors;
}
@Override
public String getConfirmationMessage() {
final StringBuilder message = new StringBuilder("Spatial index");
if (StringUtils.trimToNull(getIndexName()) != null) {
message.append(' ').append(getIndexName().trim());
}
message.append(" created");
if (StringUtils.trimToNull(getTableName()) != null) {
message.append(" on ").append(getTableName().trim());
}
return message.toString();
}
@Override
public SqlStatement[] generateStatements(final Database database) {
final String[] columns = new String[this.columns.size()];
int ii = 0;
for (final ColumnConfig columnConfig : this.columns) {
columns[ii++] = columnConfig.getName();
}
// Parse the string SRID into an integer.
Integer srid = null;
if (getSrid() != null) {
srid = Integer.valueOf(getSrid());
}
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
// Path: src/main/java/liquibase/ext/spatial/change/CreateSpatialIndexChange.java
import java.util.ArrayList;
import java.util.List;
import liquibase.change.AbstractChange;
import liquibase.change.Change;
import liquibase.change.ChangeMetaData;
import liquibase.change.ChangeWithColumns;
import liquibase.change.ColumnConfig;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.util.StringUtils;
return validationErrors;
}
@Override
public String getConfirmationMessage() {
final StringBuilder message = new StringBuilder("Spatial index");
if (StringUtils.trimToNull(getIndexName()) != null) {
message.append(' ').append(getIndexName().trim());
}
message.append(" created");
if (StringUtils.trimToNull(getTableName()) != null) {
message.append(" on ").append(getTableName().trim());
}
return message.toString();
}
@Override
public SqlStatement[] generateStatements(final Database database) {
final String[] columns = new String[this.columns.size()];
int ii = 0;
for (final ColumnConfig columnConfig : this.columns) {
columns[ii++] = columnConfig.getName();
}
// Parse the string SRID into an integer.
Integer srid = null;
if (getSrid() != null) {
srid = Integer.valueOf(getSrid());
}
|
final CreateSpatialIndexStatement statement = new CreateSpatialIndexStatement(
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/change/CreateSpatialIndexChange.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
|
import java.util.ArrayList;
import java.util.List;
import liquibase.change.AbstractChange;
import liquibase.change.Change;
import liquibase.change.ChangeMetaData;
import liquibase.change.ChangeWithColumns;
import liquibase.change.ColumnConfig;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.util.StringUtils;
|
int ii = 0;
for (final ColumnConfig columnConfig : this.columns) {
columns[ii++] = columnConfig.getName();
}
// Parse the string SRID into an integer.
Integer srid = null;
if (getSrid() != null) {
srid = Integer.valueOf(getSrid());
}
final CreateSpatialIndexStatement statement = new CreateSpatialIndexStatement(
getIndexName(), getCatalogName(), getSchemaName(), getTableName(), columns,
getTablespace(), getGeometryType(), srid);
return new SqlStatement[] { statement };
}
@Override
protected Change[] createInverses() {
final DropSpatialIndexChange inverse = new DropSpatialIndexChange();
inverse.setCatalogName(getCatalogName());
inverse.setSchemaName(getSchemaName());
inverse.setTableName(getTableName());
inverse.setIndexName(getIndexName());
return new Change[] { inverse };
}
@Override
public String getSerializedObjectNamespace() {
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
// Path: src/main/java/liquibase/ext/spatial/change/CreateSpatialIndexChange.java
import java.util.ArrayList;
import java.util.List;
import liquibase.change.AbstractChange;
import liquibase.change.Change;
import liquibase.change.ChangeMetaData;
import liquibase.change.ChangeWithColumns;
import liquibase.change.ColumnConfig;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.util.StringUtils;
int ii = 0;
for (final ColumnConfig columnConfig : this.columns) {
columns[ii++] = columnConfig.getName();
}
// Parse the string SRID into an integer.
Integer srid = null;
if (getSrid() != null) {
srid = Integer.valueOf(getSrid());
}
final CreateSpatialIndexStatement statement = new CreateSpatialIndexStatement(
getIndexName(), getCatalogName(), getSchemaName(), getTableName(), columns,
getTablespace(), getGeometryType(), srid);
return new SqlStatement[] { statement };
}
@Override
protected Change[] createInverses() {
final DropSpatialIndexChange inverse = new DropSpatialIndexChange();
inverse.setCatalogName(getCatalogName());
inverse.setSchemaName(getSchemaName());
inverse.setTableName(getTableName());
inverse.setIndexName(getIndexName());
return new Change[] { inverse };
}
@Override
public String getSerializedObjectNamespace() {
|
return XmlConstants.SPATIAL_CHANGELOG_NAMESPACE;
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorGeoDB.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.structure.core.Table;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorGeoDB</code> generates the SQL for creating a spatial index in
* Apache Derby and H2.
*/
public class CreateSpatialIndexGeneratorGeoDB extends AbstractCreateSpatialIndexGenerator {
@Override
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorGeoDB.java
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.structure.core.Table;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorGeoDB</code> generates the SQL for creating a spatial index in
* Apache Derby and H2.
*/
public class CreateSpatialIndexGeneratorGeoDB extends AbstractCreateSpatialIndexGenerator {
@Override
|
public boolean supports(final CreateSpatialIndexStatement statement, final Database database) {
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorOracle.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import liquibase.database.Database;
import liquibase.database.core.OracleDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.structure.core.Column;
import liquibase.structure.core.Table;
import liquibase.structure.core.View;
import liquibase.util.StringUtils;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorOracle</code> generates the SQL for creating a spatial index in
* Oracle.
*/
public class CreateSpatialIndexGeneratorOracle extends AbstractCreateSpatialIndexGenerator {
@Override
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorOracle.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import liquibase.database.Database;
import liquibase.database.core.OracleDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.structure.core.Column;
import liquibase.structure.core.Table;
import liquibase.structure.core.View;
import liquibase.util.StringUtils;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorOracle</code> generates the SQL for creating a spatial index in
* Oracle.
*/
public class CreateSpatialIndexGeneratorOracle extends AbstractCreateSpatialIndexGenerator {
@Override
|
public boolean supports(final CreateSpatialIndexStatement statement, final Database database) {
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/preconditions/SpatialIndexExistsPrecondition.java
|
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
|
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.ValidationErrors;
import liquibase.exception.Warnings;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.precondition.AbstractPrecondition;
import liquibase.precondition.Precondition;
import liquibase.precondition.core.IndexExistsPrecondition;
import liquibase.precondition.core.TableExistsPrecondition;
import liquibase.resource.ResourceAccessor;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Column;
import liquibase.structure.core.Index;
import liquibase.structure.core.Schema;
import liquibase.structure.core.Table;
import liquibase.util.StringUtils;
|
if ("catalogName".equals(field)) {
value = getCatalogName();
} else if ("schemaName".equals(field)) {
value = getSchemaName();
} else if ("tableName".equals(field)) {
value = getTableName();
} else if ("columnNames".equals(field)) {
value = getColumnNames();
} else if ("indexName".equals(field)) {
value = getIndexName();
} else {
throw new UnexpectedLiquibaseException("Unexpected field request on "
+ getSerializedObjectName() + ": " + field);
}
return value;
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFieldType(java.lang.String)
*/
@Override
public SerializationType getSerializableFieldType(final String field) {
return SerializationType.NAMED_FIELD;
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializedObjectNamespace()
*/
@Override
public String getSerializedObjectNamespace() {
|
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
// Path: src/main/java/liquibase/ext/spatial/preconditions/SpatialIndexExistsPrecondition.java
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.ValidationErrors;
import liquibase.exception.Warnings;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.precondition.AbstractPrecondition;
import liquibase.precondition.Precondition;
import liquibase.precondition.core.IndexExistsPrecondition;
import liquibase.precondition.core.TableExistsPrecondition;
import liquibase.resource.ResourceAccessor;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Column;
import liquibase.structure.core.Index;
import liquibase.structure.core.Schema;
import liquibase.structure.core.Table;
import liquibase.util.StringUtils;
if ("catalogName".equals(field)) {
value = getCatalogName();
} else if ("schemaName".equals(field)) {
value = getSchemaName();
} else if ("tableName".equals(field)) {
value = getTableName();
} else if ("columnNames".equals(field)) {
value = getColumnNames();
} else if ("indexName".equals(field)) {
value = getIndexName();
} else {
throw new UnexpectedLiquibaseException("Unexpected field request on "
+ getSerializedObjectName() + ": " + field);
}
return value;
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFieldType(java.lang.String)
*/
@Override
public SerializationType getSerializableFieldType(final String field) {
return SerializationType.NAMED_FIELD;
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializedObjectNamespace()
*/
@Override
public String getSerializedObjectNamespace() {
|
return XmlConstants.SPATIAL_CHANGELOG_NAMESPACE;
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorPostgreSQL.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import java.util.Arrays;
import java.util.Iterator;
import liquibase.database.Database;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.structure.core.Index;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorMySQL</code> generates the SQL for creating a spatial index in
* MySQL.
*/
public class CreateSpatialIndexGeneratorPostgreSQL extends AbstractCreateSpatialIndexGenerator {
@Override
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorPostgreSQL.java
import java.util.Arrays;
import java.util.Iterator;
import liquibase.database.Database;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.structure.core.Index;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorMySQL</code> generates the SQL for creating a spatial index in
* MySQL.
*/
public class CreateSpatialIndexGeneratorPostgreSQL extends AbstractCreateSpatialIndexGenerator {
@Override
|
public boolean supports(final CreateSpatialIndexStatement statement, final Database database) {
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/preconditions/SpatialSupportedPrecondition.java
|
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
|
import java.util.LinkedHashSet;
import java.util.Set;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.ValidationErrors;
import liquibase.exception.Warnings;
import liquibase.executor.ExecutorService;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.precondition.AbstractPrecondition;
import liquibase.precondition.ErrorPrecondition;
import liquibase.precondition.core.TableExistsPrecondition;
import liquibase.precondition.core.ViewExistsPrecondition;
import liquibase.resource.ResourceAccessor;
import liquibase.statement.core.RawSqlStatement;
|
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFields()
*/
@Override
public Set<String> getSerializableFields() {
return new LinkedHashSet<String>();
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFieldValue(java.lang.String)
*/
@Override
public Object getSerializableFieldValue(final String field) {
throw new UnexpectedLiquibaseException("Unexpected field request on "
+ getSerializedObjectName() + ": " + field);
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFieldType(java.lang.String)
*/
@Override
public SerializationType getSerializableFieldType(final String field) {
return SerializationType.NAMED_FIELD;
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializedObjectNamespace()
*/
@Override
public String getSerializedObjectNamespace() {
|
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
// Path: src/main/java/liquibase/ext/spatial/preconditions/SpatialSupportedPrecondition.java
import java.util.LinkedHashSet;
import java.util.Set;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.ValidationErrors;
import liquibase.exception.Warnings;
import liquibase.executor.ExecutorService;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.precondition.AbstractPrecondition;
import liquibase.precondition.ErrorPrecondition;
import liquibase.precondition.core.TableExistsPrecondition;
import liquibase.precondition.core.ViewExistsPrecondition;
import liquibase.resource.ResourceAccessor;
import liquibase.statement.core.RawSqlStatement;
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFields()
*/
@Override
public Set<String> getSerializableFields() {
return new LinkedHashSet<String>();
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFieldValue(java.lang.String)
*/
@Override
public Object getSerializableFieldValue(final String field) {
throw new UnexpectedLiquibaseException("Unexpected field request on "
+ getSerializedObjectName() + ": " + field);
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializableFieldType(java.lang.String)
*/
@Override
public SerializationType getSerializableFieldType(final String field) {
return SerializationType.NAMED_FIELD;
}
/**
* @see liquibase.serializer.LiquibaseSerializable#getSerializedObjectNamespace()
*/
@Override
public String getSerializedObjectNamespace() {
|
return XmlConstants.SPATIAL_CHANGELOG_NAMESPACE;
|
lonnyj/liquibase-spatial
|
src/test/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorMySQLTest.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorMySQLTest</code> tests {@link CreateSpatialIndexGeneratorMySQL}.
*/
public class CreateSpatialIndexGeneratorMySQLTest {
/**
* Tests {@link CreateSpatialIndexGeneratorMySQL#supports(CreateSpatialIndexStatement, Database)}
*/
@Test
public void testSupports() {
final CreateSpatialIndexGeneratorMySQL generator = new CreateSpatialIndexGeneratorMySQL();
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/test/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorMySQLTest.java
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorMySQLTest</code> tests {@link CreateSpatialIndexGeneratorMySQL}.
*/
public class CreateSpatialIndexGeneratorMySQLTest {
/**
* Tests {@link CreateSpatialIndexGeneratorMySQL#supports(CreateSpatialIndexStatement, Database)}
*/
@Test
public void testSupports() {
final CreateSpatialIndexGeneratorMySQL generator = new CreateSpatialIndexGeneratorMySQL();
|
final CreateSpatialIndexStatement statement = mock(CreateSpatialIndexStatement.class);
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialTableGeneratorGeoDB.java
|
// Path: src/main/java/liquibase/ext/spatial/datatype/GeometryType.java
// @DataTypeInfo(name = "geometry", aliases = { "com.vividsolutions.jts.geom.Geometry" }, minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DEFAULT)
// public class GeometryType extends LiquibaseDataType {
// /**
// * Returns the value geometry type parameter.
// *
// * @return the geometry type or <code>null</code> if not present.
// */
// public String getGeometryType() {
// String geometryType = null;
// if (getParameters().length > 0 && getParameters()[0] != null) {
// geometryType = getParameters()[0].toString();
// }
// return geometryType;
// }
//
// /**
// * Returns the value SRID parameter.
// *
// * @return the SRID or <code>null</code> if not present.
// */
// public Integer getSRID() {
// Integer srid = null;
// if (getParameters().length > 1 && getParameters()[1] != null) {
// srid = Integer.valueOf(getParameters()[1].toString());
// }
// return srid;
// }
//
// /**
// * Creates the appropriate Geometry <code>DatabaseDataType</code>.
// */
// @Override
// public DatabaseDataType toDatabaseDataType(final Database database) {
// final DatabaseDataType databaseDataType;
// if (database instanceof DerbyDatabase) {
// databaseDataType = new DatabaseDataType("VARCHAR(32672) FOR BIT DATA");
// } else if (database instanceof H2Database) {
// // User's wanting to use a BLOB can use modifySql.
// databaseDataType = new DatabaseDataType("BINARY");
// } else if (database instanceof OracleDatabase) {
// databaseDataType = new DatabaseDataType("SDO_GEOMETRY");
// } else if (database instanceof PostgresDatabase) {
// databaseDataType = new DatabaseDataType(getName(), getParameters());
// } else {
// databaseDataType = new DatabaseDataType("GEOMETRY");
// }
// return databaseDataType;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#objectToSql(java.lang.Object,
// * liquibase.database.Database)
// */
// @Override
// public String objectToSql(final Object value, final Database database) {
// final String returnValue;
// if (value instanceof Geometry) {
// // TODO: Tailor the output for the database.
// returnValue = ((Geometry) value).toText();
// } else if (value instanceof String) {
// returnValue = value.toString();
// } else if (value instanceof DatabaseFunction) {
// returnValue = value.toString();
// } else if (value == null || value.toString().equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// throw new UnexpectedLiquibaseException("Cannot convert type " + value.getClass()
// + " to a Geometry value");
// }
// return returnValue;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#sqlToObject(java.lang.String,
// * liquibase.database.Database)
// */
// @Override
// public Object sqlToObject(final String value, final Database database) {
// final Geometry returnValue;
// if (value == null || value.equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// final WKTReader reader = new WKTReader();
// try {
// // TODO: Check for SRID.
// returnValue = reader.read(value);
// } catch (final ParseException e) {
// throw new UnexpectedLiquibaseException("Cannot parse " + value + " to a Geometry", e);
// }
// }
// return returnValue;
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeSet;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.datatype.LiquibaseDataType;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.datatype.GeometryType;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.core.AbstractSqlGenerator;
import liquibase.sqlgenerator.core.CreateTableGenerator;
import liquibase.statement.core.AddColumnStatement;
import liquibase.statement.core.CreateTableStatement;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialTableGeneratorGeoDB</code> augments the built-in {@link CreateTableGenerator}
* by invoking the <code>AddGeometryColumn</code> procedure to add the standard metadata for a
* geometry column.
*/
public class CreateSpatialTableGeneratorGeoDB extends AbstractSqlGenerator<CreateTableStatement> {
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#supports(liquibase.statement.SqlStatement,
* liquibase.database.Database)
*/
@Override
public boolean supports(final CreateTableStatement statement, final Database database) {
return database instanceof DerbyDatabase || database instanceof H2Database;
}
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#getPriority()
*/
@Override
public int getPriority() {
return super.getPriority() + 1;
}
@Override
public ValidationErrors validate(final CreateTableStatement statement, final Database database,
final SqlGeneratorChain sqlGeneratorChain) {
final ValidationErrors validationErrors = new ValidationErrors();
for (final Entry<String, LiquibaseDataType> entry : statement.getColumnTypes().entrySet()) {
|
// Path: src/main/java/liquibase/ext/spatial/datatype/GeometryType.java
// @DataTypeInfo(name = "geometry", aliases = { "com.vividsolutions.jts.geom.Geometry" }, minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DEFAULT)
// public class GeometryType extends LiquibaseDataType {
// /**
// * Returns the value geometry type parameter.
// *
// * @return the geometry type or <code>null</code> if not present.
// */
// public String getGeometryType() {
// String geometryType = null;
// if (getParameters().length > 0 && getParameters()[0] != null) {
// geometryType = getParameters()[0].toString();
// }
// return geometryType;
// }
//
// /**
// * Returns the value SRID parameter.
// *
// * @return the SRID or <code>null</code> if not present.
// */
// public Integer getSRID() {
// Integer srid = null;
// if (getParameters().length > 1 && getParameters()[1] != null) {
// srid = Integer.valueOf(getParameters()[1].toString());
// }
// return srid;
// }
//
// /**
// * Creates the appropriate Geometry <code>DatabaseDataType</code>.
// */
// @Override
// public DatabaseDataType toDatabaseDataType(final Database database) {
// final DatabaseDataType databaseDataType;
// if (database instanceof DerbyDatabase) {
// databaseDataType = new DatabaseDataType("VARCHAR(32672) FOR BIT DATA");
// } else if (database instanceof H2Database) {
// // User's wanting to use a BLOB can use modifySql.
// databaseDataType = new DatabaseDataType("BINARY");
// } else if (database instanceof OracleDatabase) {
// databaseDataType = new DatabaseDataType("SDO_GEOMETRY");
// } else if (database instanceof PostgresDatabase) {
// databaseDataType = new DatabaseDataType(getName(), getParameters());
// } else {
// databaseDataType = new DatabaseDataType("GEOMETRY");
// }
// return databaseDataType;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#objectToSql(java.lang.Object,
// * liquibase.database.Database)
// */
// @Override
// public String objectToSql(final Object value, final Database database) {
// final String returnValue;
// if (value instanceof Geometry) {
// // TODO: Tailor the output for the database.
// returnValue = ((Geometry) value).toText();
// } else if (value instanceof String) {
// returnValue = value.toString();
// } else if (value instanceof DatabaseFunction) {
// returnValue = value.toString();
// } else if (value == null || value.toString().equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// throw new UnexpectedLiquibaseException("Cannot convert type " + value.getClass()
// + " to a Geometry value");
// }
// return returnValue;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#sqlToObject(java.lang.String,
// * liquibase.database.Database)
// */
// @Override
// public Object sqlToObject(final String value, final Database database) {
// final Geometry returnValue;
// if (value == null || value.equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// final WKTReader reader = new WKTReader();
// try {
// // TODO: Check for SRID.
// returnValue = reader.read(value);
// } catch (final ParseException e) {
// throw new UnexpectedLiquibaseException("Cannot parse " + value + " to a Geometry", e);
// }
// }
// return returnValue;
// }
// }
// Path: src/main/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialTableGeneratorGeoDB.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeSet;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.datatype.LiquibaseDataType;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.datatype.GeometryType;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.core.AbstractSqlGenerator;
import liquibase.sqlgenerator.core.CreateTableGenerator;
import liquibase.statement.core.AddColumnStatement;
import liquibase.statement.core.CreateTableStatement;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialTableGeneratorGeoDB</code> augments the built-in {@link CreateTableGenerator}
* by invoking the <code>AddGeometryColumn</code> procedure to add the standard metadata for a
* geometry column.
*/
public class CreateSpatialTableGeneratorGeoDB extends AbstractSqlGenerator<CreateTableStatement> {
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#supports(liquibase.statement.SqlStatement,
* liquibase.database.Database)
*/
@Override
public boolean supports(final CreateTableStatement statement, final Database database) {
return database instanceof DerbyDatabase || database instanceof H2Database;
}
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#getPriority()
*/
@Override
public int getPriority() {
return super.getPriority() + 1;
}
@Override
public ValidationErrors validate(final CreateTableStatement statement, final Database database,
final SqlGeneratorChain sqlGeneratorChain) {
final ValidationErrors validationErrors = new ValidationErrors();
for (final Entry<String, LiquibaseDataType> entry : statement.getColumnTypes().entrySet()) {
|
if (entry.getValue() instanceof GeometryType) {
|
lonnyj/liquibase-spatial
|
src/test/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorOracleTest.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.OracleDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorOracleTest</code> tests
* {@link CreateSpatialIndexGeneratorOracle}.
*/
public class CreateSpatialIndexGeneratorOracleTest {
/**
* Tests
* {@link CreateSpatialIndexGeneratorOracle#supports(CreateSpatialIndexStatement, Database)}
*/
@Test
public void testSupports() {
final CreateSpatialIndexGeneratorOracle generator = new CreateSpatialIndexGeneratorOracle();
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/test/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorOracleTest.java
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.OracleDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorOracleTest</code> tests
* {@link CreateSpatialIndexGeneratorOracle}.
*/
public class CreateSpatialIndexGeneratorOracleTest {
/**
* Tests
* {@link CreateSpatialIndexGeneratorOracle#supports(CreateSpatialIndexStatement, Database)}
*/
@Test
public void testSupports() {
final CreateSpatialIndexGeneratorOracle generator = new CreateSpatialIndexGeneratorOracle();
|
final CreateSpatialIndexStatement statement = mock(CreateSpatialIndexStatement.class);
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/sqlgenerator/AddGeometryColumnGeneratorGeoDB.java
|
// Path: src/main/java/liquibase/ext/spatial/datatype/GeometryType.java
// @DataTypeInfo(name = "geometry", aliases = { "com.vividsolutions.jts.geom.Geometry" }, minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DEFAULT)
// public class GeometryType extends LiquibaseDataType {
// /**
// * Returns the value geometry type parameter.
// *
// * @return the geometry type or <code>null</code> if not present.
// */
// public String getGeometryType() {
// String geometryType = null;
// if (getParameters().length > 0 && getParameters()[0] != null) {
// geometryType = getParameters()[0].toString();
// }
// return geometryType;
// }
//
// /**
// * Returns the value SRID parameter.
// *
// * @return the SRID or <code>null</code> if not present.
// */
// public Integer getSRID() {
// Integer srid = null;
// if (getParameters().length > 1 && getParameters()[1] != null) {
// srid = Integer.valueOf(getParameters()[1].toString());
// }
// return srid;
// }
//
// /**
// * Creates the appropriate Geometry <code>DatabaseDataType</code>.
// */
// @Override
// public DatabaseDataType toDatabaseDataType(final Database database) {
// final DatabaseDataType databaseDataType;
// if (database instanceof DerbyDatabase) {
// databaseDataType = new DatabaseDataType("VARCHAR(32672) FOR BIT DATA");
// } else if (database instanceof H2Database) {
// // User's wanting to use a BLOB can use modifySql.
// databaseDataType = new DatabaseDataType("BINARY");
// } else if (database instanceof OracleDatabase) {
// databaseDataType = new DatabaseDataType("SDO_GEOMETRY");
// } else if (database instanceof PostgresDatabase) {
// databaseDataType = new DatabaseDataType(getName(), getParameters());
// } else {
// databaseDataType = new DatabaseDataType("GEOMETRY");
// }
// return databaseDataType;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#objectToSql(java.lang.Object,
// * liquibase.database.Database)
// */
// @Override
// public String objectToSql(final Object value, final Database database) {
// final String returnValue;
// if (value instanceof Geometry) {
// // TODO: Tailor the output for the database.
// returnValue = ((Geometry) value).toText();
// } else if (value instanceof String) {
// returnValue = value.toString();
// } else if (value instanceof DatabaseFunction) {
// returnValue = value.toString();
// } else if (value == null || value.toString().equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// throw new UnexpectedLiquibaseException("Cannot convert type " + value.getClass()
// + " to a Geometry value");
// }
// return returnValue;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#sqlToObject(java.lang.String,
// * liquibase.database.Database)
// */
// @Override
// public Object sqlToObject(final String value, final Database database) {
// final Geometry returnValue;
// if (value == null || value.equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// final WKTReader reader = new WKTReader();
// try {
// // TODO: Check for SRID.
// returnValue = reader.read(value);
// } catch (final ParseException e) {
// throw new UnexpectedLiquibaseException("Cannot parse " + value + " to a Geometry", e);
// }
// }
// return returnValue;
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.datatype.DataTypeFactory;
import liquibase.datatype.LiquibaseDataType;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.datatype.GeometryType;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.core.AbstractSqlGenerator;
import liquibase.statement.core.AddColumnStatement;
import liquibase.util.StringUtils;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>AddGeometryColumnGeneratorGeoDB</code> is a SQL generator that
* specializes in GeoDB. Regardless of the column type, the next SQL generator
* in the chain is invoked to handle the normal column addition. If the column
* to be added has a geometry type, the <code>AddGeometryColumn</code> stored
* procedure is invoked to ensure that the necessary metadata is created in the
* database.
*/
public class AddGeometryColumnGeneratorGeoDB extends
AbstractSqlGenerator<AddColumnStatement> {
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#supports(liquibase.statement.SqlStatement,
* liquibase.database.Database)
*/
@Override
public boolean supports(final AddColumnStatement statement,
final Database database) {
return database instanceof DerbyDatabase
|| database instanceof H2Database;
}
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#getPriority()
*/
@Override
public int getPriority() {
return SqlGenerator.PRIORITY_DATABASE + 1;
}
@Override
public ValidationErrors validate(final AddColumnStatement statement,
final Database database, final SqlGeneratorChain sqlGeneratorChain) {
final ValidationErrors errors = new ValidationErrors();
final LiquibaseDataType dataType = DataTypeFactory.getInstance()
.fromDescription(statement.getColumnType(), database);
// Ensure that the SRID parameter is provided.
|
// Path: src/main/java/liquibase/ext/spatial/datatype/GeometryType.java
// @DataTypeInfo(name = "geometry", aliases = { "com.vividsolutions.jts.geom.Geometry" }, minParameters = 0, maxParameters = 2, priority = LiquibaseDataType.PRIORITY_DEFAULT)
// public class GeometryType extends LiquibaseDataType {
// /**
// * Returns the value geometry type parameter.
// *
// * @return the geometry type or <code>null</code> if not present.
// */
// public String getGeometryType() {
// String geometryType = null;
// if (getParameters().length > 0 && getParameters()[0] != null) {
// geometryType = getParameters()[0].toString();
// }
// return geometryType;
// }
//
// /**
// * Returns the value SRID parameter.
// *
// * @return the SRID or <code>null</code> if not present.
// */
// public Integer getSRID() {
// Integer srid = null;
// if (getParameters().length > 1 && getParameters()[1] != null) {
// srid = Integer.valueOf(getParameters()[1].toString());
// }
// return srid;
// }
//
// /**
// * Creates the appropriate Geometry <code>DatabaseDataType</code>.
// */
// @Override
// public DatabaseDataType toDatabaseDataType(final Database database) {
// final DatabaseDataType databaseDataType;
// if (database instanceof DerbyDatabase) {
// databaseDataType = new DatabaseDataType("VARCHAR(32672) FOR BIT DATA");
// } else if (database instanceof H2Database) {
// // User's wanting to use a BLOB can use modifySql.
// databaseDataType = new DatabaseDataType("BINARY");
// } else if (database instanceof OracleDatabase) {
// databaseDataType = new DatabaseDataType("SDO_GEOMETRY");
// } else if (database instanceof PostgresDatabase) {
// databaseDataType = new DatabaseDataType(getName(), getParameters());
// } else {
// databaseDataType = new DatabaseDataType("GEOMETRY");
// }
// return databaseDataType;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#objectToSql(java.lang.Object,
// * liquibase.database.Database)
// */
// @Override
// public String objectToSql(final Object value, final Database database) {
// final String returnValue;
// if (value instanceof Geometry) {
// // TODO: Tailor the output for the database.
// returnValue = ((Geometry) value).toText();
// } else if (value instanceof String) {
// returnValue = value.toString();
// } else if (value instanceof DatabaseFunction) {
// returnValue = value.toString();
// } else if (value == null || value.toString().equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// throw new UnexpectedLiquibaseException("Cannot convert type " + value.getClass()
// + " to a Geometry value");
// }
// return returnValue;
// }
//
// /**
// * @see liquibase.datatype.LiquibaseDataType#sqlToObject(java.lang.String,
// * liquibase.database.Database)
// */
// @Override
// public Object sqlToObject(final String value, final Database database) {
// final Geometry returnValue;
// if (value == null || value.equalsIgnoreCase("null")) {
// returnValue = null;
// } else {
// final WKTReader reader = new WKTReader();
// try {
// // TODO: Check for SRID.
// returnValue = reader.read(value);
// } catch (final ParseException e) {
// throw new UnexpectedLiquibaseException("Cannot parse " + value + " to a Geometry", e);
// }
// }
// return returnValue;
// }
// }
// Path: src/main/java/liquibase/ext/spatial/sqlgenerator/AddGeometryColumnGeneratorGeoDB.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.datatype.DataTypeFactory;
import liquibase.datatype.LiquibaseDataType;
import liquibase.exception.ValidationErrors;
import liquibase.ext.spatial.datatype.GeometryType;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.core.AbstractSqlGenerator;
import liquibase.statement.core.AddColumnStatement;
import liquibase.util.StringUtils;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>AddGeometryColumnGeneratorGeoDB</code> is a SQL generator that
* specializes in GeoDB. Regardless of the column type, the next SQL generator
* in the chain is invoked to handle the normal column addition. If the column
* to be added has a geometry type, the <code>AddGeometryColumn</code> stored
* procedure is invoked to ensure that the necessary metadata is created in the
* database.
*/
public class AddGeometryColumnGeneratorGeoDB extends
AbstractSqlGenerator<AddColumnStatement> {
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#supports(liquibase.statement.SqlStatement,
* liquibase.database.Database)
*/
@Override
public boolean supports(final AddColumnStatement statement,
final Database database) {
return database instanceof DerbyDatabase
|| database instanceof H2Database;
}
/**
* @see liquibase.sqlgenerator.core.AbstractSqlGenerator#getPriority()
*/
@Override
public int getPriority() {
return SqlGenerator.PRIORITY_DATABASE + 1;
}
@Override
public ValidationErrors validate(final AddColumnStatement statement,
final Database database, final SqlGeneratorChain sqlGeneratorChain) {
final ValidationErrors errors = new ValidationErrors();
final LiquibaseDataType dataType = DataTypeFactory.getInstance()
.fromDescription(statement.getColumnType(), database);
// Ensure that the SRID parameter is provided.
|
if (dataType instanceof GeometryType) {
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/change/DropSpatialIndexChange.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/DropSpatialIndexStatement.java
// public class DropSpatialIndexStatement extends AbstractSqlStatement {
// /** The index name. */
// private final String indexName;
//
// /** The table catalog name. */
// private final String tableCatalogName;
//
// /** The table schema name. */
// private final String tableSchemaName;
//
// /** The table name. */
// private final String tableName;
//
// /**
// * Creates a new instance with the given parameters.
// *
// * @param indexName
// * the index name.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// */
// public DropSpatialIndexStatement(final String indexName, final String tableCatalogName,
// final String tableSchemaName, final String tableName) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// }
//
// /**
// * Returns the index name.
// *
// * @return the index name.
// */
// public String getIndexName() {
// return this.indexName;
// }
//
// /**
// * Returns the table catalog name.
// *
// * @return the table catalog name.
// */
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// /**
// * Returns the table schema name.
// *
// * @return the table schema name.
// */
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// /**
// * Returns the table name.
// *
// * @return the table name.
// */
// public String getTableName() {
// return this.tableName;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
|
import java.util.ArrayList;
import java.util.Collection;
import liquibase.change.AbstractChange;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.DropSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.DropIndexStatement;
import liquibase.util.StringUtils;
|
package liquibase.ext.spatial.change;
/**
* @author Lonny Jacobson
*/
@DatabaseChange(name = "dropSpatialIndex", description = "Drops the spatial index on an existing column or set of columns.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "index")
public class DropSpatialIndexChange extends AbstractChange {
/** The name of the catalog. */
private String catalogName;
/** The name of the schema. */
private String schemaName;
/** The name of the indexed table. */
private String tableName;
/** The name of the index to drop. */
private String indexName;
@DatabaseChangeProperty(mustEqualExisting = "index.schema")
public String getSchemaName() {
return this.schemaName;
}
public void setSchemaName(final String schemaName) {
this.schemaName = schemaName;
}
@DatabaseChangeProperty(mustEqualExisting = "index", description = "Name of the index to drop", requiredForDatabase = "mysql, oracle, postgresql")
public String getIndexName() {
return this.indexName;
}
public void setIndexName(final String indexName) {
this.indexName = indexName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.table", description = "Name fo the indexed table.", requiredForDatabase = "h2, derby")
public String getTableName() {
return this.tableName;
}
public void setTableName(final String tableName) {
this.tableName = tableName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.catalog")
public String getCatalogName() {
return this.catalogName;
}
public void setCatalogName(final String catalogName) {
this.catalogName = catalogName;
}
@Override
public String getSerializedObjectNamespace() {
|
// Path: src/main/java/liquibase/ext/spatial/statement/DropSpatialIndexStatement.java
// public class DropSpatialIndexStatement extends AbstractSqlStatement {
// /** The index name. */
// private final String indexName;
//
// /** The table catalog name. */
// private final String tableCatalogName;
//
// /** The table schema name. */
// private final String tableSchemaName;
//
// /** The table name. */
// private final String tableName;
//
// /**
// * Creates a new instance with the given parameters.
// *
// * @param indexName
// * the index name.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// */
// public DropSpatialIndexStatement(final String indexName, final String tableCatalogName,
// final String tableSchemaName, final String tableName) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// }
//
// /**
// * Returns the index name.
// *
// * @return the index name.
// */
// public String getIndexName() {
// return this.indexName;
// }
//
// /**
// * Returns the table catalog name.
// *
// * @return the table catalog name.
// */
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// /**
// * Returns the table schema name.
// *
// * @return the table schema name.
// */
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// /**
// * Returns the table name.
// *
// * @return the table name.
// */
// public String getTableName() {
// return this.tableName;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
// Path: src/main/java/liquibase/ext/spatial/change/DropSpatialIndexChange.java
import java.util.ArrayList;
import java.util.Collection;
import liquibase.change.AbstractChange;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.DropSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.DropIndexStatement;
import liquibase.util.StringUtils;
package liquibase.ext.spatial.change;
/**
* @author Lonny Jacobson
*/
@DatabaseChange(name = "dropSpatialIndex", description = "Drops the spatial index on an existing column or set of columns.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "index")
public class DropSpatialIndexChange extends AbstractChange {
/** The name of the catalog. */
private String catalogName;
/** The name of the schema. */
private String schemaName;
/** The name of the indexed table. */
private String tableName;
/** The name of the index to drop. */
private String indexName;
@DatabaseChangeProperty(mustEqualExisting = "index.schema")
public String getSchemaName() {
return this.schemaName;
}
public void setSchemaName(final String schemaName) {
this.schemaName = schemaName;
}
@DatabaseChangeProperty(mustEqualExisting = "index", description = "Name of the index to drop", requiredForDatabase = "mysql, oracle, postgresql")
public String getIndexName() {
return this.indexName;
}
public void setIndexName(final String indexName) {
this.indexName = indexName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.table", description = "Name fo the indexed table.", requiredForDatabase = "h2, derby")
public String getTableName() {
return this.tableName;
}
public void setTableName(final String tableName) {
this.tableName = tableName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.catalog")
public String getCatalogName() {
return this.catalogName;
}
public void setCatalogName(final String catalogName) {
this.catalogName = catalogName;
}
@Override
public String getSerializedObjectNamespace() {
|
return XmlConstants.SPATIAL_CHANGELOG_NAMESPACE;
|
lonnyj/liquibase-spatial
|
src/main/java/liquibase/ext/spatial/change/DropSpatialIndexChange.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/DropSpatialIndexStatement.java
// public class DropSpatialIndexStatement extends AbstractSqlStatement {
// /** The index name. */
// private final String indexName;
//
// /** The table catalog name. */
// private final String tableCatalogName;
//
// /** The table schema name. */
// private final String tableSchemaName;
//
// /** The table name. */
// private final String tableName;
//
// /**
// * Creates a new instance with the given parameters.
// *
// * @param indexName
// * the index name.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// */
// public DropSpatialIndexStatement(final String indexName, final String tableCatalogName,
// final String tableSchemaName, final String tableName) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// }
//
// /**
// * Returns the index name.
// *
// * @return the index name.
// */
// public String getIndexName() {
// return this.indexName;
// }
//
// /**
// * Returns the table catalog name.
// *
// * @return the table catalog name.
// */
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// /**
// * Returns the table schema name.
// *
// * @return the table schema name.
// */
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// /**
// * Returns the table name.
// *
// * @return the table name.
// */
// public String getTableName() {
// return this.tableName;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
|
import java.util.ArrayList;
import java.util.Collection;
import liquibase.change.AbstractChange;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.DropSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.DropIndexStatement;
import liquibase.util.StringUtils;
|
package liquibase.ext.spatial.change;
/**
* @author Lonny Jacobson
*/
@DatabaseChange(name = "dropSpatialIndex", description = "Drops the spatial index on an existing column or set of columns.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "index")
public class DropSpatialIndexChange extends AbstractChange {
/** The name of the catalog. */
private String catalogName;
/** The name of the schema. */
private String schemaName;
/** The name of the indexed table. */
private String tableName;
/** The name of the index to drop. */
private String indexName;
@DatabaseChangeProperty(mustEqualExisting = "index.schema")
public String getSchemaName() {
return this.schemaName;
}
public void setSchemaName(final String schemaName) {
this.schemaName = schemaName;
}
@DatabaseChangeProperty(mustEqualExisting = "index", description = "Name of the index to drop", requiredForDatabase = "mysql, oracle, postgresql")
public String getIndexName() {
return this.indexName;
}
public void setIndexName(final String indexName) {
this.indexName = indexName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.table", description = "Name fo the indexed table.", requiredForDatabase = "h2, derby")
public String getTableName() {
return this.tableName;
}
public void setTableName(final String tableName) {
this.tableName = tableName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.catalog")
public String getCatalogName() {
return this.catalogName;
}
public void setCatalogName(final String catalogName) {
this.catalogName = catalogName;
}
@Override
public String getSerializedObjectNamespace() {
return XmlConstants.SPATIAL_CHANGELOG_NAMESPACE;
}
@Override
public String getConfirmationMessage() {
final StringBuilder message = new StringBuilder("Spatial index");
if (StringUtils.trimToNull(getIndexName()) != null) {
message.append(' ').append(getIndexName().trim());
}
message.append(" dropped");
if (StringUtils.trimToNull(getTableName()) != null) {
message.append(" from ").append(getTableName().trim());
}
return message.toString();
}
/**
* Generates a {@link DropSpatialIndexStatement} followed by a {@link DropIndexStatement}, if
* applicable. The first statement allows extra clean-up when dropping an index. The second
* statement leverages the normal <code>DROP INDEX</code> logic.
*/
@Override
public SqlStatement[] generateStatements(final Database database) {
final Collection<SqlStatement> statements = new ArrayList<SqlStatement>();
// MySQL and PostgreSQL only need the normal DROP INDEX statement.
if (!(database instanceof MySQLDatabase) && !(database instanceof PostgresDatabase)) {
|
// Path: src/main/java/liquibase/ext/spatial/statement/DropSpatialIndexStatement.java
// public class DropSpatialIndexStatement extends AbstractSqlStatement {
// /** The index name. */
// private final String indexName;
//
// /** The table catalog name. */
// private final String tableCatalogName;
//
// /** The table schema name. */
// private final String tableSchemaName;
//
// /** The table name. */
// private final String tableName;
//
// /**
// * Creates a new instance with the given parameters.
// *
// * @param indexName
// * the index name.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// */
// public DropSpatialIndexStatement(final String indexName, final String tableCatalogName,
// final String tableSchemaName, final String tableName) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// }
//
// /**
// * Returns the index name.
// *
// * @return the index name.
// */
// public String getIndexName() {
// return this.indexName;
// }
//
// /**
// * Returns the table catalog name.
// *
// * @return the table catalog name.
// */
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// /**
// * Returns the table schema name.
// *
// * @return the table schema name.
// */
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// /**
// * Returns the table name.
// *
// * @return the table name.
// */
// public String getTableName() {
// return this.tableName;
// }
// }
//
// Path: src/main/java/liquibase/ext/spatial/xml/XmlConstants.java
// public interface XmlConstants {
// /** The extension's XML namespace. */
// static final String SPATIAL_CHANGELOG_NAMESPACE = "http://www.liquibase.org/xml/ns/dbchangelog-ext/liquibase-spatial";
// }
// Path: src/main/java/liquibase/ext/spatial/change/DropSpatialIndexChange.java
import java.util.ArrayList;
import java.util.Collection;
import liquibase.change.AbstractChange;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.DatabaseChangeProperty;
import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.H2Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.DropSpatialIndexStatement;
import liquibase.ext.spatial.xml.XmlConstants;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.DropIndexStatement;
import liquibase.util.StringUtils;
package liquibase.ext.spatial.change;
/**
* @author Lonny Jacobson
*/
@DatabaseChange(name = "dropSpatialIndex", description = "Drops the spatial index on an existing column or set of columns.", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "index")
public class DropSpatialIndexChange extends AbstractChange {
/** The name of the catalog. */
private String catalogName;
/** The name of the schema. */
private String schemaName;
/** The name of the indexed table. */
private String tableName;
/** The name of the index to drop. */
private String indexName;
@DatabaseChangeProperty(mustEqualExisting = "index.schema")
public String getSchemaName() {
return this.schemaName;
}
public void setSchemaName(final String schemaName) {
this.schemaName = schemaName;
}
@DatabaseChangeProperty(mustEqualExisting = "index", description = "Name of the index to drop", requiredForDatabase = "mysql, oracle, postgresql")
public String getIndexName() {
return this.indexName;
}
public void setIndexName(final String indexName) {
this.indexName = indexName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.table", description = "Name fo the indexed table.", requiredForDatabase = "h2, derby")
public String getTableName() {
return this.tableName;
}
public void setTableName(final String tableName) {
this.tableName = tableName;
}
@DatabaseChangeProperty(mustEqualExisting = "index.catalog")
public String getCatalogName() {
return this.catalogName;
}
public void setCatalogName(final String catalogName) {
this.catalogName = catalogName;
}
@Override
public String getSerializedObjectNamespace() {
return XmlConstants.SPATIAL_CHANGELOG_NAMESPACE;
}
@Override
public String getConfirmationMessage() {
final StringBuilder message = new StringBuilder("Spatial index");
if (StringUtils.trimToNull(getIndexName()) != null) {
message.append(' ').append(getIndexName().trim());
}
message.append(" dropped");
if (StringUtils.trimToNull(getTableName()) != null) {
message.append(" from ").append(getTableName().trim());
}
return message.toString();
}
/**
* Generates a {@link DropSpatialIndexStatement} followed by a {@link DropIndexStatement}, if
* applicable. The first statement allows extra clean-up when dropping an index. The second
* statement leverages the normal <code>DROP INDEX</code> logic.
*/
@Override
public SqlStatement[] generateStatements(final Database database) {
final Collection<SqlStatement> statements = new ArrayList<SqlStatement>();
// MySQL and PostgreSQL only need the normal DROP INDEX statement.
if (!(database instanceof MySQLDatabase) && !(database instanceof PostgresDatabase)) {
|
final DropSpatialIndexStatement dropSpatialIndex = new DropSpatialIndexStatement(
|
lonnyj/liquibase-spatial
|
src/test/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorPostgreSQLTest.java
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
|
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
|
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorPostgreSQLTest</code> tests
* {@link CreateSpatialIndexGeneratorPostgreSQL}.
*/
public class CreateSpatialIndexGeneratorPostgreSQLTest {
/**
* Tests
* {@link CreateSpatialIndexGeneratorPostgreSQL#supports(CreateSpatialIndexStatement, Database)}
*/
@Test
public void testSupports() {
final CreateSpatialIndexGeneratorPostgreSQL generator = new CreateSpatialIndexGeneratorPostgreSQL();
|
// Path: src/main/java/liquibase/ext/spatial/statement/CreateSpatialIndexStatement.java
// public class CreateSpatialIndexStatement extends AbstractSqlStatement {
//
// private final String tableCatalogName;
// private final String tableSchemaName;
// private final String indexName;
// private final String tableName;
// private final String[] columns;
// private String tablespace;
//
// /** The WKT geometry type (e.g. Geometry, Point, etc). */
// private String geometryType;
//
// /** The Spatial Reference ID (e.g. 4326). */
// private Integer srid;
//
// /**
// * Constructs a new instance with the given parameters.
// *
// * @param indexName
// * the name of the index to create.
// * @param tableCatalogName
// * the optional table's catalog name.
// * @param tableSchemaName
// * the optional table's schema name.
// * @param tableName
// * the table name.
// * @param columns
// * the array of column names.
// * @param tablespace
// * the optional table space name.
// * @param geometryType
// * the optional geometry type.
// * @param srid
// * the optional Spatial Reference ID.
// */
// public CreateSpatialIndexStatement(final String indexName,
// final String tableCatalogName, final String tableSchemaName,
// final String tableName, final String[] columns, final String tablespace,
// final String geometryType, final Integer srid) {
// this.indexName = indexName;
// this.tableCatalogName = tableCatalogName;
// this.tableSchemaName = tableSchemaName;
// this.tableName = tableName;
// this.columns = columns.clone();
// this.tablespace = tablespace;
// this.geometryType = geometryType;
// this.srid = srid;
// }
//
// public String getTableCatalogName() {
// return this.tableCatalogName;
// }
//
// public String getTableSchemaName() {
// return this.tableSchemaName;
// }
//
// public String getIndexName() {
// return this.indexName;
// }
//
// public String getTableName() {
// return this.tableName;
// }
//
// public String[] getColumns() {
// return this.columns;
// }
//
// public String getTablespace() {
// return this.tablespace;
// }
//
// public CreateSpatialIndexStatement setTablespace(final String tablespace) {
// this.tablespace = tablespace;
// return this;
// }
//
// /**
// * Sets the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @param geometryType
// * the geometry type.
// */
// public void setGeometryType(final String geometryType) {
// this.geometryType = geometryType;
// }
//
// /**
// * Returns the WKT geometry type (e.g. Geometry, Point, etc).
// *
// * @return the geometry type.
// */
// public String getGeometryType() {
// return this.geometryType;
// }
//
// /**
// * Sets the Spatial Reference ID (e.g. 4326).
// *
// * @param srid
// * the SRID.
// */
// public void setSrid(final Integer srid) {
// this.srid = srid;
// }
//
// /**
// * Returns the Spatial Reference ID (e.g. 4326).
// *
// * @return the SRID.
// */
// public Integer getSrid() {
// return this.srid;
// }
// }
// Path: src/test/java/liquibase/ext/spatial/sqlgenerator/CreateSpatialIndexGeneratorPostgreSQLTest.java
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
import liquibase.database.Database;
import liquibase.database.core.H2Database;
import liquibase.database.core.PostgresDatabase;
import liquibase.ext.spatial.statement.CreateSpatialIndexStatement;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
package liquibase.ext.spatial.sqlgenerator;
/**
* <code>CreateSpatialIndexGeneratorPostgreSQLTest</code> tests
* {@link CreateSpatialIndexGeneratorPostgreSQL}.
*/
public class CreateSpatialIndexGeneratorPostgreSQLTest {
/**
* Tests
* {@link CreateSpatialIndexGeneratorPostgreSQL#supports(CreateSpatialIndexStatement, Database)}
*/
@Test
public void testSupports() {
final CreateSpatialIndexGeneratorPostgreSQL generator = new CreateSpatialIndexGeneratorPostgreSQL();
|
final CreateSpatialIndexStatement statement = mock(CreateSpatialIndexStatement.class);
|
kuenishi/presto-riak
|
src/main/java/com/basho/riak/presto/RiakRecordCursor.java
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
|
import com.basho.riak.client.core.util.BinaryValue;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.spi.type.BigintType;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.DoubleType;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Strings;
import io.airlift.log.Logger;
import io.airlift.slice.Slice;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.*;
|
/*
* 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.basho.riak.presto;
public class RiakRecordCursor
implements RecordCursor {
private static final Logger log = Logger.get(RiakRecordCursor.class);
//private static final Splitter LINE_SPLITTER = Splitter.on(",").trimResults();
private final BinaryValue schemaName;
private final BinaryValue tableName;
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
// Path: src/main/java/com/basho/riak/presto/RiakRecordCursor.java
import com.basho.riak.client.core.util.BinaryValue;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.spi.type.BigintType;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.DoubleType;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Strings;
import io.airlift.log.Logger;
import io.airlift.slice.Slice;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.*;
/*
* 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.basho.riak.presto;
public class RiakRecordCursor
implements RecordCursor {
private static final Logger log = Logger.get(RiakRecordCursor.class);
//private static final Splitter LINE_SPLITTER = Splitter.on(",").trimResults();
private final BinaryValue schemaName;
private final BinaryValue tableName;
|
private final List<RiakColumnHandle> columnHandles;
|
kuenishi/presto-riak
|
src/main/java/com/basho/riak/presto/models/CoverageSplit.java
|
// Path: src/main/java/com/basho/riak/presto/SplitTask.java
// public class SplitTask {
// private final String host;
// private final OtpErlangTuple task; // OtpErlangObject[] a = {vnode, filterVnodes};
//
//
// public SplitTask(String node, OtpErlangTuple task) {
// this.host = node2host(node);
// this.task = task;
// }
//
// // fromString(String)
// public SplitTask(String data)
// throws OtpErlangDecodeException, DecoderException {
//
// byte[] binary = Base64.decodeBase64(Hex.decodeHex(data.toCharArray()));
// task = (OtpErlangTuple) binary2term(binary);
// // task = {vnode, filterVnodes}
// OtpErlangTuple vnode = (OtpErlangTuple) task.elementAt(0);
// // vnode = {index, node}
// OtpErlangAtom erlangNode = (OtpErlangAtom) vnode.elementAt(1);
// // "dev" @ "127.0.0.1"
// this.host = node2host(erlangNode.atomValue());
// }
//
// private String node2host(String node) {
// String[] s = node.split("@");
// return s[1];
// }
//
// // @doc hostname without port number: Riak doesn't care about port number.
// public String getHost() {
// return host;
// }
//
// public String toString() {
// byte[] binary = term2binary(task);
// byte[] b = Base64.encodeBase64(binary);
// return Hex.encodeHexString(b);
// }
//
// public byte[] term2binary(OtpErlangObject o) {
// OtpOutputStream oos = new OtpOutputStream();
// oos.write_any(o);
// return oos.toByteArray();
// }
//
// public OtpErlangObject binary2term(byte[] data)
// throws OtpErlangDecodeException {
// OtpInputStream ois = new OtpInputStream(data);
// return ois.read_any();
// }
//
// public OtpErlangTuple getTask() {
// return this.task;
// }
//
// public OtpErlangList fetchAllData(DirectConnection conn, String schemaName, String tableName)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangList riakObjects = conn.processSplit(schemaName.getBytes(), tableName.getBytes(), vnode, filterVnodes);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// public OtpErlangList fetchViaIndex(DirectConnection conn, String schemaName, String tableName,
// OtpErlangTuple query)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangTuple result = conn.processSplitIndex(schemaName.getBytes(), tableName.getBytes(), vnode,
// filterVnodes, query);
// OtpErlangList riakObjects = (OtpErlangList) result.elementAt(1);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// }
|
import static com.google.common.base.Preconditions.checkNotNull;
import com.basho.riak.presto.SplitTask;
import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.TupleDomain;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.log.Logger;
import org.apache.commons.codec.DecoderException;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
|
public TupleDomain<ColumnHandle> getTupleDomain() {
return tupleDomain;
}
@Override
public boolean isRemotelyAccessible() {
//log.debug(new JsonCodecFactory().jsonCodec(CoverageSplit.class).toJson(this));
return false;
}
@Override
public Object getInfo() {
return ImmutableMap.builder()
.put("tableHandle", tableHandle)
.put("table", table)
.put("host", host)
.put("splitData", splitData)
.put("tupleDomain", tupleDomain)
.build();
}
@Override
public List<HostAddress> getAddresses() {
//log.debug("getAddress: %s", addresses);
//log.debug(new JsonCodecFactory().jsonCodec(CoverageSplit.class).toJson(this));
return ImmutableList.copyOf(Arrays.asList(HostAddress.fromString(host)));
}
@NotNull
|
// Path: src/main/java/com/basho/riak/presto/SplitTask.java
// public class SplitTask {
// private final String host;
// private final OtpErlangTuple task; // OtpErlangObject[] a = {vnode, filterVnodes};
//
//
// public SplitTask(String node, OtpErlangTuple task) {
// this.host = node2host(node);
// this.task = task;
// }
//
// // fromString(String)
// public SplitTask(String data)
// throws OtpErlangDecodeException, DecoderException {
//
// byte[] binary = Base64.decodeBase64(Hex.decodeHex(data.toCharArray()));
// task = (OtpErlangTuple) binary2term(binary);
// // task = {vnode, filterVnodes}
// OtpErlangTuple vnode = (OtpErlangTuple) task.elementAt(0);
// // vnode = {index, node}
// OtpErlangAtom erlangNode = (OtpErlangAtom) vnode.elementAt(1);
// // "dev" @ "127.0.0.1"
// this.host = node2host(erlangNode.atomValue());
// }
//
// private String node2host(String node) {
// String[] s = node.split("@");
// return s[1];
// }
//
// // @doc hostname without port number: Riak doesn't care about port number.
// public String getHost() {
// return host;
// }
//
// public String toString() {
// byte[] binary = term2binary(task);
// byte[] b = Base64.encodeBase64(binary);
// return Hex.encodeHexString(b);
// }
//
// public byte[] term2binary(OtpErlangObject o) {
// OtpOutputStream oos = new OtpOutputStream();
// oos.write_any(o);
// return oos.toByteArray();
// }
//
// public OtpErlangObject binary2term(byte[] data)
// throws OtpErlangDecodeException {
// OtpInputStream ois = new OtpInputStream(data);
// return ois.read_any();
// }
//
// public OtpErlangTuple getTask() {
// return this.task;
// }
//
// public OtpErlangList fetchAllData(DirectConnection conn, String schemaName, String tableName)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangList riakObjects = conn.processSplit(schemaName.getBytes(), tableName.getBytes(), vnode, filterVnodes);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// public OtpErlangList fetchViaIndex(DirectConnection conn, String schemaName, String tableName,
// OtpErlangTuple query)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangTuple result = conn.processSplitIndex(schemaName.getBytes(), tableName.getBytes(), vnode,
// filterVnodes, query);
// OtpErlangList riakObjects = (OtpErlangList) result.elementAt(1);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// }
// Path: src/main/java/com/basho/riak/presto/models/CoverageSplit.java
import static com.google.common.base.Preconditions.checkNotNull;
import com.basho.riak.presto.SplitTask;
import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.TupleDomain;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.log.Logger;
import org.apache.commons.codec.DecoderException;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
public TupleDomain<ColumnHandle> getTupleDomain() {
return tupleDomain;
}
@Override
public boolean isRemotelyAccessible() {
//log.debug(new JsonCodecFactory().jsonCodec(CoverageSplit.class).toJson(this));
return false;
}
@Override
public Object getInfo() {
return ImmutableMap.builder()
.put("tableHandle", tableHandle)
.put("table", table)
.put("host", host)
.put("splitData", splitData)
.put("tupleDomain", tupleDomain)
.build();
}
@Override
public List<HostAddress> getAddresses() {
//log.debug("getAddress: %s", addresses);
//log.debug(new JsonCodecFactory().jsonCodec(CoverageSplit.class).toJson(this));
return ImmutableList.copyOf(Arrays.asList(HostAddress.fromString(host)));
}
@NotNull
|
public SplitTask getSplitTask()
|
kuenishi/presto-riak
|
src/test/java/com/basho/riak/presto/TestSplitTask.java
|
// Path: src/main/java/com/basho/riak/presto/SplitTask.java
// public class SplitTask {
// private final String host;
// private final OtpErlangTuple task; // OtpErlangObject[] a = {vnode, filterVnodes};
//
//
// public SplitTask(String node, OtpErlangTuple task) {
// this.host = node2host(node);
// this.task = task;
// }
//
// // fromString(String)
// public SplitTask(String data)
// throws OtpErlangDecodeException, DecoderException {
//
// byte[] binary = Base64.decodeBase64(Hex.decodeHex(data.toCharArray()));
// task = (OtpErlangTuple) binary2term(binary);
// // task = {vnode, filterVnodes}
// OtpErlangTuple vnode = (OtpErlangTuple) task.elementAt(0);
// // vnode = {index, node}
// OtpErlangAtom erlangNode = (OtpErlangAtom) vnode.elementAt(1);
// // "dev" @ "127.0.0.1"
// this.host = node2host(erlangNode.atomValue());
// }
//
// private String node2host(String node) {
// String[] s = node.split("@");
// return s[1];
// }
//
// // @doc hostname without port number: Riak doesn't care about port number.
// public String getHost() {
// return host;
// }
//
// public String toString() {
// byte[] binary = term2binary(task);
// byte[] b = Base64.encodeBase64(binary);
// return Hex.encodeHexString(b);
// }
//
// public byte[] term2binary(OtpErlangObject o) {
// OtpOutputStream oos = new OtpOutputStream();
// oos.write_any(o);
// return oos.toByteArray();
// }
//
// public OtpErlangObject binary2term(byte[] data)
// throws OtpErlangDecodeException {
// OtpInputStream ois = new OtpInputStream(data);
// return ois.read_any();
// }
//
// public OtpErlangTuple getTask() {
// return this.task;
// }
//
// public OtpErlangList fetchAllData(DirectConnection conn, String schemaName, String tableName)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangList riakObjects = conn.processSplit(schemaName.getBytes(), tableName.getBytes(), vnode, filterVnodes);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// public OtpErlangList fetchViaIndex(DirectConnection conn, String schemaName, String tableName,
// OtpErlangTuple query)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangTuple result = conn.processSplitIndex(schemaName.getBytes(), tableName.getBytes(), vnode,
// filterVnodes, query);
// OtpErlangList riakObjects = (OtpErlangList) result.elementAt(1);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// }
|
import com.basho.riak.presto.SplitTask;
import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangTuple;
import com.ericsson.otp.erlang.OtpErlangLong;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.codec.DecoderException;
import org.junit.Test;
import static org.junit.Assert.*;
|
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/03/29.
*/
public class TestSplitTask {
@Test
public void testPasses() {
String expected = "Hello, JUnit!";
String hello = "Hello, JUnit!";
assertEquals(hello, expected);
}
@Test
public void testEncode()
throws OtpErlangDecodeException, DecoderException
{
OtpErlangObject[] list = {new OtpErlangLong(12),
new OtpErlangAtom("[email protected]")};
OtpErlangObject[] list2 = {new OtpErlangTuple(list),
new OtpErlangAtom("[email protected]")};
OtpErlangTuple t = new OtpErlangTuple(list2);
|
// Path: src/main/java/com/basho/riak/presto/SplitTask.java
// public class SplitTask {
// private final String host;
// private final OtpErlangTuple task; // OtpErlangObject[] a = {vnode, filterVnodes};
//
//
// public SplitTask(String node, OtpErlangTuple task) {
// this.host = node2host(node);
// this.task = task;
// }
//
// // fromString(String)
// public SplitTask(String data)
// throws OtpErlangDecodeException, DecoderException {
//
// byte[] binary = Base64.decodeBase64(Hex.decodeHex(data.toCharArray()));
// task = (OtpErlangTuple) binary2term(binary);
// // task = {vnode, filterVnodes}
// OtpErlangTuple vnode = (OtpErlangTuple) task.elementAt(0);
// // vnode = {index, node}
// OtpErlangAtom erlangNode = (OtpErlangAtom) vnode.elementAt(1);
// // "dev" @ "127.0.0.1"
// this.host = node2host(erlangNode.atomValue());
// }
//
// private String node2host(String node) {
// String[] s = node.split("@");
// return s[1];
// }
//
// // @doc hostname without port number: Riak doesn't care about port number.
// public String getHost() {
// return host;
// }
//
// public String toString() {
// byte[] binary = term2binary(task);
// byte[] b = Base64.encodeBase64(binary);
// return Hex.encodeHexString(b);
// }
//
// public byte[] term2binary(OtpErlangObject o) {
// OtpOutputStream oos = new OtpOutputStream();
// oos.write_any(o);
// return oos.toByteArray();
// }
//
// public OtpErlangObject binary2term(byte[] data)
// throws OtpErlangDecodeException {
// OtpInputStream ois = new OtpInputStream(data);
// return ois.read_any();
// }
//
// public OtpErlangTuple getTask() {
// return this.task;
// }
//
// public OtpErlangList fetchAllData(DirectConnection conn, String schemaName, String tableName)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangList riakObjects = conn.processSplit(schemaName.getBytes(), tableName.getBytes(), vnode, filterVnodes);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// public OtpErlangList fetchViaIndex(DirectConnection conn, String schemaName, String tableName,
// OtpErlangTuple query)
// throws OtpErlangDecodeException, OtpAuthException, OtpErlangExit {
// OtpErlangTuple t = (OtpErlangTuple) task;
// OtpErlangTuple vnode = (OtpErlangTuple) t.elementAt(0);
// OtpErlangList filterVnodes = (OtpErlangList) t.elementAt(1);
//
// try {
// OtpErlangTuple result = conn.processSplitIndex(schemaName.getBytes(), tableName.getBytes(), vnode,
// filterVnodes, query);
// OtpErlangList riakObjects = (OtpErlangList) result.elementAt(1);
// //System.out.println(riakObjects);
// return riakObjects;
// } catch (java.io.IOException e) {
// System.err.println(e);
// }
// return new OtpErlangList();
// }
//
// }
// Path: src/test/java/com/basho/riak/presto/TestSplitTask.java
import com.basho.riak.presto.SplitTask;
import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangTuple;
import com.ericsson.otp.erlang.OtpErlangLong;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.codec.DecoderException;
import org.junit.Test;
import static org.junit.Assert.*;
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/03/29.
*/
public class TestSplitTask {
@Test
public void testPasses() {
String expected = "Hello, JUnit!";
String hello = "Hello, JUnit!";
assertEquals(hello, expected);
}
@Test
public void testEncode()
throws OtpErlangDecodeException, DecoderException
{
OtpErlangObject[] list = {new OtpErlangLong(12),
new OtpErlangAtom("[email protected]")};
OtpErlangObject[] list2 = {new OtpErlangTuple(list),
new OtpErlangAtom("[email protected]")};
OtpErlangTuple t = new OtpErlangTuple(list2);
|
SplitTask splitTask = new SplitTask("[email protected]", t);
|
kuenishi/presto-riak
|
src/test/java/com/basho/riak/presto/TestPRSchema.java
|
// Path: src/main/java/com/basho/riak/presto/models/PRSchema.java
// public class PRSchema {
// private static final Logger log = Logger.get(PRSchema.class);
// private final Set<String> tables;
// private final Set<String> comments;
//
// @JsonCreator
// public PRSchema(
// @JsonProperty("tables") Set<String> tables,
// @JsonProperty(value = "comments", required = false) Set<String> comments) {
//
// this.tables = checkNotNull(tables, "tables is null");
// this.comments = checkNotNull(comments, "columns is null");
// }
//
// public static PRSchema example() {
// Set<String> ts = Sets.newHashSet();
// Set<String> s = Sets.newHashSet("tse;lkajsdf");
// PRSchema prs = new PRSchema(ts, s);
// prs.addTable("foobartable");
// return prs;
// }
//
// @JsonProperty
// public Set<String> getTables() {
// return tables;
// }
//
// @JsonProperty
// public Set<String> getComments() {
// return comments;
// }
//
// public void addTable(PRTable table, String comment) {
// addTable(table.getName());
// tables.addAll(table.getSubtableNames());
// comments.add(comment);
// }
//
// private void addTable(String table) {
// tables.add(table);
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<PRSchema> SCHEMA_CODEC;
|
import com.basho.riak.presto.models.PRSchema;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Set;
import static com.basho.riak.presto.MetadataUtil.SCHEMA_CODEC;
|
package com.basho.riak.presto;
/**
* Created by kuenishi on 2014/12/5.
*/
public class TestPRSchema {
@Test
public void testPRSchemaSerealization()
{
|
// Path: src/main/java/com/basho/riak/presto/models/PRSchema.java
// public class PRSchema {
// private static final Logger log = Logger.get(PRSchema.class);
// private final Set<String> tables;
// private final Set<String> comments;
//
// @JsonCreator
// public PRSchema(
// @JsonProperty("tables") Set<String> tables,
// @JsonProperty(value = "comments", required = false) Set<String> comments) {
//
// this.tables = checkNotNull(tables, "tables is null");
// this.comments = checkNotNull(comments, "columns is null");
// }
//
// public static PRSchema example() {
// Set<String> ts = Sets.newHashSet();
// Set<String> s = Sets.newHashSet("tse;lkajsdf");
// PRSchema prs = new PRSchema(ts, s);
// prs.addTable("foobartable");
// return prs;
// }
//
// @JsonProperty
// public Set<String> getTables() {
// return tables;
// }
//
// @JsonProperty
// public Set<String> getComments() {
// return comments;
// }
//
// public void addTable(PRTable table, String comment) {
// addTable(table.getName());
// tables.addAll(table.getSubtableNames());
// comments.add(comment);
// }
//
// private void addTable(String table) {
// tables.add(table);
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<PRSchema> SCHEMA_CODEC;
// Path: src/test/java/com/basho/riak/presto/TestPRSchema.java
import com.basho.riak.presto.models.PRSchema;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Set;
import static com.basho.riak.presto.MetadataUtil.SCHEMA_CODEC;
package com.basho.riak.presto;
/**
* Created by kuenishi on 2014/12/5.
*/
public class TestPRSchema {
@Test
public void testPRSchemaSerealization()
{
|
PRSchema t = PRSchema.example();
|
kuenishi/presto-riak
|
src/test/java/com/basho/riak/presto/TestPRSchema.java
|
// Path: src/main/java/com/basho/riak/presto/models/PRSchema.java
// public class PRSchema {
// private static final Logger log = Logger.get(PRSchema.class);
// private final Set<String> tables;
// private final Set<String> comments;
//
// @JsonCreator
// public PRSchema(
// @JsonProperty("tables") Set<String> tables,
// @JsonProperty(value = "comments", required = false) Set<String> comments) {
//
// this.tables = checkNotNull(tables, "tables is null");
// this.comments = checkNotNull(comments, "columns is null");
// }
//
// public static PRSchema example() {
// Set<String> ts = Sets.newHashSet();
// Set<String> s = Sets.newHashSet("tse;lkajsdf");
// PRSchema prs = new PRSchema(ts, s);
// prs.addTable("foobartable");
// return prs;
// }
//
// @JsonProperty
// public Set<String> getTables() {
// return tables;
// }
//
// @JsonProperty
// public Set<String> getComments() {
// return comments;
// }
//
// public void addTable(PRTable table, String comment) {
// addTable(table.getName());
// tables.addAll(table.getSubtableNames());
// comments.add(comment);
// }
//
// private void addTable(String table) {
// tables.add(table);
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<PRSchema> SCHEMA_CODEC;
|
import com.basho.riak.presto.models.PRSchema;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Set;
import static com.basho.riak.presto.MetadataUtil.SCHEMA_CODEC;
|
package com.basho.riak.presto;
/**
* Created by kuenishi on 2014/12/5.
*/
public class TestPRSchema {
@Test
public void testPRSchemaSerealization()
{
PRSchema t = PRSchema.example();
//System.out.println(t.toString());
|
// Path: src/main/java/com/basho/riak/presto/models/PRSchema.java
// public class PRSchema {
// private static final Logger log = Logger.get(PRSchema.class);
// private final Set<String> tables;
// private final Set<String> comments;
//
// @JsonCreator
// public PRSchema(
// @JsonProperty("tables") Set<String> tables,
// @JsonProperty(value = "comments", required = false) Set<String> comments) {
//
// this.tables = checkNotNull(tables, "tables is null");
// this.comments = checkNotNull(comments, "columns is null");
// }
//
// public static PRSchema example() {
// Set<String> ts = Sets.newHashSet();
// Set<String> s = Sets.newHashSet("tse;lkajsdf");
// PRSchema prs = new PRSchema(ts, s);
// prs.addTable("foobartable");
// return prs;
// }
//
// @JsonProperty
// public Set<String> getTables() {
// return tables;
// }
//
// @JsonProperty
// public Set<String> getComments() {
// return comments;
// }
//
// public void addTable(PRTable table, String comment) {
// addTable(table.getName());
// tables.addAll(table.getSubtableNames());
// comments.add(comment);
// }
//
// private void addTable(String table) {
// tables.add(table);
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<PRSchema> SCHEMA_CODEC;
// Path: src/test/java/com/basho/riak/presto/TestPRSchema.java
import com.basho.riak.presto.models.PRSchema;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Set;
import static com.basho.riak.presto.MetadataUtil.SCHEMA_CODEC;
package com.basho.riak.presto;
/**
* Created by kuenishi on 2014/12/5.
*/
public class TestPRSchema {
@Test
public void testPRSchemaSerealization()
{
PRSchema t = PRSchema.example();
//System.out.println(t.toString());
|
String s = SCHEMA_CODEC.toJson(t);
|
kuenishi/presto-riak
|
src/test/java/com/basho/riak/presto/TestRiakColumnHandle.java
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumn.java
// public final class RiakColumn {
// private static final Logger log = Logger.get(RiakRecordSetProvider.class);
// private final String name;
// private final Type type;
// private final String comment;
// private boolean index;
// private boolean pkey = false;
//
// @JsonCreator
// public RiakColumn(
// @JsonProperty(value = "name", required = true) String name,
// @JsonProperty(value = "type", required = true) Type type,
// @JsonProperty(value = "comment") String comment,
// @JsonProperty(value = "index", required = false) boolean index,
// @JsonProperty(value = "pkey", required = false, defaultValue = "false") boolean pkey
// ) {
// checkArgument(!isNullOrEmpty(name), "name is null or is empty");
// checkNotNull(index);
// this.name = name;
// this.type = checkNotNull(type, "type is null");
// this.comment = comment;
// this.index = index;
// this.pkey = checkNotNull(pkey);
// }
//
// @JsonProperty
// public String getName() {
// return name;
// }
//
// @JsonProperty
// public Type getType() {
// return type;
// }
//
// @JsonProperty
// public String getComment() {
// return comment;
// }
//
// @JsonProperty
// public boolean getIndex() {
// return index;
// }
//
// public void setIndex(boolean b) {
// this.index = b;
// }
//
// @JsonProperty
// public boolean getPkey() {
// return pkey;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, type);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null || getClass() != obj.getClass()) {
// return false;
// }
//
// RiakColumn other = (RiakColumn) obj;
// return Objects.equal(this.name, other.name) &&
// (this.index == other.index) &&
// Objects.equal(this.type, other.type);
// }
//
// @Override
// public String toString() {
// return name + ":" + type + "(index=" + index + ")";
// }
// }
//
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<RiakColumnHandle> COLUMN_CODEC;
|
import com.basho.riak.presto.models.RiakColumn;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.VarcharType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static com.basho.riak.presto.MetadataUtil.COLUMN_CODEC;
import java.io.IOException;
|
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/05/17.
*/
public class TestRiakColumnHandle {
@Test
public void testSerializtion2()
throws IOException
{
String connectorId = "fooo gooo";
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumn.java
// public final class RiakColumn {
// private static final Logger log = Logger.get(RiakRecordSetProvider.class);
// private final String name;
// private final Type type;
// private final String comment;
// private boolean index;
// private boolean pkey = false;
//
// @JsonCreator
// public RiakColumn(
// @JsonProperty(value = "name", required = true) String name,
// @JsonProperty(value = "type", required = true) Type type,
// @JsonProperty(value = "comment") String comment,
// @JsonProperty(value = "index", required = false) boolean index,
// @JsonProperty(value = "pkey", required = false, defaultValue = "false") boolean pkey
// ) {
// checkArgument(!isNullOrEmpty(name), "name is null or is empty");
// checkNotNull(index);
// this.name = name;
// this.type = checkNotNull(type, "type is null");
// this.comment = comment;
// this.index = index;
// this.pkey = checkNotNull(pkey);
// }
//
// @JsonProperty
// public String getName() {
// return name;
// }
//
// @JsonProperty
// public Type getType() {
// return type;
// }
//
// @JsonProperty
// public String getComment() {
// return comment;
// }
//
// @JsonProperty
// public boolean getIndex() {
// return index;
// }
//
// public void setIndex(boolean b) {
// this.index = b;
// }
//
// @JsonProperty
// public boolean getPkey() {
// return pkey;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, type);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null || getClass() != obj.getClass()) {
// return false;
// }
//
// RiakColumn other = (RiakColumn) obj;
// return Objects.equal(this.name, other.name) &&
// (this.index == other.index) &&
// Objects.equal(this.type, other.type);
// }
//
// @Override
// public String toString() {
// return name + ":" + type + "(index=" + index + ")";
// }
// }
//
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<RiakColumnHandle> COLUMN_CODEC;
// Path: src/test/java/com/basho/riak/presto/TestRiakColumnHandle.java
import com.basho.riak.presto.models.RiakColumn;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.VarcharType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static com.basho.riak.presto.MetadataUtil.COLUMN_CODEC;
import java.io.IOException;
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/05/17.
*/
public class TestRiakColumnHandle {
@Test
public void testSerializtion2()
throws IOException
{
String connectorId = "fooo gooo";
|
RiakColumn column = new RiakColumn("p", BooleanType.BOOLEAN, "boom", true, false);
|
kuenishi/presto-riak
|
src/test/java/com/basho/riak/presto/TestRiakColumnHandle.java
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumn.java
// public final class RiakColumn {
// private static final Logger log = Logger.get(RiakRecordSetProvider.class);
// private final String name;
// private final Type type;
// private final String comment;
// private boolean index;
// private boolean pkey = false;
//
// @JsonCreator
// public RiakColumn(
// @JsonProperty(value = "name", required = true) String name,
// @JsonProperty(value = "type", required = true) Type type,
// @JsonProperty(value = "comment") String comment,
// @JsonProperty(value = "index", required = false) boolean index,
// @JsonProperty(value = "pkey", required = false, defaultValue = "false") boolean pkey
// ) {
// checkArgument(!isNullOrEmpty(name), "name is null or is empty");
// checkNotNull(index);
// this.name = name;
// this.type = checkNotNull(type, "type is null");
// this.comment = comment;
// this.index = index;
// this.pkey = checkNotNull(pkey);
// }
//
// @JsonProperty
// public String getName() {
// return name;
// }
//
// @JsonProperty
// public Type getType() {
// return type;
// }
//
// @JsonProperty
// public String getComment() {
// return comment;
// }
//
// @JsonProperty
// public boolean getIndex() {
// return index;
// }
//
// public void setIndex(boolean b) {
// this.index = b;
// }
//
// @JsonProperty
// public boolean getPkey() {
// return pkey;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, type);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null || getClass() != obj.getClass()) {
// return false;
// }
//
// RiakColumn other = (RiakColumn) obj;
// return Objects.equal(this.name, other.name) &&
// (this.index == other.index) &&
// Objects.equal(this.type, other.type);
// }
//
// @Override
// public String toString() {
// return name + ":" + type + "(index=" + index + ")";
// }
// }
//
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<RiakColumnHandle> COLUMN_CODEC;
|
import com.basho.riak.presto.models.RiakColumn;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.VarcharType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static com.basho.riak.presto.MetadataUtil.COLUMN_CODEC;
import java.io.IOException;
|
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/05/17.
*/
public class TestRiakColumnHandle {
@Test
public void testSerializtion2()
throws IOException
{
String connectorId = "fooo gooo";
RiakColumn column = new RiakColumn("p", BooleanType.BOOLEAN, "boom", true, false);
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumn.java
// public final class RiakColumn {
// private static final Logger log = Logger.get(RiakRecordSetProvider.class);
// private final String name;
// private final Type type;
// private final String comment;
// private boolean index;
// private boolean pkey = false;
//
// @JsonCreator
// public RiakColumn(
// @JsonProperty(value = "name", required = true) String name,
// @JsonProperty(value = "type", required = true) Type type,
// @JsonProperty(value = "comment") String comment,
// @JsonProperty(value = "index", required = false) boolean index,
// @JsonProperty(value = "pkey", required = false, defaultValue = "false") boolean pkey
// ) {
// checkArgument(!isNullOrEmpty(name), "name is null or is empty");
// checkNotNull(index);
// this.name = name;
// this.type = checkNotNull(type, "type is null");
// this.comment = comment;
// this.index = index;
// this.pkey = checkNotNull(pkey);
// }
//
// @JsonProperty
// public String getName() {
// return name;
// }
//
// @JsonProperty
// public Type getType() {
// return type;
// }
//
// @JsonProperty
// public String getComment() {
// return comment;
// }
//
// @JsonProperty
// public boolean getIndex() {
// return index;
// }
//
// public void setIndex(boolean b) {
// this.index = b;
// }
//
// @JsonProperty
// public boolean getPkey() {
// return pkey;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, type);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null || getClass() != obj.getClass()) {
// return false;
// }
//
// RiakColumn other = (RiakColumn) obj;
// return Objects.equal(this.name, other.name) &&
// (this.index == other.index) &&
// Objects.equal(this.type, other.type);
// }
//
// @Override
// public String toString() {
// return name + ":" + type + "(index=" + index + ")";
// }
// }
//
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<RiakColumnHandle> COLUMN_CODEC;
// Path: src/test/java/com/basho/riak/presto/TestRiakColumnHandle.java
import com.basho.riak.presto.models.RiakColumn;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.VarcharType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static com.basho.riak.presto.MetadataUtil.COLUMN_CODEC;
import java.io.IOException;
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/05/17.
*/
public class TestRiakColumnHandle {
@Test
public void testSerializtion2()
throws IOException
{
String connectorId = "fooo gooo";
RiakColumn column = new RiakColumn("p", BooleanType.BOOLEAN, "boom", true, false);
|
RiakColumnHandle c = new RiakColumnHandle(connectorId, column, 4);
|
kuenishi/presto-riak
|
src/test/java/com/basho/riak/presto/TestRiakColumnHandle.java
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumn.java
// public final class RiakColumn {
// private static final Logger log = Logger.get(RiakRecordSetProvider.class);
// private final String name;
// private final Type type;
// private final String comment;
// private boolean index;
// private boolean pkey = false;
//
// @JsonCreator
// public RiakColumn(
// @JsonProperty(value = "name", required = true) String name,
// @JsonProperty(value = "type", required = true) Type type,
// @JsonProperty(value = "comment") String comment,
// @JsonProperty(value = "index", required = false) boolean index,
// @JsonProperty(value = "pkey", required = false, defaultValue = "false") boolean pkey
// ) {
// checkArgument(!isNullOrEmpty(name), "name is null or is empty");
// checkNotNull(index);
// this.name = name;
// this.type = checkNotNull(type, "type is null");
// this.comment = comment;
// this.index = index;
// this.pkey = checkNotNull(pkey);
// }
//
// @JsonProperty
// public String getName() {
// return name;
// }
//
// @JsonProperty
// public Type getType() {
// return type;
// }
//
// @JsonProperty
// public String getComment() {
// return comment;
// }
//
// @JsonProperty
// public boolean getIndex() {
// return index;
// }
//
// public void setIndex(boolean b) {
// this.index = b;
// }
//
// @JsonProperty
// public boolean getPkey() {
// return pkey;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, type);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null || getClass() != obj.getClass()) {
// return false;
// }
//
// RiakColumn other = (RiakColumn) obj;
// return Objects.equal(this.name, other.name) &&
// (this.index == other.index) &&
// Objects.equal(this.type, other.type);
// }
//
// @Override
// public String toString() {
// return name + ":" + type + "(index=" + index + ")";
// }
// }
//
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<RiakColumnHandle> COLUMN_CODEC;
|
import com.basho.riak.presto.models.RiakColumn;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.VarcharType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static com.basho.riak.presto.MetadataUtil.COLUMN_CODEC;
import java.io.IOException;
|
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/05/17.
*/
public class TestRiakColumnHandle {
@Test
public void testSerializtion2()
throws IOException
{
String connectorId = "fooo gooo";
RiakColumn column = new RiakColumn("p", BooleanType.BOOLEAN, "boom", true, false);
RiakColumnHandle c = new RiakColumnHandle(connectorId, column, 4);
assert(c.getColumn().getType() == BooleanType.BOOLEAN);
|
// Path: src/main/java/com/basho/riak/presto/models/RiakColumn.java
// public final class RiakColumn {
// private static final Logger log = Logger.get(RiakRecordSetProvider.class);
// private final String name;
// private final Type type;
// private final String comment;
// private boolean index;
// private boolean pkey = false;
//
// @JsonCreator
// public RiakColumn(
// @JsonProperty(value = "name", required = true) String name,
// @JsonProperty(value = "type", required = true) Type type,
// @JsonProperty(value = "comment") String comment,
// @JsonProperty(value = "index", required = false) boolean index,
// @JsonProperty(value = "pkey", required = false, defaultValue = "false") boolean pkey
// ) {
// checkArgument(!isNullOrEmpty(name), "name is null or is empty");
// checkNotNull(index);
// this.name = name;
// this.type = checkNotNull(type, "type is null");
// this.comment = comment;
// this.index = index;
// this.pkey = checkNotNull(pkey);
// }
//
// @JsonProperty
// public String getName() {
// return name;
// }
//
// @JsonProperty
// public Type getType() {
// return type;
// }
//
// @JsonProperty
// public String getComment() {
// return comment;
// }
//
// @JsonProperty
// public boolean getIndex() {
// return index;
// }
//
// public void setIndex(boolean b) {
// this.index = b;
// }
//
// @JsonProperty
// public boolean getPkey() {
// return pkey;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, type);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null || getClass() != obj.getClass()) {
// return false;
// }
//
// RiakColumn other = (RiakColumn) obj;
// return Objects.equal(this.name, other.name) &&
// (this.index == other.index) &&
// Objects.equal(this.type, other.type);
// }
//
// @Override
// public String toString() {
// return name + ":" + type + "(index=" + index + ")";
// }
// }
//
// Path: src/main/java/com/basho/riak/presto/models/RiakColumnHandle.java
// public final class RiakColumnHandle
// implements ColumnHandle {
// public static final String PKEY_COLUMN_NAME = "__key";
// public static final String VTAG_COLUMN_NAME = "__vtag";
//
// private static final Logger log = Logger.get(RiakColumnHandle.class);
// private final String connectorId;
// private final RiakColumn column;
// private final int ordinalPosition;
//
// @JsonCreator
// public RiakColumnHandle(
// @JsonProperty(value = "connectorId", required = true) String connectorId,
// @JsonProperty(value = "column", required = true) RiakColumn column,
// @JsonProperty("ordinalPosition") int ordinalPosition) {
// this.connectorId = checkNotNull(connectorId, "connectorId is null");
// this.column = checkNotNull(column, "column is null");
// this.ordinalPosition = ordinalPosition;
// }
//
// @JsonProperty
// public String getConnectorId() {
// return connectorId;
// }
//
// @JsonProperty
// public RiakColumn getColumn() {
// return column;
// }
//
// @JsonProperty
// public int getOrdinalPosition() {
// return ordinalPosition;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(connectorId, column);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if ((obj == null) || (getClass() != obj.getClass())) {
// return false;
// }
//
// RiakColumnHandle other = (RiakColumnHandle) obj;
// return Objects.equal(this.connectorId, other.connectorId) &&
// this.column.equals(other.column) &&
// this.ordinalPosition == other.ordinalPosition;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("connectorId", connectorId)
// .add("column", column)
// .add("ordinalPosition", ordinalPosition)
// .toString();
// }
//
// public boolean matchAndBothHasIndex(RiakColumnHandle rhs)
// {
// return getColumn().getName().equals(rhs.getColumn().getName())
// && getColumn().getType().equals(rhs.getColumn().getType())
// && getColumn().getIndex()
// && rhs.getColumn().getIndex();
// }
// }
//
// Path: src/test/java/com/basho/riak/presto/MetadataUtil.java
// public static final JsonCodec<RiakColumnHandle> COLUMN_CODEC;
// Path: src/test/java/com/basho/riak/presto/TestRiakColumnHandle.java
import com.basho.riak.presto.models.RiakColumn;
import com.basho.riak.presto.models.RiakColumnHandle;
import com.facebook.presto.spi.type.BooleanType;
import com.facebook.presto.spi.type.VarcharType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static com.basho.riak.presto.MetadataUtil.COLUMN_CODEC;
import java.io.IOException;
package com.basho.riak.presto;
/**
* Created by kuenishi on 14/05/17.
*/
public class TestRiakColumnHandle {
@Test
public void testSerializtion2()
throws IOException
{
String connectorId = "fooo gooo";
RiakColumn column = new RiakColumn("p", BooleanType.BOOLEAN, "boom", true, false);
RiakColumnHandle c = new RiakColumnHandle(connectorId, column, 4);
assert(c.getColumn().getType() == BooleanType.BOOLEAN);
|
String s = COLUMN_CODEC.toJson(c);
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/SignalZAPEventJob.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventType.java
// public enum ZAPEventType {
// SERVER_STARTED,
// SERVER_STARTUP_COMPLETE,
// SERVER_STOP_REQUESTED,
// SERVER_STOPPED,
// SCAN_SPIDER_STARTED,
// SCAN_ASCAN_STARTED,
// SCAN_PROGRESS,
// SCAN_COMPLETE,
// SCAN_CANCEL_STARTED,
// SCAN_CANCEL_COMPLETE,
// CONFIGURATION_CHANGED;
// }
|
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.UIJob;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventType;
|
package com.polyhedral.security.testing.zedattackproxy.actions.jobs;
/**
* Eclipse {@link UIJob} used to signal a ZAP event has happened in the plugin.
* This event includes possible updates to the ZAP view action buttons and ZAP
* view content.
*/
public class SignalZAPEventJob extends UIJob {
private ZAPEventType event;
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventType.java
// public enum ZAPEventType {
// SERVER_STARTED,
// SERVER_STARTUP_COMPLETE,
// SERVER_STOP_REQUESTED,
// SERVER_STOPPED,
// SCAN_SPIDER_STARTED,
// SCAN_ASCAN_STARTED,
// SCAN_PROGRESS,
// SCAN_COMPLETE,
// SCAN_CANCEL_STARTED,
// SCAN_CANCEL_COMPLETE,
// CONFIGURATION_CHANGED;
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/SignalZAPEventJob.java
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.UIJob;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventType;
package com.polyhedral.security.testing.zedattackproxy.actions.jobs;
/**
* Eclipse {@link UIJob} used to signal a ZAP event has happened in the plugin.
* This event includes possible updates to the ZAP view action buttons and ZAP
* view content.
*/
public class SignalZAPEventJob extends UIJob {
private ZAPEventType event;
|
private ZAPEventHandler eventHandler;
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/CancelZAPScanAction.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/cancel/RunCancelZAPScanJob.java
// public class RunCancelZAPScanJob extends Job {
//
// private Display display;
// private ZAPEventHandler eventHandler;
//
// /**
// * Default constructor.
// *
// * @param name
// * The name to be displayed in the Eclipse progress view while
// * this is executing.
// * @param display
// * The {@link Display} where this will trigger signal events.
// * @param eventHandler
// * The event handler needed for signal events.
// */
// public RunCancelZAPScanJob(String name, Display display, ZAPEventHandler eventHandler) {
// super(name);
// this.display = display;
// this.eventHandler = eventHandler;
// }
//
// /**
// * Execution of the cancel ZAP scan job.
// */
// @Override
// protected IStatus run(IProgressMonitor monitor) {
// // Signal that the cancel ZAP scan action is starting.
// Job signalCancelJob = new SignalZAPEventJob(display, "Signal Scan Cancel", ZAPEventType.SCAN_CANCEL_STARTED,
// eventHandler);
// signalCancelJob.setPriority(Job.INTERACTIVE);
// signalCancelJob.schedule();
//
// // Cancel the current ZAP scan.
// Job cancelZapScanJob = new CancelZAPScanJob("Cancelling ZAP Scan...");
// cancelZapScanJob.setPriority(Job.LONG);
// cancelZapScanJob.schedule();
// while (cancelZapScanJob.getResult() == null) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ConsolePlugin.log(e);
// }
// }
//
// // Signal that the cancel ZAP scan action is complete.
// Job signalCancelCompleteJob = new SignalZAPEventJob(display, "Signal Scan Cancel Complete",
// ZAPEventType.SCAN_CANCEL_COMPLETE, eventHandler);
// signalCancelCompleteJob.setPriority(Job.INTERACTIVE);
// signalCancelCompleteJob.schedule();
//
// return Status.OK_STATUS;
// }
// }
|
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import com.polyhedral.security.testing.zedattackproxy.actions.jobs.cancel.RunCancelZAPScanJob;
|
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Eclipse {@link Action} for canceling a running ZAP scan.
*/
public class CancelZAPScanAction extends ZAPAction {
/**
* Default constructor. Set the enabled/disabled icons for the action and
* the tool tip text.
*/
public CancelZAPScanAction() {
try {
this.setImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/enabled/cancel_scan.gif")));
this.setDisabledImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/disabled/cancel_scan.gif")));
this.setToolTipText("Cancel ZAP Spider/Ascan");
} catch (MalformedURLException e) {
ConsolePlugin.log(e);
}
}
/**
* {@link Job} to be performed when this action is clicked on.
*/
@Override
public void run() {
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/cancel/RunCancelZAPScanJob.java
// public class RunCancelZAPScanJob extends Job {
//
// private Display display;
// private ZAPEventHandler eventHandler;
//
// /**
// * Default constructor.
// *
// * @param name
// * The name to be displayed in the Eclipse progress view while
// * this is executing.
// * @param display
// * The {@link Display} where this will trigger signal events.
// * @param eventHandler
// * The event handler needed for signal events.
// */
// public RunCancelZAPScanJob(String name, Display display, ZAPEventHandler eventHandler) {
// super(name);
// this.display = display;
// this.eventHandler = eventHandler;
// }
//
// /**
// * Execution of the cancel ZAP scan job.
// */
// @Override
// protected IStatus run(IProgressMonitor monitor) {
// // Signal that the cancel ZAP scan action is starting.
// Job signalCancelJob = new SignalZAPEventJob(display, "Signal Scan Cancel", ZAPEventType.SCAN_CANCEL_STARTED,
// eventHandler);
// signalCancelJob.setPriority(Job.INTERACTIVE);
// signalCancelJob.schedule();
//
// // Cancel the current ZAP scan.
// Job cancelZapScanJob = new CancelZAPScanJob("Cancelling ZAP Scan...");
// cancelZapScanJob.setPriority(Job.LONG);
// cancelZapScanJob.schedule();
// while (cancelZapScanJob.getResult() == null) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ConsolePlugin.log(e);
// }
// }
//
// // Signal that the cancel ZAP scan action is complete.
// Job signalCancelCompleteJob = new SignalZAPEventJob(display, "Signal Scan Cancel Complete",
// ZAPEventType.SCAN_CANCEL_COMPLETE, eventHandler);
// signalCancelCompleteJob.setPriority(Job.INTERACTIVE);
// signalCancelCompleteJob.schedule();
//
// return Status.OK_STATUS;
// }
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/CancelZAPScanAction.java
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import com.polyhedral.security.testing.zedattackproxy.actions.jobs.cancel.RunCancelZAPScanJob;
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Eclipse {@link Action} for canceling a running ZAP scan.
*/
public class CancelZAPScanAction extends ZAPAction {
/**
* Default constructor. Set the enabled/disabled icons for the action and
* the tool tip text.
*/
public CancelZAPScanAction() {
try {
this.setImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/enabled/cancel_scan.gif")));
this.setDisabledImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/disabled/cancel_scan.gif")));
this.setToolTipText("Cancel ZAP Spider/Ascan");
} catch (MalformedURLException e) {
ConsolePlugin.log(e);
}
}
/**
* {@link Job} to be performed when this action is clicked on.
*/
@Override
public void run() {
|
Job tempJob = new RunCancelZAPScanJob("Cancelling ZAP Scan...", PlatformUI.getWorkbench().getDisplay(),
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/StartZAPAction.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/start/RunStartZAPJob.java
// public class RunStartZAPJob extends Job {
//
// private Display display;
// private ZAPEventHandler eventHandler;
//
// /**
// * Default constructor.
// *
// * @param name
// * The name to be displayed in the Eclipse progress view while
// * this is executing.
// * @param display
// * the {@link Display} where this will trigger signal events.
// * @param eventHandler
// * The event handler needed for signal events.
// */
// public RunStartZAPJob(String name, Display display, ZAPEventHandler eventHandler) {
// super(name);
// this.display = display;
// this.eventHandler = eventHandler;
// }
//
// /**
// * Execution of the start ZAP job.
// */
// @Override
// protected IStatus run(IProgressMonitor monitor) {
// // Signal that the ZAP start action is starting.
// Job signalZAPStartJob = new SignalZAPEventJob(display, "Signal ZAP Start...", ZAPEventType.SERVER_STARTED,
// eventHandler);
// signalZAPStartJob.setPriority(Job.INTERACTIVE);
// signalZAPStartJob.schedule();
//
// // Run the start ZAP job.
// Job startZAPJob = new StartZAPJob("Running ZAP Start Job...");
// startZAPJob.setPriority(Job.LONG);
// startZAPJob.schedule();
// while (startZAPJob.getResult() == null) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ConsolePlugin.log(e);
// }
// }
//
// // Signal that the ZAp start action is complete.
// Job signalZAPStartCompleteJob = new SignalZAPEventJob(display, "ZAP Start Complete",
// ZAPEventType.SERVER_STARTUP_COMPLETE, eventHandler);
// signalZAPStartCompleteJob.setPriority(Job.INTERACTIVE);
// signalZAPStartCompleteJob.schedule();
//
// return Status.OK_STATUS;
// }
// }
|
import java.net.URL;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import com.polyhedral.security.testing.zedattackproxy.actions.jobs.start.RunStartZAPJob;
|
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Eclipse {@link Action} for starting the ZAP server.
*/
public class StartZAPAction extends ZAPAction {
/**
* Default constructor. Set the enabled/disabled icons for the action and
* the tool tip text.
*/
public StartZAPAction() {
try {
this.setImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/enabled/start.gif")));
this.setDisabledImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/disabled/start.gif")));
this.setToolTipText("Start ZAP Server");
} catch (Exception e) {
ConsolePlugin.log(e);
}
}
/**
* {@link Job} to be performed when this action is clicked on.
*/
@Override
public void run() {
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/start/RunStartZAPJob.java
// public class RunStartZAPJob extends Job {
//
// private Display display;
// private ZAPEventHandler eventHandler;
//
// /**
// * Default constructor.
// *
// * @param name
// * The name to be displayed in the Eclipse progress view while
// * this is executing.
// * @param display
// * the {@link Display} where this will trigger signal events.
// * @param eventHandler
// * The event handler needed for signal events.
// */
// public RunStartZAPJob(String name, Display display, ZAPEventHandler eventHandler) {
// super(name);
// this.display = display;
// this.eventHandler = eventHandler;
// }
//
// /**
// * Execution of the start ZAP job.
// */
// @Override
// protected IStatus run(IProgressMonitor monitor) {
// // Signal that the ZAP start action is starting.
// Job signalZAPStartJob = new SignalZAPEventJob(display, "Signal ZAP Start...", ZAPEventType.SERVER_STARTED,
// eventHandler);
// signalZAPStartJob.setPriority(Job.INTERACTIVE);
// signalZAPStartJob.schedule();
//
// // Run the start ZAP job.
// Job startZAPJob = new StartZAPJob("Running ZAP Start Job...");
// startZAPJob.setPriority(Job.LONG);
// startZAPJob.schedule();
// while (startZAPJob.getResult() == null) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ConsolePlugin.log(e);
// }
// }
//
// // Signal that the ZAp start action is complete.
// Job signalZAPStartCompleteJob = new SignalZAPEventJob(display, "ZAP Start Complete",
// ZAPEventType.SERVER_STARTUP_COMPLETE, eventHandler);
// signalZAPStartCompleteJob.setPriority(Job.INTERACTIVE);
// signalZAPStartCompleteJob.schedule();
//
// return Status.OK_STATUS;
// }
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/StartZAPAction.java
import java.net.URL;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import com.polyhedral.security.testing.zedattackproxy.actions.jobs.start.RunStartZAPJob;
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Eclipse {@link Action} for starting the ZAP server.
*/
public class StartZAPAction extends ZAPAction {
/**
* Default constructor. Set the enabled/disabled icons for the action and
* the tool tip text.
*/
public StartZAPAction() {
try {
this.setImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/enabled/start.gif")));
this.setDisabledImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/disabled/start.gif")));
this.setToolTipText("Start ZAP Server");
} catch (Exception e) {
ConsolePlugin.log(e);
}
}
/**
* {@link Job} to be performed when this action is clicked on.
*/
@Override
public void run() {
|
Job runStartZAPJob = new RunStartZAPJob("Starting Zed Attack Proxy...", PlatformUI.getWorkbench().getDisplay(),
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ZAPAction.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/IZAPEventHandler.java
// public interface IZAPEventHandler {
// public void addZAPEventListener(final IZAPEventListener listener);
//
// public void removeZAPEventListener(final IZAPEventListener listener);
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/IZAPEventListener.java
// public interface IZAPEventListener extends EventListener {
// public void handleZAPEvent(ZAPEventType eventType, ScanProgress scanProgress);
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
|
import org.eclipse.jface.action.Action;
import com.polyhedral.security.testing.zedattackproxy.events.IZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.IZAPEventListener;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
|
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Base class for all ZAP actions. Includes support for the
* {@link IZAPEventHandler} interface.
*/
public abstract class ZAPAction extends Action implements IZAPEventHandler {
private ZAPEventHandler zapEventHandler = new ZAPEventHandler();
/**
* Add a new ZAP event listener.
*/
@Override
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/IZAPEventHandler.java
// public interface IZAPEventHandler {
// public void addZAPEventListener(final IZAPEventListener listener);
//
// public void removeZAPEventListener(final IZAPEventListener listener);
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/IZAPEventListener.java
// public interface IZAPEventListener extends EventListener {
// public void handleZAPEvent(ZAPEventType eventType, ScanProgress scanProgress);
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ZAPAction.java
import org.eclipse.jface.action.Action;
import com.polyhedral.security.testing.zedattackproxy.events.IZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.IZAPEventListener;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Base class for all ZAP actions. Includes support for the
* {@link IZAPEventHandler} interface.
*/
public abstract class ZAPAction extends Action implements IZAPEventHandler {
private ZAPEventHandler zapEventHandler = new ZAPEventHandler();
/**
* Add a new ZAP event listener.
*/
@Override
|
public void addZAPEventListener(IZAPEventListener listener) {
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/runscan/ZAPScanProgressJob.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ScanProgress.java
// public class ScanProgress {
// private String ascanId;
// private String spiderId;
//
// public String getAscanId() {
// return ascanId;
// }
//
// public String getSpiderId() {
// return spiderId;
// }
//
// public void setAscanId(String ascanId) {
// this.ascanId = ascanId;
// }
//
// public void setSpiderId(String spiderId) {
// this.spiderId = spiderId;
// }
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventType.java
// public enum ZAPEventType {
// SERVER_STARTED,
// SERVER_STARTUP_COMPLETE,
// SERVER_STOP_REQUESTED,
// SERVER_STOPPED,
// SCAN_SPIDER_STARTED,
// SCAN_ASCAN_STARTED,
// SCAN_PROGRESS,
// SCAN_COMPLETE,
// SCAN_CANCEL_STARTED,
// SCAN_CANCEL_COMPLETE,
// CONFIGURATION_CHANGED;
// }
|
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.UIJob;
import com.polyhedral.security.testing.zedattackproxy.actions.ScanProgress;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventType;
|
package com.polyhedral.security.testing.zedattackproxy.actions.jobs.runscan;
/**
* Eclipse {@link UIJob} for displaying the progress of a ZAP ascan in the ZAP
* view.
*/
public class ZAPScanProgressJob extends UIJob {
private ScanProgress scanProgress;
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ScanProgress.java
// public class ScanProgress {
// private String ascanId;
// private String spiderId;
//
// public String getAscanId() {
// return ascanId;
// }
//
// public String getSpiderId() {
// return spiderId;
// }
//
// public void setAscanId(String ascanId) {
// this.ascanId = ascanId;
// }
//
// public void setSpiderId(String spiderId) {
// this.spiderId = spiderId;
// }
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventType.java
// public enum ZAPEventType {
// SERVER_STARTED,
// SERVER_STARTUP_COMPLETE,
// SERVER_STOP_REQUESTED,
// SERVER_STOPPED,
// SCAN_SPIDER_STARTED,
// SCAN_ASCAN_STARTED,
// SCAN_PROGRESS,
// SCAN_COMPLETE,
// SCAN_CANCEL_STARTED,
// SCAN_CANCEL_COMPLETE,
// CONFIGURATION_CHANGED;
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/runscan/ZAPScanProgressJob.java
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.UIJob;
import com.polyhedral.security.testing.zedattackproxy.actions.ScanProgress;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventType;
package com.polyhedral.security.testing.zedattackproxy.actions.jobs.runscan;
/**
* Eclipse {@link UIJob} for displaying the progress of a ZAP ascan in the ZAP
* view.
*/
public class ZAPScanProgressJob extends UIJob {
private ScanProgress scanProgress;
|
private ZAPEventHandler eventHandler;
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/runscan/ZAPScanProgressJob.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ScanProgress.java
// public class ScanProgress {
// private String ascanId;
// private String spiderId;
//
// public String getAscanId() {
// return ascanId;
// }
//
// public String getSpiderId() {
// return spiderId;
// }
//
// public void setAscanId(String ascanId) {
// this.ascanId = ascanId;
// }
//
// public void setSpiderId(String spiderId) {
// this.spiderId = spiderId;
// }
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventType.java
// public enum ZAPEventType {
// SERVER_STARTED,
// SERVER_STARTUP_COMPLETE,
// SERVER_STOP_REQUESTED,
// SERVER_STOPPED,
// SCAN_SPIDER_STARTED,
// SCAN_ASCAN_STARTED,
// SCAN_PROGRESS,
// SCAN_COMPLETE,
// SCAN_CANCEL_STARTED,
// SCAN_CANCEL_COMPLETE,
// CONFIGURATION_CHANGED;
// }
|
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.UIJob;
import com.polyhedral.security.testing.zedattackproxy.actions.ScanProgress;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventType;
|
package com.polyhedral.security.testing.zedattackproxy.actions.jobs.runscan;
/**
* Eclipse {@link UIJob} for displaying the progress of a ZAP ascan in the ZAP
* view.
*/
public class ZAPScanProgressJob extends UIJob {
private ScanProgress scanProgress;
private ZAPEventHandler eventHandler;
/**
* Default constructor.
*
* @param jobDisplay
* The {@link Display} for the UI action.
* @param name
* The name to be displayed in the Eclipse progress view while
* this is executing.
* @param scanProgress
* The progress information to be reported.
* @param eventHandler
* The event handler to handle a progress indicator.
*/
public ZAPScanProgressJob(Display jobDisplay, String name, ScanProgress scanProgress,
ZAPEventHandler eventHandler) {
super(jobDisplay, name);
this.scanProgress = scanProgress;
this.eventHandler = eventHandler;
}
/**
* Execution of the ZAP ascan progress job.
*/
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ScanProgress.java
// public class ScanProgress {
// private String ascanId;
// private String spiderId;
//
// public String getAscanId() {
// return ascanId;
// }
//
// public String getSpiderId() {
// return spiderId;
// }
//
// public void setAscanId(String ascanId) {
// this.ascanId = ascanId;
// }
//
// public void setSpiderId(String spiderId) {
// this.spiderId = spiderId;
// }
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
// public class ZAPEventHandler implements IZAPEventHandler {
// private ListenerList actionList = new ListenerList();
//
// /**
// * Add a ZAP event listener.
// */
// public void addZAPEventListener(final IZAPEventListener listener) {
// actionList.add(listener);
// }
//
// /**
// * Fire a new ZAP event.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// */
// public void fireZAPEvent(final ZAPEventType eventType) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
// }
// }
//
// /**
// * Fire a new ZAP event. This event is part of a ZAP scan and includes
// * {@link ScanProgress} information.
// *
// * @param eventType
// * The {@link ZAPEventType} event that was triggered.
// * @param scanProgress
// * The {@link ScanProgress} details to be reported with the
// * event.
// */
// public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
// final Object[] list = actionList.getListeners();
// for (int i = 0; i < list.length; ++i) {
// ((IZAPEventListener) list[i]).handleZAPEvent(eventType, scanProgress);
// }
// }
//
// /**
// * Remove a ZAP event listener.
// */
// public void removeZAPEventListener(final IZAPEventListener listener) {
// actionList.remove(listener);
// }
//
// }
//
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventType.java
// public enum ZAPEventType {
// SERVER_STARTED,
// SERVER_STARTUP_COMPLETE,
// SERVER_STOP_REQUESTED,
// SERVER_STOPPED,
// SCAN_SPIDER_STARTED,
// SCAN_ASCAN_STARTED,
// SCAN_PROGRESS,
// SCAN_COMPLETE,
// SCAN_CANCEL_STARTED,
// SCAN_CANCEL_COMPLETE,
// CONFIGURATION_CHANGED;
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/runscan/ZAPScanProgressJob.java
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.UIJob;
import com.polyhedral.security.testing.zedattackproxy.actions.ScanProgress;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventHandler;
import com.polyhedral.security.testing.zedattackproxy.events.ZAPEventType;
package com.polyhedral.security.testing.zedattackproxy.actions.jobs.runscan;
/**
* Eclipse {@link UIJob} for displaying the progress of a ZAP ascan in the ZAP
* view.
*/
public class ZAPScanProgressJob extends UIJob {
private ScanProgress scanProgress;
private ZAPEventHandler eventHandler;
/**
* Default constructor.
*
* @param jobDisplay
* The {@link Display} for the UI action.
* @param name
* The name to be displayed in the Eclipse progress view while
* this is executing.
* @param scanProgress
* The progress information to be reported.
* @param eventHandler
* The event handler to handle a progress indicator.
*/
public ZAPScanProgressJob(Display jobDisplay, String name, ScanProgress scanProgress,
ZAPEventHandler eventHandler) {
super(jobDisplay, name);
this.scanProgress = scanProgress;
this.eventHandler = eventHandler;
}
/**
* Execution of the ZAP ascan progress job.
*/
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
|
eventHandler.fireZAPEvent(ZAPEventType.SCAN_PROGRESS, scanProgress);
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/StopZAPAction.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/stop/RunZAPStopJob.java
// public class RunZAPStopJob extends Job {
//
// private Display display;
// private ZAPEventHandler eventHandler;
//
// /**
// * Default constructor.
// *
// * @param name
// * The name to be displayed in the Eclipse progress view while
// * this is executing.
// * @param display
// * The {@link Display} where this will trigger signal events.
// * @param eventHandler
// * The event handler needed for signal events.
// */
// public RunZAPStopJob(String name, Display display, ZAPEventHandler eventHandler) {
// super(name);
// this.display = display;
// this.eventHandler = eventHandler;
// }
//
// /**
// * Execution of the stop ZAP job.
// */
// @Override
// protected IStatus run(IProgressMonitor monitor) {
// // Signal that the ZAP stop action is starting.
// Job signalZAPStopJob = new SignalZAPEventJob(display, "Signal ZAP Stop...", ZAPEventType.SERVER_STOP_REQUESTED,
// eventHandler);
// signalZAPStopJob.setPriority(Job.INTERACTIVE);
// signalZAPStopJob.schedule();
//
// // Run the stop ZAP job.
// Job stopZAPJob = new StopZAPJob("Running ZAP Stop Job...");
// stopZAPJob.setPriority(Job.LONG);
// stopZAPJob.schedule();
// while (stopZAPJob.getResult() == null) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ConsolePlugin.log(e);
// }
// }
//
// // Signal that the ZAP stop action is complete.
// Job signalZAPStopCompleteJob = new SignalZAPEventJob(display, "ZAP Stop Complete", ZAPEventType.SERVER_STOPPED,
// eventHandler);
// signalZAPStopCompleteJob.setPriority(Job.INTERACTIVE);
// signalZAPStopCompleteJob.schedule();
//
// return Status.OK_STATUS;
// }
// }
|
import java.net.URL;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import com.polyhedral.security.testing.zedattackproxy.actions.jobs.stop.RunZAPStopJob;
|
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Eclipse {@link Action} for stopping the ZAP server.
*/
public class StopZAPAction extends ZAPAction {
/**
* Default constructor. Set the enabled/disabled icons for the action and
* the tool tip text.
*/
public StopZAPAction() {
try {
this.setImageDescriptor(ImageDescriptor.createFromURL(
new URL("platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/enabled/stop.gif")));
this.setDisabledImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/disabled/stop.gif")));
this.setToolTipText("Stop ZAP Server");
} catch (Exception e) {
ConsolePlugin.log(e);
}
}
/**
* {@link Job} to be performed when this action is clicked on.
*/
@Override
public void run() {
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/stop/RunZAPStopJob.java
// public class RunZAPStopJob extends Job {
//
// private Display display;
// private ZAPEventHandler eventHandler;
//
// /**
// * Default constructor.
// *
// * @param name
// * The name to be displayed in the Eclipse progress view while
// * this is executing.
// * @param display
// * The {@link Display} where this will trigger signal events.
// * @param eventHandler
// * The event handler needed for signal events.
// */
// public RunZAPStopJob(String name, Display display, ZAPEventHandler eventHandler) {
// super(name);
// this.display = display;
// this.eventHandler = eventHandler;
// }
//
// /**
// * Execution of the stop ZAP job.
// */
// @Override
// protected IStatus run(IProgressMonitor monitor) {
// // Signal that the ZAP stop action is starting.
// Job signalZAPStopJob = new SignalZAPEventJob(display, "Signal ZAP Stop...", ZAPEventType.SERVER_STOP_REQUESTED,
// eventHandler);
// signalZAPStopJob.setPriority(Job.INTERACTIVE);
// signalZAPStopJob.schedule();
//
// // Run the stop ZAP job.
// Job stopZAPJob = new StopZAPJob("Running ZAP Stop Job...");
// stopZAPJob.setPriority(Job.LONG);
// stopZAPJob.schedule();
// while (stopZAPJob.getResult() == null) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ConsolePlugin.log(e);
// }
// }
//
// // Signal that the ZAP stop action is complete.
// Job signalZAPStopCompleteJob = new SignalZAPEventJob(display, "ZAP Stop Complete", ZAPEventType.SERVER_STOPPED,
// eventHandler);
// signalZAPStopCompleteJob.setPriority(Job.INTERACTIVE);
// signalZAPStopCompleteJob.schedule();
//
// return Status.OK_STATUS;
// }
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/StopZAPAction.java
import java.net.URL;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import com.polyhedral.security.testing.zedattackproxy.actions.jobs.stop.RunZAPStopJob;
package com.polyhedral.security.testing.zedattackproxy.actions;
/**
* Eclipse {@link Action} for stopping the ZAP server.
*/
public class StopZAPAction extends ZAPAction {
/**
* Default constructor. Set the enabled/disabled icons for the action and
* the tool tip text.
*/
public StopZAPAction() {
try {
this.setImageDescriptor(ImageDescriptor.createFromURL(
new URL("platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/enabled/stop.gif")));
this.setDisabledImageDescriptor(ImageDescriptor.createFromURL(new URL(
"platform:/plugin/com.polyhedral.security.testing.zedattackproxy/icons/disabled/stop.gif")));
this.setToolTipText("Stop ZAP Server");
} catch (Exception e) {
ConsolePlugin.log(e);
}
}
/**
* {@link Job} to be performed when this action is clicked on.
*/
@Override
public void run() {
|
Job runZapStopJob = new RunZAPStopJob("Stopping Zed Attack Proxy...", PlatformUI.getWorkbench().getDisplay(),
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/runscan/ScanTarget.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/views/ZAPPolicyEditor.java
// public class ZAPPolicyEditor {
//
// private Composite parent;
// private ApiResponseSet policyItem;
// private Combo attackStrengthCombo;
// private Combo alertThresholdCombo;
//
// /**
// * Generate the view fragment from the provided ZAP {@link ApiResponseSet}.
// *
// * @param parent
// * @param policyItem
// */
// public ZAPPolicyEditor(Composite parent, ApiResponseSet policyItem) {
// this.parent = parent;
// this.policyItem = policyItem;
//
// generateUIContent();
// }
//
// /**
// * Initialize the view fragment.
// */
// private void generateUIContent() {
//
// // Set the policy name.
// Label policyLabel = new Label(parent, SWT.WRAP);
// GridData policyGrid = new GridData(SWT.FILL, SWT.FILL, false, true);
// policyGrid.widthHint = 75;
// policyLabel.setLayoutData(policyGrid);
// policyLabel.setText(policyItem.getAttribute("name"));
//
// // Set the attack strength. If one has not been specified in ZAP, select
// // DEFAULT.
// attackStrengthCombo = new Combo(parent, SWT.READ_ONLY);
// for (ZAPAttackStrength attackStrength : ZAPAttackStrength.values()) {
// attackStrengthCombo.add(attackStrength.getValue());
// }
// String policyAttackStrength = policyItem.getAttribute("attackStrength");
// if (StringUtils.isNotBlank(policyAttackStrength)) {
// attackStrengthCombo.select(ZAPAttackStrength.valueOf(policyAttackStrength).getRank());
// } else {
// attackStrengthCombo.select(ZAPAttackStrength.DEFAULT.getRank());
// }
//
// // Set the alert threshold. If one has not be specified in ZAP, select
// // DEFAULT.
// alertThresholdCombo = new Combo(parent, SWT.READ_ONLY);
// for (ZAPAlertThreshold alertThreshold : ZAPAlertThreshold.values()) {
// alertThresholdCombo.add(alertThreshold.getValue());
// }
// String policyAlertThreshold = policyItem.getAttribute("alertThreshold");
// if (StringUtils.isNotBlank(policyAlertThreshold)) {
// alertThresholdCombo.select(ZAPAlertThreshold.valueOf(policyAlertThreshold).getRank());
// } else {
// alertThresholdCombo.select(ZAPAlertThreshold.DEFAULT.getRank());
// }
// }
//
// /**
// * @return The ZAP policy ID {@link String}.
// */
// public String getPolicyId() {
// return policyItem.getAttribute("id");
// }
//
// /**
// * @return the currently selected attack strength {@link String}.
// */
// public String getSelectedAttackStrength() {
// return attackStrengthCombo.getText();
// }
//
// /**
// * @return The currently selected alert threshold {@link String}.
// */
// public String getSelectedAlertThreshold() {
// return alertThresholdCombo.getText();
// }
// }
|
import java.util.ArrayList;
import java.util.List;
import com.polyhedral.security.testing.zedattackproxy.views.ZAPPolicyEditor;
|
package com.polyhedral.security.testing.zedattackproxy.actions.jobs.runscan;
/**
* ZAP scan target information.
*/
public class ScanTarget {
private String fileName;
private String targetUrl;
private String reportFormat;
private List<ZAPPolicyInfo> zapPolicyList;
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/views/ZAPPolicyEditor.java
// public class ZAPPolicyEditor {
//
// private Composite parent;
// private ApiResponseSet policyItem;
// private Combo attackStrengthCombo;
// private Combo alertThresholdCombo;
//
// /**
// * Generate the view fragment from the provided ZAP {@link ApiResponseSet}.
// *
// * @param parent
// * @param policyItem
// */
// public ZAPPolicyEditor(Composite parent, ApiResponseSet policyItem) {
// this.parent = parent;
// this.policyItem = policyItem;
//
// generateUIContent();
// }
//
// /**
// * Initialize the view fragment.
// */
// private void generateUIContent() {
//
// // Set the policy name.
// Label policyLabel = new Label(parent, SWT.WRAP);
// GridData policyGrid = new GridData(SWT.FILL, SWT.FILL, false, true);
// policyGrid.widthHint = 75;
// policyLabel.setLayoutData(policyGrid);
// policyLabel.setText(policyItem.getAttribute("name"));
//
// // Set the attack strength. If one has not been specified in ZAP, select
// // DEFAULT.
// attackStrengthCombo = new Combo(parent, SWT.READ_ONLY);
// for (ZAPAttackStrength attackStrength : ZAPAttackStrength.values()) {
// attackStrengthCombo.add(attackStrength.getValue());
// }
// String policyAttackStrength = policyItem.getAttribute("attackStrength");
// if (StringUtils.isNotBlank(policyAttackStrength)) {
// attackStrengthCombo.select(ZAPAttackStrength.valueOf(policyAttackStrength).getRank());
// } else {
// attackStrengthCombo.select(ZAPAttackStrength.DEFAULT.getRank());
// }
//
// // Set the alert threshold. If one has not be specified in ZAP, select
// // DEFAULT.
// alertThresholdCombo = new Combo(parent, SWT.READ_ONLY);
// for (ZAPAlertThreshold alertThreshold : ZAPAlertThreshold.values()) {
// alertThresholdCombo.add(alertThreshold.getValue());
// }
// String policyAlertThreshold = policyItem.getAttribute("alertThreshold");
// if (StringUtils.isNotBlank(policyAlertThreshold)) {
// alertThresholdCombo.select(ZAPAlertThreshold.valueOf(policyAlertThreshold).getRank());
// } else {
// alertThresholdCombo.select(ZAPAlertThreshold.DEFAULT.getRank());
// }
// }
//
// /**
// * @return The ZAP policy ID {@link String}.
// */
// public String getPolicyId() {
// return policyItem.getAttribute("id");
// }
//
// /**
// * @return the currently selected attack strength {@link String}.
// */
// public String getSelectedAttackStrength() {
// return attackStrengthCombo.getText();
// }
//
// /**
// * @return The currently selected alert threshold {@link String}.
// */
// public String getSelectedAlertThreshold() {
// return alertThresholdCombo.getText();
// }
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/jobs/runscan/ScanTarget.java
import java.util.ArrayList;
import java.util.List;
import com.polyhedral.security.testing.zedattackproxy.views.ZAPPolicyEditor;
package com.polyhedral.security.testing.zedattackproxy.actions.jobs.runscan;
/**
* ZAP scan target information.
*/
public class ScanTarget {
private String fileName;
private String targetUrl;
private String reportFormat;
private List<ZAPPolicyInfo> zapPolicyList;
|
public ScanTarget(String fileName, String targetUrl, String reportFormat, List<ZAPPolicyEditor> zapPolicyList) {
|
polyhedraltech/SecurityTesting
|
com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ScanProgress.java
// public class ScanProgress {
// private String ascanId;
// private String spiderId;
//
// public String getAscanId() {
// return ascanId;
// }
//
// public String getSpiderId() {
// return spiderId;
// }
//
// public void setAscanId(String ascanId) {
// this.ascanId = ascanId;
// }
//
// public void setSpiderId(String spiderId) {
// this.spiderId = spiderId;
// }
// }
|
import org.eclipse.core.runtime.ListenerList;
import com.polyhedral.security.testing.zedattackproxy.actions.ScanProgress;
|
package com.polyhedral.security.testing.zedattackproxy.events;
/**
* ZAP event handler implementation. When a ZAP event is fired, this will notify
* all of the appropriate listeners.
*/
public class ZAPEventHandler implements IZAPEventHandler {
private ListenerList actionList = new ListenerList();
/**
* Add a ZAP event listener.
*/
public void addZAPEventListener(final IZAPEventListener listener) {
actionList.add(listener);
}
/**
* Fire a new ZAP event.
*
* @param eventType
* The {@link ZAPEventType} event that was triggered.
*/
public void fireZAPEvent(final ZAPEventType eventType) {
final Object[] list = actionList.getListeners();
for (int i = 0; i < list.length; ++i) {
((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
}
}
/**
* Fire a new ZAP event. This event is part of a ZAP scan and includes
* {@link ScanProgress} information.
*
* @param eventType
* The {@link ZAPEventType} event that was triggered.
* @param scanProgress
* The {@link ScanProgress} details to be reported with the
* event.
*/
|
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/actions/ScanProgress.java
// public class ScanProgress {
// private String ascanId;
// private String spiderId;
//
// public String getAscanId() {
// return ascanId;
// }
//
// public String getSpiderId() {
// return spiderId;
// }
//
// public void setAscanId(String ascanId) {
// this.ascanId = ascanId;
// }
//
// public void setSpiderId(String spiderId) {
// this.spiderId = spiderId;
// }
// }
// Path: com.polyhedral.security.testing.zedattackproxy/src/com/polyhedral/security/testing/zedattackproxy/events/ZAPEventHandler.java
import org.eclipse.core.runtime.ListenerList;
import com.polyhedral.security.testing.zedattackproxy.actions.ScanProgress;
package com.polyhedral.security.testing.zedattackproxy.events;
/**
* ZAP event handler implementation. When a ZAP event is fired, this will notify
* all of the appropriate listeners.
*/
public class ZAPEventHandler implements IZAPEventHandler {
private ListenerList actionList = new ListenerList();
/**
* Add a ZAP event listener.
*/
public void addZAPEventListener(final IZAPEventListener listener) {
actionList.add(listener);
}
/**
* Fire a new ZAP event.
*
* @param eventType
* The {@link ZAPEventType} event that was triggered.
*/
public void fireZAPEvent(final ZAPEventType eventType) {
final Object[] list = actionList.getListeners();
for (int i = 0; i < list.length; ++i) {
((IZAPEventListener) list[i]).handleZAPEvent(eventType, null);
}
}
/**
* Fire a new ZAP event. This event is part of a ZAP scan and includes
* {@link ScanProgress} information.
*
* @param eventType
* The {@link ZAPEventType} event that was triggered.
* @param scanProgress
* The {@link ScanProgress} details to be reported with the
* event.
*/
|
public void fireZAPEvent(final ZAPEventType eventType, ScanProgress scanProgress) {
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/answerformat/DecimalAnswerFormat.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
|
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.TextUtils;
|
package org.researchstack.backbone.answerformat;
/**
* This class defines the attributes for a decimal answer format that participants enter using a
* numeric keyboard.
* <p>
* If you specify maximum or minimum values and the user enters a value outside the specified range,
* the DecimalQuestionBody does not allow navigation until the participant provides a value that is
* within the valid range.
*/
public class DecimalAnswerFormat extends AnswerFormat {
private float minValue;
private float maxValue;
/**
* Creates an answer format with the specified min and max values
*
* @param minValue the minimum allowed value
* @param maxValue the maximum allowed value, or 0f for unlimited
*/
public DecimalAnswerFormat(float minValue, float maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public QuestionType getQuestionType() {
return Type.Decimal;
}
/**
* Returns the min value
*
* @return returns the min value
*/
public float getMinValue() {
return minValue;
}
/**
* Returns the max value, or 0f for no maximum
*
* @return returns the max value, or 0f for no maximum
*/
public float getMaxValue() {
return maxValue;
}
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/answerformat/DecimalAnswerFormat.java
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.TextUtils;
package org.researchstack.backbone.answerformat;
/**
* This class defines the attributes for a decimal answer format that participants enter using a
* numeric keyboard.
* <p>
* If you specify maximum or minimum values and the user enters a value outside the specified range,
* the DecimalQuestionBody does not allow navigation until the participant provides a value that is
* within the valid range.
*/
public class DecimalAnswerFormat extends AnswerFormat {
private float minValue;
private float maxValue;
/**
* Creates an answer format with the specified min and max values
*
* @param minValue the minimum allowed value
* @param maxValue the maximum allowed value, or 0f for unlimited
*/
public DecimalAnswerFormat(float minValue, float maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public QuestionType getQuestionType() {
return Type.Decimal;
}
/**
* Returns the min value
*
* @return returns the min value
*/
public float getMinValue() {
return minValue;
}
/**
* Returns the max value, or 0f for no maximum
*
* @return returns the max value, or 0f for no maximum
*/
public float getMaxValue() {
return maxValue;
}
|
public BodyAnswer validateAnswer(String inputString) {
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/answerformat/DecimalAnswerFormat.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
|
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.TextUtils;
|
package org.researchstack.backbone.answerformat;
/**
* This class defines the attributes for a decimal answer format that participants enter using a
* numeric keyboard.
* <p>
* If you specify maximum or minimum values and the user enters a value outside the specified range,
* the DecimalQuestionBody does not allow navigation until the participant provides a value that is
* within the valid range.
*/
public class DecimalAnswerFormat extends AnswerFormat {
private float minValue;
private float maxValue;
/**
* Creates an answer format with the specified min and max values
*
* @param minValue the minimum allowed value
* @param maxValue the maximum allowed value, or 0f for unlimited
*/
public DecimalAnswerFormat(float minValue, float maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public QuestionType getQuestionType() {
return Type.Decimal;
}
/**
* Returns the min value
*
* @return returns the min value
*/
public float getMinValue() {
return minValue;
}
/**
* Returns the max value, or 0f for no maximum
*
* @return returns the max value, or 0f for no maximum
*/
public float getMaxValue() {
return maxValue;
}
public BodyAnswer validateAnswer(String inputString) {
// If no answer is recorded
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/answerformat/DecimalAnswerFormat.java
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.TextUtils;
package org.researchstack.backbone.answerformat;
/**
* This class defines the attributes for a decimal answer format that participants enter using a
* numeric keyboard.
* <p>
* If you specify maximum or minimum values and the user enters a value outside the specified range,
* the DecimalQuestionBody does not allow navigation until the participant provides a value that is
* within the valid range.
*/
public class DecimalAnswerFormat extends AnswerFormat {
private float minValue;
private float maxValue;
/**
* Creates an answer format with the specified min and max values
*
* @param minValue the minimum allowed value
* @param maxValue the maximum allowed value, or 0f for unlimited
*/
public DecimalAnswerFormat(float minValue, float maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public QuestionType getQuestionType() {
return Type.Decimal;
}
/**
* Returns the min value
*
* @return returns the min value
*/
public float getMinValue() {
return minValue;
}
/**
* Returns the max value, or 0f for no maximum
*
* @return returns the max value, or 0f for no maximum
*/
public float getMaxValue() {
return maxValue;
}
public BodyAnswer validateAnswer(String inputString) {
// If no answer is recorded
|
if (inputString == null || TextUtils.isEmpty(inputString)) {
|
ResearchStack/ResearchStack
|
backbone/src/test/java/org/researchstack/backbone/task/OrderedTaskTest.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/step/Step.java
// public class Step implements Serializable {
// private String identifier;
//
// private Class stepLayoutClass;
//
// private int stepTitle;
//
// private boolean optional = true;
//
// private String title;
//
// private String text;
//
// // The following fields are in RK but not implemented in ResearchStack
// // These options can be developed as needed or removed if we find they are not necessary
// private boolean restorable;
// private Task task;
// private boolean shouldTintImages;
// private boolean showsProgress;
// private boolean allowsBackNavigation;
// private boolean useSurveyMode;
//
// /**
// * Returns a new step initialized with the specified identifier.
// *
// * @param identifier The unique identifier of the step.
// */
// public Step(String identifier) {
// this.identifier = identifier;
// }
//
// /**
// * Returns a new step initialized with the specified identifier and title.
// *
// * @param identifier The unique identifier of the step.
// * @param title The primary text to display for this step.
// */
// public Step(String identifier, String title) {
// this.identifier = identifier;
// this.title = title;
// }
//
// /**
// * A short string that uniquely identifies the step within the task.
// * <p>
// * The identifier is reproduced in the results of a step. In fact, the only way to link a result
// * (a {@link org.researchstack.backbone.result.StepResult} object) to the step that generated it
// * is to look at the value of <code>identifier</code>. To accurately identify step results, you
// * need to ensure that step identifiers are unique within each task.
// * <p>
// * In some cases, it can be useful to link the step identifier to a unique identifier in a
// * database; in other cases, it can make sense to make the identifier human readable.
// */
// public String getIdentifier() {
// return identifier;
// }
//
// /**
// * A boolean value indicating whether the user can skip the step without providing an answer.
// * <p>
// * The default value of this property is <code>true</code>. When the value is
// * <code>false</code>, the Skip button does not appear on this step.
// * <p>
// * This property may not be meaningful for all steps; for example, an active step might not
// * provide a way to skip, because it requires a timer to finish.
// *
// * @return a boolean indicating whether the step is skippable
// */
// public boolean isOptional() {
// return optional;
// }
//
// /**
// * Sets whether the step is skippable
// *
// * @param optional
// * @see #isOptional()
// */
// public void setOptional(boolean optional) {
// this.optional = optional;
// }
//
// /**
// * The primary text to display for the step in a localized string.
// * <p>
// * This text is also used as the label when a step is shown in the more compact version in a
// * {@link FormStep}.
// *
// * @return the primary text for the question
// */
// public String getTitle() {
// return title;
// }
//
// /**
// * Sets the primary text to display for the step in a localized string.
// *
// * @param title the primary text for the question.
// * @see #getTitle()
// */
// public void setTitle(String title) {
// this.title = title;
// }
//
// /**
// * Additional text to display for the step in a localized string.
// * <p>
// * The additional text is displayed in a smaller font below <code>title</code>. If you need to
// * display a long question, it can work well to keep the title short and put the additional
// * content in the <code>text</code> property.
// *
// * @return
// */
// public String getText() {
// return text;
// }
//
// /**
// * Sets the additional text for the step.
// *
// * @param text the detail text for the step
// * @see #getText()
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Gets the int id for the title to display in the action bar (optional).
// *
// * @return the id for the title to display in the action bar
// */
// public int getStepTitle() {
// return stepTitle;
// }
//
// /**
// * Gets the int id for the title to display in the action bar (optional).
// *
// * @param stepTitle the Android resource id for the title
// */
// public void setStepTitle(int stepTitle) {
// this.stepTitle = stepTitle;
// }
//
// /**
// * Returns the class that the {@link org.researchstack.backbone.ui.ViewTaskActivity} should
// * instantiate to display this step.
// * <p>
// * This method is used within the framework so that steps can define their step view controller
// * pairing.
// * <p>
// * Outside the framework, developers should instantiate the required view controller in their
// * ViewTaskActivity delegate to override the ViewTaskActivity's default.
// *
// * @return the class of the {@link org.researchstack.backbone.ui.step.layout.StepLayout} for
// * this step
// */
// public Class getStepLayoutClass() {
// return stepLayoutClass;
// }
//
// /**
// * Sets the class that should be used to display this step
// *
// * @param stepLayoutClass the {@link org.researchstack.backbone.ui.step.layout.StepLayout} class
// * to be used to display this step
// */
// public void setStepLayoutClass(Class stepLayoutClass) {
// this.stepLayoutClass = stepLayoutClass;
// }
// }
|
import org.junit.Before;
import org.junit.Test;
import org.researchstack.backbone.step.Step;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
|
package org.researchstack.backbone.task;
public class OrderedTaskTest {
OrderedTask testTask;
|
// Path: backbone/src/main/java/org/researchstack/backbone/step/Step.java
// public class Step implements Serializable {
// private String identifier;
//
// private Class stepLayoutClass;
//
// private int stepTitle;
//
// private boolean optional = true;
//
// private String title;
//
// private String text;
//
// // The following fields are in RK but not implemented in ResearchStack
// // These options can be developed as needed or removed if we find they are not necessary
// private boolean restorable;
// private Task task;
// private boolean shouldTintImages;
// private boolean showsProgress;
// private boolean allowsBackNavigation;
// private boolean useSurveyMode;
//
// /**
// * Returns a new step initialized with the specified identifier.
// *
// * @param identifier The unique identifier of the step.
// */
// public Step(String identifier) {
// this.identifier = identifier;
// }
//
// /**
// * Returns a new step initialized with the specified identifier and title.
// *
// * @param identifier The unique identifier of the step.
// * @param title The primary text to display for this step.
// */
// public Step(String identifier, String title) {
// this.identifier = identifier;
// this.title = title;
// }
//
// /**
// * A short string that uniquely identifies the step within the task.
// * <p>
// * The identifier is reproduced in the results of a step. In fact, the only way to link a result
// * (a {@link org.researchstack.backbone.result.StepResult} object) to the step that generated it
// * is to look at the value of <code>identifier</code>. To accurately identify step results, you
// * need to ensure that step identifiers are unique within each task.
// * <p>
// * In some cases, it can be useful to link the step identifier to a unique identifier in a
// * database; in other cases, it can make sense to make the identifier human readable.
// */
// public String getIdentifier() {
// return identifier;
// }
//
// /**
// * A boolean value indicating whether the user can skip the step without providing an answer.
// * <p>
// * The default value of this property is <code>true</code>. When the value is
// * <code>false</code>, the Skip button does not appear on this step.
// * <p>
// * This property may not be meaningful for all steps; for example, an active step might not
// * provide a way to skip, because it requires a timer to finish.
// *
// * @return a boolean indicating whether the step is skippable
// */
// public boolean isOptional() {
// return optional;
// }
//
// /**
// * Sets whether the step is skippable
// *
// * @param optional
// * @see #isOptional()
// */
// public void setOptional(boolean optional) {
// this.optional = optional;
// }
//
// /**
// * The primary text to display for the step in a localized string.
// * <p>
// * This text is also used as the label when a step is shown in the more compact version in a
// * {@link FormStep}.
// *
// * @return the primary text for the question
// */
// public String getTitle() {
// return title;
// }
//
// /**
// * Sets the primary text to display for the step in a localized string.
// *
// * @param title the primary text for the question.
// * @see #getTitle()
// */
// public void setTitle(String title) {
// this.title = title;
// }
//
// /**
// * Additional text to display for the step in a localized string.
// * <p>
// * The additional text is displayed in a smaller font below <code>title</code>. If you need to
// * display a long question, it can work well to keep the title short and put the additional
// * content in the <code>text</code> property.
// *
// * @return
// */
// public String getText() {
// return text;
// }
//
// /**
// * Sets the additional text for the step.
// *
// * @param text the detail text for the step
// * @see #getText()
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Gets the int id for the title to display in the action bar (optional).
// *
// * @return the id for the title to display in the action bar
// */
// public int getStepTitle() {
// return stepTitle;
// }
//
// /**
// * Gets the int id for the title to display in the action bar (optional).
// *
// * @param stepTitle the Android resource id for the title
// */
// public void setStepTitle(int stepTitle) {
// this.stepTitle = stepTitle;
// }
//
// /**
// * Returns the class that the {@link org.researchstack.backbone.ui.ViewTaskActivity} should
// * instantiate to display this step.
// * <p>
// * This method is used within the framework so that steps can define their step view controller
// * pairing.
// * <p>
// * Outside the framework, developers should instantiate the required view controller in their
// * ViewTaskActivity delegate to override the ViewTaskActivity's default.
// *
// * @return the class of the {@link org.researchstack.backbone.ui.step.layout.StepLayout} for
// * this step
// */
// public Class getStepLayoutClass() {
// return stepLayoutClass;
// }
//
// /**
// * Sets the class that should be used to display this step
// *
// * @param stepLayoutClass the {@link org.researchstack.backbone.ui.step.layout.StepLayout} class
// * to be used to display this step
// */
// public void setStepLayoutClass(Class stepLayoutClass) {
// this.stepLayoutClass = stepLayoutClass;
// }
// }
// Path: backbone/src/test/java/org/researchstack/backbone/task/OrderedTaskTest.java
import org.junit.Before;
import org.junit.Test;
import org.researchstack.backbone.step.Step;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
package org.researchstack.backbone.task;
public class OrderedTaskTest {
OrderedTask testTask;
|
private Step stepOne = new Step("idOne");
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/step/InstructionStep.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/layout/InstructionStepLayout.java
// public class InstructionStepLayout extends FixedSubmitBarLayout implements StepLayout {
// private StepCallbacks callbacks;
// private Step step;
//
// public InstructionStepLayout(Context context) {
// super(context);
// }
//
// public InstructionStepLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public InstructionStepLayout(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// public void initialize(Step step, StepResult result) {
// this.step = step;
// initializeStep();
// }
//
// @Override
// public View getLayout() {
// return this;
// }
//
// @Override
// public boolean isBackEventConsumed() {
// callbacks.onSaveStep(StepCallbacks.ACTION_PREV, step, null);
// return false;
// }
//
// @Override
// public void setCallbacks(StepCallbacks callbacks) {
// this.callbacks = callbacks;
// }
//
// @Override
// public int getContentResourceId() {
// return R.layout.rsb_step_layout_instruction;
// }
//
// private void initializeStep() {
// if (step != null) {
//
// // Set Title
// if (!TextUtils.isEmpty(step.getTitle())) {
// TextView title = (TextView) findViewById(R.id.rsb_intruction_title);
// title.setVisibility(View.VISIBLE);
// title.setText(step.getTitle());
// }
//
// // Set Summary
// if (!TextUtils.isEmpty(step.getText())) {
// TextView summary = (TextView) findViewById(R.id.rsb_intruction_text);
// summary.setVisibility(View.VISIBLE);
// summary.setText(Html.fromHtml(step.getText()));
// summary.setMovementMethod(new TextViewLinkHandler() {
// @Override
// public void onLinkClick(String url) {
// String path = ResourcePathManager.getInstance().
// generateAbsolutePath(ResourcePathManager.Resource.TYPE_HTML, url);
// Intent intent = ViewWebDocumentActivity.newIntentForPath(getContext(),
// step.getTitle(),
// path);
// getContext().startActivity(intent);
// }
// });
// }
//
// // Set Next / Skip
// SubmitBar submitBar = (SubmitBar) findViewById(R.id.rsb_submit_bar);
// submitBar.setPositiveTitle(R.string.rsb_next);
// submitBar.setPositiveAction(v -> callbacks.onSaveStep(StepCallbacks.ACTION_NEXT,
// step,
// null));
//
// if (step.isOptional()) {
// submitBar.setNegativeTitle(R.string.rsb_step_skip);
// submitBar.setNegativeAction(v -> {
// if (callbacks != null) {
// callbacks.onSaveStep(StepCallbacks.ACTION_NEXT, step, null);
// }
// });
// } else {
// submitBar.getNegativeActionView().setVisibility(View.GONE);
// }
// }
// }
// }
|
import org.researchstack.backbone.ui.step.layout.InstructionStepLayout;
|
package org.researchstack.backbone.step;
/**
* An InstructionStep object gives the participant instructions for a task.
* <p>
* You can use instruction steps to present various types of content during a task, such as
* introductory content, instructions in the middle of a task, or a final message at the completion
* of a task.
*/
public class InstructionStep extends Step {
public InstructionStep(String identifier, String title, String detailText) {
super(identifier, title);
setText(detailText);
setOptional(false);
}
@Override
public Class getStepLayoutClass() {
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/layout/InstructionStepLayout.java
// public class InstructionStepLayout extends FixedSubmitBarLayout implements StepLayout {
// private StepCallbacks callbacks;
// private Step step;
//
// public InstructionStepLayout(Context context) {
// super(context);
// }
//
// public InstructionStepLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public InstructionStepLayout(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
//
// @Override
// public void initialize(Step step, StepResult result) {
// this.step = step;
// initializeStep();
// }
//
// @Override
// public View getLayout() {
// return this;
// }
//
// @Override
// public boolean isBackEventConsumed() {
// callbacks.onSaveStep(StepCallbacks.ACTION_PREV, step, null);
// return false;
// }
//
// @Override
// public void setCallbacks(StepCallbacks callbacks) {
// this.callbacks = callbacks;
// }
//
// @Override
// public int getContentResourceId() {
// return R.layout.rsb_step_layout_instruction;
// }
//
// private void initializeStep() {
// if (step != null) {
//
// // Set Title
// if (!TextUtils.isEmpty(step.getTitle())) {
// TextView title = (TextView) findViewById(R.id.rsb_intruction_title);
// title.setVisibility(View.VISIBLE);
// title.setText(step.getTitle());
// }
//
// // Set Summary
// if (!TextUtils.isEmpty(step.getText())) {
// TextView summary = (TextView) findViewById(R.id.rsb_intruction_text);
// summary.setVisibility(View.VISIBLE);
// summary.setText(Html.fromHtml(step.getText()));
// summary.setMovementMethod(new TextViewLinkHandler() {
// @Override
// public void onLinkClick(String url) {
// String path = ResourcePathManager.getInstance().
// generateAbsolutePath(ResourcePathManager.Resource.TYPE_HTML, url);
// Intent intent = ViewWebDocumentActivity.newIntentForPath(getContext(),
// step.getTitle(),
// path);
// getContext().startActivity(intent);
// }
// });
// }
//
// // Set Next / Skip
// SubmitBar submitBar = (SubmitBar) findViewById(R.id.rsb_submit_bar);
// submitBar.setPositiveTitle(R.string.rsb_next);
// submitBar.setPositiveAction(v -> callbacks.onSaveStep(StepCallbacks.ACTION_NEXT,
// step,
// null));
//
// if (step.isOptional()) {
// submitBar.setNegativeTitle(R.string.rsb_step_skip);
// submitBar.setNegativeAction(v -> {
// if (callbacks != null) {
// callbacks.onSaveStep(StepCallbacks.ACTION_NEXT, step, null);
// }
// });
// } else {
// submitBar.getNegativeActionView().setVisibility(View.GONE);
// }
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/step/InstructionStep.java
import org.researchstack.backbone.ui.step.layout.InstructionStepLayout;
package org.researchstack.backbone.step;
/**
* An InstructionStep object gives the participant instructions for a task.
* <p>
* You can use instruction steps to present various types of content during a task, such as
* introductory content, instructions in the middle of a task, or a final message at the completion
* of a task.
*/
public class InstructionStep extends Step {
public InstructionStep(String identifier, String title, String detailText) {
super(identifier, title);
setText(detailText);
setOptional(false);
}
@Override
public Class getStepLayoutClass() {
|
return InstructionStepLayout.class;
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/storage/file/PinCodeConfig.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
|
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import org.researchstack.backbone.R;
import org.researchstack.backbone.utils.TextUtils;
|
/**
* Returns the amount of time in milliseconds that the user must be gone from the app for before
* they are prompted for their pin code again.
*
* @return the lockout time
*/
public long getPinAutoLockTime() {
return autoLockTime;
}
/**
* Sets the amount of time in milliseconds that the user must be gone from the app for before
* they are prompted for their pin code again.
* <p>
* This may be a setting in your app, and therefore can be updated at any time.
*
* @param pinAutoLockTime the lockout time
*/
public void setPinAutoLockTime(long pinAutoLockTime) {
this.autoLockTime = pinAutoLockTime;
}
/**
* General {@link Type}s that should cover most desired pin code configs: Alpha, Numeric, and
* Alphanumberic.
*/
public enum PinCodeType implements Type {
Alphabetic(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS,
InputType.TYPE_TEXT_VARIATION_NORMAL,
InputType.TYPE_TEXT_VARIATION_PASSWORD,
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/storage/file/PinCodeConfig.java
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import org.researchstack.backbone.R;
import org.researchstack.backbone.utils.TextUtils;
/**
* Returns the amount of time in milliseconds that the user must be gone from the app for before
* they are prompted for their pin code again.
*
* @return the lockout time
*/
public long getPinAutoLockTime() {
return autoLockTime;
}
/**
* Sets the amount of time in milliseconds that the user must be gone from the app for before
* they are prompted for their pin code again.
* <p>
* This may be a setting in your app, and therefore can be updated at any time.
*
* @param pinAutoLockTime the lockout time
*/
public void setPinAutoLockTime(long pinAutoLockTime) {
this.autoLockTime = pinAutoLockTime;
}
/**
* General {@link Type}s that should cover most desired pin code configs: Alpha, Numeric, and
* Alphanumberic.
*/
public enum PinCodeType implements Type {
Alphabetic(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS,
InputType.TYPE_TEXT_VARIATION_NORMAL,
InputType.TYPE_TEXT_VARIATION_PASSWORD,
|
new TextUtils.AlphabeticFilter()),
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/ui/views/SignatureView.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/callbacks/SignatureCallbacks.java
// public interface SignatureCallbacks {
// void onSignatureStarted();
//
// void onSignatureCleared();
// }
|
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.shapes.PathShape;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.callbacks.SignatureCallbacks;
import java.util.ArrayList;
import java.util.List;
|
package org.researchstack.backbone.ui.views;
/**
* Note: For save-state to work, the view MUST have an ID
*/
public class SignatureView extends View {
private static final boolean DEBUG = false;
private static final String TAG = SignatureView.class.getSimpleName();
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/callbacks/SignatureCallbacks.java
// public interface SignatureCallbacks {
// void onSignatureStarted();
//
// void onSignatureCleared();
// }
// Path: backbone/src/main/java/org/researchstack/backbone/ui/views/SignatureView.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.shapes.PathShape;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.callbacks.SignatureCallbacks;
import java.util.ArrayList;
import java.util.List;
package org.researchstack.backbone.ui.views;
/**
* Note: For save-state to work, the view MUST have an ID
*/
public class SignatureView extends View {
private static final boolean DEBUG = false;
private static final String TAG = SignatureView.class.getSimpleName();
|
private SignatureCallbacks callbacks;
|
ResearchStack/ResearchStack
|
skin/src/main/java/org/researchstack/skin/ui/adapter/MainPagerAdapter.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ViewUtils.java
// public class ViewUtils {
//
// private ViewUtils() {
// }
//
// public static InputFilter[] addFilter(InputFilter[] filters, InputFilter filter) {
// if (filters == null || filters.length == 0) {
// return new InputFilter[]{filter};
// } else {
// // Overwrite value if the filter to be inserted already exists in the filters array
// for (int i = 0, size = filters.length; i < size; i++) {
// if (filters[i].getClass().isInstance(filter)) {
// filters[i] = filter;
// return filters;
// }
// }
//
// // If our loop fails to find filter class type, create a new array and insert that
// // filter at the end of the array.
// int newSize = filters.length + 1;
// InputFilter newFilters[] = new InputFilter[newSize];
// System.arraycopy(filters, 0, newFilters, 0, filters.length);
// newFilters[newSize - 1] = filter;
//
// return newFilters;
// }
// }
//
// public static void disableSoftInputFromAppearing(EditText editText) {
// if (Build.VERSION.SDK_INT >= 11) {
// editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
// editText.setTextIsSelectable(true);
// } else {
// editText.setRawInputType(InputType.TYPE_NULL);
// editText.setFocusable(true);
// }
// }
//
// public static void hideSoftInputMethod(Context context) {
// if (context instanceof Activity) {
// View currentFocus = ((Activity) context).getCurrentFocus();
//
// if (currentFocus != null && currentFocus.getWindowToken() != null) {
// InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromInputMethod(currentFocus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
// }
//
// public static void showSoftInputMethod(EditText editText) {
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) editText.getContext()
// .getSystemService(Activity.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, 0);
// }
//
// public static Fragment createFragment(String className) {
// try {
// Class fragmentClass = Class.forName(className);
// return createFragment(fragmentClass);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static Fragment createFragment(Class fragmentClass) {
// try {
// Constructor<?> fragConstructor = fragmentClass.getConstructor();
// Object fragment = fragConstructor.newInstance();
// return (Fragment) fragment;
// } catch (Throwable e) {
// throw new RuntimeException(e);
// }
// }
//
// }
|
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import org.researchstack.backbone.utils.ViewUtils;
import org.researchstack.skin.ActionItem;
import java.util.List;
|
package org.researchstack.skin.ui.adapter;
public class MainPagerAdapter extends FragmentPagerAdapter {
private List<ActionItem> items;
public MainPagerAdapter(FragmentManager fm, List<ActionItem> items) {
super(fm);
this.items = items;
}
@Override
public Fragment getItem(int position) {
ActionItem item = items.get(position);
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ViewUtils.java
// public class ViewUtils {
//
// private ViewUtils() {
// }
//
// public static InputFilter[] addFilter(InputFilter[] filters, InputFilter filter) {
// if (filters == null || filters.length == 0) {
// return new InputFilter[]{filter};
// } else {
// // Overwrite value if the filter to be inserted already exists in the filters array
// for (int i = 0, size = filters.length; i < size; i++) {
// if (filters[i].getClass().isInstance(filter)) {
// filters[i] = filter;
// return filters;
// }
// }
//
// // If our loop fails to find filter class type, create a new array and insert that
// // filter at the end of the array.
// int newSize = filters.length + 1;
// InputFilter newFilters[] = new InputFilter[newSize];
// System.arraycopy(filters, 0, newFilters, 0, filters.length);
// newFilters[newSize - 1] = filter;
//
// return newFilters;
// }
// }
//
// public static void disableSoftInputFromAppearing(EditText editText) {
// if (Build.VERSION.SDK_INT >= 11) {
// editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
// editText.setTextIsSelectable(true);
// } else {
// editText.setRawInputType(InputType.TYPE_NULL);
// editText.setFocusable(true);
// }
// }
//
// public static void hideSoftInputMethod(Context context) {
// if (context instanceof Activity) {
// View currentFocus = ((Activity) context).getCurrentFocus();
//
// if (currentFocus != null && currentFocus.getWindowToken() != null) {
// InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromInputMethod(currentFocus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
// }
//
// public static void showSoftInputMethod(EditText editText) {
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) editText.getContext()
// .getSystemService(Activity.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, 0);
// }
//
// public static Fragment createFragment(String className) {
// try {
// Class fragmentClass = Class.forName(className);
// return createFragment(fragmentClass);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static Fragment createFragment(Class fragmentClass) {
// try {
// Constructor<?> fragConstructor = fragmentClass.getConstructor();
// Object fragment = fragConstructor.newInstance();
// return (Fragment) fragment;
// } catch (Throwable e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: skin/src/main/java/org/researchstack/skin/ui/adapter/MainPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import org.researchstack.backbone.utils.ViewUtils;
import org.researchstack.skin.ActionItem;
import java.util.List;
package org.researchstack.skin.ui.adapter;
public class MainPagerAdapter extends FragmentPagerAdapter {
private List<ActionItem> items;
public MainPagerAdapter(FragmentManager fm, List<ActionItem> items) {
super(fm);
this.items = items;
}
@Override
public Fragment getItem(int position) {
ActionItem item = items.get(position);
|
return ViewUtils.createFragment(item.getClazz());
|
ResearchStack/ResearchStack
|
skin/src/main/java/org/researchstack/skin/notification/TaskAlertReceiver.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/storage/database/TaskNotification.java
// @DatabaseTable
// public class TaskNotification implements Serializable {
// @DatabaseField(generatedId = true)
// public int id;
//
// @DatabaseField
// public Date endDate;
//
// @DatabaseField
// public String chronTime;
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
|
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.researchstack.backbone.storage.NotificationHelper;
import org.researchstack.backbone.storage.database.TaskNotification;
import org.researchstack.backbone.utils.FormatHelper;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.skin.UiManager;
import org.researchstack.skin.schedule.ScheduleHelper;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import rx.Observable;
|
package org.researchstack.skin.notification;
public class TaskAlertReceiver extends BroadcastReceiver {
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Intent Actions
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
public static final String ALERT_CREATE = "org.researchstack.skin.notification.ALERT_CREATE";
public static final String ALERT_CREATE_ALL = "org.researchstack.skin.notification.ALERT_CREATE_ALL";
public static final String ALERT_DELETE = "org.researchstack.skin.notification.ALERT_DELETE";
public static final String ALERT_DELETE_ALL = "org.researchstack.skin.notification.ALERT_DELETE_ALL";
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Intent Keys
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
public static final String KEY_NOTIFICATION = "CreateAlertReceiver.KEY_NOTIFICATION";
public static final String KEY_NOTIFICATION_ID = "CreateAlertReceiver.KEY_NOTIFICATION_ID";
public static Intent createDeleteIntent(int notificationId) {
Intent deleteTaskIntent = new Intent(TaskAlertReceiver.ALERT_DELETE);
deleteTaskIntent.putExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID, notificationId);
return deleteTaskIntent;
}
public void onReceive(Context context, Intent intent) {
Log.i("CreateAlertReceiver", "onReceive() _ " + intent.getAction());
switch (intent.getAction()) {
case ALERT_CREATE:
|
// Path: backbone/src/main/java/org/researchstack/backbone/storage/database/TaskNotification.java
// @DatabaseTable
// public class TaskNotification implements Serializable {
// @DatabaseField(generatedId = true)
// public int id;
//
// @DatabaseField
// public Date endDate;
//
// @DatabaseField
// public String chronTime;
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
// Path: skin/src/main/java/org/researchstack/skin/notification/TaskAlertReceiver.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.researchstack.backbone.storage.NotificationHelper;
import org.researchstack.backbone.storage.database.TaskNotification;
import org.researchstack.backbone.utils.FormatHelper;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.skin.UiManager;
import org.researchstack.skin.schedule.ScheduleHelper;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import rx.Observable;
package org.researchstack.skin.notification;
public class TaskAlertReceiver extends BroadcastReceiver {
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Intent Actions
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
public static final String ALERT_CREATE = "org.researchstack.skin.notification.ALERT_CREATE";
public static final String ALERT_CREATE_ALL = "org.researchstack.skin.notification.ALERT_CREATE_ALL";
public static final String ALERT_DELETE = "org.researchstack.skin.notification.ALERT_DELETE";
public static final String ALERT_DELETE_ALL = "org.researchstack.skin.notification.ALERT_DELETE_ALL";
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Intent Keys
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
public static final String KEY_NOTIFICATION = "CreateAlertReceiver.KEY_NOTIFICATION";
public static final String KEY_NOTIFICATION_ID = "CreateAlertReceiver.KEY_NOTIFICATION_ID";
public static Intent createDeleteIntent(int notificationId) {
Intent deleteTaskIntent = new Intent(TaskAlertReceiver.ALERT_DELETE);
deleteTaskIntent.putExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID, notificationId);
return deleteTaskIntent;
}
public void onReceive(Context context, Intent intent) {
Log.i("CreateAlertReceiver", "onReceive() _ " + intent.getAction());
switch (intent.getAction()) {
case ALERT_CREATE:
|
TaskNotification taskNotification = (TaskNotification) intent.getSerializableExtra(
|
ResearchStack/ResearchStack
|
skin/src/main/java/org/researchstack/skin/notification/TaskAlertReceiver.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/storage/database/TaskNotification.java
// @DatabaseTable
// public class TaskNotification implements Serializable {
// @DatabaseField(generatedId = true)
// public int id;
//
// @DatabaseField
// public Date endDate;
//
// @DatabaseField
// public String chronTime;
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
|
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.researchstack.backbone.storage.NotificationHelper;
import org.researchstack.backbone.storage.database.TaskNotification;
import org.researchstack.backbone.utils.FormatHelper;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.skin.UiManager;
import org.researchstack.skin.schedule.ScheduleHelper;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import rx.Observable;
|
// Get our pending intent wrapper for our taskNotification
PendingIntent pendingIntent = createNotificationIntent(context, taskNotification.id);
// Generate the time the intent will fire
Date nextExecuteTime = ScheduleHelper.nextSchedule(taskNotification.chronTime,
taskNotification.endDate);
// Create alert
createAlert(context, pendingIntent, nextExecuteTime);
}
private PendingIntent createNotificationIntent(Context context, int taskNotificationId) {
// Create out intent that is sent to TaskNotificationReceiver
Intent taskNotificationIntent = new Intent(context,
UiManager.getInstance().getTaskNotificationReceiver());
taskNotificationIntent.putExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID, taskNotificationId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0,
taskNotificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
private void createAlert(Context context, PendingIntent pendingIntent, Date nextExecuteTime) {
// Add Alarm
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextExecuteTime.getTime(), pendingIntent);
|
// Path: backbone/src/main/java/org/researchstack/backbone/storage/database/TaskNotification.java
// @DatabaseTable
// public class TaskNotification implements Serializable {
// @DatabaseField(generatedId = true)
// public int id;
//
// @DatabaseField
// public Date endDate;
//
// @DatabaseField
// public String chronTime;
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
// Path: skin/src/main/java/org/researchstack/skin/notification/TaskAlertReceiver.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.researchstack.backbone.storage.NotificationHelper;
import org.researchstack.backbone.storage.database.TaskNotification;
import org.researchstack.backbone.utils.FormatHelper;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.skin.UiManager;
import org.researchstack.skin.schedule.ScheduleHelper;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import rx.Observable;
// Get our pending intent wrapper for our taskNotification
PendingIntent pendingIntent = createNotificationIntent(context, taskNotification.id);
// Generate the time the intent will fire
Date nextExecuteTime = ScheduleHelper.nextSchedule(taskNotification.chronTime,
taskNotification.endDate);
// Create alert
createAlert(context, pendingIntent, nextExecuteTime);
}
private PendingIntent createNotificationIntent(Context context, int taskNotificationId) {
// Create out intent that is sent to TaskNotificationReceiver
Intent taskNotificationIntent = new Intent(context,
UiManager.getInstance().getTaskNotificationReceiver());
taskNotificationIntent.putExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID, taskNotificationId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0,
taskNotificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
private void createAlert(Context context, PendingIntent pendingIntent, Date nextExecuteTime) {
// Add Alarm
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextExecuteTime.getTime(), pendingIntent);
|
DateFormat format = FormatHelper.getFormat(DateFormat.LONG, DateFormat.LONG);
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/model/ConsentSection.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
|
import com.google.gson.annotations.SerializedName;
import org.researchstack.backbone.R;
import org.researchstack.backbone.utils.TextUtils;
import java.io.Serializable;
|
return htmlContent;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
public String getCustomImageName() {
return customImageName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
this.escapedContent = null;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getEscapedContent() {
// If its null, return that. If not, escape/replace chars in var content
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/model/ConsentSection.java
import com.google.gson.annotations.SerializedName;
import org.researchstack.backbone.R;
import org.researchstack.backbone.utils.TextUtils;
import java.io.Serializable;
return htmlContent;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
public String getCustomImageName() {
return customImageName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
this.escapedContent = null;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getEscapedContent() {
// If its null, return that. If not, escape/replace chars in var content
|
if (TextUtils.isEmpty(content)) {
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/answerformat/EmailAnswerFormat.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
|
import org.researchstack.backbone.utils.TextUtils;
|
package org.researchstack.backbone.answerformat;
public class EmailAnswerFormat extends TextAnswerFormat {
private static final int MAX_EMAIL_LENGTH = 255;
public EmailAnswerFormat() {
super(MAX_EMAIL_LENGTH);
}
@Override
public boolean isAnswerValid(String text) {
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/TextUtils.java
// public class TextUtils {
// public static final Pattern EMAIL_ADDRESS = Pattern.compile(
// "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
// "\\@" +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
// "(" +
// "\\." +
// "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
// ")+");
//
// private TextUtils() {
// }
//
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(CharSequence str) {
// if (str == null || str.length() == 0) {
// return true;
// } else {
// return false;
// }
// }
//
// /**
// * Returns true if the char sequence is a valid email address
// *
// * @param text the email address to be validated
// * @return a boolean indicating whether the email is valid
// */
// public static boolean isValidEmail(CharSequence text) {
// return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();
// }
//
//
// public static class AlphabeticFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetter(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class NumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
//
// public static class AlphanumericFilter implements InputFilter {
// @Override
// public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (!Character.isLetterOrDigit(source.charAt(i))) {
// return "";
// }
// }
// return null;
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/answerformat/EmailAnswerFormat.java
import org.researchstack.backbone.utils.TextUtils;
package org.researchstack.backbone.answerformat;
public class EmailAnswerFormat extends TextAnswerFormat {
private static final int MAX_EMAIL_LENGTH = 255;
public EmailAnswerFormat() {
super(MAX_EMAIL_LENGTH);
}
@Override
public boolean isAnswerValid(String text) {
|
return super.isAnswerValid(text) && TextUtils.isValidEmail(text);
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/answerformat/DateAnswerFormat.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
|
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.FormatHelper;
import java.util.Date;
|
* Returns the minimum allowed date.
* <p>
* When the value of this property is <code>null</code>, there is no minimum.
*
* @return returns the minimum allowed date, or null
*/
public Date getMinimumDate() {
return minimumDate;
}
/**
* The maximum allowed date.
* <p>
* When the value of this property is <code>null</code>, there is no maximum.
*
* @return returns the maximum allowed date, or null
*/
public Date getMaximumDate() {
return maximumDate;
}
@Override
public QuestionType getQuestionType() {
if (style == DateAnswerStyle.Date) return Type.Date;
if (style == DateAnswerStyle.DateAndTime) return Type.DateAndTime;
if (style == DateAnswerStyle.TimeOfDay) return Type.TimeOfDay;
return Type.None;
}
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
// Path: backbone/src/main/java/org/researchstack/backbone/answerformat/DateAnswerFormat.java
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.FormatHelper;
import java.util.Date;
* Returns the minimum allowed date.
* <p>
* When the value of this property is <code>null</code>, there is no minimum.
*
* @return returns the minimum allowed date, or null
*/
public Date getMinimumDate() {
return minimumDate;
}
/**
* The maximum allowed date.
* <p>
* When the value of this property is <code>null</code>, there is no maximum.
*
* @return returns the maximum allowed date, or null
*/
public Date getMaximumDate() {
return maximumDate;
}
@Override
public QuestionType getQuestionType() {
if (style == DateAnswerStyle.Date) return Type.Date;
if (style == DateAnswerStyle.DateAndTime) return Type.DateAndTime;
if (style == DateAnswerStyle.TimeOfDay) return Type.TimeOfDay;
return Type.None;
}
|
public BodyAnswer validateAnswer(Date resultDate) {
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/answerformat/DateAnswerFormat.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
|
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.FormatHelper;
import java.util.Date;
|
* @return returns the minimum allowed date, or null
*/
public Date getMinimumDate() {
return minimumDate;
}
/**
* The maximum allowed date.
* <p>
* When the value of this property is <code>null</code>, there is no maximum.
*
* @return returns the maximum allowed date, or null
*/
public Date getMaximumDate() {
return maximumDate;
}
@Override
public QuestionType getQuestionType() {
if (style == DateAnswerStyle.Date) return Type.Date;
if (style == DateAnswerStyle.DateAndTime) return Type.DateAndTime;
if (style == DateAnswerStyle.TimeOfDay) return Type.TimeOfDay;
return Type.None;
}
public BodyAnswer validateAnswer(Date resultDate) {
if (minimumDate != null && resultDate.getTime() < minimumDate.getTime()) {
return new BodyAnswer(false,
R.string.rsb_invalid_answer_date_under,
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/FormatHelper.java
// public class FormatHelper {
//
// public static final int NONE = -1;
// public static final String DATE_FORMAT_ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
// public static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601,
// Locale.getDefault());
// public static final String DATE_FORMAT_SIMPLE_DATE = "yyyy-MM-dd";
// public static final SimpleDateFormat SIMPLE_FORMAT_DATE = new SimpleDateFormat(
// DATE_FORMAT_SIMPLE_DATE,
// Locale.getDefault());
// private FormatHelper() {
// }
//
// /**
// * Helper method to return a formatter suitable for
// * {@link ConsentSignatureStepLayout}
// *
// * @return DateFormat that is a DateInstance (only formats y, m, and d attributes)
// */
// public static DateFormat getSignatureFormat() {
// return getFormat(DateFormat.SHORT, NONE);
// }
//
// /**
// * Returns a DateFormat object based on the dateStyle and timeStyle params
// *
// * @param dateStyle style for the date defined by static constants within {@link DateFormat}
// * @param timeStyle style for the time defined by static constants within {@link DateFormat}
// * @return DateFormat object
// */
// public static DateFormat getFormat(int dateStyle, int timeStyle) {
// // Date & Time format
// if (isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
// }
//
// // Date format
// else if (isStyle(dateStyle) && !isStyle(timeStyle)) {
// return DateFormat.getDateInstance(dateStyle);
// }
//
// // Time format
// else if (!isStyle(dateStyle) && isStyle(timeStyle)) {
// return DateFormat.getTimeInstance(timeStyle);
// }
//
// // Else crash since the styles are invalid
// else {
// throw new IllegalArgumentException("dateStyle and timeStyle cannot both be ");
// }
// }
//
// public static boolean isStyle(int style) {
// return style >= DateFormat.FULL && style <= DateFormat.SHORT;
// }
//
// }
// Path: backbone/src/main/java/org/researchstack/backbone/answerformat/DateAnswerFormat.java
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.utils.FormatHelper;
import java.util.Date;
* @return returns the minimum allowed date, or null
*/
public Date getMinimumDate() {
return minimumDate;
}
/**
* The maximum allowed date.
* <p>
* When the value of this property is <code>null</code>, there is no maximum.
*
* @return returns the maximum allowed date, or null
*/
public Date getMaximumDate() {
return maximumDate;
}
@Override
public QuestionType getQuestionType() {
if (style == DateAnswerStyle.Date) return Type.Date;
if (style == DateAnswerStyle.DateAndTime) return Type.DateAndTime;
if (style == DateAnswerStyle.TimeOfDay) return Type.TimeOfDay;
return Type.None;
}
public BodyAnswer validateAnswer(Date resultDate) {
if (minimumDate != null && resultDate.getTime() < minimumDate.getTime()) {
return new BodyAnswer(false,
R.string.rsb_invalid_answer_date_under,
|
FormatHelper.SIMPLE_FORMAT_DATE.format(minimumDate));
|
ResearchStack/ResearchStack
|
skin/src/main/java/org/researchstack/skin/utils/ConsentFormUtils.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ResUtils.java
// public class ResUtils {
//
// private ResUtils() {
// }
//
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// // Resource Names
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// /**
// * Should this be here or should {@link StorageAccess} have the
// * ability to write files to SDCard
// *
// * @return of SD-Card storage folder name (used to save and share consent-PDF)
// */
// @Deprecated
// public static String getExternalSDAppFolder() {
// return "demo_researchstack";
// }
//
// @Deprecated
// public static String getHTMLFilePath(String docName) {
// return getRawFilePath(docName, "html");
// }
//
// @Deprecated
// public static String getPDFFilePath(String docName) {
// return getRawFilePath(docName, "pdf");
// }
//
// @Deprecated
// public static String getRawFilePath(String docName, String postfix) {
// return "file:///android_res/raw/" + docName + "." + postfix;
// }
//
// public static int getDrawableResourceId(Context context, String name) {
// return getDrawableResourceId(context, name, 0);
// }
//
// public static int getDrawableResourceId(Context context, String name, int defaultResId) {
// if (name == null || name.length() == 0) {
// return defaultResId;
// } else {
// int resId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
// return resId != 0 ? resId : defaultResId;
// }
// }
//
//
// public static int getRawResourceId(Context context, String name) {
// return context.getResources().getIdentifier(name, "raw", context.getPackageName());
// }
//
// }
|
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import org.researchstack.backbone.ui.ViewWebDocumentActivity;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.backbone.utils.ResUtils;
import org.researchstack.skin.R;
import org.researchstack.skin.ResourceManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import rx.Observable;
|
package org.researchstack.skin.utils;
public class ConsentFormUtils {
private ConsentFormUtils() {
}
public static void viewConsentForm(Context context) {
String path = ResourceManager.getInstance().getConsentHtml().getAbsolutePath();
String title = context.getString(R.string.rsb_consent);
Intent intent = ViewWebDocumentActivity.newIntentForPath(context, title, path);
context.startActivity(intent);
}
@Deprecated
public static void shareConsentForm(Context context) {
Observable.create(subscriber -> {
File consentFile = ConsentFormUtils.getConsentFormFileFromExternalStorage(context);
subscriber.onNext(consentFile);
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ResUtils.java
// public class ResUtils {
//
// private ResUtils() {
// }
//
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// // Resource Names
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// /**
// * Should this be here or should {@link StorageAccess} have the
// * ability to write files to SDCard
// *
// * @return of SD-Card storage folder name (used to save and share consent-PDF)
// */
// @Deprecated
// public static String getExternalSDAppFolder() {
// return "demo_researchstack";
// }
//
// @Deprecated
// public static String getHTMLFilePath(String docName) {
// return getRawFilePath(docName, "html");
// }
//
// @Deprecated
// public static String getPDFFilePath(String docName) {
// return getRawFilePath(docName, "pdf");
// }
//
// @Deprecated
// public static String getRawFilePath(String docName, String postfix) {
// return "file:///android_res/raw/" + docName + "." + postfix;
// }
//
// public static int getDrawableResourceId(Context context, String name) {
// return getDrawableResourceId(context, name, 0);
// }
//
// public static int getDrawableResourceId(Context context, String name, int defaultResId) {
// if (name == null || name.length() == 0) {
// return defaultResId;
// } else {
// int resId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
// return resId != 0 ? resId : defaultResId;
// }
// }
//
//
// public static int getRawResourceId(Context context, String name) {
// return context.getResources().getIdentifier(name, "raw", context.getPackageName());
// }
//
// }
// Path: skin/src/main/java/org/researchstack/skin/utils/ConsentFormUtils.java
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import org.researchstack.backbone.ui.ViewWebDocumentActivity;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.backbone.utils.ResUtils;
import org.researchstack.skin.R;
import org.researchstack.skin.ResourceManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import rx.Observable;
package org.researchstack.skin.utils;
public class ConsentFormUtils {
private ConsentFormUtils() {
}
public static void viewConsentForm(Context context) {
String path = ResourceManager.getInstance().getConsentHtml().getAbsolutePath();
String title = context.getString(R.string.rsb_consent);
Intent intent = ViewWebDocumentActivity.newIntentForPath(context, title, path);
context.startActivity(intent);
}
@Deprecated
public static void shareConsentForm(Context context) {
Observable.create(subscriber -> {
File consentFile = ConsentFormUtils.getConsentFormFileFromExternalStorage(context);
subscriber.onNext(consentFile);
|
}).compose(ObservableUtils.applyDefault()).subscribe(o -> {
|
ResearchStack/ResearchStack
|
skin/src/main/java/org/researchstack/skin/utils/ConsentFormUtils.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ResUtils.java
// public class ResUtils {
//
// private ResUtils() {
// }
//
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// // Resource Names
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// /**
// * Should this be here or should {@link StorageAccess} have the
// * ability to write files to SDCard
// *
// * @return of SD-Card storage folder name (used to save and share consent-PDF)
// */
// @Deprecated
// public static String getExternalSDAppFolder() {
// return "demo_researchstack";
// }
//
// @Deprecated
// public static String getHTMLFilePath(String docName) {
// return getRawFilePath(docName, "html");
// }
//
// @Deprecated
// public static String getPDFFilePath(String docName) {
// return getRawFilePath(docName, "pdf");
// }
//
// @Deprecated
// public static String getRawFilePath(String docName, String postfix) {
// return "file:///android_res/raw/" + docName + "." + postfix;
// }
//
// public static int getDrawableResourceId(Context context, String name) {
// return getDrawableResourceId(context, name, 0);
// }
//
// public static int getDrawableResourceId(Context context, String name, int defaultResId) {
// if (name == null || name.length() == 0) {
// return defaultResId;
// } else {
// int resId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
// return resId != 0 ? resId : defaultResId;
// }
// }
//
//
// public static int getRawResourceId(Context context, String name) {
// return context.getResources().getIdentifier(name, "raw", context.getPackageName());
// }
//
// }
|
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import org.researchstack.backbone.ui.ViewWebDocumentActivity;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.backbone.utils.ResUtils;
import org.researchstack.skin.R;
import org.researchstack.skin.ResourceManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import rx.Observable;
|
@Deprecated
public static void shareConsentForm(Context context) {
Observable.create(subscriber -> {
File consentFile = ConsentFormUtils.getConsentFormFileFromExternalStorage(context);
subscriber.onNext(consentFile);
}).compose(ObservableUtils.applyDefault()).subscribe(o -> {
int stringId = context.getApplicationInfo().labelRes;
String appName = context.getString(stringId);
String emailSubject = context.getResources()
.getString(R.string.rss_study_overview_email_subject, appName);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile((File) o));
String title = context.getString(R.string.rss_send_email);
context.startActivity(Intent.createChooser(intent, title));
});
}
/**
* @return Consent form pdf
*/
@NonNull
@Deprecated
public static File getConsentFormFileFromExternalStorage(Context context) {
LogExt.d(ConsentFormUtils.class, "getConsentFormFileFromExternalStorage() - - - - - - ");
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
|
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ObservableUtils.java
// public class ObservableUtils {
// private ObservableUtils() {
// }
//
// public static <T> Observable.Transformer<T, T> applyDefault() {
// return observable -> observable.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// }
//
// Path: backbone/src/main/java/org/researchstack/backbone/utils/ResUtils.java
// public class ResUtils {
//
// private ResUtils() {
// }
//
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// // Resource Names
// //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// /**
// * Should this be here or should {@link StorageAccess} have the
// * ability to write files to SDCard
// *
// * @return of SD-Card storage folder name (used to save and share consent-PDF)
// */
// @Deprecated
// public static String getExternalSDAppFolder() {
// return "demo_researchstack";
// }
//
// @Deprecated
// public static String getHTMLFilePath(String docName) {
// return getRawFilePath(docName, "html");
// }
//
// @Deprecated
// public static String getPDFFilePath(String docName) {
// return getRawFilePath(docName, "pdf");
// }
//
// @Deprecated
// public static String getRawFilePath(String docName, String postfix) {
// return "file:///android_res/raw/" + docName + "." + postfix;
// }
//
// public static int getDrawableResourceId(Context context, String name) {
// return getDrawableResourceId(context, name, 0);
// }
//
// public static int getDrawableResourceId(Context context, String name, int defaultResId) {
// if (name == null || name.length() == 0) {
// return defaultResId;
// } else {
// int resId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
// return resId != 0 ? resId : defaultResId;
// }
// }
//
//
// public static int getRawResourceId(Context context, String name) {
// return context.getResources().getIdentifier(name, "raw", context.getPackageName());
// }
//
// }
// Path: skin/src/main/java/org/researchstack/skin/utils/ConsentFormUtils.java
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import org.researchstack.backbone.ui.ViewWebDocumentActivity;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.backbone.utils.ResUtils;
import org.researchstack.skin.R;
import org.researchstack.skin.ResourceManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import rx.Observable;
@Deprecated
public static void shareConsentForm(Context context) {
Observable.create(subscriber -> {
File consentFile = ConsentFormUtils.getConsentFormFileFromExternalStorage(context);
subscriber.onNext(consentFile);
}).compose(ObservableUtils.applyDefault()).subscribe(o -> {
int stringId = context.getApplicationInfo().labelRes;
String appName = context.getString(stringId);
String emailSubject = context.getResources()
.getString(R.string.rss_study_overview_email_subject, appName);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile((File) o));
String title = context.getString(R.string.rss_send_email);
context.startActivity(Intent.createChooser(intent, title));
});
}
/**
* @return Consent form pdf
*/
@NonNull
@Deprecated
public static File getConsentFormFileFromExternalStorage(Context context) {
LogExt.d(ConsentFormUtils.class, "getConsentFormFileFromExternalStorage() - - - - - - ");
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
|
String basepath = extStorageDirectory + "/" + ResUtils.getExternalSDAppFolder();
|
ResearchStack/ResearchStack
|
backbone/src/main/java/org/researchstack/backbone/answerformat/BirthDateAnswerFormat.java
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
|
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import java.util.Calendar;
import java.util.Date;
|
package org.researchstack.backbone.answerformat;
public class BirthDateAnswerFormat extends DateAnswerFormat {
private final int minAge;
private final int maxAge;
public BirthDateAnswerFormat(Date defaultDate, int minAge, int maxAge) {
super(DateAnswerStyle.Date, defaultDate, dateFromAge(maxAge), dateFromAge(minAge));
this.minAge = minAge;
this.maxAge = maxAge;
}
private static Date dateFromAge(int age) {
Calendar calendar = Calendar.getInstance();
if (age != 0) {
calendar.add(Calendar.YEAR, -age);
return calendar.getTime();
}
return null;
}
@Override
|
// Path: backbone/src/main/java/org/researchstack/backbone/ui/step/body/BodyAnswer.java
// public class BodyAnswer {
// public static final BodyAnswer VALID = new BodyAnswer(true, 0);
// public static final BodyAnswer INVALID = new BodyAnswer(false,
// R.string.rsb_invalid_answer_default);
//
// private boolean isValid;
// private int reason;
// private String[] params;
//
// public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {
// this.isValid = isValid;
// this.reason = reason;
// this.params = params;
// }
//
// public boolean isValid() {
// return isValid;
// }
//
// @StringRes
// public int getReason() {
// return reason;
// }
//
// public String[] getParams() {
// return params;
// }
//
// public String getString(Context context) {
// if (getParams().length == 0) {
// return context.getString(getReason());
// } else {
// return context.getString(getReason(), getParams());
// }
// }
// }
// Path: backbone/src/main/java/org/researchstack/backbone/answerformat/BirthDateAnswerFormat.java
import org.researchstack.backbone.R;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import java.util.Calendar;
import java.util.Date;
package org.researchstack.backbone.answerformat;
public class BirthDateAnswerFormat extends DateAnswerFormat {
private final int minAge;
private final int maxAge;
public BirthDateAnswerFormat(Date defaultDate, int minAge, int maxAge) {
super(DateAnswerStyle.Date, defaultDate, dateFromAge(maxAge), dateFromAge(minAge));
this.minAge = minAge;
this.maxAge = maxAge;
}
private static Date dateFromAge(int age) {
Calendar calendar = Calendar.getInstance();
if (age != 0) {
calendar.add(Calendar.YEAR, -age);
return calendar.getTime();
}
return null;
}
@Override
|
public BodyAnswer validateAnswer(Date resultDate) {
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/core/data/sources/InMemoryCartDataSource.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/Cart.java
// public class Cart {
//
// public static final Cart EMPTY = new Cart(Collections.emptyList());
// public final List<CartProduct> products;
//
// public Cart(List<CartProduct> products) {
// this.products = products;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Cart cart = (Cart) o;
//
// return products != null ? products.equals(cart.products) : cart.products == null;
//
// }
//
// @Override
// public int hashCode() {
// return products != null ? products.hashCode() : 0;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartBuilder.java
// public class CartBuilder {
//
// private static final int DEFAULT_CAPACITY = 10;
// private static final int NOT_FOUND = -1;
//
// private final List<CartProduct> products;
//
// private CartBuilder(List<CartProduct> products) {
// this.products = products;
// }
//
// public static CartBuilder from(Cart cart) {
// if (cart.products == null) {
// return empty();
// }
//
// return new CartBuilder(new ArrayList<>(cart.products));
// }
//
// public static CartBuilder empty() {
// return new CartBuilder(new ArrayList<>(DEFAULT_CAPACITY));
// }
//
// public CartBuilder addProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int totalQuantity = product.quantity + includedProduct.quantity;
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, totalQuantity));
// } else {
// products.add(product);
// }
//
// return this;
// }
//
// public CartBuilder removeProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int newQuantity = includedProduct.quantity - product.quantity;
// if (newQuantity <= 0) {
// products.remove(index);
// } else {
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, newQuantity));
// }
// }
//
// return this;
// }
//
// @Nullable
// private int getProductIndexBySku(String sku) {
// for (int i = 0; i < products.size(); i++) {
// if (sku.equalsIgnoreCase(products.get(i).sku)) {
// return i;
// }
// }
//
// return NOT_FOUND;
// }
//
// public Cart build() {
// return new Cart(products);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartDataSource.java
// public interface CartDataSource {
//
// Single<Cart> getCart();
//
// Single<Cart> addProduct(CartProduct cartProduct);
//
// Single<Cart> removeProduct(CartProduct cartProduct);
//
// Single<Cart> emptyCart();
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
|
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.Cart;
import de.czyrux.store.core.domain.cart.CartBuilder;
import de.czyrux.store.core.domain.cart.CartDataSource;
import de.czyrux.store.core.domain.cart.CartProduct;
import io.reactivex.Single;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSource implements CartDataSource {
private final TimeDelayer timeDelayer;
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/Cart.java
// public class Cart {
//
// public static final Cart EMPTY = new Cart(Collections.emptyList());
// public final List<CartProduct> products;
//
// public Cart(List<CartProduct> products) {
// this.products = products;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Cart cart = (Cart) o;
//
// return products != null ? products.equals(cart.products) : cart.products == null;
//
// }
//
// @Override
// public int hashCode() {
// return products != null ? products.hashCode() : 0;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartBuilder.java
// public class CartBuilder {
//
// private static final int DEFAULT_CAPACITY = 10;
// private static final int NOT_FOUND = -1;
//
// private final List<CartProduct> products;
//
// private CartBuilder(List<CartProduct> products) {
// this.products = products;
// }
//
// public static CartBuilder from(Cart cart) {
// if (cart.products == null) {
// return empty();
// }
//
// return new CartBuilder(new ArrayList<>(cart.products));
// }
//
// public static CartBuilder empty() {
// return new CartBuilder(new ArrayList<>(DEFAULT_CAPACITY));
// }
//
// public CartBuilder addProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int totalQuantity = product.quantity + includedProduct.quantity;
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, totalQuantity));
// } else {
// products.add(product);
// }
//
// return this;
// }
//
// public CartBuilder removeProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int newQuantity = includedProduct.quantity - product.quantity;
// if (newQuantity <= 0) {
// products.remove(index);
// } else {
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, newQuantity));
// }
// }
//
// return this;
// }
//
// @Nullable
// private int getProductIndexBySku(String sku) {
// for (int i = 0; i < products.size(); i++) {
// if (sku.equalsIgnoreCase(products.get(i).sku)) {
// return i;
// }
// }
//
// return NOT_FOUND;
// }
//
// public Cart build() {
// return new Cart(products);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartDataSource.java
// public interface CartDataSource {
//
// Single<Cart> getCart();
//
// Single<Cart> addProduct(CartProduct cartProduct);
//
// Single<Cart> removeProduct(CartProduct cartProduct);
//
// Single<Cart> emptyCart();
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/main/java/de/czyrux/store/core/data/sources/InMemoryCartDataSource.java
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.Cart;
import de.czyrux.store.core.domain.cart.CartBuilder;
import de.czyrux.store.core.domain.cart.CartDataSource;
import de.czyrux.store.core.domain.cart.CartProduct;
import io.reactivex.Single;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSource implements CartDataSource {
private final TimeDelayer timeDelayer;
|
private Cart cart;
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/core/data/sources/InMemoryCartDataSource.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/Cart.java
// public class Cart {
//
// public static final Cart EMPTY = new Cart(Collections.emptyList());
// public final List<CartProduct> products;
//
// public Cart(List<CartProduct> products) {
// this.products = products;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Cart cart = (Cart) o;
//
// return products != null ? products.equals(cart.products) : cart.products == null;
//
// }
//
// @Override
// public int hashCode() {
// return products != null ? products.hashCode() : 0;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartBuilder.java
// public class CartBuilder {
//
// private static final int DEFAULT_CAPACITY = 10;
// private static final int NOT_FOUND = -1;
//
// private final List<CartProduct> products;
//
// private CartBuilder(List<CartProduct> products) {
// this.products = products;
// }
//
// public static CartBuilder from(Cart cart) {
// if (cart.products == null) {
// return empty();
// }
//
// return new CartBuilder(new ArrayList<>(cart.products));
// }
//
// public static CartBuilder empty() {
// return new CartBuilder(new ArrayList<>(DEFAULT_CAPACITY));
// }
//
// public CartBuilder addProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int totalQuantity = product.quantity + includedProduct.quantity;
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, totalQuantity));
// } else {
// products.add(product);
// }
//
// return this;
// }
//
// public CartBuilder removeProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int newQuantity = includedProduct.quantity - product.quantity;
// if (newQuantity <= 0) {
// products.remove(index);
// } else {
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, newQuantity));
// }
// }
//
// return this;
// }
//
// @Nullable
// private int getProductIndexBySku(String sku) {
// for (int i = 0; i < products.size(); i++) {
// if (sku.equalsIgnoreCase(products.get(i).sku)) {
// return i;
// }
// }
//
// return NOT_FOUND;
// }
//
// public Cart build() {
// return new Cart(products);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartDataSource.java
// public interface CartDataSource {
//
// Single<Cart> getCart();
//
// Single<Cart> addProduct(CartProduct cartProduct);
//
// Single<Cart> removeProduct(CartProduct cartProduct);
//
// Single<Cart> emptyCart();
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
|
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.Cart;
import de.czyrux.store.core.domain.cart.CartBuilder;
import de.czyrux.store.core.domain.cart.CartDataSource;
import de.czyrux.store.core.domain.cart.CartProduct;
import io.reactivex.Single;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSource implements CartDataSource {
private final TimeDelayer timeDelayer;
private Cart cart;
public InMemoryCartDataSource(TimeDelayer timeDelayer) {
this.timeDelayer = timeDelayer;
this.cart = Cart.EMPTY;
}
@Override
public synchronized Single<Cart> getCart() {
return Single.fromCallable(() -> {
timeDelayer.delay();
return cart;
});
}
@Override
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/Cart.java
// public class Cart {
//
// public static final Cart EMPTY = new Cart(Collections.emptyList());
// public final List<CartProduct> products;
//
// public Cart(List<CartProduct> products) {
// this.products = products;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Cart cart = (Cart) o;
//
// return products != null ? products.equals(cart.products) : cart.products == null;
//
// }
//
// @Override
// public int hashCode() {
// return products != null ? products.hashCode() : 0;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartBuilder.java
// public class CartBuilder {
//
// private static final int DEFAULT_CAPACITY = 10;
// private static final int NOT_FOUND = -1;
//
// private final List<CartProduct> products;
//
// private CartBuilder(List<CartProduct> products) {
// this.products = products;
// }
//
// public static CartBuilder from(Cart cart) {
// if (cart.products == null) {
// return empty();
// }
//
// return new CartBuilder(new ArrayList<>(cart.products));
// }
//
// public static CartBuilder empty() {
// return new CartBuilder(new ArrayList<>(DEFAULT_CAPACITY));
// }
//
// public CartBuilder addProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int totalQuantity = product.quantity + includedProduct.quantity;
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, totalQuantity));
// } else {
// products.add(product);
// }
//
// return this;
// }
//
// public CartBuilder removeProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int newQuantity = includedProduct.quantity - product.quantity;
// if (newQuantity <= 0) {
// products.remove(index);
// } else {
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, newQuantity));
// }
// }
//
// return this;
// }
//
// @Nullable
// private int getProductIndexBySku(String sku) {
// for (int i = 0; i < products.size(); i++) {
// if (sku.equalsIgnoreCase(products.get(i).sku)) {
// return i;
// }
// }
//
// return NOT_FOUND;
// }
//
// public Cart build() {
// return new Cart(products);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartDataSource.java
// public interface CartDataSource {
//
// Single<Cart> getCart();
//
// Single<Cart> addProduct(CartProduct cartProduct);
//
// Single<Cart> removeProduct(CartProduct cartProduct);
//
// Single<Cart> emptyCart();
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/main/java/de/czyrux/store/core/data/sources/InMemoryCartDataSource.java
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.Cart;
import de.czyrux.store.core.domain.cart.CartBuilder;
import de.czyrux.store.core.domain.cart.CartDataSource;
import de.czyrux.store.core.domain.cart.CartProduct;
import io.reactivex.Single;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSource implements CartDataSource {
private final TimeDelayer timeDelayer;
private Cart cart;
public InMemoryCartDataSource(TimeDelayer timeDelayer) {
this.timeDelayer = timeDelayer;
this.cart = Cart.EMPTY;
}
@Override
public synchronized Single<Cart> getCart() {
return Single.fromCallable(() -> {
timeDelayer.delay();
return cart;
});
}
@Override
|
public synchronized Single<Cart> addProduct(CartProduct cartProduct) {
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/core/data/sources/InMemoryCartDataSource.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/Cart.java
// public class Cart {
//
// public static final Cart EMPTY = new Cart(Collections.emptyList());
// public final List<CartProduct> products;
//
// public Cart(List<CartProduct> products) {
// this.products = products;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Cart cart = (Cart) o;
//
// return products != null ? products.equals(cart.products) : cart.products == null;
//
// }
//
// @Override
// public int hashCode() {
// return products != null ? products.hashCode() : 0;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartBuilder.java
// public class CartBuilder {
//
// private static final int DEFAULT_CAPACITY = 10;
// private static final int NOT_FOUND = -1;
//
// private final List<CartProduct> products;
//
// private CartBuilder(List<CartProduct> products) {
// this.products = products;
// }
//
// public static CartBuilder from(Cart cart) {
// if (cart.products == null) {
// return empty();
// }
//
// return new CartBuilder(new ArrayList<>(cart.products));
// }
//
// public static CartBuilder empty() {
// return new CartBuilder(new ArrayList<>(DEFAULT_CAPACITY));
// }
//
// public CartBuilder addProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int totalQuantity = product.quantity + includedProduct.quantity;
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, totalQuantity));
// } else {
// products.add(product);
// }
//
// return this;
// }
//
// public CartBuilder removeProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int newQuantity = includedProduct.quantity - product.quantity;
// if (newQuantity <= 0) {
// products.remove(index);
// } else {
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, newQuantity));
// }
// }
//
// return this;
// }
//
// @Nullable
// private int getProductIndexBySku(String sku) {
// for (int i = 0; i < products.size(); i++) {
// if (sku.equalsIgnoreCase(products.get(i).sku)) {
// return i;
// }
// }
//
// return NOT_FOUND;
// }
//
// public Cart build() {
// return new Cart(products);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartDataSource.java
// public interface CartDataSource {
//
// Single<Cart> getCart();
//
// Single<Cart> addProduct(CartProduct cartProduct);
//
// Single<Cart> removeProduct(CartProduct cartProduct);
//
// Single<Cart> emptyCart();
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
|
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.Cart;
import de.czyrux.store.core.domain.cart.CartBuilder;
import de.czyrux.store.core.domain.cart.CartDataSource;
import de.czyrux.store.core.domain.cart.CartProduct;
import io.reactivex.Single;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSource implements CartDataSource {
private final TimeDelayer timeDelayer;
private Cart cart;
public InMemoryCartDataSource(TimeDelayer timeDelayer) {
this.timeDelayer = timeDelayer;
this.cart = Cart.EMPTY;
}
@Override
public synchronized Single<Cart> getCart() {
return Single.fromCallable(() -> {
timeDelayer.delay();
return cart;
});
}
@Override
public synchronized Single<Cart> addProduct(CartProduct cartProduct) {
return Single.fromCallable(() -> {
timeDelayer.delay();
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/Cart.java
// public class Cart {
//
// public static final Cart EMPTY = new Cart(Collections.emptyList());
// public final List<CartProduct> products;
//
// public Cart(List<CartProduct> products) {
// this.products = products;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Cart cart = (Cart) o;
//
// return products != null ? products.equals(cart.products) : cart.products == null;
//
// }
//
// @Override
// public int hashCode() {
// return products != null ? products.hashCode() : 0;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartBuilder.java
// public class CartBuilder {
//
// private static final int DEFAULT_CAPACITY = 10;
// private static final int NOT_FOUND = -1;
//
// private final List<CartProduct> products;
//
// private CartBuilder(List<CartProduct> products) {
// this.products = products;
// }
//
// public static CartBuilder from(Cart cart) {
// if (cart.products == null) {
// return empty();
// }
//
// return new CartBuilder(new ArrayList<>(cart.products));
// }
//
// public static CartBuilder empty() {
// return new CartBuilder(new ArrayList<>(DEFAULT_CAPACITY));
// }
//
// public CartBuilder addProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int totalQuantity = product.quantity + includedProduct.quantity;
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, totalQuantity));
// } else {
// products.add(product);
// }
//
// return this;
// }
//
// public CartBuilder removeProduct(CartProduct product) {
// int index = getProductIndexBySku(product.sku);
// if (index != NOT_FOUND) {
// CartProduct includedProduct = products.get(index);
// int newQuantity = includedProduct.quantity - product.quantity;
// if (newQuantity <= 0) {
// products.remove(index);
// } else {
// products.set(index, new CartProduct(product.sku, product.title, product.imageUrl, product.price, newQuantity));
// }
// }
//
// return this;
// }
//
// @Nullable
// private int getProductIndexBySku(String sku) {
// for (int i = 0; i < products.size(); i++) {
// if (sku.equalsIgnoreCase(products.get(i).sku)) {
// return i;
// }
// }
//
// return NOT_FOUND;
// }
//
// public Cart build() {
// return new Cart(products);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartDataSource.java
// public interface CartDataSource {
//
// Single<Cart> getCart();
//
// Single<Cart> addProduct(CartProduct cartProduct);
//
// Single<Cart> removeProduct(CartProduct cartProduct);
//
// Single<Cart> emptyCart();
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/main/java/de/czyrux/store/core/data/sources/InMemoryCartDataSource.java
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.Cart;
import de.czyrux.store.core.domain.cart.CartBuilder;
import de.czyrux.store.core.domain.cart.CartDataSource;
import de.czyrux.store.core.domain.cart.CartProduct;
import io.reactivex.Single;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSource implements CartDataSource {
private final TimeDelayer timeDelayer;
private Cart cart;
public InMemoryCartDataSource(TimeDelayer timeDelayer) {
this.timeDelayer = timeDelayer;
this.cart = Cart.EMPTY;
}
@Override
public synchronized Single<Cart> getCart() {
return Single.fromCallable(() -> {
timeDelayer.delay();
return cart;
});
}
@Override
public synchronized Single<Cart> addProduct(CartProduct cartProduct) {
return Single.fromCallable(() -> {
timeDelayer.delay();
|
cart = CartBuilder.from(cart)
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/screen/CatalogScreen.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewInteraction.java
// public class RecyclerViewInteraction<A> {
//
// private Matcher<View> viewMatcher;
// private List<A> items;
//
// private RecyclerViewInteraction(Matcher<View> viewMatcher) {
// this.viewMatcher = viewMatcher;
// }
//
// public static <A> RecyclerViewInteraction<A> onRecyclerView(Matcher<View> viewMatcher) {
// return new RecyclerViewInteraction<>(viewMatcher);
// }
//
// public RecyclerViewInteraction<A> withItems(List<A> items) {
// this.items = items;
// return this;
// }
//
// public RecyclerViewInteraction<A> check(ItemViewAssertion<A> itemViewAssertion) {
// for (int i = 0; i < items.size(); i++) {
// onView(viewMatcher)
// .perform(scrollToPosition(i))
// .check(new RecyclerItemViewAssertion<>(i, items.get(i), itemViewAssertion));
// }
// return this;
// }
//
// public interface ItemViewAssertion<A> {
// void check(A item, View view, NoMatchingViewException e);
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewItemsCountMatcher.java
// public class RecyclerViewItemsCountMatcher extends BaseMatcher<View> {
//
// private final int expectedItemCount;
//
// public RecyclerViewItemsCountMatcher(int expectedItemCount) {
// this.expectedItemCount = expectedItemCount;
// }
//
// @Override public boolean matches(Object item) {
// RecyclerView recyclerView = (RecyclerView) item;
// if (recyclerView.getAdapter() == null) {
// return false;
// }
// return recyclerView.getAdapter().getItemCount() == expectedItemCount;
// }
//
// @Override public void describeTo(Description description) {
// description.appendText("recycler view does not contains " + expectedItemCount + " items");
// }
//
// public static Matcher<View> recyclerViewHasItemCount(int itemCount) {
// return new RecyclerViewItemsCountMatcher(itemCount);
// }
// }
|
import android.support.test.espresso.matcher.ViewMatchers;
import java.util.List;
import de.czyrux.store.R;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewInteraction;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewItemsCountMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
|
package de.czyrux.store.screen;
public class CatalogScreen {
public static void showsEmptyCatalog() {
onView(withId(R.id.catalog_emptyView)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
public static void matchesProductCount(int size) {
onView(withId(R.id.catalog_recyclerview))
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewInteraction.java
// public class RecyclerViewInteraction<A> {
//
// private Matcher<View> viewMatcher;
// private List<A> items;
//
// private RecyclerViewInteraction(Matcher<View> viewMatcher) {
// this.viewMatcher = viewMatcher;
// }
//
// public static <A> RecyclerViewInteraction<A> onRecyclerView(Matcher<View> viewMatcher) {
// return new RecyclerViewInteraction<>(viewMatcher);
// }
//
// public RecyclerViewInteraction<A> withItems(List<A> items) {
// this.items = items;
// return this;
// }
//
// public RecyclerViewInteraction<A> check(ItemViewAssertion<A> itemViewAssertion) {
// for (int i = 0; i < items.size(); i++) {
// onView(viewMatcher)
// .perform(scrollToPosition(i))
// .check(new RecyclerItemViewAssertion<>(i, items.get(i), itemViewAssertion));
// }
// return this;
// }
//
// public interface ItemViewAssertion<A> {
// void check(A item, View view, NoMatchingViewException e);
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewItemsCountMatcher.java
// public class RecyclerViewItemsCountMatcher extends BaseMatcher<View> {
//
// private final int expectedItemCount;
//
// public RecyclerViewItemsCountMatcher(int expectedItemCount) {
// this.expectedItemCount = expectedItemCount;
// }
//
// @Override public boolean matches(Object item) {
// RecyclerView recyclerView = (RecyclerView) item;
// if (recyclerView.getAdapter() == null) {
// return false;
// }
// return recyclerView.getAdapter().getItemCount() == expectedItemCount;
// }
//
// @Override public void describeTo(Description description) {
// description.appendText("recycler view does not contains " + expectedItemCount + " items");
// }
//
// public static Matcher<View> recyclerViewHasItemCount(int itemCount) {
// return new RecyclerViewItemsCountMatcher(itemCount);
// }
// }
// Path: app/src/androidTest/java/de/czyrux/store/screen/CatalogScreen.java
import android.support.test.espresso.matcher.ViewMatchers;
import java.util.List;
import de.czyrux.store.R;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewInteraction;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewItemsCountMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
package de.czyrux.store.screen;
public class CatalogScreen {
public static void showsEmptyCatalog() {
onView(withId(R.id.catalog_emptyView)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
public static void matchesProductCount(int size) {
onView(withId(R.id.catalog_recyclerview))
|
.check(matches(RecyclerViewItemsCountMatcher.recyclerViewHasItemCount(size)));
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/screen/CatalogScreen.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewInteraction.java
// public class RecyclerViewInteraction<A> {
//
// private Matcher<View> viewMatcher;
// private List<A> items;
//
// private RecyclerViewInteraction(Matcher<View> viewMatcher) {
// this.viewMatcher = viewMatcher;
// }
//
// public static <A> RecyclerViewInteraction<A> onRecyclerView(Matcher<View> viewMatcher) {
// return new RecyclerViewInteraction<>(viewMatcher);
// }
//
// public RecyclerViewInteraction<A> withItems(List<A> items) {
// this.items = items;
// return this;
// }
//
// public RecyclerViewInteraction<A> check(ItemViewAssertion<A> itemViewAssertion) {
// for (int i = 0; i < items.size(); i++) {
// onView(viewMatcher)
// .perform(scrollToPosition(i))
// .check(new RecyclerItemViewAssertion<>(i, items.get(i), itemViewAssertion));
// }
// return this;
// }
//
// public interface ItemViewAssertion<A> {
// void check(A item, View view, NoMatchingViewException e);
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewItemsCountMatcher.java
// public class RecyclerViewItemsCountMatcher extends BaseMatcher<View> {
//
// private final int expectedItemCount;
//
// public RecyclerViewItemsCountMatcher(int expectedItemCount) {
// this.expectedItemCount = expectedItemCount;
// }
//
// @Override public boolean matches(Object item) {
// RecyclerView recyclerView = (RecyclerView) item;
// if (recyclerView.getAdapter() == null) {
// return false;
// }
// return recyclerView.getAdapter().getItemCount() == expectedItemCount;
// }
//
// @Override public void describeTo(Description description) {
// description.appendText("recycler view does not contains " + expectedItemCount + " items");
// }
//
// public static Matcher<View> recyclerViewHasItemCount(int itemCount) {
// return new RecyclerViewItemsCountMatcher(itemCount);
// }
// }
|
import android.support.test.espresso.matcher.ViewMatchers;
import java.util.List;
import de.czyrux.store.R;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewInteraction;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewItemsCountMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
|
package de.czyrux.store.screen;
public class CatalogScreen {
public static void showsEmptyCatalog() {
onView(withId(R.id.catalog_emptyView)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
public static void matchesProductCount(int size) {
onView(withId(R.id.catalog_recyclerview))
.check(matches(RecyclerViewItemsCountMatcher.recyclerViewHasItemCount(size)));
}
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewInteraction.java
// public class RecyclerViewInteraction<A> {
//
// private Matcher<View> viewMatcher;
// private List<A> items;
//
// private RecyclerViewInteraction(Matcher<View> viewMatcher) {
// this.viewMatcher = viewMatcher;
// }
//
// public static <A> RecyclerViewInteraction<A> onRecyclerView(Matcher<View> viewMatcher) {
// return new RecyclerViewInteraction<>(viewMatcher);
// }
//
// public RecyclerViewInteraction<A> withItems(List<A> items) {
// this.items = items;
// return this;
// }
//
// public RecyclerViewInteraction<A> check(ItemViewAssertion<A> itemViewAssertion) {
// for (int i = 0; i < items.size(); i++) {
// onView(viewMatcher)
// .perform(scrollToPosition(i))
// .check(new RecyclerItemViewAssertion<>(i, items.get(i), itemViewAssertion));
// }
// return this;
// }
//
// public interface ItemViewAssertion<A> {
// void check(A item, View view, NoMatchingViewException e);
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewItemsCountMatcher.java
// public class RecyclerViewItemsCountMatcher extends BaseMatcher<View> {
//
// private final int expectedItemCount;
//
// public RecyclerViewItemsCountMatcher(int expectedItemCount) {
// this.expectedItemCount = expectedItemCount;
// }
//
// @Override public boolean matches(Object item) {
// RecyclerView recyclerView = (RecyclerView) item;
// if (recyclerView.getAdapter() == null) {
// return false;
// }
// return recyclerView.getAdapter().getItemCount() == expectedItemCount;
// }
//
// @Override public void describeTo(Description description) {
// description.appendText("recycler view does not contains " + expectedItemCount + " items");
// }
//
// public static Matcher<View> recyclerViewHasItemCount(int itemCount) {
// return new RecyclerViewItemsCountMatcher(itemCount);
// }
// }
// Path: app/src/androidTest/java/de/czyrux/store/screen/CatalogScreen.java
import android.support.test.espresso.matcher.ViewMatchers;
import java.util.List;
import de.czyrux.store.R;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewInteraction;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewItemsCountMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
package de.czyrux.store.screen;
public class CatalogScreen {
public static void showsEmptyCatalog() {
onView(withId(R.id.catalog_emptyView)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
public static void matchesProductCount(int size) {
onView(withId(R.id.catalog_recyclerview))
.check(matches(RecyclerViewItemsCountMatcher.recyclerViewHasItemCount(size)));
}
|
public static void containsProducts(List<Product> products) {
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/screen/CatalogScreen.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewInteraction.java
// public class RecyclerViewInteraction<A> {
//
// private Matcher<View> viewMatcher;
// private List<A> items;
//
// private RecyclerViewInteraction(Matcher<View> viewMatcher) {
// this.viewMatcher = viewMatcher;
// }
//
// public static <A> RecyclerViewInteraction<A> onRecyclerView(Matcher<View> viewMatcher) {
// return new RecyclerViewInteraction<>(viewMatcher);
// }
//
// public RecyclerViewInteraction<A> withItems(List<A> items) {
// this.items = items;
// return this;
// }
//
// public RecyclerViewInteraction<A> check(ItemViewAssertion<A> itemViewAssertion) {
// for (int i = 0; i < items.size(); i++) {
// onView(viewMatcher)
// .perform(scrollToPosition(i))
// .check(new RecyclerItemViewAssertion<>(i, items.get(i), itemViewAssertion));
// }
// return this;
// }
//
// public interface ItemViewAssertion<A> {
// void check(A item, View view, NoMatchingViewException e);
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewItemsCountMatcher.java
// public class RecyclerViewItemsCountMatcher extends BaseMatcher<View> {
//
// private final int expectedItemCount;
//
// public RecyclerViewItemsCountMatcher(int expectedItemCount) {
// this.expectedItemCount = expectedItemCount;
// }
//
// @Override public boolean matches(Object item) {
// RecyclerView recyclerView = (RecyclerView) item;
// if (recyclerView.getAdapter() == null) {
// return false;
// }
// return recyclerView.getAdapter().getItemCount() == expectedItemCount;
// }
//
// @Override public void describeTo(Description description) {
// description.appendText("recycler view does not contains " + expectedItemCount + " items");
// }
//
// public static Matcher<View> recyclerViewHasItemCount(int itemCount) {
// return new RecyclerViewItemsCountMatcher(itemCount);
// }
// }
|
import android.support.test.espresso.matcher.ViewMatchers;
import java.util.List;
import de.czyrux.store.R;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewInteraction;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewItemsCountMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
|
package de.czyrux.store.screen;
public class CatalogScreen {
public static void showsEmptyCatalog() {
onView(withId(R.id.catalog_emptyView)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
public static void matchesProductCount(int size) {
onView(withId(R.id.catalog_recyclerview))
.check(matches(RecyclerViewItemsCountMatcher.recyclerViewHasItemCount(size)));
}
public static void containsProducts(List<Product> products) {
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewInteraction.java
// public class RecyclerViewInteraction<A> {
//
// private Matcher<View> viewMatcher;
// private List<A> items;
//
// private RecyclerViewInteraction(Matcher<View> viewMatcher) {
// this.viewMatcher = viewMatcher;
// }
//
// public static <A> RecyclerViewInteraction<A> onRecyclerView(Matcher<View> viewMatcher) {
// return new RecyclerViewInteraction<>(viewMatcher);
// }
//
// public RecyclerViewInteraction<A> withItems(List<A> items) {
// this.items = items;
// return this;
// }
//
// public RecyclerViewInteraction<A> check(ItemViewAssertion<A> itemViewAssertion) {
// for (int i = 0; i < items.size(); i++) {
// onView(viewMatcher)
// .perform(scrollToPosition(i))
// .check(new RecyclerItemViewAssertion<>(i, items.get(i), itemViewAssertion));
// }
// return this;
// }
//
// public interface ItemViewAssertion<A> {
// void check(A item, View view, NoMatchingViewException e);
// }
// }
//
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/matchers/recyclerview/RecyclerViewItemsCountMatcher.java
// public class RecyclerViewItemsCountMatcher extends BaseMatcher<View> {
//
// private final int expectedItemCount;
//
// public RecyclerViewItemsCountMatcher(int expectedItemCount) {
// this.expectedItemCount = expectedItemCount;
// }
//
// @Override public boolean matches(Object item) {
// RecyclerView recyclerView = (RecyclerView) item;
// if (recyclerView.getAdapter() == null) {
// return false;
// }
// return recyclerView.getAdapter().getItemCount() == expectedItemCount;
// }
//
// @Override public void describeTo(Description description) {
// description.appendText("recycler view does not contains " + expectedItemCount + " items");
// }
//
// public static Matcher<View> recyclerViewHasItemCount(int itemCount) {
// return new RecyclerViewItemsCountMatcher(itemCount);
// }
// }
// Path: app/src/androidTest/java/de/czyrux/store/screen/CatalogScreen.java
import android.support.test.espresso.matcher.ViewMatchers;
import java.util.List;
import de.czyrux.store.R;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewInteraction;
import de.czyrux.store.toolbox.matchers.recyclerview.RecyclerViewItemsCountMatcher;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
package de.czyrux.store.screen;
public class CatalogScreen {
public static void showsEmptyCatalog() {
onView(withId(R.id.catalog_emptyView)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
public static void matchesProductCount(int size) {
onView(withId(R.id.catalog_recyclerview))
.check(matches(RecyclerViewItemsCountMatcher.recyclerViewHasItemCount(size)));
}
public static void containsProducts(List<Product> products) {
|
RecyclerViewInteraction.<Product>onRecyclerView(withId(R.id.catalog_recyclerview))
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/domain/cart/CartServiceTest.java
|
// Path: app/src/test/java/de/czyrux/store/test/ProductFakeCreator.java
// public class ProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
//
// private ProductFakeCreator() {
// }
//
// public static Product createProduct() {
// return createProduct(DEFAULT_SKU);
// }
//
// public static Product createProduct(String sku) {
// return new Product(sku, "Adidas Perf", "someImage", 23.5f);
// }
//
// }
|
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import de.czyrux.store.test.ProductFakeCreator;
import io.reactivex.Single;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
|
package de.czyrux.store.core.domain.cart;
public class CartServiceTest {
@Mock
CartDataSource cartDataSource;
@Mock
CartStore cartStore;
private CartService cartService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
cartService = new CartService(cartDataSource, cartStore);
Cart cart = Cart.EMPTY;
when(cartDataSource.getCart()).thenReturn(Single.just(cart));
}
@Test
public void addProduct_Should_CallDataSource() {
|
// Path: app/src/test/java/de/czyrux/store/test/ProductFakeCreator.java
// public class ProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
//
// private ProductFakeCreator() {
// }
//
// public static Product createProduct() {
// return createProduct(DEFAULT_SKU);
// }
//
// public static Product createProduct(String sku) {
// return new Product(sku, "Adidas Perf", "someImage", 23.5f);
// }
//
// }
// Path: app/src/test/java/de/czyrux/store/core/domain/cart/CartServiceTest.java
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import de.czyrux.store.test.ProductFakeCreator;
import io.reactivex.Single;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
package de.czyrux.store.core.domain.cart;
public class CartServiceTest {
@Mock
CartDataSource cartDataSource;
@Mock
CartStore cartStore;
private CartService cartService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
cartService = new CartService(cartDataSource, cartStore);
Cart cart = Cart.EMPTY;
when(cartDataSource.getCart()).thenReturn(Single.just(cart));
}
@Test
public void addProduct_Should_CallDataSource() {
|
CartProduct product = CartProductFactory.newCartProduct(ProductFakeCreator.createProduct(), 1);
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/core/domain/cart/CartProductFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
|
import de.czyrux.store.core.domain.product.Product;
|
package de.czyrux.store.core.domain.cart;
public final class CartProductFactory {
private CartProductFactory() {
}
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProductFactory.java
import de.czyrux.store.core.domain.product.Product;
package de.czyrux.store.core.domain.cart;
public final class CartProductFactory {
private CartProductFactory() {
}
|
public static CartProduct newCartProduct(Product product, int quantity) {
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/domain/cart/CartProductFactoryTest.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/ProductFakeCreator.java
// public class ProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
//
// private ProductFakeCreator() {
// }
//
// public static Product createProduct() {
// return createProduct(DEFAULT_SKU);
// }
//
// public static Product createProduct(String sku) {
// return new Product(sku, "Adidas Perf", "someImage", 23.5f);
// }
//
// }
|
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.test.ProductFakeCreator;
import static org.junit.Assert.assertEquals;
|
package de.czyrux.store.core.domain.cart;
public class CartProductFactoryTest {
public static final int SOME_QUANTITY = 2;
@Before
public void setUp() throws Exception {
}
@Test
public void newCartProduct_Should_CreateProductWithSpecifyQuantity() {
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/ProductFakeCreator.java
// public class ProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
//
// private ProductFakeCreator() {
// }
//
// public static Product createProduct() {
// return createProduct(DEFAULT_SKU);
// }
//
// public static Product createProduct(String sku) {
// return new Product(sku, "Adidas Perf", "someImage", 23.5f);
// }
//
// }
// Path: app/src/test/java/de/czyrux/store/core/domain/cart/CartProductFactoryTest.java
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.test.ProductFakeCreator;
import static org.junit.Assert.assertEquals;
package de.czyrux.store.core.domain.cart;
public class CartProductFactoryTest {
public static final int SOME_QUANTITY = 2;
@Before
public void setUp() throws Exception {
}
@Test
public void newCartProduct_Should_CreateProductWithSpecifyQuantity() {
|
Product testProduct = ProductFakeCreator.createProduct();
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/domain/cart/CartProductFactoryTest.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/ProductFakeCreator.java
// public class ProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
//
// private ProductFakeCreator() {
// }
//
// public static Product createProduct() {
// return createProduct(DEFAULT_SKU);
// }
//
// public static Product createProduct(String sku) {
// return new Product(sku, "Adidas Perf", "someImage", 23.5f);
// }
//
// }
|
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.test.ProductFakeCreator;
import static org.junit.Assert.assertEquals;
|
package de.czyrux.store.core.domain.cart;
public class CartProductFactoryTest {
public static final int SOME_QUANTITY = 2;
@Before
public void setUp() throws Exception {
}
@Test
public void newCartProduct_Should_CreateProductWithSpecifyQuantity() {
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/ProductFakeCreator.java
// public class ProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
//
// private ProductFakeCreator() {
// }
//
// public static Product createProduct() {
// return createProduct(DEFAULT_SKU);
// }
//
// public static Product createProduct(String sku) {
// return new Product(sku, "Adidas Perf", "someImage", 23.5f);
// }
//
// }
// Path: app/src/test/java/de/czyrux/store/core/domain/cart/CartProductFactoryTest.java
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.domain.product.Product;
import de.czyrux.store.test.ProductFakeCreator;
import static org.junit.Assert.assertEquals;
package de.czyrux.store.core.domain.cart;
public class CartProductFactoryTest {
public static final int SOME_QUANTITY = 2;
@Before
public void setUp() throws Exception {
}
@Test
public void newCartProduct_Should_CreateProductWithSpecifyQuantity() {
|
Product testProduct = ProductFakeCreator.createProduct();
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/toolbox/mock/MockProductProvider.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
|
import java.util.Arrays;
import java.util.List;
import de.czyrux.store.core.domain.product.Product;
|
package de.czyrux.store.toolbox.mock;
public class MockProductProvider {
private MockProductProvider() {
}
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/mock/MockProductProvider.java
import java.util.Arrays;
import java.util.List;
import de.czyrux.store.core.domain.product.Product;
package de.czyrux.store.toolbox.mock;
public class MockProductProvider {
private MockProductProvider() {
}
|
public static List<Product> getMockProducts() {
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
|
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
|
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
|
private final CartService cartService;
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
|
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
|
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
private final CartService cartService;
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
private final CartService cartService;
|
private final ProductService productService;
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
|
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
|
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
private final CartService cartService;
private final ProductService productService;
private TestDependenciesFactory(CartStore cartStore, CartService cartService, ProductService productService) {
this.cartStore = cartStore;
this.cartService = cartService;
this.productService = productService;
}
@Override
public CartService createCartService() {
return cartService;
}
@Override
public ProductService createProductService() {
return productService;
}
@Override
public CartStore createCartStore() {
return cartStore;
}
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
private final CartService cartService;
private final ProductService productService;
private TestDependenciesFactory(CartStore cartStore, CartService cartService, ProductService productService) {
this.cartStore = cartStore;
this.cartService = cartService;
this.productService = productService;
}
@Override
public CartService createCartService() {
return cartService;
}
@Override
public ProductService createProductService() {
return productService;
}
@Override
public CartStore createCartStore() {
return cartStore;
}
|
public static TestDependenciesFactory.Builder fromDefault(DataDependenciesFactory dataDependenciesFactory) {
|
czyrux/GroceryStore
|
app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
|
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
|
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
private final CartService cartService;
private final ProductService productService;
private TestDependenciesFactory(CartStore cartStore, CartService cartService, ProductService productService) {
this.cartStore = cartStore;
this.cartService = cartService;
this.productService = productService;
}
@Override
public CartService createCartService() {
return cartService;
}
@Override
public ProductService createProductService() {
return productService;
}
@Override
public CartStore createCartStore() {
return cartStore;
}
public static TestDependenciesFactory.Builder fromDefault(DataDependenciesFactory dataDependenciesFactory) {
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DataDependenciesFactory.java
// public interface DataDependenciesFactory {
// CartDataSource createCartDataSource();
//
// ProductDataSource createProductDataSource();
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DefaultDependenciesFactory.java
// public class DefaultDependenciesFactory implements DependenciesFactory {
//
// private final DataDependenciesFactory dataDependenciesFactory;
// private final CartStore cartStore;
//
// public DefaultDependenciesFactory(DataDependenciesFactory dataDependenciesFactory) {
// this.dataDependenciesFactory = dataDependenciesFactory;
// cartStore = new CartStore();
// }
//
// @Override
// public CartService createCartService() {
// return new CartService(dataDependenciesFactory.createCartDataSource(), cartStore);
// }
//
// @Override
// public ProductService createProductService() {
// return new ProductService(dataDependenciesFactory.createProductDataSource());
// }
//
// @Override
// public CartStore createCartStore() {
// return cartStore;
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
// public interface DependenciesFactory {
// CartService createCartService();
//
// ProductService createProductService();
//
// CartStore createCartStore();
// }
// Path: app/src/androidTest/java/de/czyrux/store/toolbox/mock/TestDependenciesFactory.java
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
import de.czyrux.store.inject.DataDependenciesFactory;
import de.czyrux.store.inject.DefaultDependenciesFactory;
import de.czyrux.store.inject.DependenciesFactory;
package de.czyrux.store.toolbox.mock;
public class TestDependenciesFactory implements DependenciesFactory {
private final CartStore cartStore;
private final CartService cartService;
private final ProductService productService;
private TestDependenciesFactory(CartStore cartStore, CartService cartService, ProductService productService) {
this.cartStore = cartStore;
this.cartService = cartService;
this.productService = productService;
}
@Override
public CartService createCartService() {
return cartService;
}
@Override
public ProductService createProductService() {
return productService;
}
@Override
public CartStore createCartStore() {
return cartStore;
}
public static TestDependenciesFactory.Builder fromDefault(DataDependenciesFactory dataDependenciesFactory) {
|
return from(new DefaultDependenciesFactory(dataDependenciesFactory));
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/core/data/sources/ProductProvider.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
|
import java.util.Arrays;
import java.util.List;
import de.czyrux.store.core.domain.product.Product;
|
package de.czyrux.store.core.data.sources;
class ProductProvider {
private ProductProvider() {
}
|
// Path: app/src/main/java/de/czyrux/store/core/domain/product/Product.java
// public class Product {
// public final String sku;
// public final String title;
// public final String imageUrl;
// public final double price;
//
// public Product(String sku, String title, String imageUrl, double price) {
// this.sku = sku;
// this.title = title;
// this.imageUrl = imageUrl;
// this.price = price;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Product product = (Product) o;
//
// if (Double.compare(product.price, price) != 0) return false;
// if (sku != null ? !sku.equals(product.sku) : product.sku != null) return false;
// if (title != null ? !title.equals(product.title) : product.title != null) return false;
// return imageUrl != null ? imageUrl.equals(product.imageUrl) : product.imageUrl == null;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// result = sku != null ? sku.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (imageUrl != null ? imageUrl.hashCode() : 0);
// temp = Double.doubleToLongBits(price);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("Product{");
// sb.append("sku='").append(sku).append('\'');
// sb.append(", title='").append(title).append('\'');
// sb.append(", imageUrl='").append(imageUrl).append('\'');
// sb.append(", price=").append(price);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/main/java/de/czyrux/store/core/data/sources/ProductProvider.java
import java.util.Arrays;
import java.util.List;
import de.czyrux.store.core.domain.product.Product;
package de.czyrux.store.core.data.sources;
class ProductProvider {
private ProductProvider() {
}
|
public static List<Product> getProductList() {
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
|
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
// Path: app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
|
TimeDelayer timeDelayer = mock(TimeDelayer.class);
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
|
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
TimeDelayer timeDelayer = mock(TimeDelayer.class);
cartDataSource = new InMemoryCartDataSource(timeDelayer);
}
@Test
public void getCart_Should_ReturnEmptyCart_When_NoOperationsMade() {
cartDataSource.getCart()
.test()
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
// Path: app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
TimeDelayer timeDelayer = mock(TimeDelayer.class);
cartDataSource = new InMemoryCartDataSource(timeDelayer);
}
@Test
public void getCart_Should_ReturnEmptyCart_When_NoOperationsMade() {
cartDataSource.getCart()
.test()
|
.assertValue(CartFakeCreator.emptyCart())
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
|
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
TimeDelayer timeDelayer = mock(TimeDelayer.class);
cartDataSource = new InMemoryCartDataSource(timeDelayer);
}
@Test
public void getCart_Should_ReturnEmptyCart_When_NoOperationsMade() {
cartDataSource.getCart()
.test()
.assertValue(CartFakeCreator.emptyCart())
.assertComplete();
}
@Test
public void addProduct_Should_AddValuesToCart() {
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
// Path: app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
TimeDelayer timeDelayer = mock(TimeDelayer.class);
cartDataSource = new InMemoryCartDataSource(timeDelayer);
}
@Test
public void getCart_Should_ReturnEmptyCart_When_NoOperationsMade() {
cartDataSource.getCart()
.test()
.assertValue(CartFakeCreator.emptyCart())
.assertComplete();
}
@Test
public void addProduct_Should_AddValuesToCart() {
|
CartProduct product = CartProductFakeCreator.createProduct("Sku1", 2);
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
|
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
|
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
TimeDelayer timeDelayer = mock(TimeDelayer.class);
cartDataSource = new InMemoryCartDataSource(timeDelayer);
}
@Test
public void getCart_Should_ReturnEmptyCart_When_NoOperationsMade() {
cartDataSource.getCart()
.test()
.assertValue(CartFakeCreator.emptyCart())
.assertComplete();
}
@Test
public void addProduct_Should_AddValuesToCart() {
|
// Path: app/src/main/java/de/czyrux/store/core/data/util/TimeDelayer.java
// public class TimeDelayer {
//
// private static final int MAX_DEFAULT_DELAY = 2000; // 2 sec
// private final Random random;
//
// public TimeDelayer() {
// random = new Random(System.nanoTime());
// }
//
// public void delay(int maxTime) {
// try {
// Thread.sleep(random.nextInt(maxTime));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// public void delay() {
// delay(MAX_DEFAULT_DELAY);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartFakeCreator.java
// public class CartFakeCreator {
//
// public static Cart emptyCart() {
// return new Cart(Collections.emptyList());
// }
//
// public static Cart cartWithElements(CartProduct... products) {
// return new Cart(Arrays.asList(products));
// }
// }
//
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
// public class CartProductFakeCreator {
//
// private static final String DEFAULT_SKU = "ada300343";
// private static final int DEFAULT_QUANTITY = 1;
//
// private CartProductFakeCreator() {
// }
//
// public static CartProduct createProduct() {
// return createProduct(DEFAULT_SKU, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku) {
// return createProduct(sku, DEFAULT_QUANTITY);
// }
//
// public static CartProduct createProduct(String sku, int quantity) {
// return new CartProduct(sku, "Adidas Perf", "someImage", 23.5f, quantity);
// }
// }
// Path: app/src/test/java/de/czyrux/store/core/data/sources/InMemoryCartDataSourceTest.java
import org.junit.Before;
import org.junit.Test;
import de.czyrux.store.core.data.util.TimeDelayer;
import de.czyrux.store.core.domain.cart.CartProduct;
import de.czyrux.store.test.CartFakeCreator;
import de.czyrux.store.test.CartProductFakeCreator;
import static org.mockito.Mockito.mock;
package de.czyrux.store.core.data.sources;
public class InMemoryCartDataSourceTest {
private InMemoryCartDataSource cartDataSource;
@Before
public void setUp() throws Exception {
TimeDelayer timeDelayer = mock(TimeDelayer.class);
cartDataSource = new InMemoryCartDataSource(timeDelayer);
}
@Test
public void getCart_Should_ReturnEmptyCart_When_NoOperationsMade() {
cartDataSource.getCart()
.test()
.assertValue(CartFakeCreator.emptyCart())
.assertComplete();
}
@Test
public void addProduct_Should_AddValuesToCart() {
|
CartProduct product = CartProductFakeCreator.createProduct("Sku1", 2);
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
|
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
|
package de.czyrux.store.inject;
public interface DependenciesFactory {
CartService createCartService();
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
package de.czyrux.store.inject;
public interface DependenciesFactory {
CartService createCartService();
|
ProductService createProductService();
|
czyrux/GroceryStore
|
app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
|
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
|
package de.czyrux.store.inject;
public interface DependenciesFactory {
CartService createCartService();
ProductService createProductService();
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartService.java
// public class CartService {
//
// private final CartDataSource cartDataSource;
// private final CartStore cartStore;
//
// public CartService(CartDataSource cartDataSource, CartStore cartStore) {
// this.cartDataSource = cartDataSource;
// this.cartStore = cartStore;
// }
//
// /**
// * Gets Cart. This Observable will receive updates every time that the
// * underlying Cart gets updated.
// */
// public Observable<Cart> getCart() {
// return cartDataSource.getCart()
// .compose(cartPublisher())
// .toObservable()
// .flatMap(cart -> cartStore.observe());
// }
//
// /**
// * Add a product to the Cart.
// */
// public Single<Cart> addProduct(CartProduct cartProduct) {
// return cartDataSource.addProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Remove a product to the Cart.
// */
// public Single<Cart> removeProduct(CartProduct cartProduct) {
// return cartDataSource.removeProduct(cartProduct)
// .compose(cartPublisher());
// }
//
// /**
// * Clear Cart content.
// */
// public Completable clear() {
// return cartDataSource.emptyCart()
// .compose(cartPublisher())
// .toCompletable();
// }
//
// private SingleTransformer<Cart, Cart> cartPublisher() {
// return cartObservable -> cartObservable.doOnSuccess(cartStore::publish);
// }
// }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartStore.java
// public class CartStore extends Store<Cart> { }
//
// Path: app/src/main/java/de/czyrux/store/core/domain/product/ProductService.java
// public class ProductService {
//
// private final ProductDataSource productDataSource;
//
// public ProductService(ProductDataSource productDataSource) {
// this.productDataSource = productDataSource;
// }
//
// public Single<ProductResponse> getAllCatalog() {
// return productDataSource.getAllCatalog()
// .map(ProductResponse::new);
// }
// }
// Path: app/src/main/java/de/czyrux/store/inject/DependenciesFactory.java
import de.czyrux.store.core.domain.cart.CartService;
import de.czyrux.store.core.domain.cart.CartStore;
import de.czyrux.store.core.domain.product.ProductService;
package de.czyrux.store.inject;
public interface DependenciesFactory {
CartService createCartService();
ProductService createProductService();
|
CartStore createCartStore();
|
czyrux/GroceryStore
|
app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
|
import de.czyrux.store.core.domain.cart.CartProduct;
|
package de.czyrux.store.test;
public class CartProductFakeCreator {
private static final String DEFAULT_SKU = "ada300343";
private static final int DEFAULT_QUANTITY = 1;
private CartProductFakeCreator() {
}
|
// Path: app/src/main/java/de/czyrux/store/core/domain/cart/CartProduct.java
// public class CartProduct extends Product {
//
// public final int quantity;
//
// public CartProduct(String sku, String title, String imageUrl, double price, int quantity) {
// super(sku, title, imageUrl, price);
// this.quantity = quantity;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// CartProduct product = (CartProduct) o;
//
// return quantity == product.quantity;
//
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + quantity;
// return result;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder("CartProduct{");
// sb.append("quantity=").append(quantity);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: app/src/test/java/de/czyrux/store/test/CartProductFakeCreator.java
import de.czyrux.store.core.domain.cart.CartProduct;
package de.czyrux.store.test;
public class CartProductFakeCreator {
private static final String DEFAULT_SKU = "ada300343";
private static final int DEFAULT_QUANTITY = 1;
private CartProductFakeCreator() {
}
|
public static CartProduct createProduct() {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.