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
hyounesy/ChAsE
src/org/sfu/chase/gui/PopupMenu.java
// Path: src/org/sfu/chase/core/ClustFramework.java // public enum SortCriteria // { // GENOMIC_LOCATION, // SIGNAL_AVERAGE, // SIGNAL_MEDIAN, // SIGNAL_MIN, // SIGNAL_PEAK, // SIGNAL_PEAK_OFFSET, // INPUT_ORDER, // INPUT_GROUP_LABEL, // };
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import org.sfu.chase.core.ClustFramework.SortCriteria;
JPopupMenu getPopupFavorite() { return m_PopupFavorite; } private void addPopupHeatmap() { m_PopupHeatmap = new JPopupMenu(); JMenu sortMenu = new JMenu("Sort by"); sortMenu.setMnemonic(KeyEvent.VK_S); String criteriaName[] = { "Genomic Location", "Average", "Median", "Min", "Max Peak", "Peak Location", "Input Order", "Input Group Label"}; ButtonGroup hmSortGroup = new ButtonGroup(); m_ItemHMSortTypes = new JRadioButtonMenuItem[criteriaName.length]; for (int i = 0; i < criteriaName.length; i++) { m_ItemHMSortTypes[i] = new JRadioButtonMenuItem(criteriaName[i]); final int i2 = i; m_ItemHMSortTypes[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
// Path: src/org/sfu/chase/core/ClustFramework.java // public enum SortCriteria // { // GENOMIC_LOCATION, // SIGNAL_AVERAGE, // SIGNAL_MEDIAN, // SIGNAL_MIN, // SIGNAL_PEAK, // SIGNAL_PEAK_OFFSET, // INPUT_ORDER, // INPUT_GROUP_LABEL, // }; // Path: src/org/sfu/chase/gui/PopupMenu.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import org.sfu.chase.core.ClustFramework.SortCriteria; JPopupMenu getPopupFavorite() { return m_PopupFavorite; } private void addPopupHeatmap() { m_PopupHeatmap = new JPopupMenu(); JMenu sortMenu = new JMenu("Sort by"); sortMenu.setMnemonic(KeyEvent.VK_S); String criteriaName[] = { "Genomic Location", "Average", "Median", "Min", "Max Peak", "Peak Location", "Input Order", "Input Group Label"}; ButtonGroup hmSortGroup = new ButtonGroup(); m_ItemHMSortTypes = new JRadioButtonMenuItem[criteriaName.length]; for (int i = 0; i < criteriaName.length; i++) { m_ItemHMSortTypes[i] = new JRadioButtonMenuItem(criteriaName[i]); final int i2 = i; m_ItemHMSortTypes[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
m_ChasePainter.setHMSortCriteria((SortCriteria.values()[i2]));
hyounesy/ChAsE
src/org/sfu/chase/input/ColorCellRenderer.java
// Path: src/org/sfu/chase/gui/ColorPalette.java // public class ColorPalette // { // public static String[] COLOR_NAMES = {"black","blue","green", "orange", "pink","purple","BYR", "GYR"}; // //public static int[] COLOR_MAX = {0x525252, 0x081D58, 0x00441B, 0xD95F0E, 0xDD3497, 0x54278F}; // //public static int[] COLOR_MED = {0xBDBDBD, 0x1D91C0, 0x90A28D, 0xECAF87, 0xEE9ACB, 0xAA93C7}; // //public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF}; // public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0x0571B0, 0x1A9850}; // public static int[] COLOR_MED = {0x969696, 0x6BAED6, 0x74C476, 0xFD8D3C, 0xF768A1, 0x9E9AC8, 0xFFFFBF, 0xFFFFBF}; // public static int[] COLOR_MAX = {0x252525, 0x08519C, 0x006D2C, 0xA63603, 0x7A0177, 0x54278F, 0xCA0020, 0xD73027}; // // public static ArrayList<String> COLOR_LIST = new ArrayList<String>(Arrays.asList(COLOR_NAMES)); // // int m_ColorIndex = 0; // // public int getColorIndex() // { // return m_ColorIndex; // } // // public void setColorIndex(int index) // { // if (index >= 0 && index < COLOR_NAMES.length) // m_ColorIndex = index; // } // // public String getColorString() // { // return COLOR_NAMES[m_ColorIndex]; // } // // public void setColor(String colorName) // { // int index = COLOR_LIST.indexOf(colorName); // if (index != -1) // m_ColorIndex = index; // } // // public int interpolateColor(double ratio) // { // return COLOR_MAX[m_ColorIndex]; //TODO // } // }
import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.border.Border; import org.sfu.chase.gui.ColorPalette;
package org.sfu.chase.input; /** * Implements a renderer for the color selection drop down */ class ColorCellRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = 1L; protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer(); Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; Color m_Color[]; public ColorCellRenderer() { this.isBordered = true; setOpaque(true); //MUST do this for background to show up. } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String colorStr = (String)value;
// Path: src/org/sfu/chase/gui/ColorPalette.java // public class ColorPalette // { // public static String[] COLOR_NAMES = {"black","blue","green", "orange", "pink","purple","BYR", "GYR"}; // //public static int[] COLOR_MAX = {0x525252, 0x081D58, 0x00441B, 0xD95F0E, 0xDD3497, 0x54278F}; // //public static int[] COLOR_MED = {0xBDBDBD, 0x1D91C0, 0x90A28D, 0xECAF87, 0xEE9ACB, 0xAA93C7}; // //public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF}; // public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0x0571B0, 0x1A9850}; // public static int[] COLOR_MED = {0x969696, 0x6BAED6, 0x74C476, 0xFD8D3C, 0xF768A1, 0x9E9AC8, 0xFFFFBF, 0xFFFFBF}; // public static int[] COLOR_MAX = {0x252525, 0x08519C, 0x006D2C, 0xA63603, 0x7A0177, 0x54278F, 0xCA0020, 0xD73027}; // // public static ArrayList<String> COLOR_LIST = new ArrayList<String>(Arrays.asList(COLOR_NAMES)); // // int m_ColorIndex = 0; // // public int getColorIndex() // { // return m_ColorIndex; // } // // public void setColorIndex(int index) // { // if (index >= 0 && index < COLOR_NAMES.length) // m_ColorIndex = index; // } // // public String getColorString() // { // return COLOR_NAMES[m_ColorIndex]; // } // // public void setColor(String colorName) // { // int index = COLOR_LIST.indexOf(colorName); // if (index != -1) // m_ColorIndex = index; // } // // public int interpolateColor(double ratio) // { // return COLOR_MAX[m_ColorIndex]; //TODO // } // } // Path: src/org/sfu/chase/input/ColorCellRenderer.java import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.border.Border; import org.sfu.chase.gui.ColorPalette; package org.sfu.chase.input; /** * Implements a renderer for the color selection drop down */ class ColorCellRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = 1L; protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer(); Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; Color m_Color[]; public ColorCellRenderer() { this.isBordered = true; setOpaque(true); //MUST do this for background to show up. } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String colorStr = (String)value;
int colorIndex = ColorPalette.COLOR_LIST.indexOf(colorStr);
hyounesy/ChAsE
src/org/sfu/chase/input/ColorRenderer.java
// Path: src/org/sfu/chase/gui/ColorPalette.java // public class ColorPalette // { // public static String[] COLOR_NAMES = {"black","blue","green", "orange", "pink","purple","BYR", "GYR"}; // //public static int[] COLOR_MAX = {0x525252, 0x081D58, 0x00441B, 0xD95F0E, 0xDD3497, 0x54278F}; // //public static int[] COLOR_MED = {0xBDBDBD, 0x1D91C0, 0x90A28D, 0xECAF87, 0xEE9ACB, 0xAA93C7}; // //public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF}; // public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0x0571B0, 0x1A9850}; // public static int[] COLOR_MED = {0x969696, 0x6BAED6, 0x74C476, 0xFD8D3C, 0xF768A1, 0x9E9AC8, 0xFFFFBF, 0xFFFFBF}; // public static int[] COLOR_MAX = {0x252525, 0x08519C, 0x006D2C, 0xA63603, 0x7A0177, 0x54278F, 0xCA0020, 0xD73027}; // // public static ArrayList<String> COLOR_LIST = new ArrayList<String>(Arrays.asList(COLOR_NAMES)); // // int m_ColorIndex = 0; // // public int getColorIndex() // { // return m_ColorIndex; // } // // public void setColorIndex(int index) // { // if (index >= 0 && index < COLOR_NAMES.length) // m_ColorIndex = index; // } // // public String getColorString() // { // return COLOR_NAMES[m_ColorIndex]; // } // // public void setColor(String colorName) // { // int index = COLOR_LIST.indexOf(colorName); // if (index != -1) // m_ColorIndex = index; // } // // public int interpolateColor(double ratio) // { // return COLOR_MAX[m_ColorIndex]; //TODO // } // }
import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.border.Border; import javax.swing.table.TableCellRenderer; import org.sfu.chase.gui.ColorPalette; import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D;
/* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sfu.chase.input; /* * ColorRenderer.java (compiles with releases 1.2, 1.3, and 1.4) is used by * TableDialogEditDemo.java. */ //import java.awt.GradientPaint; //import java.awt.Graphics; //import java.awt.Graphics2D; @SuppressWarnings("serial") public class ColorRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; Color m_Color[]; public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); //MUST do this for background to show up. } public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { //Color newColor = (Color)color; String colorStr = (String)color;
// Path: src/org/sfu/chase/gui/ColorPalette.java // public class ColorPalette // { // public static String[] COLOR_NAMES = {"black","blue","green", "orange", "pink","purple","BYR", "GYR"}; // //public static int[] COLOR_MAX = {0x525252, 0x081D58, 0x00441B, 0xD95F0E, 0xDD3497, 0x54278F}; // //public static int[] COLOR_MED = {0xBDBDBD, 0x1D91C0, 0x90A28D, 0xECAF87, 0xEE9ACB, 0xAA93C7}; // //public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF}; // public static int[] COLOR_MIN = {0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0x0571B0, 0x1A9850}; // public static int[] COLOR_MED = {0x969696, 0x6BAED6, 0x74C476, 0xFD8D3C, 0xF768A1, 0x9E9AC8, 0xFFFFBF, 0xFFFFBF}; // public static int[] COLOR_MAX = {0x252525, 0x08519C, 0x006D2C, 0xA63603, 0x7A0177, 0x54278F, 0xCA0020, 0xD73027}; // // public static ArrayList<String> COLOR_LIST = new ArrayList<String>(Arrays.asList(COLOR_NAMES)); // // int m_ColorIndex = 0; // // public int getColorIndex() // { // return m_ColorIndex; // } // // public void setColorIndex(int index) // { // if (index >= 0 && index < COLOR_NAMES.length) // m_ColorIndex = index; // } // // public String getColorString() // { // return COLOR_NAMES[m_ColorIndex]; // } // // public void setColor(String colorName) // { // int index = COLOR_LIST.indexOf(colorName); // if (index != -1) // m_ColorIndex = index; // } // // public int interpolateColor(double ratio) // { // return COLOR_MAX[m_ColorIndex]; //TODO // } // } // Path: src/org/sfu/chase/input/ColorRenderer.java import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.border.Border; import javax.swing.table.TableCellRenderer; import org.sfu.chase.gui.ColorPalette; import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sfu.chase.input; /* * ColorRenderer.java (compiles with releases 1.2, 1.3, and 1.4) is used by * TableDialogEditDemo.java. */ //import java.awt.GradientPaint; //import java.awt.Graphics; //import java.awt.Graphics2D; @SuppressWarnings("serial") public class ColorRenderer extends JLabel implements TableCellRenderer { Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; Color m_Color[]; public ColorRenderer(boolean isBordered) { this.isBordered = isBordered; setOpaque(true); //MUST do this for background to show up. } public Component getTableCellRendererComponent( JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { //Color newColor = (Color)color; String colorStr = (String)color;
int colorIndex = ColorPalette.COLOR_LIST.indexOf(colorStr);
hyounesy/ChAsE
src/org/sfu/chase/core/ClustStats.java
// Path: src/still/data/Table.java // public interface Table { // // public enum ColType { NUMERIC, ORDINAL, CATEGORICAL, ATTRIBUTE, METADATA } // // public int rows(); // public int columns(); // public boolean hasDirectAccess(); // public double[][] getTable(); // public double[] getPoint( int point_idx ); // public double getMeasurement( int point_idx, int dim ); // public String[] getCategories( int dim ); // public String[] getMetaData(int dim); // public String getMetaData(int dim, int point_idx); // public String getColName( int dim ); // // public String getAttributeString( int dim ); // public ColType[] getColTypes( ); // public ColType getColType( int dim ); // public JPanel getInputControl(); // public boolean hasInputControl(); // public ArrayList<TableListener> getTableListeners(); // public ArrayList<ActionListener> getActionListeners(); // public void addTableListener( TableListener listener ); // public void addActionListener( ActionListener listener ); // public void setMeasurement( int point_idx, int dim, double value ); // public ArrayList<DimensionDescriptor> getConstructedDimensions(); // //public void buildSplit( Map map, Group group ); // }
import java.util.Arrays; import still.data.Table;
package org.sfu.chase.core; public class ClustStats { public double[] m_ColMean; // average of each column. size:[m_NumCols] public double[] m_ColStdDev; // stddev for each column. size:[m_NumCols] public double[][] m_ColHist; // a 1D histogram per column. size:[m_NumCols][m_NumHistBins] public double[][] m_ColQuantile; // quantiles per column. size:[m_NumQuantiles][m_NumCols] public double[][] m_ColPeaks; // peaks per column. size:[m_NumCols][m_NumHistBins] public double[][] m_MeanHist; // histogram of row average size:[numGroups][m_NumHistBins] public double[][] m_PeakHist; // histogram of peaks per group size:[numGroups][m_NumHistBins] public double[][][] m_MeanVsPeak; // histogram of peaks vs Mean per group size:[numGroups][m_NumHistBins][m_NumHistBins] public int m_Count; // number of data points (rows) in this cluster public int m_NumCols; // number of columns (dimensionality) of the clusters public int m_NumHistBins = 10; // histogram bins public int m_NumQuantiles = 5; // number of quantiles. for 5, quantiles are: {min, 1stQ (%25), median, 3rdQ(75%), max} public int m_NumGroups; public int medianIndex() { return (m_NumQuantiles - 1) / 2; }
// Path: src/still/data/Table.java // public interface Table { // // public enum ColType { NUMERIC, ORDINAL, CATEGORICAL, ATTRIBUTE, METADATA } // // public int rows(); // public int columns(); // public boolean hasDirectAccess(); // public double[][] getTable(); // public double[] getPoint( int point_idx ); // public double getMeasurement( int point_idx, int dim ); // public String[] getCategories( int dim ); // public String[] getMetaData(int dim); // public String getMetaData(int dim, int point_idx); // public String getColName( int dim ); // // public String getAttributeString( int dim ); // public ColType[] getColTypes( ); // public ColType getColType( int dim ); // public JPanel getInputControl(); // public boolean hasInputControl(); // public ArrayList<TableListener> getTableListeners(); // public ArrayList<ActionListener> getActionListeners(); // public void addTableListener( TableListener listener ); // public void addActionListener( ActionListener listener ); // public void setMeasurement( int point_idx, int dim, double value ); // public ArrayList<DimensionDescriptor> getConstructedDimensions(); // //public void buildSplit( Map map, Group group ); // } // Path: src/org/sfu/chase/core/ClustStats.java import java.util.Arrays; import still.data.Table; package org.sfu.chase.core; public class ClustStats { public double[] m_ColMean; // average of each column. size:[m_NumCols] public double[] m_ColStdDev; // stddev for each column. size:[m_NumCols] public double[][] m_ColHist; // a 1D histogram per column. size:[m_NumCols][m_NumHistBins] public double[][] m_ColQuantile; // quantiles per column. size:[m_NumQuantiles][m_NumCols] public double[][] m_ColPeaks; // peaks per column. size:[m_NumCols][m_NumHistBins] public double[][] m_MeanHist; // histogram of row average size:[numGroups][m_NumHistBins] public double[][] m_PeakHist; // histogram of peaks per group size:[numGroups][m_NumHistBins] public double[][][] m_MeanVsPeak; // histogram of peaks vs Mean per group size:[numGroups][m_NumHistBins][m_NumHistBins] public int m_Count; // number of data points (rows) in this cluster public int m_NumCols; // number of columns (dimensionality) of the clusters public int m_NumHistBins = 10; // histogram bins public int m_NumQuantiles = 5; // number of quantiles. for 5, quantiles are: {min, 1stQ (%25), median, 3rdQ(75%), max} public int m_NumGroups; public int medianIndex() { return (m_NumQuantiles - 1) / 2; }
public void calcStats(Table table, int[] rows, int cols[], GroupInfo[] groups)
hyounesy/ChAsE
src/still/expression/ExpressionEvent.java
// Path: src/still/data/Table.java // public interface Table { // // public enum ColType { NUMERIC, ORDINAL, CATEGORICAL, ATTRIBUTE, METADATA } // // public int rows(); // public int columns(); // public boolean hasDirectAccess(); // public double[][] getTable(); // public double[] getPoint( int point_idx ); // public double getMeasurement( int point_idx, int dim ); // public String[] getCategories( int dim ); // public String[] getMetaData(int dim); // public String getMetaData(int dim, int point_idx); // public String getColName( int dim ); // // public String getAttributeString( int dim ); // public ColType[] getColTypes( ); // public ColType getColType( int dim ); // public JPanel getInputControl(); // public boolean hasInputControl(); // public ArrayList<TableListener> getTableListeners(); // public ArrayList<ActionListener> getActionListeners(); // public void addTableListener( TableListener listener ); // public void addActionListener( ActionListener listener ); // public void setMeasurement( int point_idx, int dim, double value ); // public ArrayList<DimensionDescriptor> getConstructedDimensions(); // //public void buildSplit( Map map, Group group ); // }
import still.data.Table;
package still.expression; /** * * Informs the expression about terms added or removed from the expression * * @author sfingram * */ public class ExpressionEvent { public enum ExpressionEventType { INVALID, TERM_ADDED, TERM_REMOVED, TERM_CHANGED, TERM_ACTIVATED, NEW_EXPRESSION, NEW_INPUT, EXPRESSION_DELETED } public Object src = null; public ExpressionEventType command = ExpressionEventType.INVALID;
// Path: src/still/data/Table.java // public interface Table { // // public enum ColType { NUMERIC, ORDINAL, CATEGORICAL, ATTRIBUTE, METADATA } // // public int rows(); // public int columns(); // public boolean hasDirectAccess(); // public double[][] getTable(); // public double[] getPoint( int point_idx ); // public double getMeasurement( int point_idx, int dim ); // public String[] getCategories( int dim ); // public String[] getMetaData(int dim); // public String getMetaData(int dim, int point_idx); // public String getColName( int dim ); // // public String getAttributeString( int dim ); // public ColType[] getColTypes( ); // public ColType getColType( int dim ); // public JPanel getInputControl(); // public boolean hasInputControl(); // public ArrayList<TableListener> getTableListeners(); // public ArrayList<ActionListener> getActionListeners(); // public void addTableListener( TableListener listener ); // public void addActionListener( ActionListener listener ); // public void setMeasurement( int point_idx, int dim, double value ); // public ArrayList<DimensionDescriptor> getConstructedDimensions(); // //public void buildSplit( Map map, Group group ); // } // Path: src/still/expression/ExpressionEvent.java import still.data.Table; package still.expression; /** * * Informs the expression about terms added or removed from the expression * * @author sfingram * */ public class ExpressionEvent { public enum ExpressionEventType { INVALID, TERM_ADDED, TERM_REMOVED, TERM_CHANGED, TERM_ACTIVATED, NEW_EXPRESSION, NEW_INPUT, EXPRESSION_DELETED } public Object src = null; public ExpressionEventType command = ExpressionEventType.INVALID;
public Table term = null;
hyounesy/ChAsE
src/still/data/Operator.java
// Path: src/still/gui/OperatorView.java // public abstract class OperatorView extends JPanel implements ActionListener, ComponentListener { // // /** // * // */ // private static final long serialVersionUID = -4170792436892412503L; // protected Operator operator = null; // protected ViewFrameAlt vframe = null; // public int last_vf_loc_x = -1; // public int last_vf_loc_y = -1; // public boolean isTorn = false; // // public ViewFrameAlt getViewFrame() { // // return vframe; // } // // public OperatorView( Operator o ) { // // super(); // // operator = o; // // this.setLayout(new BorderLayout(10,10) ); // } // // public void actionPerformed(ActionEvent e) { // // } // // @Override // public void componentHidden(ComponentEvent e) { // // TODO Auto-generated method stub // // } // // @Override // public void componentMoved(ComponentEvent e) { // // // last_vf_loc_x = (int)vframe.getLocation().getX(); // last_vf_loc_y = (int)vframe.getLocation().getY(); // } // // @Override // public void componentResized(ComponentEvent e) { // // TODO Auto-generated method stub // // } // // @Override // public void componentShown(ComponentEvent e) { // // TODO Auto-generated method stub // // } // // }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import javax.swing.JPanel; import still.gui.OperatorView;
package still.data; //import org.jblas.DoubleMatrix; public abstract class Operator implements Table, TableListener, Serializable { private static final long serialVersionUID = 8808802515298805618L; protected Map map = null; protected Function function = null; public Table input = null;
// Path: src/still/gui/OperatorView.java // public abstract class OperatorView extends JPanel implements ActionListener, ComponentListener { // // /** // * // */ // private static final long serialVersionUID = -4170792436892412503L; // protected Operator operator = null; // protected ViewFrameAlt vframe = null; // public int last_vf_loc_x = -1; // public int last_vf_loc_y = -1; // public boolean isTorn = false; // // public ViewFrameAlt getViewFrame() { // // return vframe; // } // // public OperatorView( Operator o ) { // // super(); // // operator = o; // // this.setLayout(new BorderLayout(10,10) ); // } // // public void actionPerformed(ActionEvent e) { // // } // // @Override // public void componentHidden(ComponentEvent e) { // // TODO Auto-generated method stub // // } // // @Override // public void componentMoved(ComponentEvent e) { // // // last_vf_loc_x = (int)vframe.getLocation().getX(); // last_vf_loc_y = (int)vframe.getLocation().getY(); // } // // @Override // public void componentResized(ComponentEvent e) { // // TODO Auto-generated method stub // // } // // @Override // public void componentShown(ComponentEvent e) { // // TODO Auto-generated method stub // // } // // } // Path: src/still/data/Operator.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import javax.swing.JPanel; import still.gui.OperatorView; package still.data; //import org.jblas.DoubleMatrix; public abstract class Operator implements Table, TableListener, Serializable { private static final long serialVersionUID = 8808802515298805618L; protected Map map = null; protected Function function = null; public Table input = null;
protected transient OperatorView view = null;
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/BaseService.java
// Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // }
import java.util.List; import com.cjlu.newspublish.models.Page;
package com.cjlu.newspublish.services; public interface BaseService<T> { public void saveEntity(T t); public void saveOrUpdateEntity(T t); public void updateEntity(T t); public void deleteEntity(T t); public void batchEntityByHQL(String hql, Object... objects); public T loadEntity(Integer id); public T getEntity(Integer id); public List<T> findEntityByHQL(String hql, Object... objects); public List<T> findAllEntities(); public void executeSQL(String sql, Object... objects); @SuppressWarnings("rawtypes") public List executeSQLQuery(Class clazz, String sql, Object... objects);
// Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // Path: src/com/cjlu/newspublish/services/BaseService.java import java.util.List; import com.cjlu.newspublish.models.Page; package com.cjlu.newspublish.services; public interface BaseService<T> { public void saveEntity(T t); public void saveOrUpdateEntity(T t); public void updateEntity(T t); public void deleteEntity(T t); public void batchEntityByHQL(String hql, Object... objects); public T loadEntity(Integer id); public T getEntity(Integer id); public List<T> findEntityByHQL(String hql, Object... objects); public List<T> findAllEntities(); public void executeSQL(String sql, Object... objects); @SuppressWarnings("rawtypes") public List executeSQLQuery(Class clazz, String sql, Object... objects);
public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize);
yuqirong/NewsPublish
src/com/cjlu/newspublish/utils/ExtractAllRightsUtil.java
// Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // }
import java.io.File; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cjlu.newspublish.services.RightService;
package com.cjlu.newspublish.utils; /** * ÌáÈ¡ËùÓÐȨÏÞ¹¤¾ßÀà */ public final class ExtractAllRightsUtil { private ExtractAllRightsUtil() { } @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // Path: src/com/cjlu/newspublish/utils/ExtractAllRightsUtil.java import java.io.File; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cjlu.newspublish.services.RightService; package com.cjlu.newspublish.utils; /** * ÌáÈ¡ËùÓÐȨÏÞ¹¤¾ßÀà */ public final class ExtractAllRightsUtil { private ExtractAllRightsUtil() { } @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
RightService rs = (RightService) ac.getBean("rightService");
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/RightService.java
// Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // // Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // }
import java.util.List; import java.util.Set; import com.cjlu.newspublish.models.Page; import com.cjlu.newspublish.models.security.Right;
package com.cjlu.newspublish.services; public interface RightService extends BaseService<Right> { public void saveOrUpdateRight(Right model); public void appendRightByURL(String url); public void batchSaveRight(List<Right> allRights); public List<Right> findRightsInRange(Integer[] ownRightIds); public List<Right> findRightsNotInRange(Set<Right> rights); public int getMaxRightPos();
// Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // // Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // Path: src/com/cjlu/newspublish/services/RightService.java import java.util.List; import java.util.Set; import com.cjlu.newspublish.models.Page; import com.cjlu.newspublish.models.security.Right; package com.cjlu.newspublish.services; public interface RightService extends BaseService<Right> { public void saveOrUpdateRight(Right model); public void appendRightByURL(String url); public void batchSaveRight(List<Right> allRights); public List<Right> findRightsInRange(Integer[] ownRightIds); public List<Right> findRightsNotInRange(Set<Right> rights); public int getMaxRightPos();
public Page<Right> listAllRightPage(int i, int pageSize);
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/CommentService.java
// Path: src/com/cjlu/newspublish/models/Comment.java // public class Comment extends BaseEntity { // // private static final long serialVersionUID = -5811934855848613523L; // private String content; // // 评论时间 // private Date createTime = new Date(); // // 评论者 // private User user; // // 评论者的IP地址 // private String ipAddress; // // 评论的新闻 // private News news; // // public Comment() { // // } // // public Comment(String content, Date createTime, User user, // String ipAddress, News news) { // super(); // this.content = content; // this.createTime = createTime; // this.user = user; // this.ipAddress = ipAddress; // this.news = news; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public News getNews() { // return news; // } // // public void setNews(News news) { // this.news = news; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // }
import java.util.List; import com.cjlu.newspublish.models.Comment; import com.cjlu.newspublish.models.User;
package com.cjlu.newspublish.services; public interface CommentService extends BaseService<Comment> { public List<Comment> getViewNewsAllComment(Integer newsId); public void publishComment(String content, String ipAddress,
// Path: src/com/cjlu/newspublish/models/Comment.java // public class Comment extends BaseEntity { // // private static final long serialVersionUID = -5811934855848613523L; // private String content; // // 评论时间 // private Date createTime = new Date(); // // 评论者 // private User user; // // 评论者的IP地址 // private String ipAddress; // // 评论的新闻 // private News news; // // public Comment() { // // } // // public Comment(String content, Date createTime, User user, // String ipAddress, News news) { // super(); // this.content = content; // this.createTime = createTime; // this.user = user; // this.ipAddress = ipAddress; // this.news = news; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public News getNews() { // return news; // } // // public void setNews(News news) { // this.news = news; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // Path: src/com/cjlu/newspublish/services/CommentService.java import java.util.List; import com.cjlu.newspublish.models.Comment; import com.cjlu.newspublish.models.User; package com.cjlu.newspublish.services; public interface CommentService extends BaseService<Comment> { public List<Comment> getViewNewsAllComment(Integer newsId); public void publishComment(String content, String ipAddress,
Integer newsId, User user);
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/NewsService.java
// Path: src/com/cjlu/newspublish/models/News.java // public class News extends BaseEntity { // // private static final long serialVersionUID = 6136633977314509659L; // // 标题 // private String title; // // 关键词 // private String keyword; // // 缩略图,用于轮播器 // private String thumbnail; // // 作者 // private String author; // // 来源 // private String source; // // 正文 // private String content; // // 创建时间 // private Date createTime = new Date(); // // 创建者 // private Admin admin; // // 新闻栏目 // private NewsType newsType; // // 状态 // private State state; // // 访问次数 // private Integer count; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public NewsType getNewsType() { // return newsType; // } // // public void setNewsType(NewsType newsType) { // this.newsType = newsType; // } // // public State getState() { // return state; // } // // public void setState(State state) { // this.state = state; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Admin getAdmin() { // return admin; // } // // public void setAdmin(Admin admin) { // this.admin = admin; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // }
import java.util.List; import com.cjlu.newspublish.models.News; import com.cjlu.newspublish.models.Page;
package com.cjlu.newspublish.services; public interface NewsService extends BaseService<News> { public News getViewNews(Integer id); public void deleteNews(Integer id); public void saveNews(News model, Integer adminId);
// Path: src/com/cjlu/newspublish/models/News.java // public class News extends BaseEntity { // // private static final long serialVersionUID = 6136633977314509659L; // // 标题 // private String title; // // 关键词 // private String keyword; // // 缩略图,用于轮播器 // private String thumbnail; // // 作者 // private String author; // // 来源 // private String source; // // 正文 // private String content; // // 创建时间 // private Date createTime = new Date(); // // 创建者 // private Admin admin; // // 新闻栏目 // private NewsType newsType; // // 状态 // private State state; // // 访问次数 // private Integer count; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public NewsType getNewsType() { // return newsType; // } // // public void setNewsType(NewsType newsType) { // this.newsType = newsType; // } // // public State getState() { // return state; // } // // public void setState(State state) { // this.state = state; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Admin getAdmin() { // return admin; // } // // public void setAdmin(Admin admin) { // this.admin = admin; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // Path: src/com/cjlu/newspublish/services/NewsService.java import java.util.List; import com.cjlu.newspublish.models.News; import com.cjlu.newspublish.models.Page; package com.cjlu.newspublish.services; public interface NewsService extends BaseService<News> { public News getViewNews(Integer id); public void deleteNews(Integer id); public void saveNews(News model, Integer adminId);
public Page<News> listAllNewsPage(int pageNo, int pageSize);
yuqirong/NewsPublish
src/com/cjlu/newspublish/utils/DataUtils.java
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/models/security/Role.java // public class Role extends BaseEntity{ // // private static final long serialVersionUID = 596760102394542763L; // private String roleName; // private String roleValue; // private String roleDesc; // private Set<Right> rights = new HashSet<Right>(); // // public String getRoleName() { // return roleName; // } // public void setRoleName(String roleName) { // this.roleName = roleName; // } // public String getRoleValue() { // return roleValue; // } // public void setRoleValue(String roleValue) { // this.roleValue = roleValue; // } // public String getRoleDesc() { // return roleDesc; // } // public void setRoleDesc(String roleDesc) { // this.roleDesc = roleDesc; // } // public Set<Right> getRights() { // return rights; // } // public void setRights(Set<Right> rights) { // this.rights = rights; // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.models.security.Role;
try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream( byteArrayOutputStream); objectOutputStream.writeObject(serializable); objectOutputStream.close(); byteArrayOutputStream.close(); byte[] bytes = byteArrayOutputStream.toByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( bytes); ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream); Serializable copy = (Serializable) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); return copy; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® */
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/models/security/Role.java // public class Role extends BaseEntity{ // // private static final long serialVersionUID = 596760102394542763L; // private String roleName; // private String roleValue; // private String roleDesc; // private Set<Right> rights = new HashSet<Right>(); // // public String getRoleName() { // return roleName; // } // public void setRoleName(String roleName) { // this.roleName = roleName; // } // public String getRoleValue() { // return roleValue; // } // public void setRoleValue(String roleValue) { // this.roleValue = roleValue; // } // public String getRoleDesc() { // return roleDesc; // } // public void setRoleDesc(String roleDesc) { // this.roleDesc = roleDesc; // } // public Set<Right> getRights() { // return rights; // } // public void setRights(Set<Right> rights) { // this.rights = rights; // } // // } // Path: src/com/cjlu/newspublish/utils/DataUtils.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.models.security.Role; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream( byteArrayOutputStream); objectOutputStream.writeObject(serializable); objectOutputStream.close(); byteArrayOutputStream.close(); byte[] bytes = byteArrayOutputStream.toByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( bytes); ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream); Serializable copy = (Serializable) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); return copy; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® */
public static String extractRightIds(Set<Right> rights) {
yuqirong/NewsPublish
src/com/cjlu/newspublish/utils/DataUtils.java
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/models/security/Role.java // public class Role extends BaseEntity{ // // private static final long serialVersionUID = 596760102394542763L; // private String roleName; // private String roleValue; // private String roleDesc; // private Set<Right> rights = new HashSet<Right>(); // // public String getRoleName() { // return roleName; // } // public void setRoleName(String roleName) { // this.roleName = roleName; // } // public String getRoleValue() { // return roleValue; // } // public void setRoleValue(String roleValue) { // this.roleValue = roleValue; // } // public String getRoleDesc() { // return roleDesc; // } // public void setRoleDesc(String roleDesc) { // this.roleDesc = roleDesc; // } // public Set<Right> getRights() { // return rights; // } // public void setRights(Set<Right> rights) { // this.rights = rights; // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.models.security.Role;
ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream); Serializable copy = (Serializable) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); return copy; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® */ public static String extractRightIds(Set<Right> rights) { StringBuffer buffer = new StringBuffer(); if (ValidateUtils.isValid(rights)) { for (Right r : rights) { buffer.append(r.getId() + ","); } String str = buffer.substring(0, buffer.length() - 1); return str; } return null; }
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/models/security/Role.java // public class Role extends BaseEntity{ // // private static final long serialVersionUID = 596760102394542763L; // private String roleName; // private String roleValue; // private String roleDesc; // private Set<Right> rights = new HashSet<Right>(); // // public String getRoleName() { // return roleName; // } // public void setRoleName(String roleName) { // this.roleName = roleName; // } // public String getRoleValue() { // return roleValue; // } // public void setRoleValue(String roleValue) { // this.roleValue = roleValue; // } // public String getRoleDesc() { // return roleDesc; // } // public void setRoleDesc(String roleDesc) { // this.roleDesc = roleDesc; // } // public Set<Right> getRights() { // return rights; // } // public void setRights(Set<Right> rights) { // this.rights = rights; // } // // } // Path: src/com/cjlu/newspublish/utils/DataUtils.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Set; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.models.security.Role; ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream); Serializable copy = (Serializable) objectInputStream.readObject(); objectInputStream.close(); byteArrayInputStream.close(); return copy; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® */ public static String extractRightIds(Set<Right> rights) { StringBuffer buffer = new StringBuffer(); if (ValidateUtils.isValid(rights)) { for (Right r : rights) { buffer.append(r.getId() + ","); } String str = buffer.substring(0, buffer.length() - 1); return str; } return null; }
public static String extractRoleIds(Set<Role> rights) {
yuqirong/NewsPublish
src/com/cjlu/newspublish/models/News.java
// Path: src/com/cjlu/newspublish/models/security/Admin.java // public class Admin extends BaseEntity { // // private static final long serialVersionUID = -2754043214810493011L; // // Óû§Ãû // private String username; // // ÃÜÂë // private String password; // // Email // private String email; // // ÊÇ·ñÆôÓà // private boolean enabled; // // Á¬ÐøµÇ¼ʧ°Ü´ÎÊý // private Integer loginFailureCount; // // Ëø¶¨ÈÕÆÚ // private Date lockedTime; // // ×îºóµÇ¼ÈÕÆÚ // private Date loginTime; // // ×îºóµÇ¼IP // private String ipAddress; // // ´´½¨Ê±¼ä // private Date createTime = new Date(); // // ÓµÓеÄȨÏÞ // private Set<Role> roles = new HashSet<Role>(); // // ȨÏÞ×ÜºÍ // private long[] rightSum; // // public Integer getLoginFailureCount() { // return loginFailureCount; // } // // public void setLoginFailureCount(Integer loginFailureCount) { // this.loginFailureCount = loginFailureCount; // } // // public Date getLockedTime() { // return lockedTime; // } // // public void setLockedTime(Date lockedTime) { // this.lockedTime = lockedTime; // } // // public Date getLoginTime() { // return loginTime; // } // // public void setLoginTime(Date loginTime) { // this.loginTime = loginTime; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public long[] getRightSum() { // return rightSum; // } // // public void setRightSum(long[] rightSum) { // this.rightSum = rightSum; // } // // /** // * ÅжÏÓû§ÊÇ·ñ¾ßÓÐÖ¸¶¨È¨ÏÞ // */ // public boolean hasRight(Right r) { // int pos = r.getRightPos(); // long code = r.getRightCode(); // return !((rightSum[pos] & code) == 0); // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // /** // * ¼ÆËãÓû§È¨ÏÞ×ÜºÍ // */ // public void calculateRightSum() { // int pos = 0; // long code = 0; // for (Role role : roles) { // for (Right r : role.getRights()) { // pos = r.getRightPos(); // code = r.getRightCode(); // rightSum[pos] = rightSum[pos] | code; // } // } // // ÊÍ·Å×ÊÔ´ // roles = null; // } // // }
import java.util.Date; import com.cjlu.newspublish.models.security.Admin;
package com.cjlu.newspublish.models; /** * 新闻 */ public class News extends BaseEntity { private static final long serialVersionUID = 6136633977314509659L; // 标题 private String title; // 关键词 private String keyword; // 缩略图,用于轮播器 private String thumbnail; // 作者 private String author; // 来源 private String source; // 正文 private String content; // 创建时间 private Date createTime = new Date(); // 创建者
// Path: src/com/cjlu/newspublish/models/security/Admin.java // public class Admin extends BaseEntity { // // private static final long serialVersionUID = -2754043214810493011L; // // Óû§Ãû // private String username; // // ÃÜÂë // private String password; // // Email // private String email; // // ÊÇ·ñÆôÓà // private boolean enabled; // // Á¬ÐøµÇ¼ʧ°Ü´ÎÊý // private Integer loginFailureCount; // // Ëø¶¨ÈÕÆÚ // private Date lockedTime; // // ×îºóµÇ¼ÈÕÆÚ // private Date loginTime; // // ×îºóµÇ¼IP // private String ipAddress; // // ´´½¨Ê±¼ä // private Date createTime = new Date(); // // ÓµÓеÄȨÏÞ // private Set<Role> roles = new HashSet<Role>(); // // ȨÏÞ×ÜºÍ // private long[] rightSum; // // public Integer getLoginFailureCount() { // return loginFailureCount; // } // // public void setLoginFailureCount(Integer loginFailureCount) { // this.loginFailureCount = loginFailureCount; // } // // public Date getLockedTime() { // return lockedTime; // } // // public void setLockedTime(Date lockedTime) { // this.lockedTime = lockedTime; // } // // public Date getLoginTime() { // return loginTime; // } // // public void setLoginTime(Date loginTime) { // this.loginTime = loginTime; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public long[] getRightSum() { // return rightSum; // } // // public void setRightSum(long[] rightSum) { // this.rightSum = rightSum; // } // // /** // * ÅжÏÓû§ÊÇ·ñ¾ßÓÐÖ¸¶¨È¨ÏÞ // */ // public boolean hasRight(Right r) { // int pos = r.getRightPos(); // long code = r.getRightCode(); // return !((rightSum[pos] & code) == 0); // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // /** // * ¼ÆËãÓû§È¨ÏÞ×ÜºÍ // */ // public void calculateRightSum() { // int pos = 0; // long code = 0; // for (Role role : roles) { // for (Right r : role.getRights()) { // pos = r.getRightPos(); // code = r.getRightCode(); // rightSum[pos] = rightSum[pos] | code; // } // } // // ÊÍ·Å×ÊÔ´ // roles = null; // } // // } // Path: src/com/cjlu/newspublish/models/News.java import java.util.Date; import com.cjlu.newspublish.models.security.Admin; package com.cjlu.newspublish.models; /** * 新闻 */ public class News extends BaseEntity { private static final long serialVersionUID = 6136633977314509659L; // 标题 private String title; // 关键词 private String keyword; // 缩略图,用于轮播器 private String thumbnail; // 作者 private String author; // 来源 private String source; // 正文 private String content; // 创建时间 private Date createTime = new Date(); // 创建者
private Admin admin;
yuqirong/NewsPublish
src/com/cjlu/newspublish/utils/WeatherUtils.java
// Path: src/com/cjlu/newspublish/models/Weather.java // public class Weather extends BaseEntity { // // private static final long serialVersionUID = -7231691135362868869L; // // private String province; // private String city; // private String county; // private String jweather; // private String jtemperature; // private String mweather; // private String mtemperature; // private String hweather; // private String htemperature; // private Date updateTime; // // public Weather() { // super(); // } // // public Weather(String province, String city, String county, // String jweather, String jtemperature, String mweather, // String mtemperature, String hweather, String htemperature,Date updateTime) { // this.province = province; // this.city = city; // this.county = county; // this.jweather = jweather; // this.jtemperature = jtemperature; // this.mweather = mweather; // this.mtemperature = mtemperature; // this.hweather = hweather; // this.htemperature = htemperature; // this.updateTime = updateTime; // } // // public String getJweather() { // return jweather; // } // // public void setJweather(String jweather) { // this.jweather = jweather; // } // // public String getJtemperature() { // return jtemperature; // } // // public void setJtemperature(String jtemperature) { // this.jtemperature = jtemperature; // } // // public String getMweather() { // return mweather; // } // // public void setMweather(String mweather) { // this.mweather = mweather; // } // // public String getMtemperature() { // return mtemperature; // } // // public void setMtemperature(String mtemperature) { // this.mtemperature = mtemperature; // } // // public String getHweather() { // return hweather; // } // // public void setHweather(String hweather) { // this.hweather = hweather; // } // // public String getHtemperature() { // return htemperature; // } // // public void setHtemperature(String htemperature) { // this.htemperature = htemperature; // } // // public String getProvince() { // return province; // } // // public void setProvince(String province) { // this.province = province; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getCounty() { // return county; // } // // public void setCounty(String county) { // this.county = county; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.dom4j.DocumentException; import com.cjlu.newspublish.models.Weather;
package com.cjlu.newspublish.utils; /** * ÌìÆø¹¤¾ßÀà * * @author Anyway * */ public class WeatherUtils { private WeatherUtils() { }
// Path: src/com/cjlu/newspublish/models/Weather.java // public class Weather extends BaseEntity { // // private static final long serialVersionUID = -7231691135362868869L; // // private String province; // private String city; // private String county; // private String jweather; // private String jtemperature; // private String mweather; // private String mtemperature; // private String hweather; // private String htemperature; // private Date updateTime; // // public Weather() { // super(); // } // // public Weather(String province, String city, String county, // String jweather, String jtemperature, String mweather, // String mtemperature, String hweather, String htemperature,Date updateTime) { // this.province = province; // this.city = city; // this.county = county; // this.jweather = jweather; // this.jtemperature = jtemperature; // this.mweather = mweather; // this.mtemperature = mtemperature; // this.hweather = hweather; // this.htemperature = htemperature; // this.updateTime = updateTime; // } // // public String getJweather() { // return jweather; // } // // public void setJweather(String jweather) { // this.jweather = jweather; // } // // public String getJtemperature() { // return jtemperature; // } // // public void setJtemperature(String jtemperature) { // this.jtemperature = jtemperature; // } // // public String getMweather() { // return mweather; // } // // public void setMweather(String mweather) { // this.mweather = mweather; // } // // public String getMtemperature() { // return mtemperature; // } // // public void setMtemperature(String mtemperature) { // this.mtemperature = mtemperature; // } // // public String getHweather() { // return hweather; // } // // public void setHweather(String hweather) { // this.hweather = hweather; // } // // public String getHtemperature() { // return htemperature; // } // // public void setHtemperature(String htemperature) { // this.htemperature = htemperature; // } // // public String getProvince() { // return province; // } // // public void setProvince(String province) { // this.province = province; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getCounty() { // return county; // } // // public void setCounty(String county) { // this.county = county; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // } // Path: src/com/cjlu/newspublish/utils/WeatherUtils.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.dom4j.DocumentException; import com.cjlu.newspublish.models.Weather; package com.cjlu.newspublish.utils; /** * ÌìÆø¹¤¾ßÀà * * @author Anyway * */ public class WeatherUtils { private WeatherUtils() { }
public static Weather getWeather(Weather model,
yuqirong/NewsPublish
src/com/cjlu/newspublish/models/NewsType.java
// Path: src/com/cjlu/newspublish/models/security/Admin.java // public class Admin extends BaseEntity { // // private static final long serialVersionUID = -2754043214810493011L; // // Óû§Ãû // private String username; // // ÃÜÂë // private String password; // // Email // private String email; // // ÊÇ·ñÆôÓà // private boolean enabled; // // Á¬ÐøµÇ¼ʧ°Ü´ÎÊý // private Integer loginFailureCount; // // Ëø¶¨ÈÕÆÚ // private Date lockedTime; // // ×îºóµÇ¼ÈÕÆÚ // private Date loginTime; // // ×îºóµÇ¼IP // private String ipAddress; // // ´´½¨Ê±¼ä // private Date createTime = new Date(); // // ÓµÓеÄȨÏÞ // private Set<Role> roles = new HashSet<Role>(); // // ȨÏÞ×ÜºÍ // private long[] rightSum; // // public Integer getLoginFailureCount() { // return loginFailureCount; // } // // public void setLoginFailureCount(Integer loginFailureCount) { // this.loginFailureCount = loginFailureCount; // } // // public Date getLockedTime() { // return lockedTime; // } // // public void setLockedTime(Date lockedTime) { // this.lockedTime = lockedTime; // } // // public Date getLoginTime() { // return loginTime; // } // // public void setLoginTime(Date loginTime) { // this.loginTime = loginTime; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public long[] getRightSum() { // return rightSum; // } // // public void setRightSum(long[] rightSum) { // this.rightSum = rightSum; // } // // /** // * ÅжÏÓû§ÊÇ·ñ¾ßÓÐÖ¸¶¨È¨ÏÞ // */ // public boolean hasRight(Right r) { // int pos = r.getRightPos(); // long code = r.getRightCode(); // return !((rightSum[pos] & code) == 0); // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // /** // * ¼ÆËãÓû§È¨ÏÞ×ÜºÍ // */ // public void calculateRightSum() { // int pos = 0; // long code = 0; // for (Role role : roles) { // for (Right r : role.getRights()) { // pos = r.getRightPos(); // code = r.getRightCode(); // rightSum[pos] = rightSum[pos] | code; // } // } // // ÊÍ·Å×ÊÔ´ // roles = null; // } // // }
import java.util.Date; import com.cjlu.newspublish.models.security.Admin;
package com.cjlu.newspublish.models; /** * 栏目 */ public class NewsType extends BaseEntity{ private static final long serialVersionUID = 8881138029228255355L; // 栏目名称 private String typeName; //栏目介绍 private String introduction; // 创建者
// Path: src/com/cjlu/newspublish/models/security/Admin.java // public class Admin extends BaseEntity { // // private static final long serialVersionUID = -2754043214810493011L; // // Óû§Ãû // private String username; // // ÃÜÂë // private String password; // // Email // private String email; // // ÊÇ·ñÆôÓà // private boolean enabled; // // Á¬ÐøµÇ¼ʧ°Ü´ÎÊý // private Integer loginFailureCount; // // Ëø¶¨ÈÕÆÚ // private Date lockedTime; // // ×îºóµÇ¼ÈÕÆÚ // private Date loginTime; // // ×îºóµÇ¼IP // private String ipAddress; // // ´´½¨Ê±¼ä // private Date createTime = new Date(); // // ÓµÓеÄȨÏÞ // private Set<Role> roles = new HashSet<Role>(); // // ȨÏÞ×ÜºÍ // private long[] rightSum; // // public Integer getLoginFailureCount() { // return loginFailureCount; // } // // public void setLoginFailureCount(Integer loginFailureCount) { // this.loginFailureCount = loginFailureCount; // } // // public Date getLockedTime() { // return lockedTime; // } // // public void setLockedTime(Date lockedTime) { // this.lockedTime = lockedTime; // } // // public Date getLoginTime() { // return loginTime; // } // // public void setLoginTime(Date loginTime) { // this.loginTime = loginTime; // } // // public String getIpAddress() { // return ipAddress; // } // // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public long[] getRightSum() { // return rightSum; // } // // public void setRightSum(long[] rightSum) { // this.rightSum = rightSum; // } // // /** // * ÅжÏÓû§ÊÇ·ñ¾ßÓÐÖ¸¶¨È¨ÏÞ // */ // public boolean hasRight(Right r) { // int pos = r.getRightPos(); // long code = r.getRightCode(); // return !((rightSum[pos] & code) == 0); // } // // public Set<Role> getRoles() { // return roles; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // /** // * ¼ÆËãÓû§È¨ÏÞ×ÜºÍ // */ // public void calculateRightSum() { // int pos = 0; // long code = 0; // for (Role role : roles) { // for (Right r : role.getRights()) { // pos = r.getRightPos(); // code = r.getRightCode(); // rightSum[pos] = rightSum[pos] | code; // } // } // // ÊÍ·Å×ÊÔ´ // roles = null; // } // // } // Path: src/com/cjlu/newspublish/models/NewsType.java import java.util.Date; import com.cjlu.newspublish.models.security.Admin; package com.cjlu.newspublish.models; /** * 栏目 */ public class NewsType extends BaseEntity{ private static final long serialVersionUID = 8881138029228255355L; // 栏目名称 private String typeName; //栏目介绍 private String introduction; // 创建者
private Admin admin;
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/impl/BaseServiceImpl.java
// Path: src/com/cjlu/newspublish/daos/BaseDao.java // public interface BaseDao<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List<T> executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // public List<T> findLimitEntityByHQL(String hql, int start, int end, // Object... objects); // // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // // Path: src/com/cjlu/newspublish/services/BaseService.java // public interface BaseService<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public List<T> findAllEntities(); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // }
import java.lang.reflect.ParameterizedType; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.BaseDao; import com.cjlu.newspublish.models.Page; import com.cjlu.newspublish.services.BaseService;
package com.cjlu.newspublish.services.impl; @Service("baseService") public abstract class BaseServiceImpl<T> implements BaseService<T> { @Autowired
// Path: src/com/cjlu/newspublish/daos/BaseDao.java // public interface BaseDao<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List<T> executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // public List<T> findLimitEntityByHQL(String hql, int start, int end, // Object... objects); // // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // // Path: src/com/cjlu/newspublish/services/BaseService.java // public interface BaseService<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public List<T> findAllEntities(); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // } // Path: src/com/cjlu/newspublish/services/impl/BaseServiceImpl.java import java.lang.reflect.ParameterizedType; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.BaseDao; import com.cjlu.newspublish.models.Page; import com.cjlu.newspublish.services.BaseService; package com.cjlu.newspublish.services.impl; @Service("baseService") public abstract class BaseServiceImpl<T> implements BaseService<T> { @Autowired
private BaseDao<T> baseDao;
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/impl/BaseServiceImpl.java
// Path: src/com/cjlu/newspublish/daos/BaseDao.java // public interface BaseDao<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List<T> executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // public List<T> findLimitEntityByHQL(String hql, int start, int end, // Object... objects); // // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // // Path: src/com/cjlu/newspublish/services/BaseService.java // public interface BaseService<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public List<T> findAllEntities(); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // }
import java.lang.reflect.ParameterizedType; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.BaseDao; import com.cjlu.newspublish.models.Page; import com.cjlu.newspublish.services.BaseService;
public void updateEntity(T t) { baseDao.updateEntity(t); } public void deleteEntity(T t) { baseDao.deleteEntity(t); } public void batchEntityByHQL(String hql, Object... objects) { baseDao.batchEntityByHQL(hql, objects); } public T loadEntity(Integer id) { return baseDao.loadEntity(id); } public T getEntity(Integer id) { return baseDao.getEntity(id); } public List<T> findEntityByHQL(String hql, Object... objects) { return baseDao.findEntityByHQL(hql, objects); } public List<T> findAllEntities() { String hql = "from " + clazz.getSimpleName(); return this.findEntityByHQL(hql); } @Override
// Path: src/com/cjlu/newspublish/daos/BaseDao.java // public interface BaseDao<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List<T> executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // public List<T> findLimitEntityByHQL(String hql, int start, int end, // Object... objects); // // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // // Path: src/com/cjlu/newspublish/services/BaseService.java // public interface BaseService<T> { // // public void saveEntity(T t); // // public void saveOrUpdateEntity(T t); // // public void updateEntity(T t); // // public void deleteEntity(T t); // // public void batchEntityByHQL(String hql, Object... objects); // // public T loadEntity(Integer id); // // public T getEntity(Integer id); // // public List<T> findEntityByHQL(String hql, Object... objects); // // public List<T> findAllEntities(); // // public void executeSQL(String sql, Object... objects); // // @SuppressWarnings("rawtypes") // public List executeSQLQuery(Class clazz, String sql, Object... objects); // // public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize); // // } // Path: src/com/cjlu/newspublish/services/impl/BaseServiceImpl.java import java.lang.reflect.ParameterizedType; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.BaseDao; import com.cjlu.newspublish.models.Page; import com.cjlu.newspublish.services.BaseService; public void updateEntity(T t) { baseDao.updateEntity(t); } public void deleteEntity(T t) { baseDao.deleteEntity(t); } public void batchEntityByHQL(String hql, Object... objects) { baseDao.batchEntityByHQL(hql, objects); } public T loadEntity(Integer id) { return baseDao.loadEntity(id); } public T getEntity(Integer id) { return baseDao.getEntity(id); } public List<T> findEntityByHQL(String hql, Object... objects) { return baseDao.findEntityByHQL(hql, objects); } public List<T> findAllEntities() { String hql = "from " + clazz.getSimpleName(); return this.findEntityByHQL(hql); } @Override
public Page<T> listPage(String hql,String hql2,int pageNo, int pageSize) {
yuqirong/NewsPublish
src/com/cjlu/newspublish/listener/InitRightListener.java
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.services.RightService;
package com.cjlu.newspublish.listener; @SuppressWarnings("rawtypes") @Component public class InitRightListener implements ApplicationListener, ServletContextAware { private ServletContext servletContext; @Autowired
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // Path: src/com/cjlu/newspublish/listener/InitRightListener.java import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.services.RightService; package com.cjlu.newspublish.listener; @SuppressWarnings("rawtypes") @Component public class InitRightListener implements ApplicationListener, ServletContextAware { private ServletContext servletContext; @Autowired
private RightService rightService;
yuqirong/NewsPublish
src/com/cjlu/newspublish/listener/InitRightListener.java
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.services.RightService;
package com.cjlu.newspublish.listener; @SuppressWarnings("rawtypes") @Component public class InitRightListener implements ApplicationListener, ServletContextAware { private ServletContext servletContext; @Autowired private RightService rightService; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void onApplicationEvent(ApplicationEvent arg0) { // ÉÏÏÂÎÄË¢ÐÂʼþ if (arg0 instanceof ContextRefreshedEvent) { // ²é³öËùÓÐȨÏÞ
// Path: src/com/cjlu/newspublish/models/security/Right.java // public class Right extends BaseEntity{ // // private static final long serialVersionUID = -7550772473227188714L; // private String rightName = "δÃüÃû"; // private String rightUrl; // private boolean common; // private String rightDesc; // private long rightCode;// ȨÏÞÂë,1<<n // private int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼ // // public String getRightName() { // return rightName; // } // public void setRightName(String rightName) { // this.rightName = rightName; // } // public String getRightUrl() { // return rightUrl; // } // public void setRightUrl(String rightUrl) { // this.rightUrl = rightUrl; // } // public String getRightDesc() { // return rightDesc; // } // public void setRightDesc(String rightDesc) { // this.rightDesc = rightDesc; // } // public long getRightCode() { // return rightCode; // } // public void setRightCode(long rightCode) { // this.rightCode = rightCode; // } // public int getRightPos() { // return rightPos; // } // public void setRightPos(int rightPos) { // this.rightPos = rightPos; // } // public boolean isCommon() { // return common; // } // public void setCommon(boolean common) { // this.common = common; // } // // } // // Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // Path: src/com/cjlu/newspublish/listener/InitRightListener.java import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.services.RightService; package com.cjlu.newspublish.listener; @SuppressWarnings("rawtypes") @Component public class InitRightListener implements ApplicationListener, ServletContextAware { private ServletContext servletContext; @Autowired private RightService rightService; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void onApplicationEvent(ApplicationEvent arg0) { // ÉÏÏÂÎÄË¢ÐÂʼþ if (arg0 instanceof ContextRefreshedEvent) { // ²é³öËùÓÐȨÏÞ
List<Right> rights = rightService.findAllEntities();
yuqirong/NewsPublish
src/com/cjlu/newspublish/cache/NewsPublishKeyGenerator.java
// Path: src/com/cjlu/newspublish/utils/StringUtils.java // public final class StringUtils { // // private StringUtils(){ // // } // // /** // * ½«×Ö·û´®×ª»»Îª×Ö·û´®Êý×é // */ // public static String[] string2Arr(String str, String tag) { // if (ValidateUtils.isValid(str)) { // String[] arr = str.split(tag); // return arr; // } // return null; // } // // /** // * ²éѯһ¸ö×Ö·û´®Êý×éÖÐÊÇ·ñ°üº¬Ä³×Ö·û´® // */ // public static boolean contains(String[] values, String value) { // if (ValidateUtils.isValid(value)) { // for (String str : values) { // if (str.equals(value)) // return true; // } // } // return false; // } // // /** // * ½«×Ö·û´®Êý×éת»»Îª×Ö·û´® // */ // public static String arr2String(Object[] str) { // if (ValidateUtils.isValid(str)) { // StringBuffer stringBuffer = new StringBuffer(); // for (Object s : str) { // stringBuffer.append(s + ","); // } // return stringBuffer.substring(0, stringBuffer.length() - 1); // } // return null; // } // // /** // * Èô×Ö·û´®³¤¶È³¬³ö·¶Î§£¬Ôò½ØÈ¡Ò»²¿·Ö // */ // public static String getDescString(String str, int length) { // if (str != null && str.trim().length() > length) { // return str.substring(0, length); // } // return str; // } // }
import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import com.cjlu.newspublish.utils.StringUtils;
package com.cjlu.newspublish.cache; /** * ¼üÖµÉú³ÉÆ÷ */ public class NewsPublishKeyGenerator implements KeyGenerator { @Override public Object generate(Object arg0, Method arg1, Object... arg2) { String className = arg0.getClass().getSimpleName(); String mname = arg1.getName();
// Path: src/com/cjlu/newspublish/utils/StringUtils.java // public final class StringUtils { // // private StringUtils(){ // // } // // /** // * ½«×Ö·û´®×ª»»Îª×Ö·û´®Êý×é // */ // public static String[] string2Arr(String str, String tag) { // if (ValidateUtils.isValid(str)) { // String[] arr = str.split(tag); // return arr; // } // return null; // } // // /** // * ²éѯһ¸ö×Ö·û´®Êý×éÖÐÊÇ·ñ°üº¬Ä³×Ö·û´® // */ // public static boolean contains(String[] values, String value) { // if (ValidateUtils.isValid(value)) { // for (String str : values) { // if (str.equals(value)) // return true; // } // } // return false; // } // // /** // * ½«×Ö·û´®Êý×éת»»Îª×Ö·û´® // */ // public static String arr2String(Object[] str) { // if (ValidateUtils.isValid(str)) { // StringBuffer stringBuffer = new StringBuffer(); // for (Object s : str) { // stringBuffer.append(s + ","); // } // return stringBuffer.substring(0, stringBuffer.length() - 1); // } // return null; // } // // /** // * Èô×Ö·û´®³¤¶È³¬³ö·¶Î§£¬Ôò½ØÈ¡Ò»²¿·Ö // */ // public static String getDescString(String str, int length) { // if (str != null && str.trim().length() > length) { // return str.substring(0, length); // } // return str; // } // } // Path: src/com/cjlu/newspublish/cache/NewsPublishKeyGenerator.java import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import com.cjlu.newspublish.utils.StringUtils; package com.cjlu.newspublish.cache; /** * ¼üÖµÉú³ÉÆ÷ */ public class NewsPublishKeyGenerator implements KeyGenerator { @Override public Object generate(Object arg0, Method arg1, Object... arg2) { String className = arg0.getClass().getSimpleName(); String mname = arg1.getName();
String params = StringUtils.arr2String(arg2);
yuqirong/NewsPublish
src/com/cjlu/newspublish/interceptor/CatchUrlInterceptor.java
// Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // // Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // }
import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.cjlu.newspublish.services.RightService; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.interceptor.Interceptor;
package com.cjlu.newspublish.interceptor; public class CatchUrlInterceptor implements Interceptor { private static final long serialVersionUID = 1L; @Override public void destroy() { } @Override public void init() { } @Override public String intercept(ActionInvocation invocation) throws Exception { ActionProxy proxy = invocation.getProxy(); String nameSpace = proxy.getNamespace(); String actionName = proxy.getActionName();
// Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // // Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // } // Path: src/com/cjlu/newspublish/interceptor/CatchUrlInterceptor.java import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.cjlu.newspublish.services.RightService; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.interceptor.Interceptor; package com.cjlu.newspublish.interceptor; public class CatchUrlInterceptor implements Interceptor { private static final long serialVersionUID = 1L; @Override public void destroy() { } @Override public void init() { } @Override public String intercept(ActionInvocation invocation) throws Exception { ActionProxy proxy = invocation.getProxy(); String nameSpace = proxy.getNamespace(); String actionName = proxy.getActionName();
if (!ValidateUtils.isValid(nameSpace) || nameSpace.equals("/")) {
yuqirong/NewsPublish
src/com/cjlu/newspublish/interceptor/CatchUrlInterceptor.java
// Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // // Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // }
import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.cjlu.newspublish.services.RightService; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.interceptor.Interceptor;
package com.cjlu.newspublish.interceptor; public class CatchUrlInterceptor implements Interceptor { private static final long serialVersionUID = 1L; @Override public void destroy() { } @Override public void init() { } @Override public String intercept(ActionInvocation invocation) throws Exception { ActionProxy proxy = invocation.getProxy(); String nameSpace = proxy.getNamespace(); String actionName = proxy.getActionName(); if (!ValidateUtils.isValid(nameSpace) || nameSpace.equals("/")) { nameSpace = ""; } String url = nameSpace + "/" + actionName; ServletContext servletContext = ServletActionContext .getServletContext(); ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(servletContext);
// Path: src/com/cjlu/newspublish/services/RightService.java // public interface RightService extends BaseService<Right> { // // public void saveOrUpdateRight(Right model); // // public void appendRightByURL(String url); // // public void batchSaveRight(List<Right> allRights); // // public List<Right> findRightsInRange(Integer[] ownRightIds); // // public List<Right> findRightsNotInRange(Set<Right> rights); // // public int getMaxRightPos(); // // public Page<Right> listAllRightPage(int i, int pageSize); // // } // // Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // } // Path: src/com/cjlu/newspublish/interceptor/CatchUrlInterceptor.java import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.cjlu.newspublish.services.RightService; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.interceptor.Interceptor; package com.cjlu.newspublish.interceptor; public class CatchUrlInterceptor implements Interceptor { private static final long serialVersionUID = 1L; @Override public void destroy() { } @Override public void init() { } @Override public String intercept(ActionInvocation invocation) throws Exception { ActionProxy proxy = invocation.getProxy(); String nameSpace = proxy.getNamespace(); String actionName = proxy.getActionName(); if (!ValidateUtils.isValid(nameSpace) || nameSpace.equals("/")) { nameSpace = ""; } String url = nameSpace + "/" + actionName; ServletContext servletContext = ServletActionContext .getServletContext(); ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(servletContext);
RightService rs = (RightService) applicationContext
yuqirong/NewsPublish
src/org/apache/struts2/views/jsp/ui/SubmitTag.java
// Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; import org.apache.struts2.components.Component; import org.apache.struts2.components.Submit; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.util.ValueStack;
this.method = method; } public void setAlign(String align) { this.align = align; } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setSrc(String src) { this.src = src; } public int doStartTag() throws JspException { return hasRight()?super.doStartTag() : SKIP_BODY; } public int doEndTag() throws JspException { return hasRight()?super.doEndTag() : SKIP_BODY; } private boolean hasRight(){ String ns = getFormNamespace(); String actionName = getValidActionName();
// Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // } // Path: src/org/apache/struts2/views/jsp/ui/SubmitTag.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; import org.apache.struts2.components.Component; import org.apache.struts2.components.Submit; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.util.ValueStack; this.method = method; } public void setAlign(String align) { this.align = align; } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setSrc(String src) { this.src = src; } public int doStartTag() throws JspException { return hasRight()?super.doStartTag() : SKIP_BODY; } public int doEndTag() throws JspException { return hasRight()?super.doEndTag() : SKIP_BODY; } private boolean hasRight(){ String ns = getFormNamespace(); String actionName = getValidActionName();
return ValidateUtils.hasRight(ns, actionName, (HttpServletRequest)pageContext.getRequest(), null);
yuqirong/NewsPublish
src/com/cjlu/newspublish/daos/impl/NewsDaoImpl.java
// Path: src/com/cjlu/newspublish/models/News.java // public class News extends BaseEntity { // // private static final long serialVersionUID = 6136633977314509659L; // // 标题 // private String title; // // 关键词 // private String keyword; // // 缩略图,用于轮播器 // private String thumbnail; // // 作者 // private String author; // // 来源 // private String source; // // 正文 // private String content; // // 创建时间 // private Date createTime = new Date(); // // 创建者 // private Admin admin; // // 新闻栏目 // private NewsType newsType; // // 状态 // private State state; // // 访问次数 // private Integer count; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public NewsType getNewsType() { // return newsType; // } // // public void setNewsType(NewsType newsType) { // this.newsType = newsType; // } // // public State getState() { // return state; // } // // public void setState(State state) { // this.state = state; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Admin getAdmin() { // return admin; // } // // public void setAdmin(Admin admin) { // this.admin = admin; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // }
import java.util.List; import org.springframework.stereotype.Repository; import com.cjlu.newspublish.models.News; import com.cjlu.newspublish.models.Page;
package com.cjlu.newspublish.daos.impl; @Repository("newsDao") public class NewsDaoImpl extends BaseDaoImpl<News> { public List<News> getAllNewsByNewsType(Integer typeId) { String hql = "FROM News n WHERE n.newsType.id = ?"; return this.findEntityByHQL(hql, typeId); }
// Path: src/com/cjlu/newspublish/models/News.java // public class News extends BaseEntity { // // private static final long serialVersionUID = 6136633977314509659L; // // 标题 // private String title; // // 关键词 // private String keyword; // // 缩略图,用于轮播器 // private String thumbnail; // // 作者 // private String author; // // 来源 // private String source; // // 正文 // private String content; // // 创建时间 // private Date createTime = new Date(); // // 创建者 // private Admin admin; // // 新闻栏目 // private NewsType newsType; // // 状态 // private State state; // // 访问次数 // private Integer count; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public NewsType getNewsType() { // return newsType; // } // // public void setNewsType(NewsType newsType) { // this.newsType = newsType; // } // // public State getState() { // return state; // } // // public void setState(State state) { // this.state = state; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public Admin getAdmin() { // return admin; // } // // public void setAdmin(Admin admin) { // this.admin = admin; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // // Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // Path: src/com/cjlu/newspublish/daos/impl/NewsDaoImpl.java import java.util.List; import org.springframework.stereotype.Repository; import com.cjlu.newspublish.models.News; import com.cjlu.newspublish.models.Page; package com.cjlu.newspublish.daos.impl; @Repository("newsDao") public class NewsDaoImpl extends BaseDaoImpl<News> { public List<News> getAllNewsByNewsType(Integer typeId) { String hql = "FROM News n WHERE n.newsType.id = ?"; return this.findEntityByHQL(hql, typeId); }
public Page<News> listAllNotPassedNewsPage(int pageNo, int pageSize) {
yuqirong/NewsPublish
src/com/cjlu/newspublish/actions/impl/UserAction.java
// Path: src/com/cjlu/newspublish/actions/BaseAction.java // @SuppressWarnings("unchecked") // public abstract class BaseAction<T> extends ActionSupport implements // ModelDriven<T>, Preparable, RequestAware, SessionAware ,ApplicationAware{ // // private static final long serialVersionUID = 1L; // public T model; // protected Map<String, Object> sessionMap; // protected Map<String, Object> requestMap; // @SuppressWarnings("unused") // private Map<String, Object> applicationMap; // protected HttpSession httpSession = ServletActionContext.getRequest().getSession(); // protected HttpServletRequest httpRequest = ServletActionContext.getRequest(); // protected HttpServletResponse httpResponse = ServletActionContext.getResponse(); // protected ServletContext application = ServletActionContext.getRequest().getSession().getServletContext(); // protected InputStream inputStream; // protected VerificationCodeUtils vcu = VerificationCodeUtils.Instance(); // // // public InputStream getInputStream() { // return inputStream; // } // // public void setInputStream(InputStream inputStream) { // this.inputStream = inputStream; // } // // public BaseAction() { // try { // model = (T) ReflectionUtils.getSuperGenericType(this.getClass()) // .newInstance(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void prepare() throws Exception { // // } // // public void writeJSON(Object obj) throws IOException{ // ObjectMapper om = new ObjectMapper(); // String str = null; // try { // str = om.writeValueAsString(obj); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().setContentType("text/html"); // ServletActionContext.getResponse().setCharacterEncoding("utf-8"); // try { // ServletActionContext.getResponse().getWriter().printf(str); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().getWriter().flush(); // ServletActionContext.getResponse().getWriter().close(); // } // // @Override // public T getModel() { // return model; // } // // @Override // public void setSession(Map<String, Object> sessionMap){ // this.sessionMap = sessionMap; // } // // @Override // public void setRequest(Map<String, Object> requestMap){ // this.requestMap = requestMap; // } // // @Override // public void setApplication(Map<String, Object> applicationMap) { // this.applicationMap = applicationMap; // } // // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/services/UserService.java // public interface UserService extends BaseService<User>{ // // public boolean isTokenUp(String str); // // public User isUser(String username,String password); // // public void deleteUser(Integer id); // // }
import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javassist.bytecode.stackmap.TypeData.ClassName; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cjlu.newspublish.actions.BaseAction; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.services.UserService;
package com.cjlu.newspublish.actions.impl; @Controller @Scope("prototype")
// Path: src/com/cjlu/newspublish/actions/BaseAction.java // @SuppressWarnings("unchecked") // public abstract class BaseAction<T> extends ActionSupport implements // ModelDriven<T>, Preparable, RequestAware, SessionAware ,ApplicationAware{ // // private static final long serialVersionUID = 1L; // public T model; // protected Map<String, Object> sessionMap; // protected Map<String, Object> requestMap; // @SuppressWarnings("unused") // private Map<String, Object> applicationMap; // protected HttpSession httpSession = ServletActionContext.getRequest().getSession(); // protected HttpServletRequest httpRequest = ServletActionContext.getRequest(); // protected HttpServletResponse httpResponse = ServletActionContext.getResponse(); // protected ServletContext application = ServletActionContext.getRequest().getSession().getServletContext(); // protected InputStream inputStream; // protected VerificationCodeUtils vcu = VerificationCodeUtils.Instance(); // // // public InputStream getInputStream() { // return inputStream; // } // // public void setInputStream(InputStream inputStream) { // this.inputStream = inputStream; // } // // public BaseAction() { // try { // model = (T) ReflectionUtils.getSuperGenericType(this.getClass()) // .newInstance(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void prepare() throws Exception { // // } // // public void writeJSON(Object obj) throws IOException{ // ObjectMapper om = new ObjectMapper(); // String str = null; // try { // str = om.writeValueAsString(obj); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().setContentType("text/html"); // ServletActionContext.getResponse().setCharacterEncoding("utf-8"); // try { // ServletActionContext.getResponse().getWriter().printf(str); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().getWriter().flush(); // ServletActionContext.getResponse().getWriter().close(); // } // // @Override // public T getModel() { // return model; // } // // @Override // public void setSession(Map<String, Object> sessionMap){ // this.sessionMap = sessionMap; // } // // @Override // public void setRequest(Map<String, Object> requestMap){ // this.requestMap = requestMap; // } // // @Override // public void setApplication(Map<String, Object> applicationMap) { // this.applicationMap = applicationMap; // } // // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/services/UserService.java // public interface UserService extends BaseService<User>{ // // public boolean isTokenUp(String str); // // public User isUser(String username,String password); // // public void deleteUser(Integer id); // // } // Path: src/com/cjlu/newspublish/actions/impl/UserAction.java import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javassist.bytecode.stackmap.TypeData.ClassName; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cjlu.newspublish.actions.BaseAction; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.services.UserService; package com.cjlu.newspublish.actions.impl; @Controller @Scope("prototype")
public class UserAction extends BaseAction<User> {
yuqirong/NewsPublish
src/com/cjlu/newspublish/actions/impl/UserAction.java
// Path: src/com/cjlu/newspublish/actions/BaseAction.java // @SuppressWarnings("unchecked") // public abstract class BaseAction<T> extends ActionSupport implements // ModelDriven<T>, Preparable, RequestAware, SessionAware ,ApplicationAware{ // // private static final long serialVersionUID = 1L; // public T model; // protected Map<String, Object> sessionMap; // protected Map<String, Object> requestMap; // @SuppressWarnings("unused") // private Map<String, Object> applicationMap; // protected HttpSession httpSession = ServletActionContext.getRequest().getSession(); // protected HttpServletRequest httpRequest = ServletActionContext.getRequest(); // protected HttpServletResponse httpResponse = ServletActionContext.getResponse(); // protected ServletContext application = ServletActionContext.getRequest().getSession().getServletContext(); // protected InputStream inputStream; // protected VerificationCodeUtils vcu = VerificationCodeUtils.Instance(); // // // public InputStream getInputStream() { // return inputStream; // } // // public void setInputStream(InputStream inputStream) { // this.inputStream = inputStream; // } // // public BaseAction() { // try { // model = (T) ReflectionUtils.getSuperGenericType(this.getClass()) // .newInstance(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void prepare() throws Exception { // // } // // public void writeJSON(Object obj) throws IOException{ // ObjectMapper om = new ObjectMapper(); // String str = null; // try { // str = om.writeValueAsString(obj); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().setContentType("text/html"); // ServletActionContext.getResponse().setCharacterEncoding("utf-8"); // try { // ServletActionContext.getResponse().getWriter().printf(str); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().getWriter().flush(); // ServletActionContext.getResponse().getWriter().close(); // } // // @Override // public T getModel() { // return model; // } // // @Override // public void setSession(Map<String, Object> sessionMap){ // this.sessionMap = sessionMap; // } // // @Override // public void setRequest(Map<String, Object> requestMap){ // this.requestMap = requestMap; // } // // @Override // public void setApplication(Map<String, Object> applicationMap) { // this.applicationMap = applicationMap; // } // // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/services/UserService.java // public interface UserService extends BaseService<User>{ // // public boolean isTokenUp(String str); // // public User isUser(String username,String password); // // public void deleteUser(Integer id); // // }
import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javassist.bytecode.stackmap.TypeData.ClassName; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cjlu.newspublish.actions.BaseAction; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.services.UserService;
package com.cjlu.newspublish.actions.impl; @Controller @Scope("prototype")
// Path: src/com/cjlu/newspublish/actions/BaseAction.java // @SuppressWarnings("unchecked") // public abstract class BaseAction<T> extends ActionSupport implements // ModelDriven<T>, Preparable, RequestAware, SessionAware ,ApplicationAware{ // // private static final long serialVersionUID = 1L; // public T model; // protected Map<String, Object> sessionMap; // protected Map<String, Object> requestMap; // @SuppressWarnings("unused") // private Map<String, Object> applicationMap; // protected HttpSession httpSession = ServletActionContext.getRequest().getSession(); // protected HttpServletRequest httpRequest = ServletActionContext.getRequest(); // protected HttpServletResponse httpResponse = ServletActionContext.getResponse(); // protected ServletContext application = ServletActionContext.getRequest().getSession().getServletContext(); // protected InputStream inputStream; // protected VerificationCodeUtils vcu = VerificationCodeUtils.Instance(); // // // public InputStream getInputStream() { // return inputStream; // } // // public void setInputStream(InputStream inputStream) { // this.inputStream = inputStream; // } // // public BaseAction() { // try { // model = (T) ReflectionUtils.getSuperGenericType(this.getClass()) // .newInstance(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void prepare() throws Exception { // // } // // public void writeJSON(Object obj) throws IOException{ // ObjectMapper om = new ObjectMapper(); // String str = null; // try { // str = om.writeValueAsString(obj); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().setContentType("text/html"); // ServletActionContext.getResponse().setCharacterEncoding("utf-8"); // try { // ServletActionContext.getResponse().getWriter().printf(str); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().getWriter().flush(); // ServletActionContext.getResponse().getWriter().close(); // } // // @Override // public T getModel() { // return model; // } // // @Override // public void setSession(Map<String, Object> sessionMap){ // this.sessionMap = sessionMap; // } // // @Override // public void setRequest(Map<String, Object> requestMap){ // this.requestMap = requestMap; // } // // @Override // public void setApplication(Map<String, Object> applicationMap) { // this.applicationMap = applicationMap; // } // // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/services/UserService.java // public interface UserService extends BaseService<User>{ // // public boolean isTokenUp(String str); // // public User isUser(String username,String password); // // public void deleteUser(Integer id); // // } // Path: src/com/cjlu/newspublish/actions/impl/UserAction.java import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javassist.bytecode.stackmap.TypeData.ClassName; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cjlu.newspublish.actions.BaseAction; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.services.UserService; package com.cjlu.newspublish.actions.impl; @Controller @Scope("prototype")
public class UserAction extends BaseAction<User> {
yuqirong/NewsPublish
src/com/cjlu/newspublish/actions/impl/UserAction.java
// Path: src/com/cjlu/newspublish/actions/BaseAction.java // @SuppressWarnings("unchecked") // public abstract class BaseAction<T> extends ActionSupport implements // ModelDriven<T>, Preparable, RequestAware, SessionAware ,ApplicationAware{ // // private static final long serialVersionUID = 1L; // public T model; // protected Map<String, Object> sessionMap; // protected Map<String, Object> requestMap; // @SuppressWarnings("unused") // private Map<String, Object> applicationMap; // protected HttpSession httpSession = ServletActionContext.getRequest().getSession(); // protected HttpServletRequest httpRequest = ServletActionContext.getRequest(); // protected HttpServletResponse httpResponse = ServletActionContext.getResponse(); // protected ServletContext application = ServletActionContext.getRequest().getSession().getServletContext(); // protected InputStream inputStream; // protected VerificationCodeUtils vcu = VerificationCodeUtils.Instance(); // // // public InputStream getInputStream() { // return inputStream; // } // // public void setInputStream(InputStream inputStream) { // this.inputStream = inputStream; // } // // public BaseAction() { // try { // model = (T) ReflectionUtils.getSuperGenericType(this.getClass()) // .newInstance(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void prepare() throws Exception { // // } // // public void writeJSON(Object obj) throws IOException{ // ObjectMapper om = new ObjectMapper(); // String str = null; // try { // str = om.writeValueAsString(obj); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().setContentType("text/html"); // ServletActionContext.getResponse().setCharacterEncoding("utf-8"); // try { // ServletActionContext.getResponse().getWriter().printf(str); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().getWriter().flush(); // ServletActionContext.getResponse().getWriter().close(); // } // // @Override // public T getModel() { // return model; // } // // @Override // public void setSession(Map<String, Object> sessionMap){ // this.sessionMap = sessionMap; // } // // @Override // public void setRequest(Map<String, Object> requestMap){ // this.requestMap = requestMap; // } // // @Override // public void setApplication(Map<String, Object> applicationMap) { // this.applicationMap = applicationMap; // } // // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/services/UserService.java // public interface UserService extends BaseService<User>{ // // public boolean isTokenUp(String str); // // public User isUser(String username,String password); // // public void deleteUser(Integer id); // // }
import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javassist.bytecode.stackmap.TypeData.ClassName; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cjlu.newspublish.actions.BaseAction; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.services.UserService;
package com.cjlu.newspublish.actions.impl; @Controller @Scope("prototype") public class UserAction extends BaseAction<User> { private static final long serialVersionUID = 2206176605307115958L; @Autowired
// Path: src/com/cjlu/newspublish/actions/BaseAction.java // @SuppressWarnings("unchecked") // public abstract class BaseAction<T> extends ActionSupport implements // ModelDriven<T>, Preparable, RequestAware, SessionAware ,ApplicationAware{ // // private static final long serialVersionUID = 1L; // public T model; // protected Map<String, Object> sessionMap; // protected Map<String, Object> requestMap; // @SuppressWarnings("unused") // private Map<String, Object> applicationMap; // protected HttpSession httpSession = ServletActionContext.getRequest().getSession(); // protected HttpServletRequest httpRequest = ServletActionContext.getRequest(); // protected HttpServletResponse httpResponse = ServletActionContext.getResponse(); // protected ServletContext application = ServletActionContext.getRequest().getSession().getServletContext(); // protected InputStream inputStream; // protected VerificationCodeUtils vcu = VerificationCodeUtils.Instance(); // // // public InputStream getInputStream() { // return inputStream; // } // // public void setInputStream(InputStream inputStream) { // this.inputStream = inputStream; // } // // public BaseAction() { // try { // model = (T) ReflectionUtils.getSuperGenericType(this.getClass()) // .newInstance(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void prepare() throws Exception { // // } // // public void writeJSON(Object obj) throws IOException{ // ObjectMapper om = new ObjectMapper(); // String str = null; // try { // str = om.writeValueAsString(obj); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().setContentType("text/html"); // ServletActionContext.getResponse().setCharacterEncoding("utf-8"); // try { // ServletActionContext.getResponse().getWriter().printf(str); // } catch (Exception e) { // e.printStackTrace(); // } // ServletActionContext.getResponse().getWriter().flush(); // ServletActionContext.getResponse().getWriter().close(); // } // // @Override // public T getModel() { // return model; // } // // @Override // public void setSession(Map<String, Object> sessionMap){ // this.sessionMap = sessionMap; // } // // @Override // public void setRequest(Map<String, Object> requestMap){ // this.requestMap = requestMap; // } // // @Override // public void setApplication(Map<String, Object> applicationMap) { // this.applicationMap = applicationMap; // } // // } // // Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/services/UserService.java // public interface UserService extends BaseService<User>{ // // public boolean isTokenUp(String str); // // public User isUser(String username,String password); // // public void deleteUser(Integer id); // // } // Path: src/com/cjlu/newspublish/actions/impl/UserAction.java import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javassist.bytecode.stackmap.TypeData.ClassName; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.cjlu.newspublish.actions.BaseAction; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.services.UserService; package com.cjlu.newspublish.actions.impl; @Controller @Scope("prototype") public class UserAction extends BaseAction<User> { private static final long serialVersionUID = 2206176605307115958L; @Autowired
private UserService userService;
yuqirong/NewsPublish
src/com/cjlu/newspublish/daos/impl/UserDaoImpl.java
// Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/utils/DataUtils.java // public final class DataUtils { // // private DataUtils() { // // } // // /** // * MD5¼ÓÃÜ // */ // public static String md5(String str) { // try { // StringBuffer buffer = new StringBuffer(); // char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // 'A', 'B', 'C', 'D', 'E', 'F' }; // byte[] bytes = str.getBytes(); // MessageDigest digest = MessageDigest.getInstance("md5"); // byte[] targ = digest.digest(bytes); // for (byte b : targ) { // buffer.append(chars[b >> 4 & 0x0F]); // buffer.append(b & 0x0F); // } // return buffer.toString(); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return null; // } // } // // /** // * Éî¶È¸´ÖÆ // */ // public static Serializable deeplyCopy(Serializable serializable) { // // try { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream( // byteArrayOutputStream); // objectOutputStream.writeObject(serializable); // objectOutputStream.close(); // byteArrayOutputStream.close(); // // byte[] bytes = byteArrayOutputStream.toByteArray(); // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( // bytes); // ObjectInputStream objectInputStream = new ObjectInputStream( // byteArrayInputStream); // Serializable copy = (Serializable) objectInputStream.readObject(); // objectInputStream.close(); // byteArrayInputStream.close(); // // return copy; // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // return null; // } // // /** // * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® // */ // public static String extractRightIds(Set<Right> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Right r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // public static String extractRoleIds(Set<Role> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Role r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // }
import java.util.List; import org.springframework.stereotype.Repository; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.utils.DataUtils;
package com.cjlu.newspublish.daos.impl; @SuppressWarnings("unchecked") @Repository("userDao")
// Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/utils/DataUtils.java // public final class DataUtils { // // private DataUtils() { // // } // // /** // * MD5¼ÓÃÜ // */ // public static String md5(String str) { // try { // StringBuffer buffer = new StringBuffer(); // char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // 'A', 'B', 'C', 'D', 'E', 'F' }; // byte[] bytes = str.getBytes(); // MessageDigest digest = MessageDigest.getInstance("md5"); // byte[] targ = digest.digest(bytes); // for (byte b : targ) { // buffer.append(chars[b >> 4 & 0x0F]); // buffer.append(b & 0x0F); // } // return buffer.toString(); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return null; // } // } // // /** // * Éî¶È¸´ÖÆ // */ // public static Serializable deeplyCopy(Serializable serializable) { // // try { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream( // byteArrayOutputStream); // objectOutputStream.writeObject(serializable); // objectOutputStream.close(); // byteArrayOutputStream.close(); // // byte[] bytes = byteArrayOutputStream.toByteArray(); // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( // bytes); // ObjectInputStream objectInputStream = new ObjectInputStream( // byteArrayInputStream); // Serializable copy = (Serializable) objectInputStream.readObject(); // objectInputStream.close(); // byteArrayInputStream.close(); // // return copy; // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // return null; // } // // /** // * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® // */ // public static String extractRightIds(Set<Right> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Right r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // public static String extractRoleIds(Set<Role> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Role r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // } // Path: src/com/cjlu/newspublish/daos/impl/UserDaoImpl.java import java.util.List; import org.springframework.stereotype.Repository; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.utils.DataUtils; package com.cjlu.newspublish.daos.impl; @SuppressWarnings("unchecked") @Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl<User> {
yuqirong/NewsPublish
src/com/cjlu/newspublish/daos/impl/UserDaoImpl.java
// Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/utils/DataUtils.java // public final class DataUtils { // // private DataUtils() { // // } // // /** // * MD5¼ÓÃÜ // */ // public static String md5(String str) { // try { // StringBuffer buffer = new StringBuffer(); // char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // 'A', 'B', 'C', 'D', 'E', 'F' }; // byte[] bytes = str.getBytes(); // MessageDigest digest = MessageDigest.getInstance("md5"); // byte[] targ = digest.digest(bytes); // for (byte b : targ) { // buffer.append(chars[b >> 4 & 0x0F]); // buffer.append(b & 0x0F); // } // return buffer.toString(); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return null; // } // } // // /** // * Éî¶È¸´ÖÆ // */ // public static Serializable deeplyCopy(Serializable serializable) { // // try { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream( // byteArrayOutputStream); // objectOutputStream.writeObject(serializable); // objectOutputStream.close(); // byteArrayOutputStream.close(); // // byte[] bytes = byteArrayOutputStream.toByteArray(); // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( // bytes); // ObjectInputStream objectInputStream = new ObjectInputStream( // byteArrayInputStream); // Serializable copy = (Serializable) objectInputStream.readObject(); // objectInputStream.close(); // byteArrayInputStream.close(); // // return copy; // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // return null; // } // // /** // * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® // */ // public static String extractRightIds(Set<Right> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Right r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // public static String extractRoleIds(Set<Role> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Role r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // }
import java.util.List; import org.springframework.stereotype.Repository; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.utils.DataUtils;
package com.cjlu.newspublish.daos.impl; @SuppressWarnings("unchecked") @Repository("userDao") public class UserDaoImpl extends BaseDaoImpl<User> { /** * ¼ì²âUserÖеÄÊôÐÔÊÇ·ñ±»Õ¼Óà */ public List<User> isTokenUp(String str) { String hql = "FROM User WHERE username = ?"; List<User> list = getSession().createQuery(hql).setString(0, str) .list(); return list; } /** * ¼ì²âµÇ¼ʱÊÇ·ñΪÓû§ */ public User isUser(String username, String password) { String hql = "FROM User WHERE username = ? AND password= ?"; User user = (User) getSession().createQuery(hql).setString(0, username)
// Path: src/com/cjlu/newspublish/models/User.java // public class User extends BaseEntity { // // private static final long serialVersionUID = 6923757046786572615L; // private String username; // private String password; // private String email; // private Date createTime = new Date(); // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // // Path: src/com/cjlu/newspublish/utils/DataUtils.java // public final class DataUtils { // // private DataUtils() { // // } // // /** // * MD5¼ÓÃÜ // */ // public static String md5(String str) { // try { // StringBuffer buffer = new StringBuffer(); // char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // 'A', 'B', 'C', 'D', 'E', 'F' }; // byte[] bytes = str.getBytes(); // MessageDigest digest = MessageDigest.getInstance("md5"); // byte[] targ = digest.digest(bytes); // for (byte b : targ) { // buffer.append(chars[b >> 4 & 0x0F]); // buffer.append(b & 0x0F); // } // return buffer.toString(); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return null; // } // } // // /** // * Éî¶È¸´ÖÆ // */ // public static Serializable deeplyCopy(Serializable serializable) { // // try { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream( // byteArrayOutputStream); // objectOutputStream.writeObject(serializable); // objectOutputStream.close(); // byteArrayOutputStream.close(); // // byte[] bytes = byteArrayOutputStream.toByteArray(); // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( // bytes); // ObjectInputStream objectInputStream = new ObjectInputStream( // byteArrayInputStream); // Serializable copy = (Serializable) objectInputStream.readObject(); // objectInputStream.close(); // byteArrayInputStream.close(); // // return copy; // } catch (IOException e) { // e.printStackTrace(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // return null; // } // // /** // * »ñµÃSet<Right>ÖÐÔªËØµÄId£¬×é³É×Ö·û´® // */ // public static String extractRightIds(Set<Right> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Right r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // public static String extractRoleIds(Set<Role> rights) { // StringBuffer buffer = new StringBuffer(); // if (ValidateUtils.isValid(rights)) { // for (Role r : rights) { // buffer.append(r.getId() + ","); // } // String str = buffer.substring(0, buffer.length() - 1); // return str; // } // return null; // } // // } // Path: src/com/cjlu/newspublish/daos/impl/UserDaoImpl.java import java.util.List; import org.springframework.stereotype.Repository; import com.cjlu.newspublish.models.User; import com.cjlu.newspublish.utils.DataUtils; package com.cjlu.newspublish.daos.impl; @SuppressWarnings("unchecked") @Repository("userDao") public class UserDaoImpl extends BaseDaoImpl<User> { /** * ¼ì²âUserÖеÄÊôÐÔÊÇ·ñ±»Õ¼Óà */ public List<User> isTokenUp(String str) { String hql = "FROM User WHERE username = ?"; List<User> list = getSession().createQuery(hql).setString(0, str) .list(); return list; } /** * ¼ì²âµÇ¼ʱÊÇ·ñΪÓû§ */ public User isUser(String username, String password) { String hql = "FROM User WHERE username = ? AND password= ?"; User user = (User) getSession().createQuery(hql).setString(0, username)
.setString(1, DataUtils.md5(password)).uniqueResult();
yuqirong/NewsPublish
src/org/apache/struts2/views/jsp/ui/AnchorTag.java
// Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import org.apache.struts2.components.Anchor; import org.apache.struts2.components.Component; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.util.ValueStack;
public void setValue(String value) { this.value = value; } public void setPortletMode(String portletMode) { this.portletMode = portletMode; } public void setPortletUrlType(String portletUrlType) { this.portletUrlType = portletUrlType; } public void setWindowState(String windowState) { this.windowState = windowState; } public void setAnchor(String anchor) { this.anchor = anchor; } public void setForceAddSchemeHostAndPort(String forceAddSchemeHostAndPort) { this.forceAddSchemeHostAndPort = forceAddSchemeHostAndPort; } /** * ÖØÐ´¸Ã·½·¨,ʵÏÖȨÏÞ¿ØÖÆ */ @Override public int doEndTag() throws JspException {
// Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // } // Path: src/org/apache/struts2/views/jsp/ui/AnchorTag.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import org.apache.struts2.components.Anchor; import org.apache.struts2.components.Component; import com.cjlu.newspublish.utils.ValidateUtils; import com.opensymphony.xwork2.util.ValueStack; public void setValue(String value) { this.value = value; } public void setPortletMode(String portletMode) { this.portletMode = portletMode; } public void setPortletUrlType(String portletUrlType) { this.portletUrlType = portletUrlType; } public void setWindowState(String windowState) { this.windowState = windowState; } public void setAnchor(String anchor) { this.anchor = anchor; } public void setForceAddSchemeHostAndPort(String forceAddSchemeHostAndPort) { this.forceAddSchemeHostAndPort = forceAddSchemeHostAndPort; } /** * ÖØÐ´¸Ã·½·¨,ʵÏÖȨÏÞ¿ØÖÆ */ @Override public int doEndTag() throws JspException {
if(ValidateUtils.hasRight(namespace, action, (HttpServletRequest)pageContext.getRequest(),null)){
yuqirong/NewsPublish
src/com/cjlu/newspublish/daos/BaseDao.java
// Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // }
import java.util.List; import com.cjlu.newspublish.models.Page;
package com.cjlu.newspublish.daos; public interface BaseDao<T> { public void saveEntity(T t); public void saveOrUpdateEntity(T t); public void updateEntity(T t); public void deleteEntity(T t); public void batchEntityByHQL(String hql, Object... objects); public T loadEntity(Integer id); public T getEntity(Integer id); public List<T> findEntityByHQL(String hql, Object... objects); public void executeSQL(String sql, Object... objects); @SuppressWarnings("rawtypes") public List<T> executeSQLQuery(Class clazz, String sql, Object... objects);
// Path: src/com/cjlu/newspublish/models/Page.java // public class Page<T> extends BaseEntity { // // private static final long serialVersionUID = -5688752889754349099L; // // µ±Ç°Ò³ // private int currentPage; // // ÿҳ¸ö¸öÊý // private int pageSize; // // ×ÜÌõÊý // private int totalCount; // // ×ÜÒ³Êý // private int pageCount; // // ʵÌåÀà // private List<T> list; // // public Page() { // // } // // public Page(int currentPage, int pageSize, int totalCount, List<T> list) { // super(); // this.currentPage = currentPage; // this.pageSize = pageSize; // this.totalCount = totalCount; // this.list = list; // } // // public int getPageCount() { // return pageCount; // } // // public void setPageCount(int pageCount) { // this.pageCount = pageCount; // } // // public int getCurrentPage() { // return currentPage; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getPageSize() { // return pageSize; // } // // public void setPageSize(int pageSize) { // this.pageSize = pageSize <= 0 ? 10 : pageSize; // } // // public int getTotalCount() { // return totalCount; // } // // public void setTotalCount(int totalCount) { // this.totalCount = totalCount; // } // // public List<T> getList() { // return list; // } // // public void setList(List<T> list) { // this.list = list; // } // // } // Path: src/com/cjlu/newspublish/daos/BaseDao.java import java.util.List; import com.cjlu.newspublish.models.Page; package com.cjlu.newspublish.daos; public interface BaseDao<T> { public void saveEntity(T t); public void saveOrUpdateEntity(T t); public void updateEntity(T t); public void deleteEntity(T t); public void batchEntityByHQL(String hql, Object... objects); public T loadEntity(Integer id); public T getEntity(Integer id); public List<T> findEntityByHQL(String hql, Object... objects); public void executeSQL(String sql, Object... objects); @SuppressWarnings("rawtypes") public List<T> executeSQLQuery(Class clazz, String sql, Object... objects);
public Page<T> listPage(String hql, String hql2, int pageNo, int pageSize);
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/impl/VisitorCounterServiceImpl.java
// Path: src/com/cjlu/newspublish/daos/impl/VisitorCounterDaoImpl.java // @Repository("visitorCounterDao") // public class VisitorCounterDaoImpl extends BaseDaoImpl<VisitorCounter> { // // public void deleteCounterByNewsId(Integer id) { // String hql = "FROM VisitorCounter v where v.news.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // public void deleteCounterByUserId(Integer id) { // String hql = "FROM VisitorCounter v where v.user.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // } // // Path: src/com/cjlu/newspublish/models/VisitorCounter.java // public class VisitorCounter extends BaseEntity{ // // private static final long serialVersionUID = -4862720355704098697L; // private String ipAddress; // private Date createTime; // private User user; // private News news; // // public VisitorCounter() { // // } // // public VisitorCounter(String ipAddress, Date createTime, // User user, News news) { // this.ipAddress = ipAddress; // this.createTime = createTime; // this.user = user; // this.news = news; // } // // public String getIpAddress() { // return ipAddress; // } // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // public Date getCreateTime() { // return createTime; // } // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public News getNews() { // return news; // } // public void setNews(News news) { // this.news = news; // } // // } // // Path: src/com/cjlu/newspublish/services/VisitorCounterService.java // public interface VisitorCounterService extends BaseService<VisitorCounter>{ // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.impl.VisitorCounterDaoImpl; import com.cjlu.newspublish.models.VisitorCounter; import com.cjlu.newspublish.services.VisitorCounterService;
package com.cjlu.newspublish.services.impl; @Service("visitorCounterService") public class VisitorCounterServiceImpl extends BaseServiceImpl<VisitorCounter>
// Path: src/com/cjlu/newspublish/daos/impl/VisitorCounterDaoImpl.java // @Repository("visitorCounterDao") // public class VisitorCounterDaoImpl extends BaseDaoImpl<VisitorCounter> { // // public void deleteCounterByNewsId(Integer id) { // String hql = "FROM VisitorCounter v where v.news.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // public void deleteCounterByUserId(Integer id) { // String hql = "FROM VisitorCounter v where v.user.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // } // // Path: src/com/cjlu/newspublish/models/VisitorCounter.java // public class VisitorCounter extends BaseEntity{ // // private static final long serialVersionUID = -4862720355704098697L; // private String ipAddress; // private Date createTime; // private User user; // private News news; // // public VisitorCounter() { // // } // // public VisitorCounter(String ipAddress, Date createTime, // User user, News news) { // this.ipAddress = ipAddress; // this.createTime = createTime; // this.user = user; // this.news = news; // } // // public String getIpAddress() { // return ipAddress; // } // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // public Date getCreateTime() { // return createTime; // } // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public News getNews() { // return news; // } // public void setNews(News news) { // this.news = news; // } // // } // // Path: src/com/cjlu/newspublish/services/VisitorCounterService.java // public interface VisitorCounterService extends BaseService<VisitorCounter>{ // // } // Path: src/com/cjlu/newspublish/services/impl/VisitorCounterServiceImpl.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.impl.VisitorCounterDaoImpl; import com.cjlu.newspublish.models.VisitorCounter; import com.cjlu.newspublish.services.VisitorCounterService; package com.cjlu.newspublish.services.impl; @Service("visitorCounterService") public class VisitorCounterServiceImpl extends BaseServiceImpl<VisitorCounter>
implements VisitorCounterService {
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/impl/VisitorCounterServiceImpl.java
// Path: src/com/cjlu/newspublish/daos/impl/VisitorCounterDaoImpl.java // @Repository("visitorCounterDao") // public class VisitorCounterDaoImpl extends BaseDaoImpl<VisitorCounter> { // // public void deleteCounterByNewsId(Integer id) { // String hql = "FROM VisitorCounter v where v.news.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // public void deleteCounterByUserId(Integer id) { // String hql = "FROM VisitorCounter v where v.user.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // } // // Path: src/com/cjlu/newspublish/models/VisitorCounter.java // public class VisitorCounter extends BaseEntity{ // // private static final long serialVersionUID = -4862720355704098697L; // private String ipAddress; // private Date createTime; // private User user; // private News news; // // public VisitorCounter() { // // } // // public VisitorCounter(String ipAddress, Date createTime, // User user, News news) { // this.ipAddress = ipAddress; // this.createTime = createTime; // this.user = user; // this.news = news; // } // // public String getIpAddress() { // return ipAddress; // } // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // public Date getCreateTime() { // return createTime; // } // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public News getNews() { // return news; // } // public void setNews(News news) { // this.news = news; // } // // } // // Path: src/com/cjlu/newspublish/services/VisitorCounterService.java // public interface VisitorCounterService extends BaseService<VisitorCounter>{ // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.impl.VisitorCounterDaoImpl; import com.cjlu.newspublish.models.VisitorCounter; import com.cjlu.newspublish.services.VisitorCounterService;
package com.cjlu.newspublish.services.impl; @Service("visitorCounterService") public class VisitorCounterServiceImpl extends BaseServiceImpl<VisitorCounter> implements VisitorCounterService { @Autowired
// Path: src/com/cjlu/newspublish/daos/impl/VisitorCounterDaoImpl.java // @Repository("visitorCounterDao") // public class VisitorCounterDaoImpl extends BaseDaoImpl<VisitorCounter> { // // public void deleteCounterByNewsId(Integer id) { // String hql = "FROM VisitorCounter v where v.news.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // public void deleteCounterByUserId(Integer id) { // String hql = "FROM VisitorCounter v where v.user.id = ?"; // List<VisitorCounter> counters = this.findEntityByHQL(hql, id); // if (counters != null) { // for (VisitorCounter visitorCounter : counters) { // this.deleteEntity(visitorCounter); // } // } // } // // } // // Path: src/com/cjlu/newspublish/models/VisitorCounter.java // public class VisitorCounter extends BaseEntity{ // // private static final long serialVersionUID = -4862720355704098697L; // private String ipAddress; // private Date createTime; // private User user; // private News news; // // public VisitorCounter() { // // } // // public VisitorCounter(String ipAddress, Date createTime, // User user, News news) { // this.ipAddress = ipAddress; // this.createTime = createTime; // this.user = user; // this.news = news; // } // // public String getIpAddress() { // return ipAddress; // } // public void setIpAddress(String ipAddress) { // this.ipAddress = ipAddress; // } // public Date getCreateTime() { // return createTime; // } // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // public User getUser() { // return user; // } // public void setUser(User user) { // this.user = user; // } // public News getNews() { // return news; // } // public void setNews(News news) { // this.news = news; // } // // } // // Path: src/com/cjlu/newspublish/services/VisitorCounterService.java // public interface VisitorCounterService extends BaseService<VisitorCounter>{ // // } // Path: src/com/cjlu/newspublish/services/impl/VisitorCounterServiceImpl.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.impl.VisitorCounterDaoImpl; import com.cjlu.newspublish.models.VisitorCounter; import com.cjlu.newspublish.services.VisitorCounterService; package com.cjlu.newspublish.services.impl; @Service("visitorCounterService") public class VisitorCounterServiceImpl extends BaseServiceImpl<VisitorCounter> implements VisitorCounterService { @Autowired
private VisitorCounterDaoImpl visitorCounterDao;
yuqirong/NewsPublish
src/com/cjlu/newspublish/test/test2.java
// Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang3.time.FastDateFormat; import org.junit.Test; import com.cjlu.newspublish.utils.ValidateUtils;
package com.cjlu.newspublish.test; public class test2 { @Test public void stringToDate() throws ParseException { String str = "2015/12/26 12:52:26";
// Path: src/com/cjlu/newspublish/utils/ValidateUtils.java // public final class ValidateUtils { // // private ValidateUtils(){ // // } // // /** // * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ // */ // public static boolean isValid(String str) { // if (str == null || "".equals(str.trim())) { // return false; // } // return true; // } // // /** // * Åжϼ¯ºÏµÄÓÐЧÐÔ // */ // @SuppressWarnings("rawtypes") // public static boolean isValid(Collection collection) { // if (collection == null || collection.isEmpty()) { // return false; // } // return true; // } // // /** // * ÅжÏÊý×éÊÇ·ñÓÐЧ // */ // public static boolean isValid(Object[] arr) { // if (arr == null || arr.length == 0) { // return false; // } // return true; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static boolean hasRight(String nameSpace, String actionName, // HttpServletRequest req, BaseAction baseAction) { // if (!ValidateUtils.isValid(nameSpace) || "/".equals(nameSpace)) { // nameSpace = ""; // } // // ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx // if (actionName != null && actionName.contains("?")) { // actionName = actionName.substring(0, actionName.indexOf("?")); // } // String url = nameSpace + "/" + actionName; // HttpSession session = req.getSession(); // // ServletContext sc = session.getServletContext(); // Map<String, Right> map = (Map<String, Right>) sc // .getAttribute("all_rights_map"); // Right r = map.get(url); // // ¹«¹²×ÊÔ´? // if (r == null || r.isCommon()) { // return true; // } else { // Admin admin = (Admin) session.getAttribute("admin"); // // µÇ½? // if (admin == null) { // return false; // } else { // // userAware´¦Àí // if (baseAction != null && baseAction instanceof AdminAware) { // ((AdminAware) baseAction).setAdmin(admin); // } // // ÓÐȨÏÞ? // if (admin.hasRight(r)) { // return true; // } else { // return false; // } // } // } // } // } // Path: src/com/cjlu/newspublish/test/test2.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang3.time.FastDateFormat; import org.junit.Test; import com.cjlu.newspublish.utils.ValidateUtils; package com.cjlu.newspublish.test; public class test2 { @Test public void stringToDate() throws ParseException { String str = "2015/12/26 12:52:26";
if (ValidateUtils.isValid(str)) {
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/home/HomeListContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/TodoList.java // public class TodoList extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private RealmList<Task> tasks; // private long createdTime; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public RealmList<Task> getTasks() { // return tasks; // } // // public void setTasks(RealmList<Task> tasks) { // this.tasks = tasks; // } // // public void addTask(Task task) { // tasks.add(task); // } // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.TodoList; import java.util.List; import io.realm.RealmResults;
package com.ddmeng.todorealm.home; interface HomeListContract { interface View extends BaseView { void initViews();
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/TodoList.java // public class TodoList extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private RealmList<Task> tasks; // private long createdTime; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public RealmList<Task> getTasks() { // return tasks; // } // // public void setTasks(RealmList<Task> tasks) { // this.tasks = tasks; // } // // public void addTask(Task task) { // tasks.add(task); // } // } // Path: app/src/main/java/com/ddmeng/todorealm/home/HomeListContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.TodoList; import java.util.List; import io.realm.RealmResults; package com.ddmeng.todorealm.home; interface HomeListContract { interface View extends BaseView { void initViews();
void bindListData(RealmResults<TodoList> lists);
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/home/HomeListContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/TodoList.java // public class TodoList extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private RealmList<Task> tasks; // private long createdTime; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public RealmList<Task> getTasks() { // return tasks; // } // // public void setTasks(RealmList<Task> tasks) { // this.tasks = tasks; // } // // public void addTask(Task task) { // tasks.add(task); // } // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.TodoList; import java.util.List; import io.realm.RealmResults;
package com.ddmeng.todorealm.home; interface HomeListContract { interface View extends BaseView { void initViews(); void bindListData(RealmResults<TodoList> lists); void notifyDataChanged(); void showAddNewList(); void showAddNewTask(); void showListDetail(TodoList list); void startActionMode(); void finishActionMode(); void onExitActionMode(); }
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/TodoList.java // public class TodoList extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private RealmList<Task> tasks; // private long createdTime; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public RealmList<Task> getTasks() { // return tasks; // } // // public void setTasks(RealmList<Task> tasks) { // this.tasks = tasks; // } // // public void addTask(Task task) { // tasks.add(task); // } // } // Path: app/src/main/java/com/ddmeng/todorealm/home/HomeListContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.TodoList; import java.util.List; import io.realm.RealmResults; package com.ddmeng.todorealm.home; interface HomeListContract { interface View extends BaseView { void initViews(); void bindListData(RealmResults<TodoList> lists); void notifyDataChanged(); void showAddNewList(); void showAddNewTask(); void showListDetail(TodoList list); void startActionMode(); void finishActionMode(); void onExitActionMode(); }
interface Presenter extends BasePresenter<HomeListContract.View> {
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/detail/list/ListDetailContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task; import java.util.List;
package com.ddmeng.todorealm.detail.list; interface ListDetailContract { interface View extends BaseView { void initViews(String title);
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // } // Path: app/src/main/java/com/ddmeng/todorealm/detail/list/ListDetailContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task; import java.util.List; package com.ddmeng.todorealm.detail.list; interface ListDetailContract { interface View extends BaseView { void initViews(String title);
void bingTasksData(List<Task> todoTasks, List<Task> doneTasks);
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/detail/list/ListDetailContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task; import java.util.List;
package com.ddmeng.todorealm.detail.list; interface ListDetailContract { interface View extends BaseView { void initViews(String title); void bingTasksData(List<Task> todoTasks, List<Task> doneTasks); void notifyDataChanged(String title); void clearInput(); void showTaskDetail(Task task); void startDeleteActionMode(); void onExitDeleteActionMode(); void showEditActionText(CharSequence text); void exit(); }
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // } // Path: app/src/main/java/com/ddmeng/todorealm/detail/list/ListDetailContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task; import java.util.List; package com.ddmeng.todorealm.detail.list; interface ListDetailContract { interface View extends BaseView { void initViews(String title); void bingTasksData(List<Task> todoTasks, List<Task> doneTasks); void notifyDataChanged(String title); void clearInput(); void showTaskDetail(Task task); void startDeleteActionMode(); void onExitDeleteActionMode(); void showEditActionText(CharSequence text); void exit(); }
interface Presenter extends BasePresenter<ListDetailContract.View> {
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/home/add/task/AddTaskContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView;
package com.ddmeng.todorealm.home.add.task; public interface AddTaskContract { interface View extends BaseView { void initViews(); void showSelectListDialog(); void showAddNewListDialog(); void showSelectedList(String title); void showAddNewListHint(); void exit(); }
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // Path: app/src/main/java/com/ddmeng/todorealm/home/add/task/AddTaskContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; package com.ddmeng.todorealm.home.add.task; public interface AddTaskContract { interface View extends BaseView { void initViews(); void showSelectListDialog(); void showAddNewListDialog(); void showSelectedList(String title); void showAddNewListHint(); void exit(); }
interface Presenter extends BasePresenter<AddTaskContract.View> {
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/detail/task/TaskDetailContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task;
package com.ddmeng.todorealm.detail.task; public interface TaskDetailContract { interface View extends BaseView { void initViews(); void showEditActionText(String title);
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // } // Path: app/src/main/java/com/ddmeng/todorealm/detail/task/TaskDetailContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task; package com.ddmeng.todorealm.detail.task; public interface TaskDetailContract { interface View extends BaseView { void initViews(); void showEditActionText(String title);
void updateViews(Task task);
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/detail/task/TaskDetailContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task;
package com.ddmeng.todorealm.detail.task; public interface TaskDetailContract { interface View extends BaseView { void initViews(); void showEditActionText(String title); void updateViews(Task task); void exit(); }
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // // Path: app/src/main/java/com/ddmeng/todorealm/data/models/Task.java // public class Task extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private boolean isDone; // private long listId; // private long createdTime; // private String note; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public boolean isDone() { // return isDone; // } // // public void setDone(boolean done) { // this.isDone = done; // } // // public long getListId() { // return listId; // } // // public void setListId(long listId) { // this.listId = listId; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public String getNote() { // return note; // } // // public void setNote(String note) { // this.note = note; // } // } // Path: app/src/main/java/com/ddmeng/todorealm/detail/task/TaskDetailContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; import com.ddmeng.todorealm.data.models.Task; package com.ddmeng.todorealm.detail.task; public interface TaskDetailContract { interface View extends BaseView { void initViews(); void showEditActionText(String title); void updateViews(Task task); void exit(); }
interface Presenter extends BasePresenter<TaskDetailContract.View> {
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/home/add/task/SelectionViewHolder.java
// Path: app/src/main/java/com/ddmeng/todorealm/data/models/TodoList.java // public class TodoList extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private RealmList<Task> tasks; // private long createdTime; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public RealmList<Task> getTasks() { // return tasks; // } // // public void setTasks(RealmList<Task> tasks) { // this.tasks = tasks; // } // // public void addTask(Task task) { // tasks.add(task); // } // }
import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.ddmeng.todorealm.R; import com.ddmeng.todorealm.data.models.TodoList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
package com.ddmeng.todorealm.home.add.task; public class SelectionViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.title) TextView titleView; private SelectionsListAdapter.SelectListCallback callback;
// Path: app/src/main/java/com/ddmeng/todorealm/data/models/TodoList.java // public class TodoList extends RealmObject { // @PrimaryKey // private long id; // @Required // private String title; // private RealmList<Task> tasks; // private long createdTime; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public long getCreatedTime() { // return createdTime; // } // // public void setCreatedTime(long createdTime) { // this.createdTime = createdTime; // } // // public RealmList<Task> getTasks() { // return tasks; // } // // public void setTasks(RealmList<Task> tasks) { // this.tasks = tasks; // } // // public void addTask(Task task) { // tasks.add(task); // } // } // Path: app/src/main/java/com/ddmeng/todorealm/home/add/task/SelectionViewHolder.java import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.ddmeng.todorealm.R; import com.ddmeng.todorealm.data.models.TodoList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; package com.ddmeng.todorealm.home.add.task; public class SelectionViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.title) TextView titleView; private SelectionsListAdapter.SelectListCallback callback;
private TodoList list;
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/home/add/list/AddListContract.java
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // }
import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView;
package com.ddmeng.todorealm.home.add.list; interface AddListContract { interface View extends BaseView { void exit(); }
// Path: app/src/main/java/com/ddmeng/todorealm/base/BasePresenter.java // public interface BasePresenter<T extends BaseView> { // void attachView(T view); // // void detachView(); // } // // Path: app/src/main/java/com/ddmeng/todorealm/base/BaseView.java // public interface BaseView { // } // Path: app/src/main/java/com/ddmeng/todorealm/home/add/list/AddListContract.java import com.ddmeng.todorealm.base.BasePresenter; import com.ddmeng.todorealm.base.BaseView; package com.ddmeng.todorealm.home.add.list; interface AddListContract { interface View extends BaseView { void exit(); }
interface Presenter extends BasePresenter<AddListContract.View> {
mengdd/TodoRealm
app/src/main/java/com/ddmeng/todorealm/detail/EditActionViewHolder.java
// Path: app/src/main/java/com/ddmeng/todorealm/utils/KeyboardUtils.java // public class KeyboardUtils { // public static void hideKeyboard(Context context, View view) { // InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); // inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // // public static void showKeyboard(Context context) { // InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); // inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY); // } // // public static void showKeyboardImplicit(Context context, View view) { // InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); // inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // } // }
import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.ddmeng.todorealm.R; import com.ddmeng.todorealm.utils.KeyboardUtils; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction;
package com.ddmeng.todorealm.detail; public class EditActionViewHolder { @BindView(R.id.edit_text_view) EditText editTextView; @BindView(R.id.done_button) View doneButton; private View itemView; private MenuItem menuItem; public EditActionViewHolder(View view, MenuItem menuItem) { this.itemView = view; this.menuItem = menuItem; ButterKnife.bind(this, view); } public void showCurrentText(CharSequence text) { editTextView.setText(text); editTextView.setSelection(text.length()); editTextView.requestFocus();
// Path: app/src/main/java/com/ddmeng/todorealm/utils/KeyboardUtils.java // public class KeyboardUtils { // public static void hideKeyboard(Context context, View view) { // InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); // inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // // public static void showKeyboard(Context context) { // InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); // inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY); // } // // public static void showKeyboardImplicit(Context context, View view) { // InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); // inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // } // } // Path: app/src/main/java/com/ddmeng/todorealm/detail/EditActionViewHolder.java import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.ddmeng.todorealm.R; import com.ddmeng.todorealm.utils.KeyboardUtils; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; package com.ddmeng.todorealm.detail; public class EditActionViewHolder { @BindView(R.id.edit_text_view) EditText editTextView; @BindView(R.id.done_button) View doneButton; private View itemView; private MenuItem menuItem; public EditActionViewHolder(View view, MenuItem menuItem) { this.itemView = view; this.menuItem = menuItem; ButterKnife.bind(this, view); } public void showCurrentText(CharSequence text) { editTextView.setText(text); editTextView.setSelection(text.length()); editTextView.requestFocus();
KeyboardUtils.showKeyboard(itemView.getContext());
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // }
import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope
public IPlacesApi providePlacesApi() {
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // }
import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope public IPlacesApi providePlacesApi() {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope public IPlacesApi providePlacesApi() {
return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/");
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // }
import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope public IPlacesApi providePlacesApi() { return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); } @Provides @ViewScope
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope public IPlacesApi providePlacesApi() { return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); } @Provides @ViewScope
public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) {
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // }
import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope public IPlacesApi providePlacesApi() { return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); } @Provides @ViewScope public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RetrofitUtils.java // public class RetrofitUtils { // public static <T> T create(final Class<T> clazz, final String endPoint) { // final Retrofit restAdapter = new Retrofit.Builder() // .baseUrl(endPoint) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // return restAdapter.create(clazz); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java // public class PlacesViewModel implements IPlacesViewModel { // // private IPlacesApi mPlacesApi; // private final int TIME_OUT = 5; // private final int RETRY = 3; // private List<Place> allPlaces; // // public PlacesViewModel(@NonNull IPlacesApi placesApi) { // mPlacesApi = placesApi; // } // // // observable property // private BehaviorSubject<List<Place>> mPlaces = BehaviorSubject.create(); // // /** // * Return an Observable that emits the current places // */ // public Observable<List<Place>> currentPlaces() { // return mPlaces.asObservable(); // } // // /** // * Command fetching all places // */ // @Override // public Observable<Boolean> fetchAllPlaces() { // return mPlacesApi.placesResult() // .map(googleSearchResult -> { // allPlaces = googleSearchResult.results; // mPlaces.onNext(googleSearchResult.results); // return true; // }) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // // /** // * Command filtering places // */ // @Override // public void filterPlacesByType(String type) { // if (type.equalsIgnoreCase("all")) { // mPlaces.onNext(allPlaces); // } else { // List<Place> newPlaces = new ArrayList<>(); // Observable.from(allPlaces) // .filter(place -> place.getTypes().contains(getApiType(type))) // .subscribe(newPlaces::add); // mPlaces.onNext(newPlaces); // } // } // // /** // * Helpers change type to api_type // */ // private String getApiType(String type) { // type = type.toLowerCase(); // switch (type) { // case "theater": // return "movie_theater"; // default: // return type; // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.utils.RetrofitUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import apidez.com.android_mvvm_sample.viewmodel.PlacesViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/21/15. */ @Module public class PlacesModule { @Provides @ViewScope public IPlacesApi providePlacesApi() { return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); } @Provides @ViewScope public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) {
return new PlacesViewModel(placesApi);
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // }
import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import retrofit.http.GET; import rx.Observable;
package apidez.com.android_mvvm_sample.model.api; /** * Created by nongdenchet on 10/21/15. */ public interface IPlacesApi { @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo")
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import retrofit.http.GET; import rx.Observable; package apidez.com.android_mvvm_sample.model.api; /** * Created by nongdenchet on 10/21/15. */ public interface IPlacesApi { @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo")
Observable<GoogleSearchResult> placesResult();
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // }
import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope
public IPurchaseApi providePurchaseApi(Gson gson) {
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // }
import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope public IPurchaseApi providePurchaseApi(Gson gson) {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope public IPurchaseApi providePurchaseApi(Gson gson) {
return new PurchaseApi(gson);
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // }
import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope public IPurchaseApi providePurchaseApi(Gson gson) { return new PurchaseApi(gson); } @Provides @ViewScope
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope public IPurchaseApi providePurchaseApi(Gson gson) { return new PurchaseApi(gson); } @Provides @ViewScope
public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) {
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // }
import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides;
package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope public IPurchaseApi providePurchaseApi(Gson gson) { return new PurchaseApi(gson); } @Provides @ViewScope public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java // public class PurchaseViewModel implements IPurchaseViewModel { // // private IPurchaseApi mPurchaseApi; // private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" // + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // private final int TIME_OUT = 5; // private final int RETRY = 3; // // public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { // mPurchaseApi = purchaseApi; // } // // // observable property // private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); // private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); // // /** // * Return an observable that emit the validation of credit card // */ // public Observable<Boolean> creditCardValid() { // return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText))); // } // // /** // * Return an observable that emit the validation of email // */ // public Observable<Boolean> emailValid() { // return mEmail.map(inputText -> (inputText.toString().matches(EMAIL_REGEX))); // } // // /** // * Return an observable that emit the validation submit button // */ // public Observable<Boolean> canSubmit() { // return Observable.combineLatest(creditCardValid(), emailValid(), // (validCreditCard, validEmail) -> validCreditCard && validEmail); // } // // /** // * Update the credit card // */ // public void nextCreditCard(CharSequence creditCard) { // mCreditCard.onNext(creditCard); // } // // /** // * Update the email // */ // public void nextEmail(CharSequence email) { // mEmail.onNext(email); // } // // /** // * Command submit // */ // public Observable<Boolean> submit() { // return mPurchaseApi.submitPurchase(mCreditCard.getValue().toString(), mEmail.getValue().toString()) // .timeout(TIME_OUT, TimeUnit.SECONDS) // .retry(RETRY); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import apidez.com.android_mvvm_sample.viewmodel.PurchaseViewModel; import dagger.Module; import dagger.Provides; package apidez.com.android_mvvm_sample.dependency.module; /** * Created by nongdenchet on 10/2/15. */ @Module public class PurchaseModule { @Provides @ViewScope public IPurchaseApi providePurchaseApi(Gson gson) { return new PurchaseApi(gson); } @Provides @ViewScope public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) {
return new PurchaseViewModel(purchaseApi);
nongdenchet/android-mvvm-with-tests
app/src/androidTest/java/apidez/com/android_mvvm_sample/utils/MatcherEx.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/custom/MyTextView.java // public class MyTextView extends TextView { // // private int resId; // // public MyTextView(Context context) { // super(context); // } // // public MyTextView(Context context, AttributeSet attrs) { // super(context, attrs); // } // // public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // @Override // public void setBackgroundResource(int resId) { // super.setBackgroundResource(resId); // this.resId = resId; // } // // public int getBackgroundResource() { // return resId; // } // }
import android.annotation.TargetApi; import android.os.Build; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import apidez.com.android_mvvm_sample.view.custom.MyTextView; 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.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withText;
package apidez.com.android_mvvm_sample.utils; /** * Created by nongdenchet on 10/3/15. */ public class MatcherEx { /** * Returns a matcher that matches {@link View}s is visible */ public static Matcher<View> isVisible() { return new TypeSafeMatcher<View>() { @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Override protected boolean matchesSafely(View view) { return view.getVisibility() == View.VISIBLE; } @Override public void describeTo(Description description) { description.appendText("is visible"); } }; } /** * Returns a matcher that matches {@link MyTextView}s resourceId */ public static Matcher<View> hasResId(int resId) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("has resId"); } @Override public boolean matchesSafely(View view) { try {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/custom/MyTextView.java // public class MyTextView extends TextView { // // private int resId; // // public MyTextView(Context context) { // super(context); // } // // public MyTextView(Context context, AttributeSet attrs) { // super(context, attrs); // } // // public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // @Override // public void setBackgroundResource(int resId) { // super.setBackgroundResource(resId); // this.resId = resId; // } // // public int getBackgroundResource() { // return resId; // } // } // Path: app/src/androidTest/java/apidez/com/android_mvvm_sample/utils/MatcherEx.java import android.annotation.TargetApi; import android.os.Build; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import apidez.com.android_mvvm_sample.view.custom.MyTextView; 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.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withText; package apidez.com.android_mvvm_sample.utils; /** * Created by nongdenchet on 10/3/15. */ public class MatcherEx { /** * Returns a matcher that matches {@link View}s is visible */ public static Matcher<View> isVisible() { return new TypeSafeMatcher<View>() { @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Override protected boolean matchesSafely(View view) { return view.getVisibility() == View.VISIBLE; } @Override public void describeTo(Description description) { description.appendText("is visible"); } }; } /** * Returns a matcher that matches {@link MyTextView}s resourceId */ public static Matcher<View> hasResId(int resId) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("has resId"); } @Override public boolean matchesSafely(View view) { try {
return ((MyTextView) view).getBackgroundResource() == resId;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java // public class PurchaseActivity extends BaseActivity { // // @Bind(R.id.creditCard) // EditText mEdtCreditCard; // // @Bind(R.id.email) // EditText mEdtEmail; // // @Bind(R.id.layoutCreditCard) // TextInputLayout mLayoutCreditCard; // // @Bind(R.id.layoutEmail) // TextInputLayout mLayoutEmail; // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Bind(R.id.btnSubmit) // TextView mBtnSubmit; // // @Inject // IPurchaseViewModel mViewModel; // // private ProgressDialog mProgressDialog; // private View.OnClickListener onSubmitClickListener; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_purchase); // // // Setup dependency // ((MyApplication) getApplication()) // .builder() // .purchaseComponent() // .inject(this); // // // Setup butterknife // ButterKnife.bind(this); // // // Setup views // setUpView(); // } // // private void setUpView() { // // Progress dialog // mProgressDialog = new ProgressDialog(this); // mProgressDialog.setMessage(getString(R.string.loading)); // mProgressDialog.setCancelable(false); // // // Toolbar // setSupportActionBar(mToolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // } // // private void bindViewModel() { // // binding credit card // RxTextViewEx.textChanges(mEdtCreditCard) // .takeUntil(preDestroy()) // .subscribe(mViewModel::nextCreditCard); // // // binding email // RxTextViewEx.textChanges(mEdtEmail) // .takeUntil(preDestroy()) // .subscribe(mViewModel::nextEmail); // // // create event on click on submit // onSubmitClickListener = v -> mViewModel.submit() // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .takeUntil(preDestroy()) // .doOnSubscribe(mProgressDialog::show) // .doOnTerminate(mProgressDialog::hide) // .subscribe(done -> { // UiUtils.showDialog(getString(R.string.success), this); // }, throwable -> { // UiUtils.showDialog(getString(R.string.error), this); // }); // // // binding credit card change // mViewModel.creditCardValid() // .takeUntil(preDestroy()) // .subscribe(valid -> { // mLayoutCreditCard.setError(valid ? "" : getString(R.string.error_credit_card)); // }); // // // binding password change // mViewModel.emailValid() // .takeUntil(preDestroy()) // .subscribe(valid -> { // mLayoutEmail.setError(valid ? "" : getString(R.string.error_email)); // }); // // // can submit // mViewModel.canSubmit() // .takeUntil(preDestroy()) // .subscribe(active -> { // mBtnSubmit.setBackgroundResource(active ? R.drawable.bg_submit : R.drawable.bg_inactive_submit); // mBtnSubmit.setOnClickListener(active ? onSubmitClickListener : null); // }); // } // // @Override // protected void onResume() { // super.onResume(); // // // bind to viewmodel // bindViewModel(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // onBackPressed(); // break; // } // return true; // } // }
import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.view.activity.PurchaseActivity; import dagger.Subcomponent;
package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/24/15. */ @ViewScope @Subcomponent(modules = {PurchaseModule.class}) public interface PurchaseComponent {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java // public class PurchaseActivity extends BaseActivity { // // @Bind(R.id.creditCard) // EditText mEdtCreditCard; // // @Bind(R.id.email) // EditText mEdtEmail; // // @Bind(R.id.layoutCreditCard) // TextInputLayout mLayoutCreditCard; // // @Bind(R.id.layoutEmail) // TextInputLayout mLayoutEmail; // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Bind(R.id.btnSubmit) // TextView mBtnSubmit; // // @Inject // IPurchaseViewModel mViewModel; // // private ProgressDialog mProgressDialog; // private View.OnClickListener onSubmitClickListener; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_purchase); // // // Setup dependency // ((MyApplication) getApplication()) // .builder() // .purchaseComponent() // .inject(this); // // // Setup butterknife // ButterKnife.bind(this); // // // Setup views // setUpView(); // } // // private void setUpView() { // // Progress dialog // mProgressDialog = new ProgressDialog(this); // mProgressDialog.setMessage(getString(R.string.loading)); // mProgressDialog.setCancelable(false); // // // Toolbar // setSupportActionBar(mToolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // } // // private void bindViewModel() { // // binding credit card // RxTextViewEx.textChanges(mEdtCreditCard) // .takeUntil(preDestroy()) // .subscribe(mViewModel::nextCreditCard); // // // binding email // RxTextViewEx.textChanges(mEdtEmail) // .takeUntil(preDestroy()) // .subscribe(mViewModel::nextEmail); // // // create event on click on submit // onSubmitClickListener = v -> mViewModel.submit() // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .takeUntil(preDestroy()) // .doOnSubscribe(mProgressDialog::show) // .doOnTerminate(mProgressDialog::hide) // .subscribe(done -> { // UiUtils.showDialog(getString(R.string.success), this); // }, throwable -> { // UiUtils.showDialog(getString(R.string.error), this); // }); // // // binding credit card change // mViewModel.creditCardValid() // .takeUntil(preDestroy()) // .subscribe(valid -> { // mLayoutCreditCard.setError(valid ? "" : getString(R.string.error_credit_card)); // }); // // // binding password change // mViewModel.emailValid() // .takeUntil(preDestroy()) // .subscribe(valid -> { // mLayoutEmail.setError(valid ? "" : getString(R.string.error_email)); // }); // // // can submit // mViewModel.canSubmit() // .takeUntil(preDestroy()) // .subscribe(active -> { // mBtnSubmit.setBackgroundResource(active ? R.drawable.bg_submit : R.drawable.bg_inactive_submit); // mBtnSubmit.setOnClickListener(active ? onSubmitClickListener : null); // }); // } // // @Override // protected void onResume() { // super.onResume(); // // // bind to viewmodel // bindViewModel(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // onBackPressed(); // break; // } // return true; // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.view.activity.PurchaseActivity; import dagger.Subcomponent; package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/24/15. */ @ViewScope @Subcomponent(modules = {PurchaseModule.class}) public interface PurchaseComponent {
void inject(PurchaseActivity purchaseActivity);
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package apidez.com.android_mvvm_sample.view.activity; /** * Created by nongdenchet on 10/1/15. */ public class PurchaseActivity extends BaseActivity { @Bind(R.id.creditCard) EditText mEdtCreditCard; @Bind(R.id.email) EditText mEdtEmail; @Bind(R.id.layoutCreditCard) TextInputLayout mLayoutCreditCard; @Bind(R.id.layoutEmail) TextInputLayout mLayoutEmail; @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.btnSubmit) TextView mBtnSubmit; @Inject
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package apidez.com.android_mvvm_sample.view.activity; /** * Created by nongdenchet on 10/1/15. */ public class PurchaseActivity extends BaseActivity { @Bind(R.id.creditCard) EditText mEdtCreditCard; @Bind(R.id.email) EditText mEdtEmail; @Bind(R.id.layoutCreditCard) TextInputLayout mLayoutCreditCard; @Bind(R.id.layoutEmail) TextInputLayout mLayoutEmail; @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.btnSubmit) TextView mBtnSubmit; @Inject
IPurchaseViewModel mViewModel;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package apidez.com.android_mvvm_sample.view.activity; /** * Created by nongdenchet on 10/1/15. */ public class PurchaseActivity extends BaseActivity { @Bind(R.id.creditCard) EditText mEdtCreditCard; @Bind(R.id.email) EditText mEdtEmail; @Bind(R.id.layoutCreditCard) TextInputLayout mLayoutCreditCard; @Bind(R.id.layoutEmail) TextInputLayout mLayoutEmail; @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.btnSubmit) TextView mBtnSubmit; @Inject IPurchaseViewModel mViewModel; private ProgressDialog mProgressDialog; private View.OnClickListener onSubmitClickListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase); // Setup dependency
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package apidez.com.android_mvvm_sample.view.activity; /** * Created by nongdenchet on 10/1/15. */ public class PurchaseActivity extends BaseActivity { @Bind(R.id.creditCard) EditText mEdtCreditCard; @Bind(R.id.email) EditText mEdtEmail; @Bind(R.id.layoutCreditCard) TextInputLayout mLayoutCreditCard; @Bind(R.id.layoutEmail) TextInputLayout mLayoutEmail; @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.btnSubmit) TextView mBtnSubmit; @Inject IPurchaseViewModel mViewModel; private ProgressDialog mProgressDialog; private View.OnClickListener onSubmitClickListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase); // Setup dependency
((MyApplication) getApplication())
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase); // Setup dependency ((MyApplication) getApplication()) .builder() .purchaseComponent() .inject(this); // Setup butterknife ButterKnife.bind(this); // Setup views setUpView(); } private void setUpView() { // Progress dialog mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setCancelable(false); // Toolbar setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void bindViewModel() { // binding credit card
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase); // Setup dependency ((MyApplication) getApplication()) .builder() .purchaseComponent() .inject(this); // Setup butterknife ButterKnife.bind(this); // Setup views setUpView(); } private void setUpView() { // Progress dialog mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setCancelable(false); // Toolbar setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void bindViewModel() { // binding credit card
RxTextViewEx.textChanges(mEdtCreditCard)
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
private void setUpView() { // Progress dialog mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setCancelable(false); // Toolbar setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void bindViewModel() { // binding credit card RxTextViewEx.textChanges(mEdtCreditCard) .takeUntil(preDestroy()) .subscribe(mViewModel::nextCreditCard); // binding email RxTextViewEx.textChanges(mEdtEmail) .takeUntil(preDestroy()) .subscribe(mViewModel::nextEmail); // create event on click on submit onSubmitClickListener = v -> mViewModel.submit() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .takeUntil(preDestroy()) .doOnSubscribe(mProgressDialog::show) .doOnTerminate(mProgressDialog::hide) .subscribe(done -> {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/RxTextViewEx.java // public class RxTextViewEx { // // /** // * Create an observable of character sequences for text changes on {@code view}. // * <p> // * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe // * to free this reference. // * <p> // * <em>Note:</em> A value will be emitted immediately on subscribe. // */ // @CheckResult // @NonNull // public static Observable<CharSequence> textChanges(@NonNull TextView view) { // return Observable.create(new TextViewSubscribeUnInit(view)); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/UiUtils.java // public class UiUtils { // public static void resetTintColor(Context context, View view) { // TintManager tintManager = TintManager.get(context); // ViewCompat.setBackgroundTintList(view, // tintManager.getTintList(android.support.design.R.drawable.abc_edit_text_material)); // } // // public static void showDialog(String text, Context context) { // new AlertDialog.Builder(context) // .setMessage(text) // .setPositiveButton(android.R.string.yes, (dialog, which) -> { // }) // .show(); // } // // public static void closeKeyboard(Activity context) { // // Check if no view has focus: // View view = context.getCurrentFocus(); // if (view != null) { // InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPurchaseViewModel.java // public interface IPurchaseViewModel { // /** // * Return observable that check valid credit card // */ // Observable<Boolean> creditCardValid(); // // /** // * Return observable check valid email // */ // Observable<Boolean> emailValid(); // // /** // * update credit card // */ // void nextCreditCard(CharSequence creditCard); // // /** // * update email // */ // void nextEmail(CharSequence email); // // /** // * Create observable check be able to submit? // */ // Observable<Boolean> canSubmit(); // // /** // * Command submit // */ // Observable<Boolean> submit(); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/PurchaseActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.utils.RxTextViewEx; import apidez.com.android_mvvm_sample.utils.UiUtils; import apidez.com.android_mvvm_sample.viewmodel.IPurchaseViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; private void setUpView() { // Progress dialog mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setCancelable(false); // Toolbar setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void bindViewModel() { // binding credit card RxTextViewEx.textChanges(mEdtCreditCard) .takeUntil(preDestroy()) .subscribe(mViewModel::nextCreditCard); // binding email RxTextViewEx.textChanges(mEdtEmail) .takeUntil(preDestroy()) .subscribe(mViewModel::nextEmail); // create event on click on submit onSubmitClickListener = v -> mViewModel.submit() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .takeUntil(preDestroy()) .doOnSubscribe(mProgressDialog::show) .doOnTerminate(mProgressDialog::hide) .subscribe(done -> {
UiUtils.showDialog(getString(R.string.success), this);
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java // public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // // private Context mContext; // private List<Place> mPlaces; // // public PlacesAdapter(Context context) { // mContext = context; // mPlaces = new ArrayList<>(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final View view = LayoutInflater.from(mContext).inflate(R.layout.item_place, parent, false); // return new PlaceViewHolder(view); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // PlaceViewHolder holder = (PlaceViewHolder) viewHolder; // holder.itemView.setOnClickListener(v -> {}); // // Place place = mPlaces.get(position); // holder.name.setText(place.getName()); // Picasso.with(mContext) // .load(place.getIcon()) // .placeholder(R.drawable.ic_place_36dp) // .into(holder.icon); // } // // @Override // public int getItemCount() { // return mPlaces.size(); // } // // // this view holder hold the view of one particular card // public static class PlaceViewHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.name) // TextView name; // // @Bind(R.id.icon) // ImageView icon; // // public PlaceViewHolder(View view) { // super(view); // ButterKnife.bind(this, view); // } // } // // /** // * Update the list item // */ // public void updatePlaces(List<Place> places) { // mPlaces = places; // notifyDataSetChanged(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.view.adapter.PlacesAdapter; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package apidez.com.android_mvvm_sample.view.fragment; public class PlacesFragment extends BaseFragment { @Bind(R.id.recycler_view) RecyclerView mRecyclerView; @Bind(R.id.toolbar) Toolbar mToolbar; @Inject
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java // public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // // private Context mContext; // private List<Place> mPlaces; // // public PlacesAdapter(Context context) { // mContext = context; // mPlaces = new ArrayList<>(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final View view = LayoutInflater.from(mContext).inflate(R.layout.item_place, parent, false); // return new PlaceViewHolder(view); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // PlaceViewHolder holder = (PlaceViewHolder) viewHolder; // holder.itemView.setOnClickListener(v -> {}); // // Place place = mPlaces.get(position); // holder.name.setText(place.getName()); // Picasso.with(mContext) // .load(place.getIcon()) // .placeholder(R.drawable.ic_place_36dp) // .into(holder.icon); // } // // @Override // public int getItemCount() { // return mPlaces.size(); // } // // // this view holder hold the view of one particular card // public static class PlaceViewHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.name) // TextView name; // // @Bind(R.id.icon) // ImageView icon; // // public PlaceViewHolder(View view) { // super(view); // ButterKnife.bind(this, view); // } // } // // /** // * Update the list item // */ // public void updatePlaces(List<Place> places) { // mPlaces = places; // notifyDataSetChanged(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.view.adapter.PlacesAdapter; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package apidez.com.android_mvvm_sample.view.fragment; public class PlacesFragment extends BaseFragment { @Bind(R.id.recycler_view) RecyclerView mRecyclerView; @Bind(R.id.toolbar) Toolbar mToolbar; @Inject
IPlacesViewModel mViewModel;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java // public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // // private Context mContext; // private List<Place> mPlaces; // // public PlacesAdapter(Context context) { // mContext = context; // mPlaces = new ArrayList<>(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final View view = LayoutInflater.from(mContext).inflate(R.layout.item_place, parent, false); // return new PlaceViewHolder(view); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // PlaceViewHolder holder = (PlaceViewHolder) viewHolder; // holder.itemView.setOnClickListener(v -> {}); // // Place place = mPlaces.get(position); // holder.name.setText(place.getName()); // Picasso.with(mContext) // .load(place.getIcon()) // .placeholder(R.drawable.ic_place_36dp) // .into(holder.icon); // } // // @Override // public int getItemCount() { // return mPlaces.size(); // } // // // this view holder hold the view of one particular card // public static class PlaceViewHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.name) // TextView name; // // @Bind(R.id.icon) // ImageView icon; // // public PlaceViewHolder(View view) { // super(view); // ButterKnife.bind(this, view); // } // } // // /** // * Update the list item // */ // public void updatePlaces(List<Place> places) { // mPlaces = places; // notifyDataSetChanged(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.view.adapter.PlacesAdapter; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package apidez.com.android_mvvm_sample.view.fragment; public class PlacesFragment extends BaseFragment { @Bind(R.id.recycler_view) RecyclerView mRecyclerView; @Bind(R.id.toolbar) Toolbar mToolbar; @Inject IPlacesViewModel mViewModel; private ProgressDialog mProgressDialog;
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java // public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // // private Context mContext; // private List<Place> mPlaces; // // public PlacesAdapter(Context context) { // mContext = context; // mPlaces = new ArrayList<>(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final View view = LayoutInflater.from(mContext).inflate(R.layout.item_place, parent, false); // return new PlaceViewHolder(view); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // PlaceViewHolder holder = (PlaceViewHolder) viewHolder; // holder.itemView.setOnClickListener(v -> {}); // // Place place = mPlaces.get(position); // holder.name.setText(place.getName()); // Picasso.with(mContext) // .load(place.getIcon()) // .placeholder(R.drawable.ic_place_36dp) // .into(holder.icon); // } // // @Override // public int getItemCount() { // return mPlaces.size(); // } // // // this view holder hold the view of one particular card // public static class PlaceViewHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.name) // TextView name; // // @Bind(R.id.icon) // ImageView icon; // // public PlaceViewHolder(View view) { // super(view); // ButterKnife.bind(this, view); // } // } // // /** // * Update the list item // */ // public void updatePlaces(List<Place> places) { // mPlaces = places; // notifyDataSetChanged(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.view.adapter.PlacesAdapter; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package apidez.com.android_mvvm_sample.view.fragment; public class PlacesFragment extends BaseFragment { @Bind(R.id.recycler_view) RecyclerView mRecyclerView; @Bind(R.id.toolbar) Toolbar mToolbar; @Inject IPlacesViewModel mViewModel; private ProgressDialog mProgressDialog;
private PlacesAdapter mPlacesAdapter;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java // public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // // private Context mContext; // private List<Place> mPlaces; // // public PlacesAdapter(Context context) { // mContext = context; // mPlaces = new ArrayList<>(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final View view = LayoutInflater.from(mContext).inflate(R.layout.item_place, parent, false); // return new PlaceViewHolder(view); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // PlaceViewHolder holder = (PlaceViewHolder) viewHolder; // holder.itemView.setOnClickListener(v -> {}); // // Place place = mPlaces.get(position); // holder.name.setText(place.getName()); // Picasso.with(mContext) // .load(place.getIcon()) // .placeholder(R.drawable.ic_place_36dp) // .into(holder.icon); // } // // @Override // public int getItemCount() { // return mPlaces.size(); // } // // // this view holder hold the view of one particular card // public static class PlaceViewHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.name) // TextView name; // // @Bind(R.id.icon) // ImageView icon; // // public PlaceViewHolder(View view) { // super(view); // ButterKnife.bind(this, view); // } // } // // /** // * Update the list item // */ // public void updatePlaces(List<Place> places) { // mPlaces = places; // notifyDataSetChanged(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.view.adapter.PlacesAdapter; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package apidez.com.android_mvvm_sample.view.fragment; public class PlacesFragment extends BaseFragment { @Bind(R.id.recycler_view) RecyclerView mRecyclerView; @Bind(R.id.toolbar) Toolbar mToolbar; @Inject IPlacesViewModel mViewModel; private ProgressDialog mProgressDialog; private PlacesAdapter mPlacesAdapter; public static PlacesFragment newInstance() { PlacesFragment fragment = new PlacesFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public PlacesFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java // public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { // // private Context mContext; // private List<Place> mPlaces; // // public PlacesAdapter(Context context) { // mContext = context; // mPlaces = new ArrayList<>(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // final View view = LayoutInflater.from(mContext).inflate(R.layout.item_place, parent, false); // return new PlaceViewHolder(view); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // PlaceViewHolder holder = (PlaceViewHolder) viewHolder; // holder.itemView.setOnClickListener(v -> {}); // // Place place = mPlaces.get(position); // holder.name.setText(place.getName()); // Picasso.with(mContext) // .load(place.getIcon()) // .placeholder(R.drawable.ic_place_36dp) // .into(holder.icon); // } // // @Override // public int getItemCount() { // return mPlaces.size(); // } // // // this view holder hold the view of one particular card // public static class PlaceViewHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.name) // TextView name; // // @Bind(R.id.icon) // ImageView icon; // // public PlaceViewHolder(View view) { // super(view); // ButterKnife.bind(this, view); // } // } // // /** // * Update the list item // */ // public void updatePlaces(List<Place> places) { // mPlaces = places; // notifyDataSetChanged(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java // public class MyApplication extends Application { // // protected AppComponent mAppComponent; // protected ComponentBuilder mComponentBuilder; // // @Override // public void onCreate() { // super.onCreate(); // // // Create app component // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule()) // .build(); // // // Create component builder // mComponentBuilder = new ComponentBuilder(mAppComponent); // } // // public AppComponent component() { // return mAppComponent; // } // // public ComponentBuilder builder() { // return mComponentBuilder; // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.view.adapter.PlacesAdapter; import apidez.com.android_mvvm_sample.MyApplication; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import butterknife.Bind; import butterknife.ButterKnife; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package apidez.com.android_mvvm_sample.view.fragment; public class PlacesFragment extends BaseFragment { @Bind(R.id.recycler_view) RecyclerView mRecyclerView; @Bind(R.id.toolbar) Toolbar mToolbar; @Inject IPlacesViewModel mViewModel; private ProgressDialog mProgressDialog; private PlacesAdapter mPlacesAdapter; public static PlacesFragment newInstance() { PlacesFragment fragment = new PlacesFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public PlacesFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true);
((MyApplication) getActivity().getApplication())
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // }
import java.util.List; import apidez.com.android_mvvm_sample.model.entity.Place; import rx.Observable;
package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public interface IPlacesViewModel { /** * Fetch all places from google */ Observable<Boolean> fetchAllPlaces(); /** * Observe current places */
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java import java.util.List; import apidez.com.android_mvvm_sample.model.entity.Place; import rx.Observable; package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public interface IPlacesViewModel { /** * Fetch all places from google */ Observable<Boolean> fetchAllPlaces(); /** * Observe current places */
Observable<List<Place>> currentPlaces();
nongdenchet/android-mvvm-with-tests
app/src/test/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModelTest.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // }
import android.test.suitebuilder.annotation.SmallTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import rx.Observable; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package apidez.com.android_mvvm_sample.viewmodel; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ @SmallTest @RunWith(JUnit4.class) public class PurchaseViewModelTest { private PurchaseViewModel purchaseViewModel;
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java // public class PurchaseApi implements IPurchaseApi { // private Gson mGson; // // public PurchaseApi(@NonNull Gson gson) { // mGson = gson; // } // // /** // * Fake networking // */ // public Observable<Boolean> submitPurchase(String creditCard, String email) { // Purchase purchase = new Purchase(creditCard, email); // return Observable.create(subscriber -> { // try { // String json = mGson.toJson(purchase); // Thread.sleep((json.length() % 3) * 1000); // subscriber.onNext(true); // subscriber.onCompleted(); // } catch (Exception exception) { // subscriber.onError(exception); // } // }); // } // } // Path: app/src/test/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModelTest.java import android.test.suitebuilder.annotation.SmallTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import apidez.com.android_mvvm_sample.model.api.PurchaseApi; import rx.Observable; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package apidez.com.android_mvvm_sample.viewmodel; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ @SmallTest @RunWith(JUnit4.class) public class PurchaseViewModelTest { private PurchaseViewModel purchaseViewModel;
private PurchaseApi purchaseApi;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java // public class PlacesFragment extends BaseFragment { // // @Bind(R.id.recycler_view) // RecyclerView mRecyclerView; // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Inject // IPlacesViewModel mViewModel; // // private ProgressDialog mProgressDialog; // private PlacesAdapter mPlacesAdapter; // // public static PlacesFragment newInstance() { // PlacesFragment fragment = new PlacesFragment(); // Bundle args = new Bundle(); // fragment.setArguments(args); // return fragment; // } // // public PlacesFragment() { // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setHasOptionsMenu(true); // ((MyApplication) getActivity().getApplication()) // .builder() // .placesComponent() // .inject(this); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.fragment_places, container, false); // ButterKnife.bind(this, rootView); // setupView(); // return rootView; // } // // private void setupView() { // // Progress dialog setup // mProgressDialog = new ProgressDialog(getActivity()); // mProgressDialog.setMessage(getString(R.string.loading)); // mProgressDialog.setCancelable(false); // // // Actionbar setup // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // // Recyclerview setup // mPlacesAdapter = new PlacesAdapter(getActivity()); // mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); // mRecyclerView.setAdapter(mPlacesAdapter); // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // // Observe current places // mViewModel.currentPlaces() // .takeUntil(preDestroy()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(mPlacesAdapter::updatePlaces); // // // fetch all places // mViewModel.fetchAllPlaces() // .observeOn(AndroidSchedulers.mainThread()) // .subscribeOn(Schedulers.io()) // .takeUntil(preDestroy()) // .doOnSubscribe(mProgressDialog::show) // .doOnTerminate(mProgressDialog::hide) // .subscribe(succes -> {}, throwable -> {}); // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // super.onCreateOptionsMenu(menu, inflater); // inflater.inflate(R.menu.menu_places, menu); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // getActivity().onBackPressed(); // return true; // case R.id.action_cafe: // case R.id.action_food: // case R.id.action_store: // case R.id.action_theater: // case R.id.action_restaurant: // case R.id.action_all: // // Filter the items // mViewModel.filterPlacesByType(item.getTitle().toString()); // return true; // } // return super.onOptionsItemSelected(item); // } // }
import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.view.fragment.PlacesFragment; import dagger.Subcomponent;
package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/24/15. */ @ViewScope @Subcomponent(modules = {PlacesModule.class}) public interface PlacesComponent {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragment.java // public class PlacesFragment extends BaseFragment { // // @Bind(R.id.recycler_view) // RecyclerView mRecyclerView; // // @Bind(R.id.toolbar) // Toolbar mToolbar; // // @Inject // IPlacesViewModel mViewModel; // // private ProgressDialog mProgressDialog; // private PlacesAdapter mPlacesAdapter; // // public static PlacesFragment newInstance() { // PlacesFragment fragment = new PlacesFragment(); // Bundle args = new Bundle(); // fragment.setArguments(args); // return fragment; // } // // public PlacesFragment() { // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setHasOptionsMenu(true); // ((MyApplication) getActivity().getApplication()) // .builder() // .placesComponent() // .inject(this); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.fragment_places, container, false); // ButterKnife.bind(this, rootView); // setupView(); // return rootView; // } // // private void setupView() { // // Progress dialog setup // mProgressDialog = new ProgressDialog(getActivity()); // mProgressDialog.setMessage(getString(R.string.loading)); // mProgressDialog.setCancelable(false); // // // Actionbar setup // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // // Recyclerview setup // mPlacesAdapter = new PlacesAdapter(getActivity()); // mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); // mRecyclerView.setAdapter(mPlacesAdapter); // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // // Observe current places // mViewModel.currentPlaces() // .takeUntil(preDestroy()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(mPlacesAdapter::updatePlaces); // // // fetch all places // mViewModel.fetchAllPlaces() // .observeOn(AndroidSchedulers.mainThread()) // .subscribeOn(Schedulers.io()) // .takeUntil(preDestroy()) // .doOnSubscribe(mProgressDialog::show) // .doOnTerminate(mProgressDialog::hide) // .subscribe(succes -> {}, throwable -> {}); // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // super.onCreateOptionsMenu(menu, inflater); // inflater.inflate(R.menu.menu_places, menu); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // getActivity().onBackPressed(); // return true; // case R.id.action_cafe: // case R.id.action_food: // case R.id.action_store: // case R.id.action_theater: // case R.id.action_restaurant: // case R.id.action_all: // // Filter the items // mViewModel.filterPlacesByType(item.getTitle().toString()); // return true; // } // return super.onOptionsItemSelected(item); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.scope.ViewScope; import apidez.com.android_mvvm_sample.view.fragment.PlacesFragment; import dagger.Subcomponent; package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/24/15. */ @ViewScope @Subcomponent(modules = {PlacesModule.class}) public interface PlacesComponent {
void inject(PlacesFragment placesFragment);
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/NumericUtils.java // public class NumericUtils { // /** // * Check if a string is Integer // */ // public static boolean isNumeric(String number) { // return number.matches("-?\\d+(\\.\\d+)?"); // } // // /** // * Check if a string is Integer // */ // public static boolean isNumeric(CharSequence number) { // return isNumeric(number.toString()); // } // }
import android.support.annotation.NonNull; import java.util.concurrent.TimeUnit; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.utils.NumericUtils; import rx.Observable; import rx.subjects.BehaviorSubject;
package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/2/15. */ public class PurchaseViewModel implements IPurchaseViewModel { private IPurchaseApi mPurchaseApi; private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private final int TIME_OUT = 5; private final int RETRY = 3; public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { mPurchaseApi = purchaseApi; } // observable property private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); /** * Return an observable that emit the validation of credit card */ public Observable<Boolean> creditCardValid() {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPurchaseApi.java // public interface IPurchaseApi { // Observable<Boolean> submitPurchase(String creditCard, String email); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/NumericUtils.java // public class NumericUtils { // /** // * Check if a string is Integer // */ // public static boolean isNumeric(String number) { // return number.matches("-?\\d+(\\.\\d+)?"); // } // // /** // * Check if a string is Integer // */ // public static boolean isNumeric(CharSequence number) { // return isNumeric(number.toString()); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PurchaseViewModel.java import android.support.annotation.NonNull; import java.util.concurrent.TimeUnit; import apidez.com.android_mvvm_sample.model.api.IPurchaseApi; import apidez.com.android_mvvm_sample.utils.NumericUtils; import rx.Observable; import rx.subjects.BehaviorSubject; package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/2/15. */ public class PurchaseViewModel implements IPurchaseViewModel { private IPurchaseApi mPurchaseApi; private final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private final int TIME_OUT = 5; private final int RETRY = 3; public PurchaseViewModel(@NonNull IPurchaseApi purchaseApi) { mPurchaseApi = purchaseApi; } // observable property private BehaviorSubject<CharSequence> mCreditCard = BehaviorSubject.create(); private BehaviorSubject<CharSequence> mEmail = BehaviorSubject.create(); /** * Return an observable that emit the validation of credit card */ public Observable<Boolean> creditCardValid() {
return mCreditCard.map(inputText -> (inputText.length() == 12 && NumericUtils.isNumeric(inputText)));
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // }
import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule;
package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; }
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; }
public PlacesComponent placesComponent() {
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // }
import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule;
package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; } public PlacesComponent placesComponent() {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; } public PlacesComponent placesComponent() {
return appComponent.plus(new PlacesModule());
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // }
import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule;
package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; } public PlacesComponent placesComponent() { return appComponent.plus(new PlacesModule()); }
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; } public PlacesComponent placesComponent() { return appComponent.plus(new PlacesModule()); }
public PurchaseComponent purchaseComponent() {
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // }
import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule;
package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; } public PlacesComponent placesComponent() { return appComponent.plus(new PlacesModule()); } public PurchaseComponent purchaseComponent() {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PlacesComponent.java // @ViewScope // @Subcomponent(modules = {PlacesModule.class}) // public interface PlacesComponent { // void inject(PlacesFragment placesFragment); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/PurchaseComponent.java // @ViewScope // @Subcomponent(modules = {PurchaseModule.class}) // public interface PurchaseComponent { // void inject(PurchaseActivity purchaseActivity); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/ComponentBuilder.java import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent; import apidez.com.android_mvvm_sample.dependency.component.PurchaseComponent; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/24/15. */ /** * Use to build subcomponent */ public class ComponentBuilder { private AppComponent appComponent; public ComponentBuilder(AppComponent appComponent) { this.appComponent = appComponent; } public PlacesComponent placesComponent() { return appComponent.plus(new PlacesModule()); } public PurchaseComponent purchaseComponent() {
return appComponent.plus(new PurchaseModule());
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/utils/TestDataUtils.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import apidez.com.android_mvvm_sample.model.entity.Place;
package apidez.com.android_mvvm_sample.utils; /** * Created by nongdenchet on 10/22/15. */ public class TestDataUtils { /** * Google search nearby test data */ public static GoogleSearchResult nearByData() {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/TestDataUtils.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import apidez.com.android_mvvm_sample.model.entity.Place; package apidez.com.android_mvvm_sample.utils; /** * Created by nongdenchet on 10/22/15. */ public class TestDataUtils { /** * Google search nearby test data */ public static GoogleSearchResult nearByData() {
List<Place> places = new ArrayList<>();
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/AppModule.java // @Module // public class AppModule { // @Singleton // @Provides // public Gson provideGson() { // return new Gson(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // }
import javax.inject.Singleton; import apidez.com.android_mvvm_sample.dependency.module.AppModule; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; import dagger.Component;
package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/2/15. */ @Singleton @Component(modules = {AppModule.class}) public interface AppComponent {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/AppModule.java // @Module // public class AppModule { // @Singleton // @Provides // public Gson provideGson() { // return new Gson(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java import javax.inject.Singleton; import apidez.com.android_mvvm_sample.dependency.module.AppModule; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; import dagger.Component; package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/2/15. */ @Singleton @Component(modules = {AppModule.class}) public interface AppComponent {
PlacesComponent plus(PlacesModule placesModule);
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/AppModule.java // @Module // public class AppModule { // @Singleton // @Provides // public Gson provideGson() { // return new Gson(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // }
import javax.inject.Singleton; import apidez.com.android_mvvm_sample.dependency.module.AppModule; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; import dagger.Component;
package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/2/15. */ @Singleton @Component(modules = {AppModule.class}) public interface AppComponent { PlacesComponent plus(PlacesModule placesModule);
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/AppModule.java // @Module // public class AppModule { // @Singleton // @Provides // public Gson provideGson() { // return new Gson(); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PlacesModule.java // @Module // public class PlacesModule { // @Provides // @ViewScope // public IPlacesApi providePlacesApi() { // return RetrofitUtils.create(IPlacesApi.class, "https://maps.googleapis.com/maps/api/place/"); // } // // @Provides // @ViewScope // public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) { // return new PlacesViewModel(placesApi); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/PurchaseModule.java // @Module // public class PurchaseModule { // @Provides // @ViewScope // public IPurchaseApi providePurchaseApi(Gson gson) { // return new PurchaseApi(gson); // } // // @Provides // @ViewScope // public IPurchaseViewModel providePurchaseViewModel(IPurchaseApi purchaseApi) { // return new PurchaseViewModel(purchaseApi); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java import javax.inject.Singleton; import apidez.com.android_mvvm_sample.dependency.module.AppModule; import apidez.com.android_mvvm_sample.dependency.module.PlacesModule; import apidez.com.android_mvvm_sample.dependency.module.PurchaseModule; import dagger.Component; package apidez.com.android_mvvm_sample.dependency.component; /** * Created by nongdenchet on 10/2/15. */ @Singleton @Component(modules = {AppModule.class}) public interface AppComponent { PlacesComponent plus(PlacesModule placesModule);
PurchaseComponent plus(PurchaseModule purchaseModule);
nongdenchet/android-mvvm-with-tests
app/src/androidTest/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragmentInteractTest.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/EmptyActivity.java // public class EmptyActivity extends BaseActivity { // }
import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.test.rule.ActivityTestRule; import android.test.suitebuilder.annotation.MediumTest; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.concurrent.CountDownLatch; import apidez.com.android_mvvm_sample.view.activity.EmptyActivity;
package apidez.com.android_mvvm_sample.view.fragment; /** * Created by nongdenchet on 10/21/15. */ @MediumTest @RunWith(JUnit4.class) public class PlacesFragmentInteractTest { @Rule
// Path: app/src/main/java/apidez/com/android_mvvm_sample/view/activity/EmptyActivity.java // public class EmptyActivity extends BaseActivity { // } // Path: app/src/androidTest/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragmentInteractTest.java import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.test.rule.ActivityTestRule; import android.test.suitebuilder.annotation.MediumTest; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.concurrent.CountDownLatch; import apidez.com.android_mvvm_sample.view.activity.EmptyActivity; package apidez.com.android_mvvm_sample.view.fragment; /** * Created by nongdenchet on 10/21/15. */ @MediumTest @RunWith(JUnit4.class) public class PlacesFragmentInteractTest { @Rule
public ActivityTestRule<EmptyActivity> activityTestRule =
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/AppModule.java // @Module // public class AppModule { // @Singleton // @Provides // public Gson provideGson() { // return new Gson(); // } // }
import android.app.Application; import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.DaggerAppComponent; import apidez.com.android_mvvm_sample.dependency.module.AppModule;
package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/2/15. */ public class MyApplication extends Application { protected AppComponent mAppComponent; protected ComponentBuilder mComponentBuilder; @Override public void onCreate() { super.onCreate(); // Create app component mAppComponent = DaggerAppComponent.builder()
// Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class}) // public interface AppComponent { // PlacesComponent plus(PlacesModule placesModule); // PurchaseComponent plus(PurchaseModule purchaseModule); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/dependency/module/AppModule.java // @Module // public class AppModule { // @Singleton // @Provides // public Gson provideGson() { // return new Gson(); // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/MyApplication.java import android.app.Application; import apidez.com.android_mvvm_sample.dependency.component.AppComponent; import apidez.com.android_mvvm_sample.dependency.component.DaggerAppComponent; import apidez.com.android_mvvm_sample.dependency.module.AppModule; package apidez.com.android_mvvm_sample; /** * Created by nongdenchet on 10/2/15. */ public class MyApplication extends Application { protected AppComponent mAppComponent; protected ComponentBuilder mComponentBuilder; @Override public void onCreate() { super.onCreate(); // Create app component mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule())
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.model.entity.Place; import butterknife.Bind; import butterknife.ButterKnife;
package apidez.com.android_mvvm_sample.view.adapter; /** * Created by nongdenchet on 10/21/15. */ public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext;
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/view/adapter/PlacesAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import apidez.com.android_mvvm_sample.R; import apidez.com.android_mvvm_sample.model.entity.Place; import butterknife.Bind; import butterknife.ButterKnife; package apidez.com.android_mvvm_sample.view.adapter; /** * Created by nongdenchet on 10/21/15. */ public class PlacesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext;
private List<Place> mPlaces;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // }
import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.model.entity.Place; import rx.Observable; import rx.subjects.BehaviorSubject;
package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public class PlacesViewModel implements IPlacesViewModel { private IPlacesApi mPlacesApi; private final int TIME_OUT = 5; private final int RETRY = 3;
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModel.java import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.model.entity.Place; import rx.Observable; import rx.subjects.BehaviorSubject; package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public class PlacesViewModel implements IPlacesViewModel { private IPlacesApi mPlacesApi; private final int TIME_OUT = 5; private final int RETRY = 3;
private List<Place> allPlaces;
nongdenchet/android-mvvm-with-tests
app/src/androidTest/java/apidez/com/android_mvvm_sample/stub/StubPlacesViewModel.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/StringUtils.java // public class StringUtils { // public static String generateString(String characters, int length) { // Random rand = new Random(); // char[] text = new char[length]; // for (int i = 0; i < length; i++) { // text[i] = characters.charAt(rand.nextInt(characters.length())); // } // return new String(text); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // }
import java.util.Arrays; import java.util.List; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.StringUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import rx.Observable;
package apidez.com.android_mvvm_sample.stub; /** * Created by nongdenchet on 10/21/15. */ /** * UI only related test */ public class StubPlacesViewModel implements IPlacesViewModel { @Override public Observable<Boolean> fetchAllPlaces() { return Observable.just(true); } @Override
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/StringUtils.java // public class StringUtils { // public static String generateString(String characters, int length) { // Random rand = new Random(); // char[] text = new char[length]; // for (int i = 0; i < length; i++) { // text[i] = characters.charAt(rand.nextInt(characters.length())); // } // return new String(text); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // Path: app/src/androidTest/java/apidez/com/android_mvvm_sample/stub/StubPlacesViewModel.java import java.util.Arrays; import java.util.List; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.StringUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import rx.Observable; package apidez.com.android_mvvm_sample.stub; /** * Created by nongdenchet on 10/21/15. */ /** * UI only related test */ public class StubPlacesViewModel implements IPlacesViewModel { @Override public Observable<Boolean> fetchAllPlaces() { return Observable.just(true); } @Override
public Observable<List<Place>> currentPlaces() {
nongdenchet/android-mvvm-with-tests
app/src/androidTest/java/apidez/com/android_mvvm_sample/stub/StubPlacesViewModel.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/StringUtils.java // public class StringUtils { // public static String generateString(String characters, int length) { // Random rand = new Random(); // char[] text = new char[length]; // for (int i = 0; i < length; i++) { // text[i] = characters.charAt(rand.nextInt(characters.length())); // } // return new String(text); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // }
import java.util.Arrays; import java.util.List; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.StringUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import rx.Observable;
package apidez.com.android_mvvm_sample.stub; /** * Created by nongdenchet on 10/21/15. */ /** * UI only related test */ public class StubPlacesViewModel implements IPlacesViewModel { @Override public Observable<Boolean> fetchAllPlaces() { return Observable.just(true); } @Override public Observable<List<Place>> currentPlaces() {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/StringUtils.java // public class StringUtils { // public static String generateString(String characters, int length) { // Random rand = new Random(); // char[] text = new char[length]; // for (int i = 0; i < length; i++) { // text[i] = characters.charAt(rand.nextInt(characters.length())); // } // return new String(text); // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/viewmodel/IPlacesViewModel.java // public interface IPlacesViewModel { // /** // * Fetch all places from google // */ // Observable<Boolean> fetchAllPlaces(); // // /** // * Observe current places // */ // Observable<List<Place>> currentPlaces(); // // /** // * Filter the places // */ // void filterPlacesByType(String type); // } // Path: app/src/androidTest/java/apidez/com/android_mvvm_sample/stub/StubPlacesViewModel.java import java.util.Arrays; import java.util.List; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.StringUtils; import apidez.com.android_mvvm_sample.viewmodel.IPlacesViewModel; import rx.Observable; package apidez.com.android_mvvm_sample.stub; /** * Created by nongdenchet on 10/21/15. */ /** * UI only related test */ public class StubPlacesViewModel implements IPlacesViewModel { @Override public Observable<Boolean> fetchAllPlaces() { return Observable.just(true); } @Override public Observable<List<Place>> currentPlaces() {
Place[] places = new Place[]{new Place.Builder().name(StringUtils.generateString("apidez", 500)).build()};
nongdenchet/android-mvvm-with-tests
app/src/test/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModelTest.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/TestDataUtils.java // public class TestDataUtils { // // /** // * Google search nearby test data // */ // public static GoogleSearchResult nearByData() { // List<Place> places = new ArrayList<>(); // places.add(new Place.Builder().name("A").types(Arrays.asList("food", "cafe")).build()); // places.add(new Place.Builder().name("B").types(Arrays.asList("food", "movie_theater")).build()); // places.add(new Place.Builder().name("C").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("D").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("E").types(Arrays.asList("cafe")).build()); // places.add(new Place.Builder().name("F").types(Arrays.asList("food", "store", "cafe", "movie_theater")).build()); // places.add(new Place.Builder().name("G").types(Arrays.asList("restaurant", "store")).build()); // places.add(new Place.Builder().name("H").types(Arrays.asList("restaurant", "cafe")).build()); // places.add(new Place.Builder().name("I").types(Arrays.asList("restaurant")).build()); // places.add(new Place.Builder().name("K").types(Arrays.asList("movie_theater", "cafe", "food")).build()); // GoogleSearchResult googleSearchResult = new GoogleSearchResult(); // googleSearchResult.status = "OK"; // googleSearchResult.results = places; // return googleSearchResult; // } // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.TestDataUtils; import rx.Observable; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public class PlacesViewModelTest { private PlacesViewModel placesViewModel;
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/TestDataUtils.java // public class TestDataUtils { // // /** // * Google search nearby test data // */ // public static GoogleSearchResult nearByData() { // List<Place> places = new ArrayList<>(); // places.add(new Place.Builder().name("A").types(Arrays.asList("food", "cafe")).build()); // places.add(new Place.Builder().name("B").types(Arrays.asList("food", "movie_theater")).build()); // places.add(new Place.Builder().name("C").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("D").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("E").types(Arrays.asList("cafe")).build()); // places.add(new Place.Builder().name("F").types(Arrays.asList("food", "store", "cafe", "movie_theater")).build()); // places.add(new Place.Builder().name("G").types(Arrays.asList("restaurant", "store")).build()); // places.add(new Place.Builder().name("H").types(Arrays.asList("restaurant", "cafe")).build()); // places.add(new Place.Builder().name("I").types(Arrays.asList("restaurant")).build()); // places.add(new Place.Builder().name("K").types(Arrays.asList("movie_theater", "cafe", "food")).build()); // GoogleSearchResult googleSearchResult = new GoogleSearchResult(); // googleSearchResult.status = "OK"; // googleSearchResult.results = places; // return googleSearchResult; // } // } // Path: app/src/test/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModelTest.java import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.TestDataUtils; import rx.Observable; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public class PlacesViewModelTest { private PlacesViewModel placesViewModel;
private IPlacesApi placesApi;
nongdenchet/android-mvvm-with-tests
app/src/test/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModelTest.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/TestDataUtils.java // public class TestDataUtils { // // /** // * Google search nearby test data // */ // public static GoogleSearchResult nearByData() { // List<Place> places = new ArrayList<>(); // places.add(new Place.Builder().name("A").types(Arrays.asList("food", "cafe")).build()); // places.add(new Place.Builder().name("B").types(Arrays.asList("food", "movie_theater")).build()); // places.add(new Place.Builder().name("C").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("D").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("E").types(Arrays.asList("cafe")).build()); // places.add(new Place.Builder().name("F").types(Arrays.asList("food", "store", "cafe", "movie_theater")).build()); // places.add(new Place.Builder().name("G").types(Arrays.asList("restaurant", "store")).build()); // places.add(new Place.Builder().name("H").types(Arrays.asList("restaurant", "cafe")).build()); // places.add(new Place.Builder().name("I").types(Arrays.asList("restaurant")).build()); // places.add(new Place.Builder().name("K").types(Arrays.asList("movie_theater", "cafe", "food")).build()); // GoogleSearchResult googleSearchResult = new GoogleSearchResult(); // googleSearchResult.status = "OK"; // googleSearchResult.results = places; // return googleSearchResult; // } // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.TestDataUtils; import rx.Observable; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public class PlacesViewModelTest { private PlacesViewModel placesViewModel; private IPlacesApi placesApi; private TestSubscriber<Boolean> testSubscriber;
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/IPlacesApi.java // public interface IPlacesApi { // @GET("nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo") // Observable<GoogleSearchResult> placesResult(); // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/GoogleSearchResult.java // public class GoogleSearchResult { // @SerializedName("status") // public String status; // // @SerializedName("results") // public List<Place> results; // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Place.java // public class Place implements Parcelable { // @SerializedName("icon") // private String icon; // // @SerializedName("place_id") // private String id; // // @SerializedName("name") // private String name; // // @SerializedName("types") // List<String> types; // // protected Place(Parcel in) { // icon = in.readString(); // id = in.readString(); // name = in.readString(); // types = in.createStringArrayList(); // } // // public static final Creator<Place> CREATOR = new Creator<Place>() { // @Override // public Place createFromParcel(Parcel in) { // return new Place(in); // } // // @Override // public Place[] newArray(int size) { // return new Place[size]; // } // }; // // private Place(String icon, String id, String name, List<String> types) { // this.icon = icon; // this.id = id; // this.name = name; // this.types = types; // } // // public String getIcon() { // return icon; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public List<String> getTypes() { // return types; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(icon); // dest.writeString(id); // dest.writeString(name); // dest.writeStringList(types); // } // // public static class Builder { // private String id = UUID.randomUUID().toString(); // private String icon; // private String name; // List<String> types; // // public Builder name(String name) { // this.name = name; // return this; // } // // public Builder icon(String icon) { // this.icon = icon; // return this; // } // // public Builder types(List<String> types) { // this.types = types; // return this; // } // // public Place build() { // return new Place(icon, id, name, types); // } // } // } // // Path: app/src/main/java/apidez/com/android_mvvm_sample/utils/TestDataUtils.java // public class TestDataUtils { // // /** // * Google search nearby test data // */ // public static GoogleSearchResult nearByData() { // List<Place> places = new ArrayList<>(); // places.add(new Place.Builder().name("A").types(Arrays.asList("food", "cafe")).build()); // places.add(new Place.Builder().name("B").types(Arrays.asList("food", "movie_theater")).build()); // places.add(new Place.Builder().name("C").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("D").types(Arrays.asList("store")).build()); // places.add(new Place.Builder().name("E").types(Arrays.asList("cafe")).build()); // places.add(new Place.Builder().name("F").types(Arrays.asList("food", "store", "cafe", "movie_theater")).build()); // places.add(new Place.Builder().name("G").types(Arrays.asList("restaurant", "store")).build()); // places.add(new Place.Builder().name("H").types(Arrays.asList("restaurant", "cafe")).build()); // places.add(new Place.Builder().name("I").types(Arrays.asList("restaurant")).build()); // places.add(new Place.Builder().name("K").types(Arrays.asList("movie_theater", "cafe", "food")).build()); // GoogleSearchResult googleSearchResult = new GoogleSearchResult(); // googleSearchResult.status = "OK"; // googleSearchResult.results = places; // return googleSearchResult; // } // } // Path: app/src/test/java/apidez/com/android_mvvm_sample/viewmodel/PlacesViewModelTest.java import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import apidez.com.android_mvvm_sample.model.api.IPlacesApi; import apidez.com.android_mvvm_sample.model.entity.GoogleSearchResult; import apidez.com.android_mvvm_sample.model.entity.Place; import apidez.com.android_mvvm_sample.utils.TestDataUtils; import rx.Observable; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package apidez.com.android_mvvm_sample.viewmodel; /** * Created by nongdenchet on 10/21/15. */ public class PlacesViewModelTest { private PlacesViewModel placesViewModel; private IPlacesApi placesApi; private TestSubscriber<Boolean> testSubscriber;
private TestSubscriber<List<Place>> testSubscriberPlaces;
nongdenchet/android-mvvm-with-tests
app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Purchase.java // public class Purchase { // // @SerializedName("creditCard") // private String creditCard; // // @SerializedName("email") // private String email; // // public Purchase() { // } // // public Purchase(String creditCard, String email) { // this.creditCard = creditCard; // this.email = email; // } // // public String getCreditCard() { // return creditCard; // } // // public void setCreditCard(String creditCard) { // this.creditCard = creditCard; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // }
import android.support.annotation.NonNull; import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.entity.Purchase; import rx.Observable;
package apidez.com.android_mvvm_sample.model.api; /** * Created by nongdenchet on 10/3/15. */ public class PurchaseApi implements IPurchaseApi { private Gson mGson; public PurchaseApi(@NonNull Gson gson) { mGson = gson; } /** * Fake networking */ public Observable<Boolean> submitPurchase(String creditCard, String email) {
// Path: app/src/main/java/apidez/com/android_mvvm_sample/model/entity/Purchase.java // public class Purchase { // // @SerializedName("creditCard") // private String creditCard; // // @SerializedName("email") // private String email; // // public Purchase() { // } // // public Purchase(String creditCard, String email) { // this.creditCard = creditCard; // this.email = email; // } // // public String getCreditCard() { // return creditCard; // } // // public void setCreditCard(String creditCard) { // this.creditCard = creditCard; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // } // Path: app/src/main/java/apidez/com/android_mvvm_sample/model/api/PurchaseApi.java import android.support.annotation.NonNull; import com.google.gson.Gson; import apidez.com.android_mvvm_sample.model.entity.Purchase; import rx.Observable; package apidez.com.android_mvvm_sample.model.api; /** * Created by nongdenchet on 10/3/15. */ public class PurchaseApi implements IPurchaseApi { private Gson mGson; public PurchaseApi(@NonNull Gson gson) { mGson = gson; } /** * Fake networking */ public Observable<Boolean> submitPurchase(String creditCard, String email) {
Purchase purchase = new Purchase(creditCard, email);
CyberCRI/RedMetrics
src/test/java/org/cri/redmetrics/backend/Backends.java
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // }
import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException;
package org.cri.redmetrics.backend; public class Backends { public static final EventBackend EVENT = new EventBackend(); public static final GameBackend GAME = new GameBackend(); public static final GameVersionBackend GAME_VERSION = new GameVersionBackend(); public static final GroupBackend GROUP = new GroupBackend(); public static final PlayerBackend PLAYER = new PlayerBackend(); public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); private static int gameNo = 0;
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // } // Path: src/test/java/org/cri/redmetrics/backend/Backends.java import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException; package org.cri.redmetrics.backend; public class Backends { public static final EventBackend EVENT = new EventBackend(); public static final GameBackend GAME = new GameBackend(); public static final GameVersionBackend GAME_VERSION = new GameVersionBackend(); public static final GroupBackend GROUP = new GroupBackend(); public static final PlayerBackend PLAYER = new PlayerBackend(); public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); private static int gameNo = 0;
public static TestGame newSavedGame() {
CyberCRI/RedMetrics
src/test/java/org/cri/redmetrics/backend/Backends.java
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // }
import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException;
package org.cri.redmetrics.backend; public class Backends { public static final EventBackend EVENT = new EventBackend(); public static final GameBackend GAME = new GameBackend(); public static final GameVersionBackend GAME_VERSION = new GameVersionBackend(); public static final GroupBackend GROUP = new GroupBackend(); public static final PlayerBackend PLAYER = new PlayerBackend(); public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); private static int gameNo = 0; public static TestGame newSavedGame() { try { TestGame game = new TestGame(); game.setName("My Test Game " + gameNo); ++gameNo; TestGame savedGame = GAME.post(game); return savedGame; } catch (IOException e) { throw new RuntimeException(e); } }
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // } // Path: src/test/java/org/cri/redmetrics/backend/Backends.java import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException; package org.cri.redmetrics.backend; public class Backends { public static final EventBackend EVENT = new EventBackend(); public static final GameBackend GAME = new GameBackend(); public static final GameVersionBackend GAME_VERSION = new GameVersionBackend(); public static final GroupBackend GROUP = new GroupBackend(); public static final PlayerBackend PLAYER = new PlayerBackend(); public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); private static int gameNo = 0; public static TestGame newSavedGame() { try { TestGame game = new TestGame(); game.setName("My Test Game " + gameNo); ++gameNo; TestGame savedGame = GAME.post(game); return savedGame; } catch (IOException e) { throw new RuntimeException(e); } }
public static TestGameVersion newSavedGameVersion() {
CyberCRI/RedMetrics
src/test/java/org/cri/redmetrics/backend/Backends.java
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // }
import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException;
public static final PlayerBackend PLAYER = new PlayerBackend(); public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); private static int gameNo = 0; public static TestGame newSavedGame() { try { TestGame game = new TestGame(); game.setName("My Test Game " + gameNo); ++gameNo; TestGame savedGame = GAME.post(game); return savedGame; } catch (IOException e) { throw new RuntimeException(e); } } public static TestGameVersion newSavedGameVersion() { try { TestGame game = newSavedGame(); TestGameVersion gameVersion = new TestGameVersion(); gameVersion.setGame(game.getId()); gameVersion.setName("version 1"); gameVersion = GAME_VERSION.post(gameVersion); return gameVersion; } catch (IOException e) { throw new RuntimeException(e); } }
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // } // Path: src/test/java/org/cri/redmetrics/backend/Backends.java import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException; public static final PlayerBackend PLAYER = new PlayerBackend(); public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); private static int gameNo = 0; public static TestGame newSavedGame() { try { TestGame game = new TestGame(); game.setName("My Test Game " + gameNo); ++gameNo; TestGame savedGame = GAME.post(game); return savedGame; } catch (IOException e) { throw new RuntimeException(e); } } public static TestGameVersion newSavedGameVersion() { try { TestGame game = newSavedGame(); TestGameVersion gameVersion = new TestGameVersion(); gameVersion.setGame(game.getId()); gameVersion.setName("version 1"); gameVersion = GAME_VERSION.post(gameVersion); return gameVersion; } catch (IOException e) { throw new RuntimeException(e); } }
public static TestPlayer newSavedPlayer() {
CyberCRI/RedMetrics
src/test/java/org/cri/redmetrics/backend/Backends.java
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // }
import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException;
private static int gameNo = 0; public static TestGame newSavedGame() { try { TestGame game = new TestGame(); game.setName("My Test Game " + gameNo); ++gameNo; TestGame savedGame = GAME.post(game); return savedGame; } catch (IOException e) { throw new RuntimeException(e); } } public static TestGameVersion newSavedGameVersion() { try { TestGame game = newSavedGame(); TestGameVersion gameVersion = new TestGameVersion(); gameVersion.setGame(game.getId()); gameVersion.setName("version 1"); gameVersion = GAME_VERSION.post(gameVersion); return gameVersion; } catch (IOException e) { throw new RuntimeException(e); } } public static TestPlayer newSavedPlayer() { try {
// Path: src/test/java/org/cri/redmetrics/model/Players.java // public class Players { // // public static TestPlayer newJohnSnow() { // return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build(); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGame.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGame extends TestEntity { // // @Key // private String adminKey; // // @Key // private String name; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGameVersion extends TestEntity { // // @Key // private String game; // // @Key // private String name = "v1"; // // } // // Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestPlayer extends TestEntity { // // @Key // private String birthDate; // // @Key // private String region; // // @Key // private String country; // // @Key // private String gender; // // @Key // private String externalId; // } // Path: src/test/java/org/cri/redmetrics/backend/Backends.java import org.cri.redmetrics.model.Players; import org.cri.redmetrics.model.TestGame; import org.cri.redmetrics.model.TestGameVersion; import org.cri.redmetrics.model.TestPlayer; import java.io.IOException; private static int gameNo = 0; public static TestGame newSavedGame() { try { TestGame game = new TestGame(); game.setName("My Test Game " + gameNo); ++gameNo; TestGame savedGame = GAME.post(game); return savedGame; } catch (IOException e) { throw new RuntimeException(e); } } public static TestGameVersion newSavedGameVersion() { try { TestGame game = newSavedGame(); TestGameVersion gameVersion = new TestGameVersion(); gameVersion.setGame(game.getId()); gameVersion.setName("version 1"); gameVersion = GAME_VERSION.post(gameVersion); return gameVersion; } catch (IOException e) { throw new RuntimeException(e); } } public static TestPlayer newSavedPlayer() { try {
TestPlayer player = Players.newJohnSnow();
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/controller/SnapshotController.java
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/SnapshotDao.java // public class SnapshotDao extends ProgressDataDao<Snapshot> { // // @Inject // public SnapshotDao(ConnectionSource connectionSource, GameVersionDao gameVersionDao, PlayerDao playerDao) throws SQLException { // super(connectionSource, gameVersionDao, playerDao, Snapshot.class); // } // // } // // Path: src/main/java/org/cri/redmetrics/json/SnapshotJsonConverter.java // public class SnapshotJsonConverter extends ProgressDataJsonConverter<Snapshot> { // // @Inject // SnapshotJsonConverter(@Named("ProgressData") Gson gson, JsonParser jsonParser) { // super(Snapshot.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Snapshot.java // @Data // @DatabaseTable(tableName = "snapshots") // @EqualsAndHashCode(callSuper = true) // public class Snapshot extends ProgressData { // // }
import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.SnapshotDao; import org.cri.redmetrics.json.SnapshotJsonConverter; import org.cri.redmetrics.model.Snapshot;
package org.cri.redmetrics.controller; public class SnapshotController extends ProgressDataController<Snapshot, SnapshotDao> { @Inject
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/SnapshotDao.java // public class SnapshotDao extends ProgressDataDao<Snapshot> { // // @Inject // public SnapshotDao(ConnectionSource connectionSource, GameVersionDao gameVersionDao, PlayerDao playerDao) throws SQLException { // super(connectionSource, gameVersionDao, playerDao, Snapshot.class); // } // // } // // Path: src/main/java/org/cri/redmetrics/json/SnapshotJsonConverter.java // public class SnapshotJsonConverter extends ProgressDataJsonConverter<Snapshot> { // // @Inject // SnapshotJsonConverter(@Named("ProgressData") Gson gson, JsonParser jsonParser) { // super(Snapshot.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Snapshot.java // @Data // @DatabaseTable(tableName = "snapshots") // @EqualsAndHashCode(callSuper = true) // public class Snapshot extends ProgressData { // // } // Path: src/main/java/org/cri/redmetrics/controller/SnapshotController.java import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.SnapshotDao; import org.cri.redmetrics.json.SnapshotJsonConverter; import org.cri.redmetrics.model.Snapshot; package org.cri.redmetrics.controller; public class SnapshotController extends ProgressDataController<Snapshot, SnapshotDao> { @Inject
SnapshotController(SnapshotDao dao, SnapshotJsonConverter json, CsvEntityConverter<Snapshot> csvEntityConverter) {
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/controller/SnapshotController.java
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/SnapshotDao.java // public class SnapshotDao extends ProgressDataDao<Snapshot> { // // @Inject // public SnapshotDao(ConnectionSource connectionSource, GameVersionDao gameVersionDao, PlayerDao playerDao) throws SQLException { // super(connectionSource, gameVersionDao, playerDao, Snapshot.class); // } // // } // // Path: src/main/java/org/cri/redmetrics/json/SnapshotJsonConverter.java // public class SnapshotJsonConverter extends ProgressDataJsonConverter<Snapshot> { // // @Inject // SnapshotJsonConverter(@Named("ProgressData") Gson gson, JsonParser jsonParser) { // super(Snapshot.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Snapshot.java // @Data // @DatabaseTable(tableName = "snapshots") // @EqualsAndHashCode(callSuper = true) // public class Snapshot extends ProgressData { // // }
import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.SnapshotDao; import org.cri.redmetrics.json.SnapshotJsonConverter; import org.cri.redmetrics.model.Snapshot;
package org.cri.redmetrics.controller; public class SnapshotController extends ProgressDataController<Snapshot, SnapshotDao> { @Inject
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/SnapshotDao.java // public class SnapshotDao extends ProgressDataDao<Snapshot> { // // @Inject // public SnapshotDao(ConnectionSource connectionSource, GameVersionDao gameVersionDao, PlayerDao playerDao) throws SQLException { // super(connectionSource, gameVersionDao, playerDao, Snapshot.class); // } // // } // // Path: src/main/java/org/cri/redmetrics/json/SnapshotJsonConverter.java // public class SnapshotJsonConverter extends ProgressDataJsonConverter<Snapshot> { // // @Inject // SnapshotJsonConverter(@Named("ProgressData") Gson gson, JsonParser jsonParser) { // super(Snapshot.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Snapshot.java // @Data // @DatabaseTable(tableName = "snapshots") // @EqualsAndHashCode(callSuper = true) // public class Snapshot extends ProgressData { // // } // Path: src/main/java/org/cri/redmetrics/controller/SnapshotController.java import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.SnapshotDao; import org.cri.redmetrics.json.SnapshotJsonConverter; import org.cri.redmetrics.model.Snapshot; package org.cri.redmetrics.controller; public class SnapshotController extends ProgressDataController<Snapshot, SnapshotDao> { @Inject
SnapshotController(SnapshotDao dao, SnapshotJsonConverter json, CsvEntityConverter<Snapshot> csvEntityConverter) {
CyberCRI/RedMetrics
src/test/java/org/cri/redmetrics/GroupBackendTest.java
// Path: src/test/java/org/cri/redmetrics/backend/Backends.java // public class Backends { // // public static final EventBackend EVENT = new EventBackend(); // public static final GameBackend GAME = new GameBackend(); // public static final GameVersionBackend GAME_VERSION = new GameVersionBackend(); // public static final GroupBackend GROUP = new GroupBackend(); // public static final PlayerBackend PLAYER = new PlayerBackend(); // public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); // private static int gameNo = 0; // // public static TestGame newSavedGame() { // // try { // TestGame game = new TestGame(); // game.setName("My Test Game " + gameNo); // ++gameNo; // TestGame savedGame = GAME.post(game); // return savedGame; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static TestGameVersion newSavedGameVersion() { // try { // TestGame game = newSavedGame(); // TestGameVersion gameVersion = new TestGameVersion(); // gameVersion.setGame(game.getId()); // gameVersion.setName("version 1"); // gameVersion = GAME_VERSION.post(gameVersion); // return gameVersion; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static TestPlayer newSavedPlayer() { // try { // TestPlayer player = Players.newJohnSnow(); // TestPlayer savedPlayer = PLAYER.post(player); // return savedPlayer; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: src/test/java/org/cri/redmetrics/backend/GroupBackend.java // public class GroupBackend extends HttpBackend<TestGroup> { // // GroupBackend() { // super("group", TestGroup.class); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGroup.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGroup extends TestEntity{ // // @Key // private String name; // // @Key // private String description; // // @Key // private String creator; // // @Key // private boolean open; // }
import com.google.api.client.http.HttpResponseException; import org.cri.redmetrics.backend.Backends; import org.cri.redmetrics.backend.GroupBackend; import org.cri.redmetrics.model.TestGroup; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.util.UUID; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics; public class GroupBackendTest { static final GroupBackend groups = Backends.GROUP;
// Path: src/test/java/org/cri/redmetrics/backend/Backends.java // public class Backends { // // public static final EventBackend EVENT = new EventBackend(); // public static final GameBackend GAME = new GameBackend(); // public static final GameVersionBackend GAME_VERSION = new GameVersionBackend(); // public static final GroupBackend GROUP = new GroupBackend(); // public static final PlayerBackend PLAYER = new PlayerBackend(); // public static final SnapshotBackend SNAPSHOT = new SnapshotBackend(); // private static int gameNo = 0; // // public static TestGame newSavedGame() { // // try { // TestGame game = new TestGame(); // game.setName("My Test Game " + gameNo); // ++gameNo; // TestGame savedGame = GAME.post(game); // return savedGame; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static TestGameVersion newSavedGameVersion() { // try { // TestGame game = newSavedGame(); // TestGameVersion gameVersion = new TestGameVersion(); // gameVersion.setGame(game.getId()); // gameVersion.setName("version 1"); // gameVersion = GAME_VERSION.post(gameVersion); // return gameVersion; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public static TestPlayer newSavedPlayer() { // try { // TestPlayer player = Players.newJohnSnow(); // TestPlayer savedPlayer = PLAYER.post(player); // return savedPlayer; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // } // // Path: src/test/java/org/cri/redmetrics/backend/GroupBackend.java // public class GroupBackend extends HttpBackend<TestGroup> { // // GroupBackend() { // super("group", TestGroup.class); // } // // } // // Path: src/test/java/org/cri/redmetrics/model/TestGroup.java // @Data // @EqualsAndHashCode(callSuper = true) // @ToString(callSuper = true) // public class TestGroup extends TestEntity{ // // @Key // private String name; // // @Key // private String description; // // @Key // private String creator; // // @Key // private boolean open; // } // Path: src/test/java/org/cri/redmetrics/GroupBackendTest.java import com.google.api.client.http.HttpResponseException; import org.cri.redmetrics.backend.Backends; import org.cri.redmetrics.backend.GroupBackend; import org.cri.redmetrics.model.TestGroup; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.util.UUID; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; package org.cri.redmetrics; public class GroupBackendTest { static final GroupBackend groups = Backends.GROUP;
TestGroup original;
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/controller/PlayerController.java
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/PlayerDao.java // public class PlayerDao extends EntityDao<Player> { // // @Inject // public PlayerDao(ConnectionSource connectionSource) throws SQLException { // super(connectionSource, Player.class); // } // // public Player findByEmail(String email) { // try { // if (email == null) return null; // List<Player> players = orm.queryForEq("email", email); // assert players.size() <= 1; // email should be unique // if (players.isEmpty()) return null; // else return players.get(0); // } catch (SQLException e) { // throw new DbException(e); // } // } // // } // // Path: src/main/java/org/cri/redmetrics/json/PlayerJsonConverter.java // public class PlayerJsonConverter extends EntityJsonConverter<Player> { // // @Inject // PlayerJsonConverter(Gson gson, JsonParser jsonParser) { // super(Player.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // }
import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.PlayerDao; import org.cri.redmetrics.json.PlayerJsonConverter; import org.cri.redmetrics.model.Player;
package org.cri.redmetrics.controller; public class PlayerController extends Controller<Player, PlayerDao> { @Inject
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/PlayerDao.java // public class PlayerDao extends EntityDao<Player> { // // @Inject // public PlayerDao(ConnectionSource connectionSource) throws SQLException { // super(connectionSource, Player.class); // } // // public Player findByEmail(String email) { // try { // if (email == null) return null; // List<Player> players = orm.queryForEq("email", email); // assert players.size() <= 1; // email should be unique // if (players.isEmpty()) return null; // else return players.get(0); // } catch (SQLException e) { // throw new DbException(e); // } // } // // } // // Path: src/main/java/org/cri/redmetrics/json/PlayerJsonConverter.java // public class PlayerJsonConverter extends EntityJsonConverter<Player> { // // @Inject // PlayerJsonConverter(Gson gson, JsonParser jsonParser) { // super(Player.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // Path: src/main/java/org/cri/redmetrics/controller/PlayerController.java import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.PlayerDao; import org.cri.redmetrics.json.PlayerJsonConverter; import org.cri.redmetrics.model.Player; package org.cri.redmetrics.controller; public class PlayerController extends Controller<Player, PlayerDao> { @Inject
PlayerController(PlayerDao dao, PlayerJsonConverter jsonConverter, CsvEntityConverter<Player> csvEntityConverter) {
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/controller/PlayerController.java
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/PlayerDao.java // public class PlayerDao extends EntityDao<Player> { // // @Inject // public PlayerDao(ConnectionSource connectionSource) throws SQLException { // super(connectionSource, Player.class); // } // // public Player findByEmail(String email) { // try { // if (email == null) return null; // List<Player> players = orm.queryForEq("email", email); // assert players.size() <= 1; // email should be unique // if (players.isEmpty()) return null; // else return players.get(0); // } catch (SQLException e) { // throw new DbException(e); // } // } // // } // // Path: src/main/java/org/cri/redmetrics/json/PlayerJsonConverter.java // public class PlayerJsonConverter extends EntityJsonConverter<Player> { // // @Inject // PlayerJsonConverter(Gson gson, JsonParser jsonParser) { // super(Player.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // }
import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.PlayerDao; import org.cri.redmetrics.json.PlayerJsonConverter; import org.cri.redmetrics.model.Player;
package org.cri.redmetrics.controller; public class PlayerController extends Controller<Player, PlayerDao> { @Inject
// Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java // public interface CsvEntityConverter<E extends Entity> { // // public void write(CSVWriter csvWriter, List<E> models); // // } // // Path: src/main/java/org/cri/redmetrics/dao/PlayerDao.java // public class PlayerDao extends EntityDao<Player> { // // @Inject // public PlayerDao(ConnectionSource connectionSource) throws SQLException { // super(connectionSource, Player.class); // } // // public Player findByEmail(String email) { // try { // if (email == null) return null; // List<Player> players = orm.queryForEq("email", email); // assert players.size() <= 1; // email should be unique // if (players.isEmpty()) return null; // else return players.get(0); // } catch (SQLException e) { // throw new DbException(e); // } // } // // } // // Path: src/main/java/org/cri/redmetrics/json/PlayerJsonConverter.java // public class PlayerJsonConverter extends EntityJsonConverter<Player> { // // @Inject // PlayerJsonConverter(Gson gson, JsonParser jsonParser) { // super(Player.class, gson, jsonParser); // } // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // Path: src/main/java/org/cri/redmetrics/controller/PlayerController.java import com.google.inject.Inject; import org.cri.redmetrics.csv.CsvEntityConverter; import org.cri.redmetrics.dao.PlayerDao; import org.cri.redmetrics.json.PlayerJsonConverter; import org.cri.redmetrics.model.Player; package org.cri.redmetrics.controller; public class PlayerController extends Controller<Player, PlayerDao> { @Inject
PlayerController(PlayerDao dao, PlayerJsonConverter jsonConverter, CsvEntityConverter<Player> csvEntityConverter) {
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/csv/CsvHelper.java
// Path: src/main/java/org/cri/redmetrics/model/Entity.java // @Data // public abstract class Entity { // // public static UUID parseId(String id) { // return UUID.fromString(id); // } // // @DatabaseField(generatedId = true) // private UUID id; // // @DatabaseField(columnDefinition = "text") // private String customData; // // } // // Path: src/main/java/org/cri/redmetrics/model/Gender.java // public enum Gender { // // @DatabaseField // MALE, // // @DatabaseField // FEMALE, // // @DatabaseField // OTHER, // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.cri.redmetrics.model.Entity; import org.cri.redmetrics.model.Gender; import org.cri.redmetrics.util.DateFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
package org.cri.redmetrics.csv; /** * Created by himmelattack on 03/03/15. */ public class CsvHelper { public static String formatDate(Date date) {
// Path: src/main/java/org/cri/redmetrics/model/Entity.java // @Data // public abstract class Entity { // // public static UUID parseId(String id) { // return UUID.fromString(id); // } // // @DatabaseField(generatedId = true) // private UUID id; // // @DatabaseField(columnDefinition = "text") // private String customData; // // } // // Path: src/main/java/org/cri/redmetrics/model/Gender.java // public enum Gender { // // @DatabaseField // MALE, // // @DatabaseField // FEMALE, // // @DatabaseField // OTHER, // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/csv/CsvHelper.java import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.cri.redmetrics.model.Entity; import org.cri.redmetrics.model.Gender; import org.cri.redmetrics.util.DateFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; package org.cri.redmetrics.csv; /** * Created by himmelattack on 03/03/15. */ public class CsvHelper { public static String formatDate(Date date) {
return date != null ? DateFormatter.printIso(date) : null;
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/csv/CsvHelper.java
// Path: src/main/java/org/cri/redmetrics/model/Entity.java // @Data // public abstract class Entity { // // public static UUID parseId(String id) { // return UUID.fromString(id); // } // // @DatabaseField(generatedId = true) // private UUID id; // // @DatabaseField(columnDefinition = "text") // private String customData; // // } // // Path: src/main/java/org/cri/redmetrics/model/Gender.java // public enum Gender { // // @DatabaseField // MALE, // // @DatabaseField // FEMALE, // // @DatabaseField // OTHER, // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.cri.redmetrics.model.Entity; import org.cri.redmetrics.model.Gender; import org.cri.redmetrics.util.DateFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
package org.cri.redmetrics.csv; /** * Created by himmelattack on 03/03/15. */ public class CsvHelper { public static String formatDate(Date date) { return date != null ? DateFormatter.printIso(date) : null; } public static String formatCoordinates(Integer[] coordinates) { if(coordinates == null) return null; // Write out coordinates in JSON array format return "[" + Arrays.stream(coordinates).map(x -> x.toString()).collect(Collectors.joining(", ")) + "]"; } public static String formatBoolean(boolean bool) { return bool ? "true" : "false"; }
// Path: src/main/java/org/cri/redmetrics/model/Entity.java // @Data // public abstract class Entity { // // public static UUID parseId(String id) { // return UUID.fromString(id); // } // // @DatabaseField(generatedId = true) // private UUID id; // // @DatabaseField(columnDefinition = "text") // private String customData; // // } // // Path: src/main/java/org/cri/redmetrics/model/Gender.java // public enum Gender { // // @DatabaseField // MALE, // // @DatabaseField // FEMALE, // // @DatabaseField // OTHER, // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/csv/CsvHelper.java import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.cri.redmetrics.model.Entity; import org.cri.redmetrics.model.Gender; import org.cri.redmetrics.util.DateFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; package org.cri.redmetrics.csv; /** * Created by himmelattack on 03/03/15. */ public class CsvHelper { public static String formatDate(Date date) { return date != null ? DateFormatter.printIso(date) : null; } public static String formatCoordinates(Integer[] coordinates) { if(coordinates == null) return null; // Write out coordinates in JSON array format return "[" + Arrays.stream(coordinates).map(x -> x.toString()).collect(Collectors.joining(", ")) + "]"; } public static String formatBoolean(boolean bool) { return bool ? "true" : "false"; }
public static String formatGender(Gender gender) {
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/csv/CsvHelper.java
// Path: src/main/java/org/cri/redmetrics/model/Entity.java // @Data // public abstract class Entity { // // public static UUID parseId(String id) { // return UUID.fromString(id); // } // // @DatabaseField(generatedId = true) // private UUID id; // // @DatabaseField(columnDefinition = "text") // private String customData; // // } // // Path: src/main/java/org/cri/redmetrics/model/Gender.java // public enum Gender { // // @DatabaseField // MALE, // // @DatabaseField // FEMALE, // // @DatabaseField // OTHER, // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.cri.redmetrics.model.Entity; import org.cri.redmetrics.model.Gender; import org.cri.redmetrics.util.DateFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
package org.cri.redmetrics.csv; /** * Created by himmelattack on 03/03/15. */ public class CsvHelper { public static String formatDate(Date date) { return date != null ? DateFormatter.printIso(date) : null; } public static String formatCoordinates(Integer[] coordinates) { if(coordinates == null) return null; // Write out coordinates in JSON array format return "[" + Arrays.stream(coordinates).map(x -> x.toString()).collect(Collectors.joining(", ")) + "]"; } public static String formatBoolean(boolean bool) { return bool ? "true" : "false"; } public static String formatGender(Gender gender) { return gender != null ? gender.name() : null; } public static class UnpackedCustomData { public Set<String> columnNames = new HashSet<>(); public List<Map<String, String>> rowValues = new ArrayList<>(); }
// Path: src/main/java/org/cri/redmetrics/model/Entity.java // @Data // public abstract class Entity { // // public static UUID parseId(String id) { // return UUID.fromString(id); // } // // @DatabaseField(generatedId = true) // private UUID id; // // @DatabaseField(columnDefinition = "text") // private String customData; // // } // // Path: src/main/java/org/cri/redmetrics/model/Gender.java // public enum Gender { // // @DatabaseField // MALE, // // @DatabaseField // FEMALE, // // @DatabaseField // OTHER, // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/csv/CsvHelper.java import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.cri.redmetrics.model.Entity; import org.cri.redmetrics.model.Gender; import org.cri.redmetrics.util.DateFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; package org.cri.redmetrics.csv; /** * Created by himmelattack on 03/03/15. */ public class CsvHelper { public static String formatDate(Date date) { return date != null ? DateFormatter.printIso(date) : null; } public static String formatCoordinates(Integer[] coordinates) { if(coordinates == null) return null; // Write out coordinates in JSON array format return "[" + Arrays.stream(coordinates).map(x -> x.toString()).collect(Collectors.joining(", ")) + "]"; } public static String formatBoolean(boolean bool) { return bool ? "true" : "false"; } public static String formatGender(Gender gender) { return gender != null ? gender.name() : null; } public static class UnpackedCustomData { public Set<String> columnNames = new HashSet<>(); public List<Map<String, String>> rowValues = new ArrayList<>(); }
public static UnpackedCustomData unpackCustomData(List<? extends Entity> entityList) {
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/json/DefaultGsonBuilder.java
// Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.google.gson.*; import org.cri.redmetrics.util.DateFormatter; import java.lang.reflect.Type; import java.util.Date;
package org.cri.redmetrics.json; class DefaultGsonBuilder { private static final JsonSerializer<Date> DATE_SERIALIZER = (Date date, Type typeOfSrc, JsonSerializationContext context) -> { if (date == null) return null;
// Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/json/DefaultGsonBuilder.java import com.google.gson.*; import org.cri.redmetrics.util.DateFormatter; import java.lang.reflect.Type; import java.util.Date; package org.cri.redmetrics.json; class DefaultGsonBuilder { private static final JsonSerializer<Date> DATE_SERIALIZER = (Date date, Type typeOfSrc, JsonSerializationContext context) -> { if (date == null) return null;
else return new JsonPrimitive(DateFormatter.printIso(date));
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/dao/SearchQuery.java
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream;
package org.cri.redmetrics.dao; public class SearchQuery<E extends ProgressData> { private final QueryBuilder<E, UUID> queryBuilder;
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/dao/SearchQuery.java import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream; package org.cri.redmetrics.dao; public class SearchQuery<E extends ProgressData> { private final QueryBuilder<E, UUID> queryBuilder;
private final QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder;
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/dao/SearchQuery.java
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream;
package org.cri.redmetrics.dao; public class SearchQuery<E extends ProgressData> { private final QueryBuilder<E, UUID> queryBuilder; private final QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder; private final Dao<E, UUID> orm; private Where where; private final Where whereGameVersion;
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/dao/SearchQuery.java import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream; package org.cri.redmetrics.dao; public class SearchQuery<E extends ProgressData> { private final QueryBuilder<E, UUID> queryBuilder; private final QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder; private final Dao<E, UUID> orm; private Where where; private final Where whereGameVersion;
private final QueryBuilder<Player, UUID> playerQueryBuilder;
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/dao/SearchQuery.java
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream;
private boolean hasGameFilter = false; SearchQuery(Dao<E, UUID> orm, QueryBuilder<E, UUID> queryBuilder, QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder, QueryBuilder<Player, UUID> playerQueryBuilder) { this.orm = orm; this.queryBuilder = queryBuilder; this.gameVersionQueryBuilder = gameVersionQueryBuilder; this.whereGameVersion = gameVersionQueryBuilder.where(); this.playerQueryBuilder = playerQueryBuilder; } public List<E> execute() { if (!hasStatement && !hasGameFilter) throw new IllegalArgumentException("No parameters were specified for search query"); try { return queryBuilder.query(); } catch (SQLException e) { throw new DbException(e); } } public long countResults() { try { queryBuilder.setCountOf(true); long count = orm.countOf(queryBuilder.prepare()); queryBuilder.setCountOf(false); return count; } catch (SQLException e) { throw new DbException(e); } }
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/dao/SearchQuery.java import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream; private boolean hasGameFilter = false; SearchQuery(Dao<E, UUID> orm, QueryBuilder<E, UUID> queryBuilder, QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder, QueryBuilder<Player, UUID> playerQueryBuilder) { this.orm = orm; this.queryBuilder = queryBuilder; this.gameVersionQueryBuilder = gameVersionQueryBuilder; this.whereGameVersion = gameVersionQueryBuilder.where(); this.playerQueryBuilder = playerQueryBuilder; } public List<E> execute() { if (!hasStatement && !hasGameFilter) throw new IllegalArgumentException("No parameters were specified for search query"); try { return queryBuilder.query(); } catch (SQLException e) { throw new DbException(e); } } public long countResults() { try { queryBuilder.setCountOf(true); long count = orm.countOf(queryBuilder.prepare()); queryBuilder.setCountOf(false); return count; } catch (SQLException e) { throw new DbException(e); } }
public List<BinCount> countResultsOverTime(Date minTime, Date maxTime, int binCount) {
CyberCRI/RedMetrics
src/main/java/org/cri/redmetrics/dao/SearchQuery.java
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // }
import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream;
SearchQuery(Dao<E, UUID> orm, QueryBuilder<E, UUID> queryBuilder, QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder, QueryBuilder<Player, UUID> playerQueryBuilder) { this.orm = orm; this.queryBuilder = queryBuilder; this.gameVersionQueryBuilder = gameVersionQueryBuilder; this.whereGameVersion = gameVersionQueryBuilder.where(); this.playerQueryBuilder = playerQueryBuilder; } public List<E> execute() { if (!hasStatement && !hasGameFilter) throw new IllegalArgumentException("No parameters were specified for search query"); try { return queryBuilder.query(); } catch (SQLException e) { throw new DbException(e); } } public long countResults() { try { queryBuilder.setCountOf(true); long count = orm.countOf(queryBuilder.prepare()); queryBuilder.setCountOf(false); return count; } catch (SQLException e) { throw new DbException(e); } } public List<BinCount> countResultsOverTime(Date minTime, Date maxTime, int binCount) { try {
// Path: src/main/java/org/cri/redmetrics/model/BinCount.java // public class BinCount { // public BinCount(Date date, long count) { // this.date = date; // this.count = count; // } // // public Date date; // public long count; // } // // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java // @Data // @DatabaseTable(tableName = "game_versions") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class GameVersion extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)") // private Game game; // // @DatabaseField(canBeNull = false) // private String name; // // @DatabaseField // private String author; // // @DatabaseField // private String description; // // } // // Path: src/main/java/org/cri/redmetrics/model/Player.java // @Data // @DatabaseTable(tableName = "players") // @NoArgsConstructor // @AllArgsConstructor // @EqualsAndHashCode(callSuper = true) // public class Player extends Entity { // // @DatabaseField // private Date birthDate; // // @DatabaseField // private String region; // // @DatabaseField // private String country; // // @DatabaseField // private Gender gender; // // @DatabaseField(index = true) // private String externalId; // // } // // Path: src/main/java/org/cri/redmetrics/model/ProgressData.java // @Data // @EqualsAndHashCode(callSuper = true) // public abstract class ProgressData extends Entity { // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)") // private GameVersion gameVersion; // // @DatabaseField( // canBeNull = false, // foreign = true, // columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)") // private Player player; // // @DatabaseField(canBeNull = false) // private Date serverTime = new Date(); // // @DatabaseField // private Date userTime; // // @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") // private String section; // // @DatabaseField(canBeNull = false) // private String type; // // } // // Path: src/main/java/org/cri/redmetrics/util/DateFormatter.java // public class DateFormatter { // // // ISO 8601 Extended Format // private static final DateTimeFormatter ISO_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC); // // private static final DateTimeFormatter DB_DAY_DATE_FORMATTER = // DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC); // // public static Date parseIso(String date) { // return ISO_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printIso(Date date) { // return ISO_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static Date parseDbDay(String date) { // return DB_DAY_DATE_FORMATTER.parseDateTime(date).toDate(); // } // // public static String printDbDay(Date date) { // return DB_DAY_DATE_FORMATTER.print(new DateTime(date.getTime())); // } // // public static double dateToSeconds(Date date) { // return date.getTime() / 1000; // } // // public static Date secondsToDate(double seconds) { // return new Date((long) seconds * 1000); // } // } // Path: src/main/java/org/cri/redmetrics/dao/SearchQuery.java import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import org.cri.redmetrics.model.BinCount; import org.cri.redmetrics.model.GameVersion; import org.cri.redmetrics.model.Player; import org.cri.redmetrics.model.ProgressData; import org.cri.redmetrics.util.DateFormatter; import java.sql.SQLException; import java.util.*; import java.util.stream.Stream; SearchQuery(Dao<E, UUID> orm, QueryBuilder<E, UUID> queryBuilder, QueryBuilder<GameVersion, UUID> gameVersionQueryBuilder, QueryBuilder<Player, UUID> playerQueryBuilder) { this.orm = orm; this.queryBuilder = queryBuilder; this.gameVersionQueryBuilder = gameVersionQueryBuilder; this.whereGameVersion = gameVersionQueryBuilder.where(); this.playerQueryBuilder = playerQueryBuilder; } public List<E> execute() { if (!hasStatement && !hasGameFilter) throw new IllegalArgumentException("No parameters were specified for search query"); try { return queryBuilder.query(); } catch (SQLException e) { throw new DbException(e); } } public long countResults() { try { queryBuilder.setCountOf(true); long count = orm.countOf(queryBuilder.prepare()); queryBuilder.setCountOf(false); return count; } catch (SQLException e) { throw new DbException(e); } } public List<BinCount> countResultsOverTime(Date minTime, Date maxTime, int binCount) { try {
double minTimeSeconds = DateFormatter.dateToSeconds(minTime);