code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * AboutJDialog.java * * Created on Dec 23, 2010, 8:45:49 PM */ package dataclustering; /** * * @author Thuan Loc */ public class AboutJDialog extends javax.swing.JDialog { /** Creates new form AboutJDialog */ public AboutJDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("About"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); jLabel1.setForeground(new java.awt.Color(0, 0, 204)); jLabel1.setText("Group 10: K-MEANS CLUSTERING"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel2.setText("1. Ngo Thuan Loc"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel3.setText("2. Tran Quoc Trieu"); jLabel4.setForeground(new java.awt.Color(0, 136, 0)); jLabel4.setText("Faculty of Computer Science & Engineering - HCMC University"); jLabel5.setForeground(new java.awt.Color(0, 136, 0)); jLabel5.setText("Honor Program 07"); jLabel6.setForeground(new java.awt.Color(200, 0, 0)); jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("Version 1.0"); jLabel7.setForeground(new java.awt.Color(200, 0, 0)); jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel7.setText("12 - 2010"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(32, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 166, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel7) .addGap(18, 18, 18) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(jLabel3) .addGap(23, 23, 23) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; // End of variables declaration//GEN-END:variables }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/AboutJDialog.java
Java
mit
5,736
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dataclustering; import java.io.File; import javax.swing.filechooser.FileFilter; /** * * @author Thuan Loc */ class ExtensionFileFilter extends FileFilter { String description; String extensions[]; public ExtensionFileFilter(String description, String extension) { this(description, new String[] { extension }); } public ExtensionFileFilter(String description, String extensions[]) { if (description == null) { this.description = extensions[0]; } else { this.description = description; } this.extensions = (String[]) extensions.clone(); toLower(this.extensions); } private void toLower(String array[]) { for (int i = 0, n = array.length; i < n; i++) { array[i] = array[i].toLowerCase(); } } public String getDescription() { return description; } public boolean accept(File file) { if (file.isDirectory()) { return true; } else { String path = file.getAbsolutePath().toLowerCase(); for (int i = 0, n = extensions.length; i < n; i++) { String extension = extensions[i]; if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) { return true; } } } return false; } }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/ExtensionFileFilter.java
Java
mit
1,375
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dataclustering; import java.math.BigDecimal; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.PriorityQueue; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTabbedPane; import javax.swing.JTable; import org.math.plot.Plot3DPanel; class MyComparator implements Comparator<Cluster> { public int compare(Cluster o1, Cluster o2) { if (o1.SSE < o2.SSE) { return 1; } if (o1.SSE > o2.SSE) { return -1; } return 0; } } /** * * @author Thuan Loc */ public class ChartThread extends Thread { private Vector<Point3D> VP; private int K; private int MaxLoops; private Plot3DPanel ClusteringPanelChart; private JTable jTable; private JLabel jLabel4; private JButton jButton2; private int KMeansType; private JTabbedPane jTabbedPane; private int DistanceType; ChartThread(int KMeansType, Vector<Point3D> VP, int K, int MaxLoops, Plot3DPanel ClusteringPanelChart, JTable jTable, JLabel jLabel4, JButton jButton2, JTabbedPane jTabbedPane, int DistanceType) { this.VP = new Vector<Point3D>(); for (int i = 0; i < VP.size(); i++) { this.VP.add(new Point3D(VP.elementAt(i).x, VP.elementAt(i).y, VP.elementAt(i).z)); } this.K = K; this.MaxLoops = MaxLoops; this.ClusteringPanelChart = ClusteringPanelChart; this.jTable = jTable; this.jLabel4 = jLabel4; this.jButton2 = jButton2; this.KMeansType = KMeansType; this.jTabbedPane = jTabbedPane; this.DistanceType = DistanceType; } private void createChart(Vector<Cluster> ClusterVector) { try { this.ClusteringPanelChart.removeAllPlots(); Thread.sleep(Math.max(1000, VP.size() / 50)); for (int i = 0; i < ClusterVector.size(); i++) { double[] x = new double[ClusterVector.elementAt(i).V.size()]; double[] y = new double[ClusterVector.elementAt(i).V.size()]; double[] z = new double[ClusterVector.elementAt(i).V.size()]; for (int j = 0; j < ClusterVector.elementAt(i).V.size(); j++) { x[j] = ClusterVector.elementAt(i).V.elementAt(j).x; y[j] = ClusterVector.elementAt(i).V.elementAt(j).y; z[j] = ClusterVector.elementAt(i).V.elementAt(j).z; } this.ClusteringPanelChart.addScatterPlot("Cluster " + Integer.toString(i), x, y, z); jTable.setValueAt(i + 1, i, 0); jTable.setValueAt(ClusterVector.elementAt(i).V.size(), i, 1); BigDecimal bd = new BigDecimal(ClusterVector.elementAt(i).Centroid.x); jTable.setValueAt(bd.setScale(5, BigDecimal.ROUND_HALF_UP).toString(), i, 2); bd = new BigDecimal(ClusterVector.elementAt(i).Centroid.y); jTable.setValueAt(bd.setScale(5, BigDecimal.ROUND_HALF_UP).toString(), i, 3); bd = new BigDecimal(ClusterVector.elementAt(i).Centroid.z); jTable.setValueAt(bd.setScale(5, BigDecimal.ROUND_HALF_UP).toString(), i, 4); Thread.sleep(Math.max(1000, VP.size() / 50)); } } catch (Exception e) { } } private Vector<Cluster> K_Means_Clustering(Cluster MainCluster, int K, int MaxLoops, int[] Seeds, boolean showChart) { Vector<Cluster> ClusterVector = new Vector<Cluster>(); for (int i = 0; i < K; i++) { ClusterVector.add(new Cluster(MainCluster.V.elementAt(Seeds[i]))); } int loops = 0; while (loops < Math.min(10, MaxLoops)) { for (int i = 0; i < K; i++) { ClusterVector.elementAt(i).V.removeAllElements(); } for (int i = 0; i < MainCluster.V.size(); i++) { Point3D p = MainCluster.V.elementAt(i); double MinDist = CONST.INF; int ChosenCluster = 0; for (int j = 0; j < K; j++) { if (MinDist > CONST.Distance(p, ClusterVector.get(j).Centroid, this.DistanceType)) { MinDist = CONST.Distance(p, ClusterVector.get(j).Centroid, this.DistanceType); ChosenCluster = j; } } ClusterVector.get(ChosenCluster).V.add(p); } boolean Terminate = true; for (int i = 0; i < K; i++) { if (!CONST.Equal(ClusterVector.get(i).Centroid, CONST.getCentroid(ClusterVector.get(i).V), this.DistanceType)) { Terminate = false; } ClusterVector.get(i).Centroid = CONST.getCentroid(ClusterVector.get(i).V); ClusterVector.get(i).SSE = CONST.calSSE(ClusterVector.get(i), this.DistanceType); } if (Terminate) { break; } loops++; if (CONST.STOP) { this.jLabel4.setVisible(false); break; } if (showChart) { createChart(ClusterVector); } } return ClusterVector; } private void Bisecting_K_Means_Clustering(Cluster MainCluster, int K, int MaxLoops) { MainCluster.SSE = CONST.calSSE(MainCluster, this.DistanceType); Comparator<Cluster> cmp = new MyComparator(); PriorityQueue<Cluster> Q = new PriorityQueue<Cluster>(K, cmp); Q.add(MainCluster); while (Q.size() < K) { Vector<Cluster> V = new Vector<Cluster>(); Iterator<Cluster> I = Q.iterator(); while (I.hasNext()) { V.add(I.next()); } createChart(V); Cluster MaxCluster = Q.poll(); double MinTotalSSE = CONST.INF; Cluster C1 = null; Cluster C2 = null; for (int i = 0; i < MaxCluster.V.size() - 1; i = i * 10 + 1) { for (int j = i + 1; j < MaxCluster.V.size(); j *= 10) { int[] Seeds = new int[2]; Seeds[0] = i; Seeds[1] = j; Vector<Cluster> BiClusters = K_Means_Clustering(MaxCluster, 2, Math.min(MaxLoops, 5), Seeds, false); if (MinTotalSSE > BiClusters.elementAt(0).SSE + BiClusters.elementAt(1).SSE) { C1 = BiClusters.elementAt(0); C2 = BiClusters.elementAt(1); MinTotalSSE = BiClusters.elementAt(0).SSE + BiClusters.elementAt(1).SSE; } } } Q.add(C1); Q.add(C2); } Vector<Cluster> V = new Vector<Cluster>(); Iterator<Cluster> I = Q.iterator(); while (I.hasNext()) { V.add(I.next()); } createChart(V); } private void EM_K_Means_Clustering(Cluster MainCluster, int K) { int R = MainCluster.V.size(); Point3D[] Means = new Point3D[K]; double[][] PxBelongsToC = new double[R][K]; Vector<Cluster> ClusterVector; MainCluster.SSE = CONST.calSSE(MainCluster, CONST.EUCLIDEAN); double Deviation = MainCluster.SSE; Deviation /= MainCluster.V.size(); Deviation = Math.sqrt(Deviation); for (int i = 0; i < K; i++) { Means[i] = new Point3D(MainCluster.V.elementAt(i)); } ClusterVector = new Vector<Cluster>(); for (int i = 0; i < K; i++) { ClusterVector.add(new Cluster(new Point3D(Means[i]))); } //Expectation Step for (int k = 0; k < R; k++) { double SumOfPxBelongsToC = 0; for (int i = 0; i < K; i++) { SumOfPxBelongsToC += CONST.NormalDistribution(MainCluster.V.elementAt(k), Means[i], Deviation); } for (int i = 0; i < K; i++) { PxBelongsToC[k][i] = CONST.NormalDistribution(MainCluster.V.elementAt(k), Means[i], Deviation) / SumOfPxBelongsToC; } } //Maximization Step for (int i = 0; i < K; i++) { Point3D SumOfMeanPx = new Point3D(0, 0, 0); double SumOfPx = 0; for (int k = 0; k < R; k++) { SumOfMeanPx.x += PxBelongsToC[k][i] * MainCluster.V.elementAt(k).x; SumOfMeanPx.y += PxBelongsToC[k][i] * MainCluster.V.elementAt(k).y; SumOfMeanPx.z += PxBelongsToC[k][i] * MainCluster.V.elementAt(k).z; SumOfPx += PxBelongsToC[k][i]; } Means[i].x = SumOfMeanPx.x / SumOfPx; Means[i].y = SumOfMeanPx.y / SumOfPx; Means[i].z = SumOfMeanPx.z / SumOfPx; } ClusterVector = new Vector<Cluster>(); for (int i = 0; i < K; i++) { ClusterVector.add(new Cluster(new Point3D(Means[i]))); } for (int i = 0; i < R; i++) { double Min = CONST.INF; int pos = 0; for (int k = 0; k < K; k++) { if (Min > CONST.Distance(Means[k], MainCluster.V.elementAt(i), CONST.EUCLIDEAN)) { Min = CONST.Distance(Means[k], MainCluster.V.elementAt(i), CONST.EUCLIDEAN); pos = k; } } ClusterVector.elementAt(pos).V.add(MainCluster.V.elementAt(i)); } createChart(ClusterVector); } private void K_Medoids_Clustering(Cluster MainCluster, int K) { int N = MainCluster.V.size(); int[] M = new int[K];//Array Of Medoids boolean[] IsMedoids = new boolean[N]; Arrays.fill(IsMedoids, false); for (int i = 0; i < K; i++) { M[i] = i; IsMedoids[i] = true; } int[] B = new int[N];//which medoid point i belongs to int[] NB = new int[N]; double SE = CONST.SumOfError(M, B, IsMedoids, K, MainCluster.V, this.DistanceType); int loops = 0; while (loops < this.MaxLoops) { boolean found = false; int O = 0; int P = 0; for (int i = 0; i < K; i++) { for (int j = 0; j < N; j++) { if (!IsMedoids[j]&&NB[j]==i) { IsMedoids[j] = true; IsMedoids[M[i]] = false; double tmp = CONST.SumOfError(M, B, IsMedoids, K, MainCluster.V, this.DistanceType); if (SE > tmp) { SE = tmp; O = i; P = j; NB = Arrays.copyOf(B, N); found = true; } IsMedoids[j] = false; IsMedoids[M[i]] = true; } } } if (found) { IsMedoids[M[O]] = false; M[O] = P; IsMedoids[P] = true; Vector<Cluster> ClusterVector = new Vector<Cluster>(); for (int i = 0; i < K; i++) { ClusterVector.add(new Cluster(new Point3D(0, 0, 0))); } for (int i = 0; i < K; i++) { ClusterVector.elementAt(i).V.add(MainCluster.V.elementAt(M[i])); } for (int i = 0; i < N; i++) { if (!IsMedoids[i]) { ClusterVector.elementAt(NB[i]).V.add(MainCluster.V.elementAt(i)); } } for(int i=0;i<K;i++) ClusterVector.elementAt(i).Centroid = CONST.getCentroid(ClusterVector.elementAt(i).V); createChart(ClusterVector); } else { this.jLabel4.setVisible(false); break; } if (CONST.STOP) { this.jLabel4.setVisible(false); break; } loops++; } } private void createKMeansChart() { Cluster C = new Cluster(VP); jTable.setModel(new javax.swing.table.DefaultTableModel( new Object[K][5], new String[]{ "Cluster No", "NOf Objects", "Centroid's X", "Centroid's Y", "Centroid's Z" }) { Class[] types = new Class[]{ java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class }; @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } }); switch (KMeansType) { case CONST.BASIC_KMEANS: int[] Seeds = new int[K]; for (int i = 0; i < K; i++) { Seeds[i] = i; } K_Means_Clustering(C, K, MaxLoops, Seeds, true); break; case CONST.BISECTING_KMEANS: this.jButton2.setEnabled(false); Bisecting_K_Means_Clustering(C, K, MaxLoops); break; case CONST.EM_KMEANS: this.jButton2.setEnabled(false); EM_K_Means_Clustering(C, K); break; case CONST.K_MEDOIDS: K_Medoids_Clustering(C, K); break; } } @Override public void run() { createKMeansChart(); this.jButton2.setEnabled(false); this.jTabbedPane.setEnabledAt(0, true); } }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/ChartThread.java
Java
mit
13,837
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dataclustering; import java.util.Vector; /** * * @author Thuan Loc */ public class CONST { static final double INF = (double) 2000000000 * (double) 2000000000; static final int EUCLIDEAN = 1; static final int MANHATTAN = 2; static final int BASIC_KMEANS = 1; static final int EM_KMEANS = 2; static final int BISECTING_KMEANS = 3; static final int K_MEDOIDS = 4; static boolean STOP; static double Distance(Point3D p1, Point3D p2, int DistanceType) { switch (DistanceType) { case EUCLIDEAN: return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y) + (p2.z - p1.z) * (p2.z - p1.z)); default: return Math.abs(p2.x - p1.x) + Math.abs(p2.y - p1.y) + Math.abs(p2.z - p1.z); } } static double calSSE(Cluster C, int DistanceType) { double sum = 0; for (int i = 0; i < C.V.size(); i++) { sum += Distance(C.V.elementAt(i), C.Centroid, CONST.EUCLIDEAN) * Distance(C.V.elementAt(i), C.Centroid, DistanceType); } return sum; } static Point3D getCentroid(Vector<Point3D> V) { double x = 0; double y = 0; double z = 0; for (int i = 0; i < V.size(); i++) { x += V.elementAt(i).x; y += V.elementAt(i).y; z += V.elementAt(i).z; } x /= V.size(); y /= V.size(); z /= V.size(); return new Point3D(x, y, z); } static boolean Equal(Point3D p1, Point3D p2, int DistanceType) { switch (DistanceType) { case EUCLIDEAN: if (Distance(p1, p2, EUCLIDEAN) < 0.001) { return true; } return false; default://MANHATTAN if (Distance(p1, p2, MANHATTAN) < 0.005) { return true; } return false; } } static double SumOfError(int[] M,int[] B,boolean[] IsMedoids,int K,Vector<Point3D> V,int DistanceType) { double SOE = 0; for(int i=0;i<V.size();i++) if(!IsMedoids[i]) { double MinDis = INF; for(int j=0;j<K;j++) { if(MinDis>Distance(V.elementAt(i),V.elementAt(M[j]),DistanceType)) { MinDis=Distance(V.elementAt(i),V.elementAt(M[j]),DistanceType); B[i] = j; } } SOE += MinDis; } return SOE; } static double NormalDistribution(Point3D p, Point3D mean, double Deviation) { double result = Math.exp(-(Distance(p, mean, EUCLIDEAN) * Distance(p, mean, EUCLIDEAN)) / (2 * Deviation * Deviation)); return result; } }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/CONST.java
Java
mit
2,959
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dataclustering; import java.util.Vector; /** * * @author Thuan Loc */ public class Cluster { Vector<Point3D> V; Point3D Centroid; double SSE; Cluster(Point3D Centroid) { this.V = new Vector<Point3D>(); this.Centroid = Centroid; } Cluster(Vector<Point3D> V) { this.V = V; double x = 0; double y = 0; double z = 0; for (int i = 0; i < V.size(); i++) { x += V.elementAt(i).x; y += V.elementAt(i).y; z += V.elementAt(i).z; } x /= V.size(); y /= V.size(); z /= V.size(); Centroid = new Point3D(x, y, z); } }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/Cluster.java
Java
mit
779
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dataclustering; /** * * @author Thuan Loc */ public class Point3D { double x; double y; double z; Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } Point3D(Point3D newPoint) { this.x = newPoint.x; this.y = newPoint.y; this.z = newPoint.z; } } class Anobject{ public double x; public double y; public double z; public int center; public int cluster; public Anobject(double x, double y, double z){ this.x = x; this.y = y; this.z = z; } } class SumNum{ public double sumx = 0; public double sumy = 0; public double sumz = 0; public int num = 0; }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/Point3D.java
Java
mit
833
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dataclustering; /** * * @author Thuan Loc */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here MainFrame mf = new MainFrame(); mf.setVisible(true); } }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/Main.java
Java
mit
407
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * NewJFrame.java * * Created on Nov 14, 2010, 2:35:36 PM */ package dataclustering; import java.awt.Cursor; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.Scanner; import java.util.Vector; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingWorker; import javax.swing.filechooser.FileFilter; /** * * @author Thuan Loc */ public class MainFrame extends javax.swing.JFrame implements ActionListener, PropertyChangeListener { Vector<Point3D> VP; private Task task; private File FR; private void hideStatus() { this.jLabelStatus.setVisible(false); this.jLabelSizeOfFileName.setVisible(false); this.jLabelNumOfOName.setVisible(false); this.jLabelNofO.setVisible(false); this.jLabelSizeofF.setVisible(false); this.jLabelSizeOfFileName.setVisible(false); } class Task extends SwingWorker<Void, Void> { /* * Main task. Executed in background thread. */ @Override public Void doInBackground() { int progress = 0; //Initialize progress property. setProgress(0); try { Scanner in = new Scanner(FR); long len = 0; for (int i = 0; i < 12; i++) { len += (in.next().length() + 1); } while (in.hasNext()) { String s = in.next(); len += (s.length() + 1); String[] SP = s.split(","); VP.add(new Point3D(Double.parseDouble(SP[0]), Double.parseDouble(SP[1]), Double.parseDouble(SP[2]))); progress = (int) ((double) len / (double) FR.length() * 100); setProgress(progress); } setProgress(100); } catch (Exception e) { } return null; } /** * Invoked when task's progress property changes. */ public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().compareTo("progress") == 0) { int progress = (Integer) evt.getNewValue(); jProgressBarTestFile.setValue(progress); } } /* * Executed in event dispatching thread */ @Override public void done() { Toolkit.getDefaultToolkit().beep(); if (VP.isEmpty()) { jLabelStatus.setText("Please choose an .arff file"); jLabelStatus.setVisible(true); jButtonTestFile.setEnabled(true); } else { jLabelSizeofF.setText(Long.toString(FR.length() / 1024) + "KB"); jLabelNofO.setText(Integer.toString(VP.size())); jButtonTestFile.setEnabled(true); jLabelStatus.setText("Status"); jLabelStatus.setVisible(true); jLabelSizeOfFileName.setVisible(true); jLabelNumOfOName.setVisible(true); jLabelNofO.setVisible(true); jLabelSizeofF.setVisible(true); jLabelSizeOfFileName.setVisible(true); jTextFieldClusterNumber.setEditable(true); if (!jRadioButtonMenuItemEM.isSelected()) { jTextFieldIterations.setEditable(true); } } setCursor(null); //turn off the wait cursor } } /** Creates new form NewJFrame */ public MainFrame() { initComponents(); VP = new Vector<Point3D>(); this.jTabbedPane.remove(1); this.jTextFieldClusterNumber.setEditable(false); this.jTextFieldIterations.setEditable(false); this.ClusteringPanelChart.plotToolBar.setVisible(false); this.hideStatus(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); jTabbedPane = new javax.swing.JTabbedPane(); jPanelSpecification = new javax.swing.JPanel(); jTextFieldClusterNumber = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jButtonAnalysis = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jTextFieldFileChoice = new javax.swing.JTextField(); jButtonBrowse = new javax.swing.JButton(); jButtonTestFile = new javax.swing.JButton(); jLabelSizeOfFileName = new javax.swing.JLabel(); jLabelStatus = new javax.swing.JLabel(); jLabelNumOfOName = new javax.swing.JLabel(); jLabelSizeofF = new javax.swing.JLabel(); jLabelNofO = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jRadioButtonEuclidean = new javax.swing.JRadioButton(); jRadioButtonManhattan = new javax.swing.JRadioButton(); jLabelDistanceMeasureDiscription = new javax.swing.JLabel(); jLabel1DistanceFormula = new javax.swing.JLabel(); jProgressBarTestFile = new javax.swing.JProgressBar(); jPanel2 = new javax.swing.JPanel(); jLabel12 = new javax.swing.JLabel(); jTextFieldIterations = new javax.swing.JTextField(); jPanelPerformance = new javax.swing.JPanel(); ClusteringPanelChart = new org.math.plot.Plot3DPanel(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton2 = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); jMenuBar = new javax.swing.JMenuBar(); jMenuAlgorithm = new javax.swing.JMenu(); jRadioButtonMenuItemBasicKMeans = new javax.swing.JRadioButtonMenuItem(); jSeparatorAlgorithm = new javax.swing.JPopupMenu.Separator(); jRadioButtonMenuItemKMedoids = new javax.swing.JRadioButtonMenuItem(); jRadioButtonMenuItemBisectingKMeans = new javax.swing.JRadioButtonMenuItem(); jRadioButtonMenuItemEM = new javax.swing.JRadioButtonMenuItem(); jMenuHelp = new javax.swing.JMenu(); jSeparatorHelp = new javax.swing.JPopupMenu.Separator(); jMenuItemAbout = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("K-Means Paradigm"); setBounds(new java.awt.Rectangle(55, 45, 50, 50)); jTextFieldClusterNumber.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); jLabel1.setText("Number of Clusters"); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jButtonAnalysis.setFont(new java.awt.Font("Tahoma", 0, 14)); jButtonAnalysis.setText("Analyze"); jButtonAnalysis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAnalysisActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); jLabel3.setText("Choose a sample file (*.arff)"); jTextFieldFileChoice.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextFieldFileChoice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldFileChoiceActionPerformed(evt); } }); jButtonBrowse.setText("Browse"); jButtonBrowse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBrowseActionPerformed(evt); } }); jButtonTestFile.setText("Test File"); jButtonTestFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTestFileActionPerformed(evt); } }); jLabelSizeOfFileName.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N jLabelSizeOfFileName.setText("Size of file"); jLabelStatus.setFont(new java.awt.Font("Tahoma", 0, 18)); jLabelStatus.setText("Status"); jLabelNumOfOName.setFont(new java.awt.Font("Tahoma", 0, 16)); jLabelNumOfOName.setText("Number of objects"); jLabelSizeofF.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N jLabelSizeofF.setText("N/A"); jLabelNofO.setFont(new java.awt.Font("Tahoma", 0, 16)); jLabelNofO.setText("N/A"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); jLabel2.setText("( *Positive integer less or equal to N)"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); jLabel11.setText("Distance Measures"); buttonGroup2.add(jRadioButtonEuclidean); jRadioButtonEuclidean.setFont(new java.awt.Font("Tahoma", 0, 12)); jRadioButtonEuclidean.setSelected(true); jRadioButtonEuclidean.setText("Euclidean"); jRadioButtonEuclidean.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonEuclideanActionPerformed(evt); } }); buttonGroup2.add(jRadioButtonManhattan); jRadioButtonManhattan.setFont(new java.awt.Font("Tahoma", 0, 12)); jRadioButtonManhattan.setText("Manhattan"); jRadioButtonManhattan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonManhattanActionPerformed(evt); } }); jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); // NOI18N jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Additional Configuration", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); jLabel12.setText("Maximum number of iterations"); jTextFieldIterations.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE) .addComponent(jTextFieldIterations, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(jTextFieldIterations, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(27, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanelSpecificationLayout = new javax.swing.GroupLayout(jPanelSpecification); jPanelSpecification.setLayout(jPanelSpecificationLayout); jPanelSpecificationLayout.setHorizontalGroup( jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabelSizeOfFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelNumOfOName, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextFieldFileChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jProgressBarTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonBrowse, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE))) .addComponent(jLabelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSpecificationLayout.createSequentialGroup() .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabelNofO, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelSizeofF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(113, 113, 113))) .addGap(35, 35, 35) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1DistanceFormula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelDistanceMeasureDiscription, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jLabel2) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGap(68, 68, 68) .addComponent(jRadioButtonEuclidean))) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGap(55, 55, 55) .addComponent(jRadioButtonManhattan)) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldClusterNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(jButtonAnalysis, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(45, 45, 45)) ); jPanelSpecificationLayout.setVerticalGroup( jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGap(46, 46, 46) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createSequentialGroup() .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextFieldFileChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButtonBrowse)) .addGap(87, 87, 87) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jProgressBarTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(64, 64, 64) .addComponent(jLabelStatus) .addGap(54, 54, 54) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSizeOfFileName) .addComponent(jLabelSizeofF)) .addGap(41, 41, 41) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelNumOfOName) .addComponent(jLabelNofO))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSpecificationLayout.createSequentialGroup() .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelSpecificationLayout.createSequentialGroup() .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldClusterNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addGap(28, 28, 28) .addComponent(jLabel11) .addGap(19, 19, 19) .addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButtonEuclidean) .addComponent(jRadioButtonManhattan)) .addGap(24, 24, 24) .addComponent(jLabelDistanceMeasureDiscription) .addGap(18, 18, 18) .addComponent(jLabel1DistanceFormula) .addGap(70, 70, 70) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(76, 76, 76) .addComponent(jButtonAnalysis, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(27, 27, 27)))) ); jTabbedPane.addTab("Specification", jPanelSpecification); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Cluster No", "NOf Objects", "Centroid's X", "Centroid's Y", "Centroid's Z" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); jButton2.setText("Stop"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); jLabel4.setForeground(new java.awt.Color(255, 0, 0)); jLabel4.setText("Please wait..."); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 553, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout jPanelPerformanceLayout = new javax.swing.GroupLayout(jPanelPerformance); jPanelPerformance.setLayout(jPanelPerformanceLayout); jPanelPerformanceLayout.setHorizontalGroup( jPanelPerformanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelPerformanceLayout.createSequentialGroup() .addComponent(ClusteringPanelChart, javax.swing.GroupLayout.PREFERRED_SIZE, 720, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelPerformanceLayout.setVerticalGroup( jPanelPerformanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ClusteringPanelChart, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jTabbedPane.addTab("Performance", jPanelPerformance); jMenuAlgorithm.setText("Algorithms"); buttonGroup1.add(jRadioButtonMenuItemBasicKMeans); jRadioButtonMenuItemBasicKMeans.setSelected(true); jRadioButtonMenuItemBasicKMeans.setText("Basic K-Means"); jRadioButtonMenuItemBasicKMeans.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonMenuItemBasicKMeansActionPerformed(evt); } }); jMenuAlgorithm.add(jRadioButtonMenuItemBasicKMeans); jMenuAlgorithm.add(jSeparatorAlgorithm); buttonGroup1.add(jRadioButtonMenuItemKMedoids); jRadioButtonMenuItemKMedoids.setText("K-Medoids"); jRadioButtonMenuItemKMedoids.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonMenuItemKMedoidsActionPerformed(evt); } }); jMenuAlgorithm.add(jRadioButtonMenuItemKMedoids); buttonGroup1.add(jRadioButtonMenuItemBisectingKMeans); jRadioButtonMenuItemBisectingKMeans.setText("Bisecting K-Means"); jRadioButtonMenuItemBisectingKMeans.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonMenuItemBisectingKMeansActionPerformed(evt); } }); jMenuAlgorithm.add(jRadioButtonMenuItemBisectingKMeans); buttonGroup1.add(jRadioButtonMenuItemEM); jRadioButtonMenuItemEM.setText("Expectation Maximization (EM)"); jRadioButtonMenuItemEM.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonMenuItemEMActionPerformed(evt); } }); jMenuAlgorithm.add(jRadioButtonMenuItemEM); jMenuBar.add(jMenuAlgorithm); jMenuHelp.setText("Help"); jMenuHelp.add(jSeparatorHelp); jMenuItemAbout.setText("About"); jMenuItemAbout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemAboutActionPerformed(evt); } }); jMenuHelp.add(jMenuItemAbout); jMenuBar.add(jMenuHelp); setJMenuBar(jMenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1144, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private int ensureClusterNumber() { String s = this.jTextFieldClusterNumber.getText(); if (s.length() == 0 || s.length() > 9) { JOptionPane.showMessageDialog(this, "Number of Clusters is invalid"); return -1; } for (int i = 0; i < s.length(); i++) { if (s.charAt(i) < '0' || s.charAt(i) > '9') { JOptionPane.showMessageDialog(this, "Number of Clusters is invalid"); return -1; } } int K = Integer.parseInt(s); if (K == 0 || K > this.VP.size()) { JOptionPane.showMessageDialog(this, "Number of Clusters is invalid"); return -1; } return K; } private int ensureIterations() { String s = this.jTextFieldIterations.getText(); if (s.length() == 0) { return 1000000000; } if (s.length() > 9) { JOptionPane.showMessageDialog(this, "Number of Interations is not valid"); return -1; } for (int i = 0; i < s.length(); i++) { if (s.charAt(i) < '0' || s.charAt(i) > '9') { JOptionPane.showMessageDialog(this, "Number of Interations is invalid"); return -1; } } int MaxLoops = Integer.parseInt(s); if (MaxLoops == 0 || MaxLoops > this.VP.size()) { JOptionPane.showMessageDialog(this, "Number of Interations is invalid"); return -1; } return MaxLoops; } /** * Invoked when task's progress property changes. */ public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().compareTo("progress") == 0) { int progress = (Integer) evt.getNewValue(); jProgressBarTestFile.setValue(progress); } } private void jRadioButtonMenuItemEMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemEMActionPerformed // TODO add your handling code here: this.jTextFieldIterations.setEditable(false); this.jTextFieldIterations.setText(null); this.jRadioButtonManhattan.setEnabled(false); this.jRadioButtonEuclidean.setSelected(true); jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); }//GEN-LAST:event_jRadioButtonMenuItemEMActionPerformed private void jRadioButtonMenuItemBasicKMeansActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBasicKMeansActionPerformed // TODO add your handling code here: this.jTextFieldIterations.setEditable(true); this.jRadioButtonManhattan.setEnabled(true); this.jRadioButtonEuclidean.setSelected(true); jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); }//GEN-LAST:event_jRadioButtonMenuItemBasicKMeansActionPerformed private void jRadioButtonMenuItemKMedoidsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemKMedoidsActionPerformed // TODO add your handling code here: this.jTextFieldIterations.setEditable(true); this.jRadioButtonManhattan.setEnabled(true); this.jRadioButtonEuclidean.setSelected(true); jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); }//GEN-LAST:event_jRadioButtonMenuItemKMedoidsActionPerformed private void jRadioButtonMenuItemBisectingKMeansActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBisectingKMeansActionPerformed // TODO add your handling code here: this.jTextFieldIterations.setEditable(true); this.jRadioButtonManhattan.setEnabled(true); this.jRadioButtonEuclidean.setSelected(true); jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); }//GEN-LAST:event_jRadioButtonMenuItemBisectingKMeansActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: CONST.STOP = true; this.jLabel4.setVisible(true); this.jButton2.setEnabled(false); }//GEN-LAST:event_jButton2ActionPerformed private void jRadioButtonManhattanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonManhattanActionPerformed // TODO add your handling code here: jLabelDistanceMeasureDiscription.setText("A pseudonym is city block distance, which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Manhattan_Distance.png")); }//GEN-LAST:event_jRadioButtonManhattanActionPerformed private void jRadioButtonEuclideanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonEuclideanActionPerformed // TODO add your handling code here: jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as"); jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); }//GEN-LAST:event_jRadioButtonEuclideanActionPerformed private void jButtonTestFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestFileActionPerformed // TODO add your handling code here: try { hideStatus(); this.VP.removeAllElements(); jProgressBarTestFile.setValue(0); jProgressBarTestFile.setStringPainted(true); this.jButtonTestFile.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //Instances of javax.swing.SwingWorker are not reusuable, so //we create new instances as needed. FR = new File(this.jTextFieldFileChoice.getText()); task = new Task(); task.addPropertyChangeListener(this); task.execute(); } catch (Exception e) { } }//GEN-LAST:event_jButtonTestFileActionPerformed private void jButtonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseActionPerformed // TODO add your handling code here: FileFilter filter = new ExtensionFileFilter("*.arff", new String[]{"arff"}); JFileChooser fileChooser = new JFileChooser(); // Note: source for ExampleFileFilter can be found in FileChooserDemo, // under the demo/jfc directory in the Java 2 SDK, Standard Edition fileChooser.setFileFilter(filter); int status = fileChooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); this.jTextFieldFileChoice.setText(selectedFile.getAbsolutePath()); } }//GEN-LAST:event_jButtonBrowseActionPerformed private void jTextFieldFileChoiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldFileChoiceActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldFileChoiceActionPerformed private void jButtonAnalysisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnalysisActionPerformed // TODO add your handling code here: CONST.STOP = false; this.jTabbedPane.addTab("Performance", this.jPanelPerformance); this.jButton2.setEnabled(true); this.jLabel4.setVisible(false); int K = ensureClusterNumber(); int MaxLoops = ensureIterations(); if (K == -1 || MaxLoops == -1) { return; } this.jTabbedPane.setSelectedIndex(1); this.jTabbedPane.setEnabledAt(0, false); int DistanceType = CONST.EUCLIDEAN; if (this.jRadioButtonManhattan.isSelected()) { DistanceType = CONST.MANHATTAN; } if (this.jRadioButtonMenuItemBasicKMeans.isSelected()) { Thread thread = new ChartThread(CONST.BASIC_KMEANS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType); thread.start(); } else if (this.jRadioButtonMenuItemBisectingKMeans.isSelected()) { Thread thread = new ChartThread(CONST.BISECTING_KMEANS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType); thread.start(); } else if (this.jRadioButtonMenuItemEM.isSelected()) { Thread thread = new ChartThread(CONST.EM_KMEANS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType); thread.start(); } else if (this.jRadioButtonMenuItemKMedoids.isSelected()) { Thread thread = new ChartThread(CONST.K_MEDOIDS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType); thread.start(); } }//GEN-LAST:event_jButtonAnalysisActionPerformed private void jMenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAboutActionPerformed // TODO add your handling code here: AboutJDialog aboutJDialog = new AboutJDialog(this, true); Point O = new Point(); O.setLocation(this.getLocation().x, this.getLocation().y); O.move(this.getWidth()/2 - aboutJDialog.getWidth()/2, this.getHeight()/2 - aboutJDialog.getHeight()/2); aboutJDialog.setLocation(O); aboutJDialog.setVisible(true); }//GEN-LAST:event_jMenuItemAboutActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private org.math.plot.Plot3DPanel ClusteringPanelChart; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.JButton jButton2; private javax.swing.JButton jButtonAnalysis; private javax.swing.JButton jButtonBrowse; private javax.swing.JButton jButtonTestFile; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel1DistanceFormula; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabelDistanceMeasureDiscription; private javax.swing.JLabel jLabelNofO; private javax.swing.JLabel jLabelNumOfOName; private javax.swing.JLabel jLabelSizeOfFileName; private javax.swing.JLabel jLabelSizeofF; private javax.swing.JLabel jLabelStatus; private javax.swing.JMenu jMenuAlgorithm; private javax.swing.JMenuBar jMenuBar; private javax.swing.JMenu jMenuHelp; private javax.swing.JMenuItem jMenuItemAbout; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanelPerformance; private javax.swing.JPanel jPanelSpecification; private javax.swing.JProgressBar jProgressBarTestFile; private javax.swing.JRadioButton jRadioButtonEuclidean; private javax.swing.JRadioButton jRadioButtonManhattan; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBasicKMeans; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBisectingKMeans; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemEM; private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemKMedoids; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparatorAlgorithm; private javax.swing.JPopupMenu.Separator jSeparatorHelp; private javax.swing.JTabbedPane jTabbedPane; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextFieldClusterNumber; private javax.swing.JTextField jTextFieldFileChoice; private javax.swing.JTextField jTextFieldIterations; // End of variables declaration//GEN-END:variables public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }
12phdrirfan-abc
Source Code/Data Clustering/src/dataclustering/MainFrame.java
Java
mit
42,913
using System; using System.Text; namespace ArrayFormat { class NewLine : Line { public NewLine(int wrap, Page page) : base(wrap, page) { } internal override void IntoText(StringBuilder text) { throw new NotImplementedException(); } /// <summary> /// will return the length of the string without spaces /// </summary> /// <returns></returns> internal override int Length() { int templength = 0; //Space spaceobject = new Space(); foreach (object obj in Text) { //if (obj.GetType() != spaceobject.GetType()) //{ templength += obj.ToString().Length; //} } return templength; } internal override bool Overflow(string s) { //if (s.Length + Length() <= WrapColumn) return false; // else // return true; } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/NewLine.cs
C#
gpl3
1,130
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArrayFormat { public abstract class Line { public Page Page { get; set; } internal List<object> Text = new List<object>(); internal int WrapColumn; internal Line(int wrap, Page page) { Page = page; if (wrap < 0) { throw new ArgumentException("Wrap column cannot be negative: " + wrap); } WrapColumn = wrap; } /// <summary> /// Number of strings on line. /// </summary> /// <returns></returns> internal int Count() { int templength = 0; Space spaceobject = new Space(); foreach (object obj in Text) { if (obj.GetType() != spaceobject.GetType()) { templength++; } } return templength; } internal abstract int Length(); /// <summary> /// True if line violates line condition. /// </summary> /// <returns></returns> internal abstract bool Overflow(string add); /// <summary> /// String at supplied index /// </summary> /// <param name="i"></param> /// <returns></returns> internal String At(int i) { Space spaceobject = new Space(); var stringList = Text.Where(obj => obj.GetType() != spaceobject.GetType()).ToList(); //Without Spaces return stringList[i].ToString(); //return Text[i].ToString(); } /// <summary> /// Set supplied string at supplied index /// </summary> /// <param name="i"></param> /// <param name="s"> </param> /// <returns></returns> internal void At(int i, String s) { Space newspaceobject = new Space(); int counter = 0; int incrementer = 0; while (true) { while (Text[incrementer].GetType() == newspaceobject.GetType()) //Find Only the Strings { incrementer++; //If position is a space, increment til its a number } //We Will Get Here When We Have a String if (i == counter) { i = incrementer; //Location of the String break; } counter++; //Next String incrementer++; //Move Along One } object currentobject; if (s != " ") { currentobject = new TextString(s); } else { currentobject = new Space(); } Text.Insert(i + 1, currentobject); } public void Adjust() { int index = 0, i = 0; Space space = new Space(); while(index != Count()) { if(Text[i].ToString() != space.ToString()) { index++; } i++; } for (int h = i; h < Text.Count; h++) //Moving spaces to the end { Text.RemoveAt(h); Text.Insert(0,space); } } /// <summary> /// Add string to this line subject to overflow constraint. /// True if added and hence no new line required. /// False if not added to line. /// </summary> /// <param name="s"></param> /// <returns></returns> internal bool Add(String s) { try { if (Overflow(s)) { return false; } TextString input = new TextString(s); //Create a Custom String Object with the string Text.Add(input); //Add it to the Object Collection Space space = new Space(); Text.Add(space); return true; } catch (Exception) { return false; //If We Could Not Add It } } /// <summary> /// Place strings into supplied buffer /// </summary> /// <param name="text"></param> internal abstract void IntoText(StringBuilder text); /// <summary> /// Overrides the Lines ToString Method /// </summary> /// <returns></returns> public override string ToString() { string temp = ""; foreach (object obj in Text) { temp += obj.ToString(); } return temp + ((char) 10); } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/Line.cs
C#
gpl3
4,875
namespace ArrayFormat { class Text : Page { public Text(int wrap) : base(wrap) { } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/Text.cs
C#
gpl3
117
using System; namespace ArrayFormat { public class Space : IComparable { internal int Position = -1; public int CompareTo(Object x) { return 0; } public override string ToString() { return "#"; } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/Space.cs
C#
gpl3
291
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ArrayFormat")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("University of Hull")] [assembly: AssemblyProduct("ArrayFormat")] [assembly: AssemblyCopyright("Copyright © University of Hull 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("37f4c63f-9203-4486-92ef-68a779b3250e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ArrayFormatTest")]
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/Properties/AssemblyInfo.cs
C#
gpl3
1,553
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ArrayFormat { public abstract class Page { internal int Wrap; internal List<Line> Lines = new List<Line>(); internal Page(int wrap) { if (wrap < 0) { throw new ArgumentException("Line count cannot be less than zero: " + wrap); } Wrap = wrap; } /// <summary> /// Add strings to this page maintaining the format /// </summary> /// <param name="sarray"> </param> internal void Add(String[] sarray) { Line newline = new NewLine(Wrap, this); for (int i = 0; i < sarray.Length; i++) { if (newline.Add(sarray[i]) == false) break; } Lines.Add(newline); } /// <summary> /// Place strings into supplied buffer /// </summary> /// <param name="text"></param> internal void IntoText(StringBuilder text) { for(int i =0; i < Lines.Count; i++) { text.AppendLine(Lines[i].ToString()); } } internal void ToFile(String fileName) { StringBuilder outText = new StringBuilder(9999); IntoText(outText); try { using (StreamWriter sw = new StreamWriter(fileName)) { sw.Write(outText.ToString()); } } catch (Exception e) { String message = "Failed to write output file: " + e.Message; Console.WriteLine(message); throw new Exception(message); } } public override String ToString() { string tempstring = ""; foreach (Line node in Lines) { tempstring += node.ToString(); } return tempstring; } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/Page.cs
C#
gpl3
1,815
using System; namespace ArrayFormat { class TextString : IComparable { internal int Position = -1; internal string Text = ""; public TextString(string input) { Text = input; } public override string ToString() { return Text; } public int CompareTo(Object x) { return 0; } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/TextString.cs
C#
gpl3
419
using System; namespace ArrayFormat { internal class ArrayMethods { public void Fill(string[] inputstrings, int wrapcolumn, Page page) { bool startingaNewLine = true; int stringCounter = 0; int offset = 0; //offset int linelength = 0; for (int j = 0; j <= (inputstrings.Length - 1); j++) //for the amount of values in the array - 1 { if (startingaNewLine) { stringCounter = 0; linelength = inputstrings[offset].Length + 1; } //check if the last one #region Last Element if (j == (inputstrings.Length - 1) && startingaNewLine == false) // { var array = new string[stringCounter + 1]; for (int i = 0; i <= stringCounter; i++) { array[i] = inputstrings[i + offset]; } page.Add(array); break; } if (j == (inputstrings.Length - 1) && startingaNewLine) // { var array = new string[stringCounter + 1]; for (int i = 0; i <= stringCounter; i++) { array[i] = inputstrings[i + offset]; } page.Add(array); break; } #endregion if (inputstrings[(j + 1)].Length + (linelength + 1) <= wrapcolumn) //if we can fit it on the same line { stringCounter++; linelength += inputstrings[(j + 1)].Length + 1; startingaNewLine = false; } else { var array = new string[stringCounter + 1]; for (int i = 0; i <= stringCounter; i++) { array[i] = inputstrings[i + offset]; } offset += stringCounter + 1; //Update Offset page.Add(array); startingaNewLine = true; } } } private void FillMod(string[] inputstrings, int wrapcolumn, Page page, int maxelements) { bool startingaNewLine = true; int stringCounter = 0; int offset = 0; //offset int linelength = 0; int elementlimit = 0; for (int j = 0; j <= (inputstrings.Length - 1); j++) //for the amount of values in the array - 1 { if (startingaNewLine) { stringCounter = 0; linelength = inputstrings[offset].Length + 1; elementlimit = 1; } //check if the last one #region Last Element if (j == (inputstrings.Length - 1) && startingaNewLine == false) // { var array = new string[stringCounter + 1]; for (int i = 0; i <= stringCounter; i++) { array[i] = inputstrings[i + offset]; } page.Add(array); break; } if (j == (inputstrings.Length - 1) && startingaNewLine) // { var array = new string[stringCounter + 1]; for (int i = 0; i <= stringCounter; i++) { array[i] = inputstrings[i + offset]; } page.Add(array); break; } #endregion if (inputstrings[(j + 1)].Length + (linelength + 1) <= wrapcolumn && elementlimit < maxelements) //if we can fit it on the same line { stringCounter++; elementlimit++; linelength += inputstrings[(j + 1)].Length + 1; startingaNewLine = false; } else { var array = new string[stringCounter + 1]; for (int i = 0; i <= stringCounter; i++) { array[i] = inputstrings[i + offset]; } offset += stringCounter + 1; //Update Offset page.Add(array); startingaNewLine = true; } } } public int UniformCount(string[] inputstrings, int wrapcolumn, Page page, bool strict) { int strictoffset = 0; if (strict == false) strictoffset = 1; int maxPossibleColumn = 0; for (int h = 1; h < wrapcolumn; h++) { Page temp = new Text(wrapcolumn); FillMod(inputstrings, wrapcolumn, temp, h); int maxcolumns = 0; int elementsperline = temp.Lines[0].Count(); //will break if there is one line bool alltheSame = false; for (int i = 1; i < temp.Lines.Count - strictoffset; i++) //Get the total amount of elements { if (elementsperline == temp.Lines[i].Count()) { alltheSame = true; maxcolumns = elementsperline; } else { alltheSame = false; break; } } if (alltheSame) { maxPossibleColumn = maxcolumns; } } FillMod(inputstrings, wrapcolumn, page, maxPossibleColumn); return maxPossibleColumn; } public void Column(string[] inputstrings, int wrapcolumn, Page page, bool strict) { int totalcolumns = UniformCount(inputstrings, wrapcolumn, page, strict); if (totalcolumns != 1) { //Efficency at its finest LOL for (int column = 0; column < totalcolumns; column++) { int longestline = 0; for (int i = 0; i < page.Lines.Count; i++) //Find the Longest String { if (page.Lines[i].Count() > column) //Wont Break If Its the Last Column if (longestline < page.Lines[i].At(column).Length) //If Current Line is Longer than Previous longestline = page.Lines[i].At(column).Length; //Set as New Longest Line } foreach (Line t in page.Lines) { if (t.Count() > column) { int num = t.At(column).Length; //Get Length of the String for (int h = num; h < longestline; h++) //Repeat for the amount of spaces to add { if (t.Count() > column) t.At(column, " "); //Add a Space } } } } } } public void Set(string[] inputstrings, int wrapcolumn, Page page) { SortArray(inputstrings); var used = new bool[inputstrings.Length]; //Create a Boolean Array var organisedStrings = new string[inputstrings.Length]; int counter = 0; for (int i = 0; i < inputstrings.Length; i++) { used[i] = false; //Initialise them all as true } for (int g = 0; g < inputstrings.Length; g++) { if (inputstrings[g].Length != wrapcolumn && used[g] == false) //If we are not already at the limit { used[g] = true; organisedStrings[counter] = inputstrings[g]; counter++; int diff = wrapcolumn - inputstrings[g].Length; for (int i = 0; i < inputstrings.Length; i++) { if (inputstrings[i].Length == diff && used[i] == false) { used[i] = true; organisedStrings[counter] = inputstrings[i]; counter++; //Console.WriteLine(inputstrings[i]); } } } } for (int i = 0; i < used.Length; i++) //Add Ones That Wouldn't Fit { if (used[i] == false) { organisedStrings[counter] = inputstrings[i]; counter++; } } Fill(organisedStrings, wrapcolumn, page); } private void SortArray(string[] stringsort) { for (int i = (stringsort.Length - 1); i >= 0; i--) { int j; for (j = 1; j <= i; j++) { if (stringsort[j - 1].Length < stringsort[j].Length) { string temp = stringsort[j - 1]; stringsort[j - 1] = stringsort[j]; stringsort[j] = temp; } } } } public void FillAdjust(string[] inputstrings, int wrapcolumn, Page page) { Fill(inputstrings, wrapcolumn, page); foreach (Line t in page.Lines) { int spacestoadd = (wrapcolumn - t.Length()); if (spacestoadd < 0) //If there are no spaces to add spacestoadd = 0; int divide = t.Count()%2; bool divisable = Convert.ToBoolean(divide); //Spaces are Evenly Divisable if (divisable) { #region Even Spaces //case divisable by 2 bool evenspaces = spacestoadd%2 == 0; if (evenspaces) { int equalspaces = (spacestoadd/2); for (int g = 0; g < t.Count(); g++) //For Each Gap { for (int h = 0; h < equalspaces; h++) //For each of the spaces to add { t.At(g, " "); //Add space } } } else { int remainder = spacestoadd % 2; int leftToAdd = (spacestoadd - remainder) / 2; for (int g = 0; g < t.Count(); g++) //For Each Gap { for (int h = 0; h < leftToAdd; h++) //For each of the spaces to add { t.At(g, " "); //Add space } } int gapdiff = -100; //set it very high to start int marker = 0; //this will tell us where it was int previous = 0; //will set the previous one //Now the Remaining One for (int g = 0; g < t.Count(); g++) //For Each Gap { if(previous + t.At(g).Length > gapdiff) { marker = g - 1; gapdiff = previous - t.At(g).Length; previous = t.At(g).Length; } } t.At(marker, " "); } #endregion } else { int loopreps = spacestoadd/t.Count(); bool[] usedarray = new bool[t.Count()]; //Add As Many even spaces as possible for (int g = 0; g < t.Count(); g++) //For Each Gap { for (int h = 0; h < loopreps; h++) //For each of the spaces to add { t.At(g, " "); //Add space } } int oddspacestoadd = spacestoadd - (loopreps*t.Count()); //get biggest elements and add space for (int f = 0; f < oddspacestoadd; f++) //Spaces to Add { int gapdiff = -100; //set it very high to start int marker = 0; //this will tell us where it was int previous = 0; //will set the previous one //Now the Remaining One for (int g = 0; g < t.Count(); g++) //For Each Gap { if (previous + t.At(g).Length > gapdiff && !usedarray[g]) { marker = g - 1; gapdiff = previous + t.At(g).Length; previous = t.At(g).Length; } } for (int h = 0; h < t.Count(); h++) { if (!usedarray[h]) { t.At(marker, " "); usedarray[marker] = true; break; } } } } //move end spaces to the start t.Adjust(); } } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/ArrayMethods.cs
C#
gpl3
14,635
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ArrayFormat { public class Program { const String outputFileSuffix = ".out"; const String whiteSpaceChars = @" \n\t\r"; public enum ArrayFormat : int { Fill, UniformCount, UniformCountStrict, Column, ColumnStrict, Adjust, Set }; internal static ArrayFormat format; public static void Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Incorrect number of args, usage: arrayFormat.exe filename wrapColumn formatSpec"); return; } String inputFile = args[0]; // read wrap column int wrap; try { wrap = Int32.Parse(args[1]); } catch (Exception e) { Console.WriteLine("Bad input, cannot read wrap column: " + args[1]); Console.WriteLine(e.Message); return; } switch (args[2]) { case "Fill": format = ArrayFormat.Fill; break; case "UniformCount": format = ArrayFormat.UniformCount; break; case "UniformCountStrict": format = ArrayFormat.UniformCountStrict; break; case "Column": format = ArrayFormat.Column; break; case "ColumnStrict": format = ArrayFormat.ColumnStrict; break; case "Adjust": format = ArrayFormat.Adjust; break; case "Set": format = ArrayFormat.Set; break; default: throw new Exception("Unknown format specification: " + args[2]); } String[] sarray = InputStrings(inputFile); Page page = null; switch (format) { case ArrayFormat.Fill: page = new Text(wrap); ArrayMethods hi = new ArrayMethods(); Console.WriteLine("SET"); hi.Column(sarray, wrap, page,false); foreach (Line t in page.Lines) { Console.WriteLine(t.ToString()); } break; case ArrayFormat.UniformCount: break; case ArrayFormat.UniformCountStrict: break; case ArrayFormat.Column: break; case ArrayFormat.ColumnStrict: break; case ArrayFormat.Adjust: break; case ArrayFormat.Set: break; default: throw new Exception("Unknown format specification: " + args[2]); } page.ToFile(inputFile + outputFileSuffix); //Console.ReadLine(); } /// <summary> /// Input strings from supplied file and return as array. /// </summary> /// <param name="fileName"></param> private static String[] InputStrings(String fileName) { // open input FileInfo fileInfo = new FileInfo(fileName); if (!fileInfo.Exists) { Console.WriteLine("Input file not found : " + fileInfo.Directory.FullName + @"\" + fileName); return new String[0]; ; } List<String> sarray = new List<String>(); using (FileStream inStream = fileInfo.OpenRead()) { using (StreamReader reader = new StreamReader(inStream)) { String line = reader.ReadLine(); while (line != null) { String[] lineParts = line.Split(whiteSpaceChars.ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries); // line.Split(' '); in student version foreach (String s in lineParts) { sarray.Add(s); } line = reader.ReadLine(); } } } return sarray.ToArray(); } } }
08230-software-engineering
trunk/ 08230-software-engineering --username AshleyButcher989@gmail.com/ArrayFormat/Program.cs
C#
gpl3
3,794
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("1042133")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HCMUS")] [assembly: AssemblyProduct("1042133")] [assembly: AssemblyCopyright("Copyright © HCMUS 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5bee1f43-0075-449d-ad6d-382ef78045c4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1042133-quanlynhasach
trunk/src/1042133/Properties/AssemblyInfo.cs
C#
asf20
1,436
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _1042133 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
1042133-quanlynhasach
trunk/src/1042133/Form1.cs
C#
asf20
370
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace _1042133 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
1042133-quanlynhasach
trunk/src/1042133/Program.cs
C#
asf20
500
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ListActivity; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.ClipboardManager; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import de.shandschuh.sparserss.provider.FeedData; public class EntriesListActivity extends ListActivity implements Requeryable { private static final int CONTEXTMENU_MARKASREAD_ID = 6; private static final int CONTEXTMENU_MARKASUNREAD_ID = 7; private static final int CONTEXTMENU_DELETE_ID = 8; private static final int CONTEXTMENU_COPYURL = 9; public static final String EXTRA_SHOWFEEDINFO = "show_feedinfo"; public static final String EXTRA_AUTORELOAD = "autoreload"; private static final String FAVORITES = "favorites"; private static final String ALLENTRIES = "allentries"; private static final String[] FEED_PROJECTION = {FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.ICON, FeedData.FeedColumns.HIDE_READ }; private Uri uri; private EntriesListAdapter entriesListAdapter; private byte[] iconBytes; private String feedName; private long feedId; private boolean hideRead; @Override protected void onCreate(Bundle savedInstanceState) { if (MainTabActivity.isLightTheme(this)) { setTheme(R.style.Theme_Light); } super.onCreate(savedInstanceState); feedName = null; iconBytes = null; Intent intent = getIntent(); feedId = intent.getLongExtra(FeedData.FeedColumns._ID, 0); uri = intent.getData(); if (feedId > 0) { Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(feedId), FEED_PROJECTION, null, null, null); if (cursor.moveToFirst()) { feedName = cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0); iconBytes = cursor.getBlob(2); hideRead = cursor.getInt(3) == 1; } cursor.close(); } else { hideRead = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(new StringBuilder(uri.equals(FeedData.EntryColumns.FAVORITES_CONTENT_URI) ? FAVORITES : ALLENTRIES).append('.').append(FeedData.FeedColumns.HIDE_READ).toString(), false); } if (!MainTabActivity.POSTGINGERBREAD && iconBytes != null && iconBytes.length > 0) { // we cannot insert the icon here because it would be overwritten, but we have to reserve the icon here if (!requestWindowFeature(Window.FEATURE_LEFT_ICON)) { iconBytes = null; } } setContentView(R.layout.entries); entriesListAdapter = new EntriesListAdapter(this, uri, intent.getBooleanExtra(EXTRA_SHOWFEEDINFO, false), intent.getBooleanExtra(EXTRA_AUTORELOAD, false), hideRead); setListAdapter(entriesListAdapter); if (feedName != null) { setTitle(feedName); } if (iconBytes != null && iconBytes.length > 0) { int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics()); Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null) { if (bitmap.getHeight() != bitmapSizeInDip) { bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false); } if (MainTabActivity.POSTGINGERBREAD) { CompatibilityHelper.setActionBarDrawable(this, new BitmapDrawable(bitmap)); } else { setFeatureDrawable(Window.FEATURE_LEFT_ICON, new BitmapDrawable(bitmap)); } } } if (RSSOverview.notificationManager != null) { RSSOverview.notificationManager.cancel(0); } getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText()); menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread).setIcon(android.R.drawable.ic_menu_manage); menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread).setIcon(android.R.drawable.ic_menu_manage); menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete).setIcon(android.R.drawable.ic_menu_delete); menu.add(0, CONTEXTMENU_COPYURL, Menu.NONE, R.string.contextmenu_copyurl).setIcon(android.R.drawable.ic_menu_share); } }); } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setTypeface(Typeface.DEFAULT); textView.setEnabled(false); view.findViewById(android.R.id.text2).setEnabled(false); entriesListAdapter.neutralizeReadState(); startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(uri, id)).putExtra(FeedData.FeedColumns.HIDE_READ, entriesListAdapter.isHideRead()).putExtra(FeedData.FeedColumns.ICON, iconBytes).putExtra(FeedData.FeedColumns.NAME, feedName)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.entrylist, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (menu != null) { menu.setGroupVisible(R.id.menu_group_0, entriesListAdapter.getCount() > 0); if (hideRead) { menu.findItem(R.id.menu_hideread).setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view); } else { menu.findItem(R.id.menu_hideread).setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel); } } return true; } public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.menu_markasread: { new Thread() { // the update process takes some time public void run() { getContentResolver().update(uri, RSSOverview.getReadContentValues(), null, null); } }.start(); entriesListAdapter.markAsRead(); break; } case R.id.menu_markasunread: { new Thread() { // the update process takes some time public void run() { getContentResolver().update(uri, RSSOverview.getUnreadContentValues(), null, null); } }.start(); entriesListAdapter.markAsUnread(); break; } case R.id.menu_hideread: { hideRead = !entriesListAdapter.isHideRead(); if (hideRead) { item.setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel); entriesListAdapter.setHideRead(true); } else { item.setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view); entriesListAdapter.setHideRead(false); } setHideReadFromUri(); break; } case R.id.menu_deleteread: { new Thread() { // the delete process takes some time public void run() { String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")"; getContentResolver().delete(uri, selection, null); FeedData.deletePicturesOfFeed(EntriesListActivity.this, uri, selection); runOnUiThread(new Runnable() { public void run() { entriesListAdapter.getCursor().requery(); } }); } }.start(); break; } case R.id.menu_deleteallentries: { Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(R.string.contextmenu_deleteallentries); builder.setMessage(R.string.question_areyousure); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { new Thread() { public void run() { getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null); runOnUiThread(new Runnable() { public void run() { entriesListAdapter.getCursor().requery(); } }); } }.start(); } }); builder.setNegativeButton(android.R.string.no, null); builder.show(); break; } case CONTEXTMENU_MARKASREAD_ID: { long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id; getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getReadContentValues(), null, null); entriesListAdapter.markAsRead(id); break; } case CONTEXTMENU_MARKASUNREAD_ID: { long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id; getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getUnreadContentValues(), null, null); entriesListAdapter.markAsUnread(id); break; } case CONTEXTMENU_DELETE_ID: { long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id; getContentResolver().delete(ContentUris.withAppendedId(uri, id), null, null); FeedData.deletePicturesOfEntry(Long.toString(id)); entriesListAdapter.getCursor().requery(); // we have no other choice break; } case CONTEXTMENU_COPYURL: { ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).targetView.getTag().toString()); break; } } return true; } private void setHideReadFromUri() { if (feedId > 0) { ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.HIDE_READ, hideRead); getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(feedId), values, null, null); } else { Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putBoolean(new StringBuilder(uri.equals(FeedData.EntryColumns.FAVORITES_CONTENT_URI) ? FAVORITES : ALLENTRIES).append('.').append(FeedData.FeedColumns.HIDE_READ).toString(), hideRead); editor.commit(); } } @Override public void requery() { if (entriesListAdapter != null) { entriesListAdapter.reloadCursor(); } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/EntriesListActivity.java
Java
mit
11,912
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.ClipboardManager; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.TypedValue; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.animation.Animation; import android.webkit.WebView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; import de.shandschuh.sparserss.provider.FeedData; public class EntryActivity extends Activity { /* private static final String NEWLINE = "\n"; private static final String BR = "<br/>"; */ private static final String TEXT_HTML = "text/html"; private static final String UTF8 = "utf-8"; private static final String OR_DATE = " or date "; private static final String DATE = "(date="; private static final String AND_ID = " and _id"; private static final String ASC = "date asc, _id desc limit 1"; private static final String DESC = "date desc, _id asc limit 1"; private static final String CSS = "<head><style type=\"text/css\">body {max-width: 100%}\nimg {max-width: 100%; height: auto;}\ndiv[style] {max-width: 100%;}\npre {white-space: pre-wrap;}</style></head>"; private static final String FONT_START = CSS+"<body link=\"#97ACE5\" text=\"#C0C0C0\">"; private static final String FONT_FONTSIZE_START = CSS+"<body link=\"#97ACE5\" text=\"#C0C0C0\"><font size=\"+"; private static final String FONTSIZE_START = "<font size=\"+"; private static final String FONTSIZE_MIDDLE = "\">"; private static final String FONTSIZE_END = "</font>"; private static final String FONT_END = "</font><br/><br/><br/><br/></body>"; private static final String BODY_START = "<body>"; private static final String BODY_END = "<br/><br/><br/><br/></body>"; private static final int BUTTON_ALPHA = 180; private static final String IMAGE_ENCLOSURE = "[@]image/"; private static final String TEXTPLAIN = "text/plain"; private static final String BRACKET = " ("; private int titlePosition; private int datePosition; private int abstractPosition; private int linkPosition; private int feedIdPosition; private int favoritePosition; private int readDatePosition; private int enclosurePosition; private int authorPosition; private String _id; private String _nextId; private String _previousId; private Uri uri; private Uri parentUri; private int feedId; boolean favorite; private boolean hideRead; private boolean canShowIcon; private byte[] iconBytes; private String feedName; private WebView webView; private WebView webView0; // only needed for the animation private ViewFlipper viewFlipper; private ImageButton nextButton; private ImageButton urlButton; private ImageButton previousButton; private ImageButton playButton; int scrollX; int scrollY; private String link; private LayoutParams layoutParams; private View content; private SharedPreferences preferences; private boolean localPictures; private TextView titleTextView; @Override protected void onCreate(Bundle savedInstanceState) { if (MainTabActivity.isLightTheme(this)) { setTheme(R.style.Theme_Light); } super.onCreate(savedInstanceState); int titleId = -1; if (MainTabActivity.POSTGINGERBREAD) { canShowIcon = true; setContentView(R.layout.entry); try { /* This is a trick as com.android.internal.R.id.action_bar_title is not directly accessible */ titleId = (Integer) Class.forName("com.android.internal.R$id").getField("action_bar_title").get(null); } catch (Exception exception) { } } else { canShowIcon = requestWindowFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.entry); titleId = android.R.id.title; } try { titleTextView = (TextView) findViewById(titleId); titleTextView.setSingleLine(true); titleTextView.setHorizontallyScrolling(true); titleTextView.setMarqueeRepeatLimit(1); titleTextView.setEllipsize(TextUtils.TruncateAt.MARQUEE); titleTextView.setFocusable(true); titleTextView.setFocusableInTouchMode(true); } catch (Exception e) { // just in case for non standard android, nullpointer etc } uri = getIntent().getData(); parentUri = FeedData.EntryColumns.PARENT_URI(uri.getPath()); hideRead = getIntent().getBooleanExtra(FeedData.FeedColumns.HIDE_READ, false); iconBytes = getIntent().getByteArrayExtra(FeedData.FeedColumns.ICON); feedName = getIntent().getStringExtra(FeedData.FeedColumns.NAME); feedId = 0; Cursor entryCursor = getContentResolver().query(uri, null, null, null, null); titlePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.TITLE); datePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.DATE); abstractPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.ABSTRACT); linkPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.LINK); feedIdPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.FEED_ID); favoritePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.FAVORITE); readDatePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.READDATE); enclosurePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.ENCLOSURE); authorPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.AUTHOR); entryCursor.close(); if (RSSOverview.notificationManager == null) { RSSOverview.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } nextButton = (ImageButton) findViewById(R.id.next_button); urlButton = (ImageButton) findViewById(R.id.url_button); urlButton.setAlpha(BUTTON_ALPHA+30); previousButton = (ImageButton) findViewById(R.id.prev_button); playButton = (ImageButton) findViewById(R.id.play_button); playButton.setAlpha(BUTTON_ALPHA); viewFlipper = (ViewFlipper) findViewById(R.id.content_flipper); layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); webView = new WebView(this); viewFlipper.addView(webView, layoutParams); OnKeyListener onKeyEventListener = new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == 92 || keyCode == 94) { scrollUp(); return true; } else if (keyCode == 93 || keyCode == 95) { scrollDown(); return true; } } return false; } }; webView.setOnKeyListener(onKeyEventListener); content = findViewById(R.id.entry_content); webView0 = new WebView(this); webView0.setOnKeyListener(onKeyEventListener); preferences = PreferenceManager.getDefaultSharedPreferences(this); final boolean gestures = preferences.getBoolean(Strings.SETTINGS_GESTURESENABLED, true); final GestureDetector gestureDetector = new GestureDetector(this, new OnGestureListener() { public boolean onDown(MotionEvent e) { return false; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (gestures) { if (Math.abs(velocityY) < Math.abs(velocityX)) { if (velocityX > 800) { if (previousButton.isEnabled()) { previousEntry(true); } } else if (velocityX < -800) { if (nextButton.isEnabled()) { nextEntry(true); } } } } return false; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void onShowPress(MotionEvent e) { } public boolean onSingleTapUp(MotionEvent e) { return false; } }); OnTouchListener onTouchListener = new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }; webView.setOnTouchListener(onTouchListener); content.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { gestureDetector.onTouchEvent(event); return true; // different to the above one! } }); webView0.setOnTouchListener(onTouchListener); scrollX = 0; scrollY = 0; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); webView.restoreState(savedInstanceState); } @Override protected void onResume() { super.onResume(); if (RSSOverview.notificationManager != null) { RSSOverview.notificationManager.cancel(0); } uri = getIntent().getData(); parentUri = FeedData.EntryColumns.PARENT_URI(uri.getPath()); if (MainTabActivity.POSTGINGERBREAD) { CompatibilityHelper.onResume(webView); } reload(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } private void reload() { if (_id != null && _id.equals(uri.getLastPathSegment())) { return; } _id = uri.getLastPathSegment(); ContentValues values = new ContentValues(); values.put(FeedData.EntryColumns.READDATE, System.currentTimeMillis()); Cursor entryCursor = getContentResolver().query(uri, null, null, null, null); if (entryCursor.moveToFirst()) { String abstractText = entryCursor.getString(abstractPosition); if (entryCursor.isNull(readDatePosition)) { getContentResolver().update(uri, values, new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null); } if (abstractText == null || abstractText.trim().length() == 0) { link = entryCursor.getString(linkPosition); entryCursor.close(); finish(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link))); } else { link = entryCursor.getString(linkPosition); String title = entryCursor.getString(titlePosition); setTitle(title == null || title.length() == 0 ? link : title); if (titleTextView != null) { titleTextView.requestFocus(); // restart ellipsize } int _feedId = entryCursor.getInt(feedIdPosition); if (feedId != _feedId) { if (feedId != 0) { iconBytes = null; // triggers re-fetch of the icon } feedId = _feedId; } if (feedName == null || (canShowIcon && (iconBytes == null || iconBytes.length == 0))) { Cursor feedCursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(Integer.toString(feedId)), new String[] {FeedData.FeedColumns._ID, FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.ICON}, null, null, null); if (feedCursor.moveToFirst()) { feedName = feedCursor.isNull(1) ? feedCursor.getString(2) : feedCursor.getString(1); iconBytes = feedCursor.getBlob(3); } feedCursor.close(); } if (canShowIcon) { Drawable icon = null; if (iconBytes != null && iconBytes.length > 0) { int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics()); Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null) { if (bitmap.getHeight() != bitmapSizeInDip) { bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false); } icon = new BitmapDrawable(bitmap); } } if (MainTabActivity.POSTGINGERBREAD) { if (icon == null) { icon = getResources().getDrawable(de.shandschuh.sparserss.R.drawable.icon); } CompatibilityHelper.setActionBarDrawable(this, icon); } else { setFeatureDrawable(Window.FEATURE_LEFT_ICON, icon); } } long timestamp = entryCursor.getLong(datePosition); Date date = new Date(timestamp); StringBuilder dateStringBuilder = new StringBuilder(DateFormat.getDateFormat(this).format(date)).append(' ').append(DateFormat.getTimeFormat(this).format(date)); String author = entryCursor.getString(authorPosition); if (feedName != null && feedName.length() > 0) { dateStringBuilder.append(' ').append(feedName); } if (author != null && author.length() > 0) { dateStringBuilder.append(BRACKET).append(author).append(')'); } ((TextView) findViewById(R.id.entry_date)).setText(dateStringBuilder); final ImageView imageView = (ImageView) findViewById(android.R.id.icon); favorite = entryCursor.getInt(favoritePosition) == 1; imageView.setImageResource(favorite ? android.R.drawable.star_on : android.R.drawable.star_off); imageView.setOnClickListener(new OnClickListener() { public void onClick(View view) { favorite = !favorite; imageView.setImageResource(favorite ? android.R.drawable.star_on : android.R.drawable.star_off); ContentValues values = new ContentValues(); values.put(FeedData.EntryColumns.FAVORITE, favorite ? 1 : 0); getContentResolver().update(uri, values, null, null); } }); // loadData does not recognize the encoding without correct html-header localPictures = abstractText.indexOf(Strings.IMAGEID_REPLACEMENT) > -1; if (localPictures) { abstractText = abstractText.replace(Strings.IMAGEID_REPLACEMENT, _id+Strings.IMAGEFILE_IDSEPARATOR); } if (preferences.getBoolean(Strings.SETTINGS_DISABLEPICTURES, false)) { abstractText = abstractText.replaceAll(Strings.HTML_IMG_REGEX, Strings.EMPTY); webView.getSettings().setBlockNetworkImage(true); } else { if (webView.getSettings().getBlockNetworkImage()) { /* * setBlockNetwortImage(false) calls postSync, which takes time, * so we clean up the html first and change the value afterwards */ webView.loadData(Strings.EMPTY, TEXT_HTML, UTF8); webView.getSettings().setBlockNetworkImage(false); } } int fontsize = Integer.parseInt(preferences.getString(Strings.SETTINGS_FONTSIZE, Strings.ONE)); /* if (abstractText.indexOf('<') > -1 && abstractText.indexOf('>') > -1) { abstractText = abstractText.replace(NEWLINE, BR); } */ if (MainTabActivity.isLightTheme(this) || preferences.getBoolean(Strings.SETTINGS_BLACKTEXTONWHITE, false)) { if (fontsize > 0) { webView.loadDataWithBaseURL(null, new StringBuilder(CSS).append(FONTSIZE_START).append(fontsize).append(FONTSIZE_MIDDLE).append(abstractText).append(FONTSIZE_END).toString(), TEXT_HTML, UTF8, null); } else { webView.loadDataWithBaseURL(null, new StringBuilder(CSS).append(BODY_START).append(abstractText).append(BODY_END).toString(), TEXT_HTML, UTF8, null); } webView.setBackgroundColor(Color.WHITE); content.setBackgroundColor(Color.WHITE); } else { if (fontsize > 0) { webView.loadDataWithBaseURL(null, new StringBuilder(FONT_FONTSIZE_START).append(fontsize).append(FONTSIZE_MIDDLE).append(abstractText).append(FONT_END).toString(), TEXT_HTML, UTF8, null); } else { webView.loadDataWithBaseURL(null, new StringBuilder(FONT_START).append(abstractText).append(BODY_END).toString(), TEXT_HTML, UTF8, null); } webView.setBackgroundColor(Color.BLACK); content.setBackgroundColor(Color.BLACK); } if (link != null && link.length() > 0) { urlButton.setEnabled(true); urlButton.setAlpha(BUTTON_ALPHA+20); urlButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(link)), 0); } }); } else { urlButton.setEnabled(false); urlButton.setAlpha(80); } final String enclosure = entryCursor.getString(enclosurePosition); if (enclosure != null && enclosure.length() > 6 && enclosure.indexOf(IMAGE_ENCLOSURE) == -1) { playButton.setVisibility(View.VISIBLE); playButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { final int position1 = enclosure.indexOf(Strings.ENCLOSURE_SEPARATOR); final int position2 = enclosure.indexOf(Strings.ENCLOSURE_SEPARATOR, position1+3); final Uri uri = Uri.parse(enclosure.substring(0, position1)); if (preferences.getBoolean(Strings.SETTINGS_ENCLOSUREWARNINGSENABLED, true)) { Builder builder = new AlertDialog.Builder(EntryActivity.this); builder.setTitle(R.string.question_areyousure); builder.setIcon(android.R.drawable.ic_dialog_alert); if (position2+4 > enclosure.length()) { builder.setMessage(getString(R.string.question_playenclosure, uri, position2+4 > enclosure.length() ? Strings.QUESTIONMARKS : enclosure.substring(position2+3))); } else { try { builder.setMessage(getString(R.string.question_playenclosure, uri, (Integer.parseInt(enclosure.substring(position2+3)) / 1024f)+getString(R.string.kb))); } catch (Exception e) { builder.setMessage(getString(R.string.question_playenclosure, uri, enclosure.substring(position2+3))); } } builder.setCancelable(true); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { showEnclosure(uri, enclosure, position1, position2); } }); builder.setNeutralButton(R.string.button_alwaysokforall, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(Strings.SETTINGS_ENCLOSUREWARNINGSENABLED, false).commit(); showEnclosure(uri, enclosure, position1, position2); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } else { showEnclosure(uri, enclosure, position1, position2); } } }); } else { playButton.setVisibility(View.GONE); } entryCursor.close(); setupButton(previousButton, false, timestamp); setupButton(nextButton, true, timestamp); webView.scrollTo(scrollX, scrollY); // resets the scrolling } } else { entryCursor.close(); } /* new Thread() { public void run() { sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET)); // this is slow } }.start(); */ } private void showEnclosure(Uri uri, String enclosure, int position1, int position2) { try { startActivityForResult(new Intent(Intent.ACTION_VIEW).setDataAndType(uri, enclosure.substring(position1+3, position2)), 0); } catch (Exception e) { try { startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), 0); // fallbackmode - let the browser handle this } catch (Throwable t) { Toast.makeText(EntryActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } } } private void setupButton(ImageButton button, final boolean successor, long date) { StringBuilder queryString = new StringBuilder(DATE).append(date).append(AND_ID).append(successor ? '>' : '<').append(_id).append(')').append(OR_DATE).append(successor ? '<' : '>').append(date); if (hideRead) { queryString.append(Strings.DB_AND).append(EntriesListAdapter.READDATEISNULL); } Cursor cursor = getContentResolver().query(parentUri, new String[] {FeedData.EntryColumns._ID}, queryString.toString() , null, successor ? DESC : ASC); if (cursor.moveToFirst()) { button.setEnabled(true); button.setAlpha(BUTTON_ALPHA); final String id = cursor.getString(0); if (successor) { _nextId = id; } else { _previousId = id; } button.setOnClickListener(new OnClickListener() { public void onClick(View view) { if (successor) { nextEntry(false); } else { previousEntry(false); } } }); } else { button.setEnabled(false); button.setAlpha(60); } cursor.close(); } private void switchEntry(String id, boolean animate, Animation inAnimation, Animation outAnimation) { uri = parentUri.buildUpon().appendPath(id).build(); getIntent().setData(uri); scrollX = 0; scrollY = 0; if (animate) { WebView dummy = webView; // switch reference webView = webView0; webView0 = dummy; } reload(); if (animate) { viewFlipper.setInAnimation(inAnimation); viewFlipper.setOutAnimation(outAnimation); viewFlipper.addView(webView, layoutParams); viewFlipper.showNext(); viewFlipper.removeViewAt(0); } } private void nextEntry(boolean animate) { switchEntry(_nextId, animate, Animations.SLIDE_IN_RIGHT, Animations.SLIDE_OUT_LEFT); } private void previousEntry(boolean animate) { switchEntry(_previousId, animate, Animations.SLIDE_IN_LEFT, Animations.SLIDE_OUT_RIGHT); } @Override protected void onPause() { super.onPause(); if (MainTabActivity.POSTGINGERBREAD) { CompatibilityHelper.onPause(webView); } scrollX = webView.getScrollX(); scrollY = webView.getScrollY(); } @Override protected void onSaveInstanceState(Bundle outState) { webView.saveState(outState); super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.entry, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.menu_copytoclipboard: { if (link != null) { ((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(link); } break; } case R.id.menu_delete: { getContentResolver().delete(uri, null, null); if (localPictures) { FeedData.deletePicturesOfEntry(_id); } if (nextButton.isEnabled()) { nextButton.performClick(); } else { if (previousButton.isEnabled()) { previousButton.performClick(); } else { finish(); } } break; } case R.id.menu_share: { if (link != null) { startActivity(Intent.createChooser(new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, link).setType(TEXTPLAIN), getString(R.string.menu_share))); } break; } } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == 92 || keyCode == 94) { scrollUp(); return true; } else if (keyCode == 93 || keyCode == 95) { scrollDown(); return true; } } return super.onKeyDown(keyCode, event); } private void scrollUp() { if (webView != null) { webView.pageUp(false); } } private void scrollDown() { if (webView != null) { webView.pageDown(false); } } /** * Works around android issue 6191 */ @Override public void unregisterReceiver(BroadcastReceiver receiver) { try { super.unregisterReceiver(receiver); } catch (Exception e) { // do nothing } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/EntryActivity.java
Java
mit
25,380
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.handler; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.preference.PreferenceManager; import android.text.Html; import de.shandschuh.sparserss.Strings; import de.shandschuh.sparserss.provider.FeedData; import de.shandschuh.sparserss.provider.FeedDataContentProvider; import de.shandschuh.sparserss.service.FetcherService; public class RSSHandler extends DefaultHandler { private static final String ANDRHOMBUS = "&#"; private static final String TAG_RSS = "rss"; private static final String TAG_RDF = "rdf"; private static final String TAG_FEED = "feed"; private static final String TAG_ENTRY = "entry"; private static final String TAG_ITEM = "item"; private static final String TAG_UPDATED = "updated"; private static final String TAG_TITLE = "title"; private static final String TAG_LINK = "link"; private static final String TAG_DESCRIPTION = "description"; private static final String TAG_MEDIA_DESCRIPTION = "media:description"; private static final String TAG_CONTENT = "content"; private static final String TAG_MEDIA_CONTENT = "media:content"; private static final String TAG_ENCODEDCONTENT = "encoded"; private static final String TAG_SUMMARY = "summary"; private static final String TAG_PUBDATE = "pubDate"; private static final String TAG_DATE = "date"; private static final String TAG_LASTBUILDDATE = "lastBuildDate"; private static final String TAG_ENCLOSURE = "enclosure"; private static final String TAG_GUID = "guid"; private static final String TAG_AUTHOR = "author"; private static final String TAG_NAME = "name"; private static final String TAG_CREATOR = "creator"; private static final String TAG_ENCLOSUREURL = "url"; private static final String TAG_ENCLOSURETYPE = "type"; private static final String TAG_ENCLOSURELENGTH = "length"; private static final String ATTRIBUTE_URL = "url"; private static final String ATTRIBUTE_HREF = "href"; private static final String ATTRIBUTE_TYPE = "type"; private static final String ATTRIBUTE_LENGTH = "length"; private static final String ATTRIBUTE_REL = "rel"; private static final String UTF8 = "UTF-8"; private static final String PERCENT = "%"; /** This can be any valid filename character sequence which does not contain '%' */ private static final String PERCENT_REPLACE = "____"; private static final String[] TIMEZONES = {"MEST", "EST", "PST"}; private static final String[] TIMEZONES_REPLACE = {"+0200", "-0500", "-0800"}; private static final int TIMEZONES_COUNT = 3; private static long KEEP_TIME = 345600000l; // 4 days private static final DateFormat[] PUBDATE_DATEFORMATS = { new SimpleDateFormat("EEE', 'd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US), new SimpleDateFormat("d' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US), new SimpleDateFormat("EEE', 'd' 'MMM' 'yyyy' 'HH:mm:ss' 'z", Locale.US), }; private static final int PUBDATEFORMAT_COUNT = 3; private static final DateFormat[] UPDATE_DATEFORMATS = { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz", Locale.US), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US), }; private static final int DATEFORMAT_COUNT = 3; private static final String Z = "Z"; private static final String GMT = "GMT"; private static final StringBuilder DB_FAVORITE = new StringBuilder(" AND (").append(Strings.DB_EXCUDEFAVORITE).append(')'); private static final Pattern imgPattern = Pattern.compile("<img src=\\s*['\"]([^'\"]+)['\"][^>]*>", Pattern.CASE_INSENSITIVE); // middle () is group 1; s* is important for non-whitespaces; ' also usable private Context context; private Date lastUpdateDate; String id; private boolean titleTagEntered; private boolean updatedTagEntered; private boolean linkTagEntered; private boolean descriptionTagEntered; private boolean pubDateTagEntered; private boolean dateTagEntered; private boolean lastUpdateDateTagEntered; private boolean guidTagEntered; private StringBuilder title; private StringBuilder dateStringBuilder; private Date entryDate; private StringBuilder entryLink; private StringBuilder description; private StringBuilder enclosure; private Uri feedEntiresUri; private int newCount; private boolean feedRefreshed; private String feedTitle; private String feedBaseUrl; private boolean done; private Date keepDateBorder; private InputStream inputStream; private Reader reader; private boolean fetchImages; private boolean cancelled; private Date lastBuildDate; private long realLastUpdate; private long now; private StringBuilder guid; private boolean efficientFeedParsing; private boolean authorTagEntered; private StringBuilder author; private boolean nameTagEntered; private boolean enclosureTagEntered; private boolean enclosureUrlTagEntered; private boolean enclosureTypeTagEntered; private boolean enclosureLengthTagEntered; private StringBuilder enclosureUrl; private StringBuilder enclosureType; private StringBuilder enclosureLength; public RSSHandler(Context context) { KEEP_TIME = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(context).getString(Strings.SETTINGS_KEEPTIME, "4"))*86400000l; this.context = context; this.efficientFeedParsing = true; } public void init(Date lastUpdateDate, final String id, String title, String url) { final long keepDateBorderTime = KEEP_TIME > 0 ? System.currentTimeMillis()-KEEP_TIME : 0; keepDateBorder = new Date(keepDateBorderTime); this.lastUpdateDate = lastUpdateDate; this.id = id; feedEntiresUri = FeedData.EntryColumns.CONTENT_URI(id); final String query = new StringBuilder(FeedData.EntryColumns.DATE).append('<').append(keepDateBorderTime).append(DB_FAVORITE).toString(); FeedData.deletePicturesOfFeed(context, feedEntiresUri, query); context.getContentResolver().delete(feedEntiresUri, query, null); newCount = 0; feedRefreshed = false; feedTitle = title; initFeedBaseUrl(url); this.title = null; this.dateStringBuilder = null; this.entryLink = null; this.description = null; this.enclosure = null; inputStream = null; reader = null; entryDate = null; lastBuildDate = null; realLastUpdate = lastUpdateDate.getTime(); done = false; cancelled = false; titleTagEntered = false; updatedTagEntered = false; linkTagEntered = false; descriptionTagEntered = false; pubDateTagEntered = false; dateTagEntered = false; lastUpdateDateTagEntered = false; now = System.currentTimeMillis(); guid = null; guidTagEntered = false; authorTagEntered = false; author = null; enclosureTagEntered = false; enclosureUrlTagEntered = false; enclosureUrl = null; enclosureTypeTagEntered = false; enclosureType = null; enclosureLengthTagEntered = false; enclosureLength = null; } public void initFeedBaseUrl(String url) { int index = url.indexOf('/', 8); // this also covers https:// if (index > -1) { feedBaseUrl = url.substring(0, index); } else { feedBaseUrl = null; } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (TAG_UPDATED.equals(localName)) { updatedTagEntered = true; dateStringBuilder = new StringBuilder(); } else if (TAG_ENTRY.equals(localName) || TAG_ITEM.equals(localName)) { description = null; entryLink = null; if (!feedRefreshed) { ContentValues values = new ContentValues(); if (feedTitle == null && title != null && title.length() > 0) { values.put(FeedData.FeedColumns.NAME, title.toString().trim()); } values.put(FeedData.FeedColumns.ERROR, (String) null); values.put(FeedData.FeedColumns.LASTUPDATE, System.currentTimeMillis() - 1000); if (lastBuildDate != null) { realLastUpdate = Math.max(entryDate != null && entryDate.after(lastBuildDate) ? entryDate.getTime() : lastBuildDate.getTime(), realLastUpdate); } else { realLastUpdate = Math.max(entryDate != null ? entryDate.getTime() : System.currentTimeMillis() - 1000, realLastUpdate); } values.put(FeedData.FeedColumns.REALLASTUPDATE, realLastUpdate); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); title = null; feedRefreshed = true; } } else if (TAG_TITLE.equals(localName)) { if (title == null) { titleTagEntered = true; title = new StringBuilder(); } } else if (TAG_LINK.equals(localName)) { if (authorTagEntered) { return; } if (TAG_ENCLOSURE.equals(attributes.getValue(Strings.EMPTY, ATTRIBUTE_REL))) { startEnclosure(attributes, attributes.getValue(Strings.EMPTY, ATTRIBUTE_HREF)); } else if (entryLink == null || qName.equals(localName)) { // this indicates either there is no link yet or it is a non prefix tag which is preferred entryLink = new StringBuilder(); boolean foundLink = false; for (int n = 0, i = attributes.getLength(); n < i; n++) { if (ATTRIBUTE_HREF.equals(attributes.getLocalName(n))) { if (attributes.getValue(n) != null) { entryLink.append(attributes.getValue(n)); foundLink = true; linkTagEntered = false; } else { linkTagEntered = true; } break; } } if (!foundLink) { linkTagEntered = true; } } } else if ((TAG_DESCRIPTION.equals(localName) && !TAG_MEDIA_DESCRIPTION.equals(qName)) || (TAG_CONTENT.equals(localName) && !TAG_MEDIA_CONTENT.equals(qName))) { descriptionTagEntered = true; description = new StringBuilder(); } else if (TAG_SUMMARY.equals(localName)) { if (description == null) { descriptionTagEntered = true; description = new StringBuilder(); } } else if (TAG_PUBDATE.equals(localName)) { pubDateTagEntered = true; dateStringBuilder = new StringBuilder(); } else if (TAG_DATE.equals(localName)) { dateTagEntered = true; dateStringBuilder = new StringBuilder(); } else if (TAG_LASTBUILDDATE.equals(localName)) { lastUpdateDateTagEntered = true; dateStringBuilder = new StringBuilder(); } else if (TAG_ENCODEDCONTENT.equals(localName)) { descriptionTagEntered = true; description = new StringBuilder(); } else if (TAG_ENCLOSURE.equals(localName)) { enclosureTagEntered = true; startEnclosure(attributes, attributes.getValue(Strings.EMPTY, ATTRIBUTE_URL)); } else if (TAG_GUID.equals(localName)) { guidTagEntered = true; guid = new StringBuilder(); } else if (TAG_AUTHOR.equals(localName) || TAG_CREATOR.equals(localName)) { authorTagEntered = true; if (TAG_CREATOR.equals(localName)) { nameTagEntered = true; // we simulate the existence of a name tag to trigger the characters(..) method } if (author == null) { author = new StringBuilder(); } else if (author.length() > 0){ // this indicates multiple authors author.append(Strings.COMMASPACE); } } else if (TAG_NAME.equals(localName)) { nameTagEntered = true; } else if (enclosureTagEntered) { if (TAG_ENCLOSUREURL.equals(localName)) { enclosureUrlTagEntered = true; enclosureUrl = new StringBuilder(); } else if (TAG_ENCLOSURETYPE.equals(localName)) { enclosureTypeTagEntered = true; enclosureType = new StringBuilder(); } else if (TAG_ENCLOSURELENGTH.equals(localName)) { enclosureLengthTagEntered = true; enclosureLength = new StringBuilder(); } } } private void startEnclosure(Attributes attributes, String url) { if (enclosure == null && url != null && url.length() > 0) { // fetch the first enclosure only enclosure = new StringBuilder(url); enclosure.append(Strings.ENCLOSURE_SEPARATOR); String value = attributes.getValue(Strings.EMPTY, ATTRIBUTE_TYPE); if (value != null) { enclosure.append(value); } enclosure.append(Strings.ENCLOSURE_SEPARATOR); value = attributes.getValue(Strings.EMPTY, ATTRIBUTE_LENGTH); if (value != null) { enclosure.append(value); } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (titleTagEntered) { title.append(ch, start, length); } else if (updatedTagEntered) { dateStringBuilder.append(ch, start, length); } else if (linkTagEntered) { entryLink.append(ch, start, length); } else if (descriptionTagEntered) { description.append(ch, start, length); } else if (pubDateTagEntered) { dateStringBuilder.append(ch, start, length); } else if (dateTagEntered) { dateStringBuilder.append(ch, start, length); } else if (lastUpdateDateTagEntered) { dateStringBuilder.append(ch, start, length); } else if (guidTagEntered) { guid.append(ch, start, length); } else if (authorTagEntered && nameTagEntered) { author.append(ch, start, length); } else if (enclosureUrlTagEntered) { enclosureUrl.append(ch, start, length); } else if (enclosureTypeTagEntered) { enclosureType.append(ch, start, length); } else if (enclosureLengthTagEntered) { enclosureLength.append(ch, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (TAG_TITLE.equals(localName)) { titleTagEntered = false; } else if ((TAG_DESCRIPTION.equals(localName) && !TAG_MEDIA_DESCRIPTION.equals(qName)) || TAG_SUMMARY.equals(localName) || (TAG_CONTENT.equals(localName) && !TAG_MEDIA_CONTENT.equals(qName)) || TAG_ENCODEDCONTENT.equals(localName)) { descriptionTagEntered = false; } else if (TAG_LINK.equals(localName)) { linkTagEntered = false; } else if (TAG_UPDATED.equals(localName)) { entryDate = parseUpdateDate(dateStringBuilder.toString()); updatedTagEntered = false; } else if (TAG_PUBDATE.equals(localName)) { entryDate = parsePubdateDate(dateStringBuilder.toString().replace(Strings.TWOSPACE, Strings.SPACE)); pubDateTagEntered = false; } else if (TAG_LASTBUILDDATE.equals(localName)) { lastBuildDate = parsePubdateDate(dateStringBuilder.toString().replace(Strings.TWOSPACE, Strings.SPACE)); lastUpdateDateTagEntered = false; } else if (TAG_DATE.equals(localName)) { entryDate = parseUpdateDate(dateStringBuilder.toString()); dateTagEntered = false; } else if (TAG_ENTRY.equals(localName) || TAG_ITEM.equals(localName)) { if (title != null && (entryDate == null || ((entryDate.after(lastUpdateDate) || !efficientFeedParsing) && entryDate.after(keepDateBorder)))) { ContentValues values = new ContentValues(); if (entryDate != null && entryDate.getTime() > realLastUpdate) { realLastUpdate = entryDate.getTime(); values.put(FeedData.FeedColumns.REALLASTUPDATE, realLastUpdate); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); values.clear(); } if (entryDate != null) { values.put(FeedData.EntryColumns.DATE, entryDate.getTime()); values.putNull(FeedData.EntryColumns.READDATE); } values.put(FeedData.EntryColumns.TITLE, unescapeString(title.toString().trim())); if (author != null) { values.put(FeedData.EntryColumns.AUTHOR, unescapeString(author.toString())); } Vector<String> images = null; if (description != null) { String descriptionString = description.toString().trim().replaceAll(Strings.HTML_SPAN_REGEX, Strings.EMPTY); if (descriptionString.length() > 0) { if (fetchImages) { images = new Vector<String>(4); Matcher matcher = imgPattern.matcher(description); while (matcher.find()) { String match = matcher.group(1).replace(Strings.SPACE, Strings.URL_SPACE); images.add(match); try { // replace the '%' that may occur while urlencode such that the img-src url (in the abstract text) does reinterpret the parameters descriptionString = descriptionString.replace(match, new StringBuilder(Strings.FILEURL).append(FeedDataContentProvider.IMAGEFOLDER).append(Strings.IMAGEID_REPLACEMENT).append(URLEncoder.encode(match.substring(match.lastIndexOf('/')+1), UTF8)).toString().replace(PERCENT, PERCENT_REPLACE)); } catch (UnsupportedEncodingException e) { // UTF-8 should be supported } } } values.put(FeedData.EntryColumns.ABSTRACT, descriptionString); } } String enclosureString = null; StringBuilder existanceStringBuilder = new StringBuilder(FeedData.EntryColumns.LINK).append(Strings.DB_ARG); if (enclosure == null && enclosureUrl != null && enclosureUrl.length() > 0) { enclosure = enclosureUrl; enclosure.append(Strings.ENCLOSURE_SEPARATOR); if (enclosureType != null && enclosureType.length() > 0) { enclosure.append(enclosureType); } enclosure.append(Strings.ENCLOSURE_SEPARATOR); if (enclosureLength != null && enclosureLength.length() > 0) { enclosure.append(enclosureLength); } } if (enclosure != null && enclosure.length() > 0) { enclosureString = enclosure.toString(); values.put(FeedData.EntryColumns.ENCLOSURE, enclosureString); existanceStringBuilder.append(Strings.DB_AND).append(FeedData.EntryColumns.ENCLOSURE).append(Strings.DB_ARG); } String guidString = null; if (guid != null && guid.length() > 0) { guidString = guid.toString(); values.put(FeedData.EntryColumns.GUID, guidString); existanceStringBuilder.append(Strings.DB_AND).append(FeedData.EntryColumns.GUID).append(Strings.DB_ARG); } String entryLinkString = Strings.EMPTY; // don't set this to null as we need *some* value if (entryLink != null && entryLink.length() > 0) { entryLinkString = entryLink.toString().trim(); if (feedBaseUrl != null && !entryLinkString.startsWith(Strings.HTTP) && !entryLinkString.startsWith(Strings.HTTPS)) { entryLinkString = feedBaseUrl + (entryLinkString.startsWith(Strings.SLASH) ? entryLinkString : Strings.SLASH + entryLinkString); } } String[] existanceValues = enclosureString != null ? (guidString != null ? new String[] {entryLinkString, enclosureString, guidString}: new String[] {entryLinkString, enclosureString}) : (guidString != null ? new String[] {entryLinkString, guidString} : new String[] {entryLinkString}); boolean skip = false; if (!efficientFeedParsing) { if (context.getContentResolver().update(feedEntiresUri, values, existanceStringBuilder.toString()+" AND "+FeedData.EntryColumns.DATE+"<"+entryDate.getTime(), existanceValues) == 1) { newCount++; skip = true; } else { values.remove(FeedData.EntryColumns.READDATE); // continue with the standard procedure but don't reset the read-date } } if (!skip && ((entryLinkString.length() == 0 && guidString == null) || context.getContentResolver().update(feedEntiresUri, values, existanceStringBuilder.toString(), existanceValues) == 0)) { values.put(FeedData.EntryColumns.LINK, entryLinkString); if (entryDate == null) { values.put(FeedData.EntryColumns.DATE, now--); } String entryId = context.getContentResolver().insert(feedEntiresUri, values).getLastPathSegment(); if (fetchImages) { FeedDataContentProvider.IMAGEFOLDER_FILE.mkdir(); // create images dir for (int n = 0, i = images != null ? images.size() : 0; n < i; n++) { try { String match = images.get(n); byte[] data = FetcherService.getBytes(new URL(images.get(n)).openStream()); // see the comment where the img regex is executed for details about this replacement FileOutputStream fos = new FileOutputStream(new StringBuilder(FeedDataContentProvider.IMAGEFOLDER).append(entryId).append(Strings.IMAGEFILE_IDSEPARATOR).append(URLEncoder.encode(match.substring(match.lastIndexOf('/')+1), UTF8)).toString().replace(PERCENT, PERCENT_REPLACE)); fos.write(data); fos.close(); } catch (Exception e) { } } } newCount++; } else if (entryDate == null && efficientFeedParsing) { cancel(); } } else if (efficientFeedParsing) { cancel(); } description = null; title = null; enclosure = null; guid = null; author = null; enclosureUrl = null; enclosureType = null; enclosureLength = null; entryLink = null; } else if (TAG_RSS.equals(localName) || TAG_RDF.equals(localName) || TAG_FEED.equals(localName)) { done = true; } else if (TAG_GUID.equals(localName)) { guidTagEntered = false; } else if (TAG_NAME.equals(localName)) { nameTagEntered = false; } else if (TAG_AUTHOR.equals(localName) || TAG_CREATOR.equals(localName)) { authorTagEntered = false; } else if (TAG_ENCLOSURE.equals(localName)) { enclosureTagEntered = false; } else if (TAG_ENCLOSUREURL.equals(localName)) { enclosureUrlTagEntered = false; } else if (TAG_ENCLOSURETYPE.equals(localName)) { enclosureTypeTagEntered = false; } else if (TAG_ENCLOSURELENGTH.equals(localName)) { enclosureLengthTagEntered = false; } } public int getNewCount() { return newCount; } public boolean isDone() { return done; } public boolean isCancelled() { return cancelled; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; reader = null; } public void setReader(Reader reader) { this.reader = reader; inputStream = null; } public void cancel() { if (!cancelled) { cancelled = true; done = true; if (inputStream != null) { try { inputStream.close(); // stops all parsing } catch (IOException e) { } } else if (reader != null) { try { reader.close(); // stops all parsing } catch (IOException e) { } } } } public void setFetchImages(boolean fetchImages) { this.fetchImages = fetchImages; } private static Date parseUpdateDate(String string) { string = string.replace(Z, GMT); for (int n = 0; n < DATEFORMAT_COUNT; n++) { try { return UPDATE_DATEFORMATS[n].parse(string); } catch (ParseException e) { } // just do nothing } return null; } private static Date parsePubdateDate(String string) { for (int n = 0; n < TIMEZONES_COUNT; n++) { string = string.replace(TIMEZONES[n], TIMEZONES_REPLACE[n]); } for (int n = 0; n < PUBDATEFORMAT_COUNT; n++) { try { return PUBDATE_DATEFORMATS[n].parse(string); } catch (ParseException e) { } // just do nothing } return null; } private static String unescapeString(String str) { String result = str.replace(Strings.AMP_SG, Strings.AMP).replaceAll(Strings.HTML_TAG_REGEX, Strings.EMPTY).replace(Strings.HTML_LT, Strings.LT).replace(Strings.HTML_GT, Strings.GT).replace(Strings.HTML_QUOT, Strings.QUOT).replace(Strings.HTML_APOS, Strings.APOSTROPHE); if (result.indexOf(ANDRHOMBUS) > -1) { return Html.fromHtml(result, null, null).toString(); } else { return result; } } public void setEfficientFeedParsing(boolean efficientFeedParsing) { this.efficientFeedParsing = efficientFeedParsing; } }
025003b-gfgfgf
src/de/shandschuh/sparserss/handler/RSSHandler.java
Java
mit
25,006
/** * Sparse rss * * Copyright (c) 2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.handler; import java.io.File; import java.io.FilenameFilter; import java.util.regex.Pattern; import de.shandschuh.sparserss.provider.FeedDataContentProvider; public class PictureFilenameFilter implements FilenameFilter { private static final String REGEX = "__[^\\.]*\\.[A-Za-z]*"; private Pattern pattern; public PictureFilenameFilter(String entryId) { setEntryId(entryId); } public PictureFilenameFilter() { } public void setEntryId(String entryId) { pattern = Pattern.compile(entryId+REGEX); } public boolean accept(File dir, String filename) { if (dir != null && dir.equals(FeedDataContentProvider.IMAGEFOLDER_FILE)) { // this should be always true but lets check it anyway return pattern.matcher(filename).find(); } else { return false; } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/handler/PictureFilenameFilter.java
Java
mit
1,961
/** * Sparse rss * * Copyright (c) 2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; public interface Requeryable { public void requery(); }
025003b-gfgfgf
src/de/shandschuh/sparserss/Requeryable.java
Java
mit
1,234
/** * Sparse rss * * Copyright (c) 2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.app.Activity; public class EmptyActivity extends Activity { }
025003b-gfgfgf
src/de/shandschuh/sparserss/EmptyActivity.java
Java
mit
1,256
/** * Sparse rss * * Copyright (c) 2010 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageManager.NameNotFoundException; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; import de.shandschuh.sparserss.Strings; public class RefreshService extends Service { private static final String SIXTYMINUTES = "3600000"; private OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (Strings.SETTINGS_REFRESHINTERVAL.equals(key)) { restartTimer(false); } } }; private Intent refreshBroadcastIntent; private AlarmManager alarmManager; private PendingIntent timerIntent; private SharedPreferences preferences = null; @Override public IBinder onBind(Intent intent) { onRebind(intent); return null; } @Override public void onRebind(Intent intent) { super.onRebind(intent); } @Override public boolean onUnbind(Intent intent) { return true; // we want to use rebind } @Override public void onCreate() { super.onCreate(); try { preferences = PreferenceManager.getDefaultSharedPreferences(createPackageContext(Strings.PACKAGE, 0)); } catch (NameNotFoundException e) { preferences = PreferenceManager.getDefaultSharedPreferences(this); } refreshBroadcastIntent = new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SCHEDULED, true); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); preferences.registerOnSharedPreferenceChangeListener(listener); restartTimer(true); } private void restartTimer(boolean created) { if (timerIntent == null) { timerIntent = PendingIntent.getBroadcast(this, 0, refreshBroadcastIntent, 0); } else { alarmManager.cancel(timerIntent); } int time = 3600000; try { time = Math.max(60000, Integer.parseInt(preferences.getString(Strings.SETTINGS_REFRESHINTERVAL, SIXTYMINUTES))); } catch (Exception exception) { } long initialRefreshTime = SystemClock.elapsedRealtime() + 10000; if (created) { long lastRefresh = preferences.getLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, 0); if (lastRefresh > 0) { // this indicates a service restart by the system initialRefreshTime = Math.max(SystemClock.elapsedRealtime() + 10000, lastRefresh+time); } } alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, initialRefreshTime, time, timerIntent); } @Override public void onDestroy() { if (timerIntent != null) { alarmManager.cancel(timerIntent); } preferences.unregisterOnSharedPreferenceChangeListener(listener); super.onDestroy(); } }
025003b-gfgfgf
src/de/shandschuh/sparserss/service/RefreshService.java
Java
mit
4,083
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.service; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Xml; import de.shandschuh.sparserss.BASE64; import de.shandschuh.sparserss.MainTabActivity; import de.shandschuh.sparserss.R; import de.shandschuh.sparserss.Strings; import de.shandschuh.sparserss.handler.RSSHandler; import de.shandschuh.sparserss.provider.FeedData; public class FetcherService extends IntentService { private static final int FETCHMODE_DIRECT = 1; private static final int FETCHMODE_REENCODE = 2; private static final String KEY_USERAGENT = "User-agent"; private static final String VALUE_USERAGENT = "Mozilla/5.0"; private static final String CHARSET = "charset="; private static final String COUNT = "COUNT(*)"; private static final String CONTENT_TYPE_TEXT_HTML = "text/html"; private static final String HREF = "href=\""; private static final String HTML_BODY = "<body"; private static final String ENCODING = "encoding=\""; private static final String SERVICENAME = "RssFetcherService"; private static final String ZERO = "0"; private static final String GZIP = "gzip"; /* Allow different positions of the "rel" attribute w.r.t. the "href" attribute */ private static final Pattern feedLinkPattern = Pattern.compile("[.]*<link[^>]* ((rel=alternate|rel=\"alternate\")[^>]* href=\"[^\"]*\"|href=\"[^\"]*\"[^>]* (rel=alternate|rel=\"alternate\"))[^>]*>", Pattern.CASE_INSENSITIVE); /* Case insensitive */ private static final Pattern feedIconPattern = Pattern.compile("[.]*<link[^>]* (rel=(\"shortcut icon\"|\"icon\"|icon)[^>]* href=\"[^\"]*\"|href=\"[^\"]*\"[^>]* rel=(\"shortcut icon\"|\"icon\"|icon))[^>]*>", Pattern.CASE_INSENSITIVE); private NotificationManager notificationManager; private static SharedPreferences preferences = null; private static Proxy proxy; private boolean destroyed; private RSSHandler handler; public FetcherService() { super(SERVICENAME); destroyed = false; HttpURLConnection.setFollowRedirects(true); } @Override public synchronized void onHandleIntent(Intent intent) { if (preferences == null) { try { preferences = PreferenceManager.getDefaultSharedPreferences(createPackageContext(Strings.PACKAGE, 0)); } catch (NameNotFoundException e) { preferences = PreferenceManager.getDefaultSharedPreferences(FetcherService.this); } } if (intent.getBooleanExtra(Strings.SCHEDULED, false)) { SharedPreferences.Editor editor = preferences.edit(); editor.putLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, SystemClock.elapsedRealtime()); editor.commit(); } ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED && intent != null) { if (preferences.getBoolean(Strings.SETTINGS_PROXYENABLED, false) && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || !preferences.getBoolean(Strings.SETTINGS_PROXYWIFIONLY, false))) { try { proxy = new Proxy(ZERO.equals(preferences.getString(Strings.SETTINGS_PROXYTYPE, ZERO)) ? Proxy.Type.HTTP : Proxy.Type.SOCKS, new InetSocketAddress(preferences.getString(Strings.SETTINGS_PROXYHOST, Strings.EMPTY), Integer.parseInt(preferences.getString(Strings.SETTINGS_PROXYPORT, Strings.DEFAULTPROXYPORT)))); } catch (Exception e) { proxy = null; } } else { proxy = null; } int newCount = refreshFeeds(FetcherService.this, intent.getStringExtra(Strings.FEEDID), networkInfo, intent.getBooleanExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, false)); if (newCount > 0) { if (preferences.getBoolean(Strings.SETTINGS_NOTIFICATIONSENABLED, false)) { Cursor cursor = getContentResolver().query(FeedData.EntryColumns.CONTENT_URI, new String[] {COUNT}, new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null, null); cursor.moveToFirst(); newCount = cursor.getInt(0); cursor.close(); String text = new StringBuilder().append(newCount).append(' ').append(getString(R.string.newentries)).toString(); Notification notification = new Notification(R.drawable.ic_statusbar_rss, text, System.currentTimeMillis()); Intent notificationIntent = new Intent(FetcherService.this, MainTabActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(FetcherService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (preferences.getBoolean(Strings.SETTINGS_NOTIFICATIONSVIBRATE, false)) { notification.defaults = Notification.DEFAULT_VIBRATE; } notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = 0xffffffff; notification.ledOnMS = 300; notification.ledOffMS = 1000; String ringtone = preferences.getString(Strings.SETTINGS_NOTIFICATIONSRINGTONE, null); if (ringtone != null && ringtone.length() > 0) { notification.sound = Uri.parse(ringtone); } notification.setLatestEventInfo(FetcherService.this, getString(R.string.rss_feeds), text, contentIntent); notificationManager.notify(0, notification); } else { notificationManager.cancel(0); } } } } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } @Override public void onDestroy() { if (MainTabActivity.INSTANCE != null) { MainTabActivity.INSTANCE.internalSetProgressBarIndeterminateVisibility(false); } destroyed = true; if (handler != null) { handler.cancel(); } super.onDestroy(); } private int refreshFeeds(Context context, String feedId, NetworkInfo networkInfo, boolean overrideWifiOnly) { String selection = null; if (!overrideWifiOnly && networkInfo.getType() != ConnectivityManager.TYPE_WIFI) { selection = new StringBuilder(FeedData.FeedColumns.WIFIONLY).append("=0 or ").append(FeedData.FeedColumns.WIFIONLY).append(" IS NULL").toString(); // "IS NOT 1" does not work on 2.1 } Cursor cursor = context.getContentResolver().query(feedId == null ? FeedData.FeedColumns.CONTENT_URI : FeedData.FeedColumns.CONTENT_URI(feedId), null, selection, null, null); // no managed query here int urlPosition = cursor.getColumnIndex(FeedData.FeedColumns.URL); int idPosition = cursor.getColumnIndex(FeedData.FeedColumns._ID); int lastUpdatePosition = cursor.getColumnIndex(FeedData.FeedColumns.REALLASTUPDATE); int titlePosition = cursor.getColumnIndex(FeedData.FeedColumns.NAME); int fetchmodePosition = cursor.getColumnIndex(FeedData.FeedColumns.FETCHMODE); int iconPosition = cursor.getColumnIndex(FeedData.FeedColumns.ICON); int imposeUseragentPosition = cursor.getColumnIndex(FeedData.FeedColumns.IMPOSE_USERAGENT); boolean followHttpHttpsRedirects = preferences.getBoolean(Strings.SETTINGS_HTTPHTTPSREDIRECTS, false); int result = 0; if (handler == null) { handler = new RSSHandler(context); } handler.setEfficientFeedParsing(preferences.getBoolean(Strings.SETTINGS_EFFICIENTFEEDPARSING, true)); handler.setFetchImages(preferences.getBoolean(Strings.SETTINGS_FETCHPICTURES, false)); while(!destroyed && cursor.moveToNext()) { String id = cursor.getString(idPosition); boolean imposeUserAgent = !cursor.isNull(imposeUseragentPosition) && cursor.getInt(imposeUseragentPosition) == 1; HttpURLConnection connection = null; try { String feedUrl = cursor.getString(urlPosition); connection = setupConnection(feedUrl, imposeUserAgent, followHttpHttpsRedirects); String redirectHost = connection.getURL().getHost(); // Feed icon should be fetched from target site, not from feedburner, so we're tracking all redirections String contentType = connection.getContentType(); int fetchMode = cursor.getInt(fetchmodePosition); String iconUrl = null; handler.init(new Date(cursor.getLong(lastUpdatePosition)), id, cursor.getString(titlePosition), feedUrl); if (fetchMode == 0) { if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) { BufferedReader reader = new BufferedReader(new InputStreamReader(getConnectionInputStream(connection))); String line = null; String newFeedUrl = null; while ((line = reader.readLine()) != null) { if (line.indexOf(HTML_BODY) > -1) { break; } else { if (newFeedUrl == null) { Matcher matcher = feedLinkPattern.matcher(line); if (matcher.find()) { // not "while" as only one link is needed newFeedUrl = getHref(matcher.group(), feedUrl); } } if (iconUrl == null) { Matcher matcher = feedIconPattern.matcher(line); if (matcher.find()) { // not "while" as only one link is needed iconUrl = getHref(matcher.group(), feedUrl); } } if (newFeedUrl != null && iconUrl != null) { break; } } } if (newFeedUrl != null) { redirectHost = connection.getURL().getHost(); connection.disconnect(); connection = setupConnection(newFeedUrl, imposeUserAgent, followHttpHttpsRedirects); contentType = connection.getContentType(); handler.initFeedBaseUrl(newFeedUrl); ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.URL, newFeedUrl); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); } } if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { Xml.findEncodingByName(index2 > -1 ?contentType.substring(index+8, index2) : contentType.substring(index+8)); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException usee) { fetchMode = FETCHMODE_REENCODE; } } else { fetchMode = FETCHMODE_REENCODE; } } else { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getConnectionInputStream(connection))); char[] chars = new char[20]; int length = bufferedReader.read(chars); String xmlDescription = new String(chars, 0, length); redirectHost = connection.getURL().getHost(); connection.disconnect(); connection = setupConnection(connection.getURL(), imposeUserAgent, followHttpHttpsRedirects); int start = xmlDescription != null ? xmlDescription.indexOf(ENCODING) : -1; if (start > -1) { try { Xml.findEncodingByName(xmlDescription.substring(start+10, xmlDescription.indexOf('"', start+11))); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException usee) { fetchMode = FETCHMODE_REENCODE; } } else { fetchMode = FETCHMODE_DIRECT; // absolutely no encoding information found } } ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.FETCHMODE, fetchMode); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); } /* check and optionally find favicon */ byte[] iconBytes = cursor.getBlob(iconPosition); if (iconBytes == null) { if (iconUrl == null) { String baseUrl = new StringBuilder(connection.getURL().getProtocol()).append(Strings.PROTOCOL_SEPARATOR).append(redirectHost).toString(); HttpURLConnection iconURLConnection = setupConnection(new URL(baseUrl), imposeUserAgent, followHttpHttpsRedirects); try { BufferedReader reader = new BufferedReader(new InputStreamReader(getConnectionInputStream(iconURLConnection))); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf(HTML_BODY) > -1) { break; } else { Matcher matcher = feedIconPattern.matcher(line); if (matcher.find()) { // not "while" as only one link is needed iconUrl = getHref(matcher.group(), baseUrl); if (iconUrl != null) { break; } } } } } catch (Exception e) { } finally { iconURLConnection.disconnect(); } if (iconUrl == null) { iconUrl = new StringBuilder(baseUrl).append(Strings.FILE_FAVICON).toString(); } } HttpURLConnection iconURLConnection = setupConnection(new URL(iconUrl), imposeUserAgent, followHttpHttpsRedirects); try { iconBytes = getBytes(getConnectionInputStream(iconURLConnection)); ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.ICON, iconBytes); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); } catch (Exception e) { ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.ICON, new byte[0]); // no icon found or error context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); } finally { iconURLConnection.disconnect(); } } switch (fetchMode) { default: case FETCHMODE_DIRECT: { if (contentType != null) { int index = contentType.indexOf(CHARSET); int index2 = contentType.indexOf(';', index); InputStream inputStream = getConnectionInputStream(connection); handler.setInputStream(inputStream); Xml.parse(inputStream, Xml.findEncodingByName(index2 > -1 ?contentType.substring(index+8, index2) : contentType.substring(index+8)), handler); } else { InputStreamReader reader = new InputStreamReader(getConnectionInputStream(connection)); handler.setReader(reader); Xml.parse(reader, handler); } break; } case FETCHMODE_REENCODE: { ByteArrayOutputStream ouputStream = new ByteArrayOutputStream(); InputStream inputStream = getConnectionInputStream(connection); byte[] byteBuffer = new byte[4096]; int n; while ( (n = inputStream.read(byteBuffer)) > 0 ) { ouputStream.write(byteBuffer, 0, n); } String xmlText = ouputStream.toString(); int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1; if (start > -1) { Xml.parse(new StringReader(new String(ouputStream.toByteArray(), xmlText.substring(start+10, xmlText.indexOf('"', start+11)))), handler); } else { // use content type if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { StringReader reader = new StringReader(new String(ouputStream.toByteArray(), index2 > -1 ?contentType.substring(index+8, index2) : contentType.substring(index+8))); handler.setReader(reader); Xml.parse(reader, handler); } catch (Exception e) { } } else { StringReader reader = new StringReader(new String(ouputStream.toByteArray())); handler.setReader(reader); Xml.parse(reader, handler); } } } break; } } connection.disconnect(); } catch (FileNotFoundException e) { if (!handler.isDone() && !handler.isCancelled()) { ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.FETCHMODE, 0); // resets the fetchmode to determine it again later values.put(FeedData.FeedColumns.ERROR, context.getString(R.string.error_feederror)); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); } } catch (Throwable e) { if (!handler.isDone() && !handler.isCancelled()) { ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.FETCHMODE, 0); // resets the fetchmode to determine it again later values.put(FeedData.FeedColumns.ERROR, e.getMessage()); context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null); } } finally { if (connection != null) { connection.disconnect(); } } result += handler.getNewCount(); } cursor.close(); if (result > 0) { context.sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET).putExtra(Strings.COUNT, result)); } return result; } private static String getHref(String line, String baseUrl) { int posStart = line.indexOf(HREF); if (posStart > -1) { String url = line.substring(posStart+6, line.indexOf('"', posStart+10)).replace(Strings.AMP_SG, Strings.AMP); if (url.startsWith(Strings.SLASH)) { int index = baseUrl.indexOf('/', 8); if (index > -1) { url = baseUrl.substring(0, index)+url; } else { url = baseUrl+url; } } else if (!url.startsWith(Strings.HTTP) && !url.startsWith(Strings.HTTPS)) { url = new StringBuilder(baseUrl).append('/').append(url).toString(); } return url; } else { return null; } } private static final HttpURLConnection setupConnection(String url, boolean imposeUseragent, boolean followHttpHttpsRedirects) throws IOException, NoSuchAlgorithmException, KeyManagementException { return setupConnection(new URL(url), imposeUseragent, followHttpHttpsRedirects); } private static final HttpURLConnection setupConnection(URL url, boolean imposeUseragent, boolean followHttpHttpsRedirects) throws IOException, NoSuchAlgorithmException, KeyManagementException { return setupConnection(url, imposeUseragent, followHttpHttpsRedirects, 0); } private static final HttpURLConnection setupConnection(URL url, boolean imposeUseragent, boolean followHttpHttpsRedirects, int cycle) throws IOException, NoSuchAlgorithmException, KeyManagementException { HttpURLConnection connection = proxy == null ? (HttpURLConnection) url.openConnection() : (HttpURLConnection) url.openConnection(proxy); connection.setDoInput(true); connection.setDoOutput(false); if (imposeUseragent) { connection.setRequestProperty(KEY_USERAGENT, VALUE_USERAGENT); // some feeds need this to work properly } connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.setUseCaches(false); if (url.getUserInfo() != null) { connection.setRequestProperty("Authorization", "Basic "+BASE64.encode(url.getUserInfo().getBytes())); } connection.setRequestProperty("connection", "close"); // Workaround for android issue 7786 connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); connection.connect(); String location = connection.getHeaderField("Location"); if (location != null && (url.getProtocol().equals(Strings._HTTP) && location.startsWith(Strings.HTTPS) || url.getProtocol().equals(Strings._HTTPS) && location.startsWith(Strings.HTTP))) { // if location != null, the system-automatic redirect has failed which indicates a protocol change if (followHttpHttpsRedirects) { connection.disconnect(); if (cycle < 5) { return setupConnection(new URL(location), imposeUseragent, followHttpHttpsRedirects, cycle+1); } else { throw new IOException("Too many redirects."); } } else { throw new IOException("https<->http redirect - enable in settings"); } } return connection; } public static byte[] getBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n; while ((n = inputStream.read(buffer)) > 0) { output.write(buffer, 0, n); } byte[] result = output.toByteArray(); output.close(); inputStream.close(); return result; } /** * This is a small wrapper for getting the properly encoded inputstream if is is gzip compressed * and not properly recognized. */ private static InputStream getConnectionInputStream(HttpURLConnection connection) throws IOException { InputStream inputStream = connection.getInputStream(); if (GZIP.equals(connection.getContentEncoding()) && !(inputStream instanceof GZIPInputStream)) { return new GZIPInputStream(inputStream); } else { return inputStream; } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/service/FetcherService.java
Java
mit
23,085
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import java.util.Vector; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.AlertDialog; import android.app.Dialog; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import android.widget.TextView; import de.shandschuh.sparserss.provider.FeedData; import de.shandschuh.sparserss.service.FetcherService; public class MainTabActivity extends TabActivity { private static final int DIALOG_LICENSEAGREEMENT = 0; private boolean tabsAdded; private static final String TAG_NORMAL = "normal"; private static final String TAG_ALL = "all"; private static final String TAG_FAVORITE = "favorite"; public static MainTabActivity INSTANCE; public static final boolean POSTGINGERBREAD = !Build.VERSION.RELEASE.startsWith("1") && !Build.VERSION.RELEASE.startsWith("2"); // this way around is future save private static Boolean LIGHTTHEME; public static boolean isLightTheme(Context context) { if (LIGHTTHEME == null) { LIGHTTHEME = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Strings.SETTINGS_LIGHTTHEME, false); } return LIGHTTHEME; } private Menu menu; private BroadcastReceiver refreshReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { internalSetProgressBarIndeterminateVisibility(true); } }; private boolean hasContent; private boolean progressBarVisible; private Vector<String> visitedTabs; public void onCreate(Bundle savedInstanceState) { if (isLightTheme(this)) { setTheme(R.style.Theme_Light); } super.onCreate(savedInstanceState); // We need to display progress information requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.tabs); INSTANCE = this; hasContent = false; visitedTabs = new Vector<String>(3); if (getPreferences(MODE_PRIVATE).getBoolean(Strings.PREFERENCE_LICENSEACCEPTED, false)) { setContent(); } else { /* Workaround for android issue 4499 on 1.5 devices */ getTabHost().addTab(getTabHost().newTabSpec(Strings.EMPTY).setIndicator(Strings.EMPTY).setContent(new Intent(this, EmptyActivity.class))); showDialog(DIALOG_LICENSEAGREEMENT); } } @Override protected void onResume() { super.onResume(); internalSetProgressBarIndeterminateVisibility(isCurrentlyRefreshing()); registerReceiver(refreshReceiver, new IntentFilter("de.shandschuh.sparserss.REFRESH")); } @Override protected void onPause() { unregisterReceiver(refreshReceiver); super.onPause(); } @Override protected Dialog onCreateDialog(int id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(R.string.dialog_licenseagreement); builder.setNegativeButton(R.string.button_decline, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); finish(); } }); builder.setPositiveButton(R.string.button_accept, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putBoolean(Strings.PREFERENCE_LICENSEACCEPTED, true); editor.commit(); /* Part of workaround for android issue 4499 on 1.5 devices */ getTabHost().clearAllTabs(); /* we only want to invoke actions if the license is accepted */ setContent(); } }); setupLicenseText(builder); builder.setOnKeyListener(new OnKeyListener() { public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.cancel(); finish(); } return true; } }); return builder.create(); } @Override public boolean onCreateOptionsMenu(Menu menu) { this.menu = menu; Activity activity = getCurrentActivity(); if (hasContent && activity != null) { return activity.onCreateOptionsMenu(menu); } else { menu.add(Strings.EMPTY); // to let the menu be available return true; } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { Activity activity = getCurrentActivity(); if (hasContent && activity != null) { return activity.onMenuItemSelected(featureId, item); } else { return super.onMenuItemSelected(featureId, item); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { Activity activity = getCurrentActivity(); if (hasContent && activity != null) { return activity.onPrepareOptionsMenu(menu); } else { return super.onPrepareOptionsMenu(menu); } } private void setContent() { TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec(TAG_NORMAL).setIndicator(getString(R.string.overview)).setContent(new Intent().setClass(this, RSSOverview.class))); hasContent = true; if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Strings.SETTINGS_SHOWTABS, false)) { setTabWidgetVisible(true); } final MainTabActivity mainTabActivity = this; if (POSTGINGERBREAD) { /* Change the menu also on ICS when tab is changed */ tabHost.setOnTabChangedListener(new OnTabChangeListener() { public void onTabChanged(String tabId) { if (menu != null) { menu.clear(); onCreateOptionsMenu(menu); } SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mainTabActivity).edit(); editor.putString(Strings.PREFERENCE_LASTTAB, tabId); editor.commit(); setCurrentTab(tabId); } }); if (menu != null) { menu.clear(); onCreateOptionsMenu(menu); } } else { tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { setCurrentTab(tabId); } }); } } private void setCurrentTab(String currentTab) { if (visitedTabs.contains(currentTab)) { // requery the tab but only if it has been shown already Activity activity = getCurrentActivity(); if (hasContent && activity != null) { ((Requeryable) activity).requery(); } } else { visitedTabs.add(currentTab); } } public void setTabWidgetVisible(boolean visible) { if (visible) { TabHost tabHost = getTabHost(); if (!tabsAdded) { tabHost.addTab(tabHost.newTabSpec(TAG_ALL).setIndicator(getString(R.string.all)).setContent(new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.CONTENT_URI).putExtra(EntriesListActivity.EXTRA_SHOWFEEDINFO, true))); tabHost.addTab(tabHost.newTabSpec(TAG_FAVORITE).setIndicator(getString(R.string.favorites), getResources().getDrawable(android.R.drawable.star_big_on)).setContent(new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.FAVORITES_CONTENT_URI).putExtra(EntriesListActivity.EXTRA_SHOWFEEDINFO, true).putExtra(EntriesListActivity.EXTRA_AUTORELOAD, true))); tabsAdded = true; } getTabWidget().setVisibility(View.VISIBLE); String lastTab = PreferenceManager.getDefaultSharedPreferences(this).getString(Strings.PREFERENCE_LASTTAB, TAG_NORMAL); boolean tabFound = false; for(int i = 0; i < tabHost.getTabWidget().getChildCount(); ++i) { tabHost.setCurrentTab(i); String currentTab = tabHost.getCurrentTabTag(); if (lastTab.equals(currentTab)) { tabFound = true; break; } } if (!tabFound) { tabHost.setCurrentTab(0); } } else { getTabWidget().setVisibility(View.GONE); } } void setupLicenseText(AlertDialog.Builder builder) { View view = getLayoutInflater().inflate(R.layout.license, null); final TextView textView = (TextView) view.findViewById(R.id.license_text); textView.setTextColor(textView.getTextColors().getDefaultColor()); // disables color change on selection textView.setText(new StringBuilder(getString(R.string.license_intro)).append(Strings.THREENEWLINES).append(getString(R.string.license))); final TextView contributorsTextView = (TextView) view.findViewById(R.id.contributors_togglebutton); contributorsTextView.setOnClickListener(new OnClickListener() { boolean showingLicense = true; @Override public void onClick(View view) { if (showingLicense) { textView.setText(R.string.contributors_list); contributorsTextView.setText(R.string.license_word); } else { textView.setText(new StringBuilder(getString(R.string.license_intro)).append(Strings.THREENEWLINES).append(getString(R.string.license))); contributorsTextView.setText(R.string.contributors); } showingLicense = !showingLicense; } }); builder.setView(view); } private boolean isCurrentlyRefreshing() { ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE); for (RunningServiceInfo service: manager.getRunningServices(Integer.MAX_VALUE)) { if (FetcherService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } public void internalSetProgressBarIndeterminateVisibility(boolean progressBarVisible) { setProgressBarIndeterminateVisibility(progressBarVisible); this.progressBarVisible = progressBarVisible; Activity activity = getCurrentActivity(); if (activity != null) { activity.onPrepareOptionsMenu(null); } } public boolean isProgressBarVisible() { return progressBarVisible; } }
025003b-gfgfgf
src/de/shandschuh/sparserss/MainTabActivity.java
Java
mit
11,279
/** * Sparse rss * * Copyright (c) 2010, 2011 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * (this is an excerpt from BASE64 class of jaolt, except for the license) */ package de.shandschuh.sparserss; public class BASE64 { private static char[] TOCHAR = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; public static String encode(byte[] bytes) { StringBuilder builder = new StringBuilder(); int i = bytes.length; int k = i/3; for (int n = 0; n < k; n++) { if (n > 0 && n % 19 == 0) { builder.append('\n'); } builder.append(convertToString(bytes[3*n], bytes[3*n+1], bytes[3*n+2])); } k = i % 3; if (k == 2) { char[] chars = convertToString(bytes[i-2], bytes[i-1], 0); chars[3] = '='; builder.append(chars); } else if (k == 1) { char[] chars = convertToString(bytes[i-1], 0, 0); chars[2] = '='; chars[3] = '='; builder.append(chars); } return builder.toString(); } private static char[] convertToString(int b, int c, int d) { char[] result = new char[4]; if (b < 0) { b += 256; } if (c < 0) { c += 256; } if (d < 0) { d += 256; } int f = d+(c+b*256)*256; result[3] = TOCHAR[f % 64]; f /= 64; result[2] = TOCHAR[f % 64]; f /= 64; result[1] = TOCHAR[f % 64]; f /= 64; result[0] = TOCHAR[f % 64]; return result; } }
025003b-gfgfgf
src/de/shandschuh/sparserss/BASE64.java
Java
mit
2,697
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import java.io.File; import java.io.FilenameFilter; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ListActivity; import android.app.NotificationManager; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import de.shandschuh.sparserss.provider.FeedData; import de.shandschuh.sparserss.provider.OPML; import de.shandschuh.sparserss.service.RefreshService; public class RSSOverview extends ListActivity implements Requeryable { private static final int DIALOG_ERROR_FEEDIMPORT = 3; private static final int DIALOG_ERROR_FEEDEXPORT = 4; private static final int DIALOG_ERROR_INVALIDIMPORTFILE = 5; private static final int DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE = 6; private static final int DIALOG_ABOUT = 7; private static final int CONTEXTMENU_EDIT_ID = 3; private static final int CONTEXTMENU_REFRESH_ID = 4; private static final int CONTEXTMENU_DELETE_ID = 5; private static final int CONTEXTMENU_MARKASREAD_ID = 6; private static final int CONTEXTMENU_MARKASUNREAD_ID = 7; private static final int CONTEXTMENU_DELETEREAD_ID = 8; private static final int CONTEXTMENU_DELETEALLENTRIES_ID = 9; private static final int CONTEXTMENU_RESETUPDATEDATE_ID = 10; private static final int ACTIVITY_APPLICATIONPREFERENCES_ID = 1; private static final Uri CANGELOG_URI = Uri.parse("http://code.google.com/p/sparserss/wiki/Changelog"); static NotificationManager notificationManager; // package scope boolean feedSort; private RSSOverviewListAdapter listAdapter; private Menu menu; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { if (MainTabActivity.isLightTheme(this)) { setTheme(R.style.Theme_Light); } super.onCreate(savedInstanceState); if (notificationManager == null) { notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } setContentView(R.layout.main); listAdapter = new RSSOverviewListAdapter(this); setListAdapter(listAdapter); getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText()); menu.add(0, CONTEXTMENU_REFRESH_ID, Menu.NONE, R.string.contextmenu_refresh); menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread); menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread); menu.add(0, CONTEXTMENU_DELETEREAD_ID, Menu.NONE, R.string.contextmenu_deleteread); menu.add(0, CONTEXTMENU_DELETEALLENTRIES_ID, Menu.NONE, R.string.contextmenu_deleteallentries); menu.add(0, CONTEXTMENU_EDIT_ID, Menu.NONE, R.string.contextmenu_edit); menu.add(0, CONTEXTMENU_RESETUPDATEDATE_ID, Menu.NONE, R.string.contextmenu_resetupdatedate); menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete); } }); getListView().setOnTouchListener(new OnTouchListener() { private int dragedItem = -1; private ImageView dragedView; private WindowManager windowManager = RSSOverview.this.getWindowManager(); private LayoutParams layoutParams; private int minY; private ListView listView = getListView(); public boolean onTouch(View v, MotionEvent event) { if (feedSort) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: { // this is the drag/move action if (dragedItem == -1) { dragedItem = listView.pointToPosition((int) event.getX(), (int) event.getY()); if (dragedItem > -1) { dragedView = new ImageView(listView.getContext()); View item = listView.getChildAt(dragedItem - listView.getFirstVisiblePosition()); if (item != null) { View sortView = item.findViewById(R.id.sortitem); if (sortView.getLeft() <= event.getX()) { minY = getMinY(); // this has to be determined after the layouting process item.setDrawingCacheEnabled(true); dragedView.setImageBitmap(Bitmap.createBitmap(item.getDrawingCache())); layoutParams = new LayoutParams(); layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.TOP; layoutParams.y = (int) event.getY(); windowManager.addView(dragedView, layoutParams); } else { dragedItem = -1; return false; // do not consume } } else { dragedItem = -1; } } } else if (dragedView != null) { layoutParams.y = Math.max(minY, Math.max(0, Math.min((int) event.getY(), listView.getHeight()-minY))); windowManager.updateViewLayout(dragedView, layoutParams); } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { // this is the drop action if (dragedItem > -1) { windowManager.removeView(dragedView); int newPosition = listView.pointToPosition((int) event.getX(), (int) event.getY()); if (newPosition == -1) { newPosition = listView.getCount()-1; } if (newPosition != dragedItem) { ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.PRIORITY, newPosition); getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(listView.getItemIdAtPosition(dragedItem)), values, null, null); } dragedItem = -1; return true; } else { return false; } } } return true; } else { return false; } } private int getMinY() { int[] xy = new int[2]; getListView().getLocationInWindow(xy); return xy[1] - 25; } }); if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Strings.SETTINGS_REFRESHENABLED, false)) { startService(new Intent(this, RefreshService.class)); // starts the service independent to this activity } else { stopService(new Intent(this, RefreshService.class)); } if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Strings.SETTINGS_REFRESHONPENENABLED, false)) { new Thread() { public void run() { sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS)); } }.start(); } } @Override protected void onResume() { super.onResume(); if (RSSOverview.notificationManager != null) { notificationManager.cancel(0); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.feedoverview, menu); this.menu = menu; return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (menu == null) { menu = this.menu; } if (menu != null) { // menu can still be null since the MainTabActivity.internalSetProgressBarIndeterminateVisibility method may be called first menu.setGroupVisible(R.id.menu_group_1, feedSort); if (feedSort) { menu.setGroupVisible(R.id.menu_group_0, false); } else { menu.setGroupVisible(R.id.menu_group_0, true); MenuItem refreshMenuItem = menu.findItem(R.id.menu_refresh); if (MainTabActivity.INSTANCE.isProgressBarVisible()) { refreshMenuItem.setIcon(android.R.drawable.ic_menu_close_clear_cancel); refreshMenuItem.setTitle(R.string.menu_cancelrefresh); } else { refreshMenuItem.setIcon(android.R.drawable.ic_menu_rotate); refreshMenuItem.setTitle(R.string.menu_refresh); } } } return true; } @Override public boolean onMenuItemSelected(int featureId, final MenuItem item) { setFeedSortEnabled(false); switch (item.getItemId()) { case R.id.menu_addfeed: { startActivity(new Intent(Intent.ACTION_INSERT).setData(FeedData.FeedColumns.CONTENT_URI)); break; } case R.id.menu_refresh: { if (MainTabActivity.INSTANCE.isProgressBarVisible()) { sendBroadcast(new Intent(Strings.ACTION_STOPREFRESHFEEDS)); } else { new Thread() { public void run() { sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(RSSOverview.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false))); } }.start(); } break; } case CONTEXTMENU_EDIT_ID: { startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedData.FeedColumns.CONTENT_URI(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id))); break; } case CONTEXTMENU_REFRESH_ID: { final String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) { // since we have acquired the networkInfo, we use it for basic checks final Intent intent = new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.FEEDID, id); final Thread thread = new Thread() { public void run() { sendBroadcast(intent); } }; if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || PreferenceManager.getDefaultSharedPreferences(RSSOverview.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)) { intent.putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, true); thread.start(); } else { Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(id), new String[] {FeedData.FeedColumns.WIFIONLY}, null, null, null); cursor.moveToFirst(); if (cursor.isNull(0) || cursor.getInt(0) == 0) { thread.start(); } else { Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(R.string.dialog_hint); builder.setMessage(R.string.question_refreshwowifi); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { intent.putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, true); thread.start(); } }); builder.setNeutralButton(R.string.button_alwaysokforall, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { PreferenceManager.getDefaultSharedPreferences(RSSOverview.this).edit().putBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, true).commit(); intent.putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, true); thread.start(); } }); builder.setNegativeButton(android.R.string.no, null); builder.show(); } cursor.close(); } } break; } case CONTEXTMENU_DELETE_ID: { String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id); Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(id), new String[] {FeedData.FeedColumns.NAME}, null, null, null); cursor.moveToFirst(); Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(cursor.getString(0)); builder.setMessage(R.string.question_deletefeed); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { new Thread() { public void run() { getContentResolver().delete(FeedData.FeedColumns.CONTENT_URI(Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id)), null, null); sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET)); } }.start(); } }); builder.setNegativeButton(android.R.string.no, null); cursor.close(); builder.show(); break; } case CONTEXTMENU_MARKASREAD_ID: { new Thread() { public void run() { String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id); if (getContentResolver().update(FeedData.EntryColumns.CONTENT_URI(id), getReadContentValues(), new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null) > 0) { getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI(id), null); } } }.start(); break; } case CONTEXTMENU_MARKASUNREAD_ID: { new Thread() { public void run() { String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id); if (getContentResolver().update(FeedData.EntryColumns.CONTENT_URI(id), getUnreadContentValues(), null, null) > 0) { getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI(id), null);; } } }.start(); break; } case CONTEXTMENU_DELETEREAD_ID: { new Thread() { public void run() { String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id); Uri uri = FeedData.EntryColumns.CONTENT_URI(id); String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")"; FeedData.deletePicturesOfFeed(RSSOverview.this, uri, selection); if (getContentResolver().delete(uri, selection, null) > 0) { getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI(id), null); } } }.start(); break; } case CONTEXTMENU_DELETEALLENTRIES_ID: { showDeleteAllEntriesQuestion(this, FeedData.EntryColumns.CONTENT_URI(Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id))); break; } case CONTEXTMENU_RESETUPDATEDATE_ID: { ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.LASTUPDATE, 0); values.put(FeedData.FeedColumns.REALLASTUPDATE, 0); getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id)), values, null, null); break; } case R.id.menu_settings: { startActivityForResult(new Intent(this, ApplicationPreferencesActivity.class), ACTIVITY_APPLICATIONPREFERENCES_ID); break; } case R.id.menu_allread: { new Thread() { public void run() { if (getContentResolver().update(FeedData.EntryColumns.CONTENT_URI, getReadContentValues(), new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null) > 0) { getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI, null); } } }.start(); break; } case R.id.menu_about: { showDialog(DIALOG_ABOUT); break; } case R.id.menu_import: { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ||Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.select_file); try { final String[] fileNames = Environment.getExternalStorageDirectory().list(new FilenameFilter() { public boolean accept(File dir, String filename) { return new File(dir, filename).isFile(); } }); builder.setItems(fileNames, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { OPML.importFromFile(new StringBuilder(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(fileNames[which]).toString(), RSSOverview.this); } catch (Exception e) { showDialog(DIALOG_ERROR_FEEDIMPORT); } } }); builder.show(); } catch (Exception e) { showDialog(DIALOG_ERROR_FEEDIMPORT); } } else { showDialog(DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE); } break; } case R.id.menu_export: { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ||Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { try { String filename = new StringBuilder(Environment.getExternalStorageDirectory().toString()).append("/sparse_rss_").append(System.currentTimeMillis()).append(".opml").toString(); OPML.exportToFile(filename, this); Toast.makeText(this, String.format(getString(R.string.message_exportedto), filename), Toast.LENGTH_LONG).show(); } catch (Exception e) { showDialog(DIALOG_ERROR_FEEDEXPORT); } } else { showDialog(DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE); } break; } case R.id.menu_enablefeedsort: { setFeedSortEnabled(true); break; } case R.id.menu_deleteread: { FeedData.deletePicturesOfFeedAsync(this, FeedData.EntryColumns.CONTENT_URI, Strings.READDATE_GREATERZERO); getContentResolver().delete(FeedData.EntryColumns.CONTENT_URI, Strings.READDATE_GREATERZERO, null); ((RSSOverviewListAdapter) getListAdapter()).notifyDataSetChanged(); break; } case R.id.menu_deleteallentries: { showDeleteAllEntriesQuestion(this, FeedData.EntryColumns.CONTENT_URI); break; } case R.id.menu_disablefeedsort: { // do nothing as the feed sort gets disabled anyway break; } } return true; } public static final ContentValues getReadContentValues() { ContentValues values = new ContentValues(); values.put(FeedData.EntryColumns.READDATE, System.currentTimeMillis()); return values; } public static final ContentValues getUnreadContentValues() { ContentValues values = new ContentValues(); values.putNull(FeedData.EntryColumns.READDATE); return values; } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { setFeedSortEnabled(false); Intent intent = new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.CONTENT_URI(Long.toString(id))); intent.putExtra(FeedData.FeedColumns._ID, id); startActivity(intent); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch (id) { case DIALOG_ERROR_FEEDIMPORT: { dialog = createErrorDialog(R.string.error_feedimport); break; } case DIALOG_ERROR_FEEDEXPORT: { dialog = createErrorDialog(R.string.error_feedexport); break; } case DIALOG_ERROR_INVALIDIMPORTFILE: { dialog = createErrorDialog(R.string.error_invalidimportfile); break; } case DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE: { dialog = createErrorDialog(R.string.error_externalstoragenotavailable); break; } case DIALOG_ABOUT: { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(R.string.menu_about); MainTabActivity.INSTANCE.setupLicenseText(builder); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setNeutralButton(R.string.changelog, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(Intent.ACTION_VIEW, CANGELOG_URI)); } }); return builder.create(); } default: dialog = null; } return dialog; } private Dialog createErrorDialog(int messageId) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(messageId); builder.setTitle(R.string.error); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(android.R.string.ok, null); return builder.create(); } private static void showDeleteAllEntriesQuestion(final Context context, final Uri uri) { Builder builder = new AlertDialog.Builder(context); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(R.string.contextmenu_deleteallentries); builder.setMessage(R.string.question_areyousure); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { new Thread() { public void run() { FeedData.deletePicturesOfFeed(context, uri, Strings.DB_EXCUDEFAVORITE); if (context.getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null) > 0) { context.getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI, null); } } }.start(); } }); builder.setNegativeButton(android.R.string.no, null); builder.show(); } private void setFeedSortEnabled(boolean enabled) { if (enabled != feedSort) { listAdapter.setFeedSortEnabled(enabled); feedSort = enabled; } } @Override public void requery() { if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/RSSOverview.java
Java
mit
23,337
/** * Sparse rss * * Copyright (c) 2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; public class Animations { /** Slide in from right */ public static final TranslateAnimation SLIDE_IN_RIGHT = generateAnimation(1, 0); /** Slide in from left */ public static final TranslateAnimation SLIDE_IN_LEFT = generateAnimation(-1, 0); /** Slide out to right */ public static final TranslateAnimation SLIDE_OUT_RIGHT = generateAnimation(0, 1); /** Slide out to left */ public static final TranslateAnimation SLIDE_OUT_LEFT = generateAnimation(0, -1); /** Duration of one animation */ private static final long DURATION = 180; private static TranslateAnimation generateAnimation(float fromX, float toX) { TranslateAnimation transformAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, fromX, Animation.RELATIVE_TO_SELF, toX, 0, 0, 0, 0); transformAnimation.setDuration(DURATION); return transformAnimation; } }
025003b-gfgfgf
src/de/shandschuh/sparserss/Animations.java
Java
mit
2,126
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import java.text.DateFormat; import java.util.Date; import java.util.Vector; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.preference.PreferenceManager; import android.util.TypedValue; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import de.shandschuh.sparserss.provider.FeedData; public class EntriesListAdapter extends ResourceCursorAdapter { private static final int STATE_NEUTRAL = 0; private static final int STATE_ALLREAD = 1; private static final int STATE_ALLUNREAD = 2; private int titleColumnPosition; private int dateColumn; private int readDateColumn; private int favoriteColumn; private int idColumn; private int feedIconColumn; private int feedNameColumn; private int linkColumn; private static final String SQLREAD = "length(readdate) ASC, "; public static final String READDATEISNULL = FeedData.EntryColumns.READDATE+Strings.DB_ISNULL; private boolean hideRead; private Activity context; private Uri uri; private boolean showFeedInfo; private int forcedState; private Vector<Long> markedAsRead; private Vector<Long> markedAsUnread; private Vector<Long> favorited; private Vector<Long> unfavorited; private DateFormat dateFormat; private DateFormat timeFormat; public EntriesListAdapter(Activity context, Uri uri, boolean showFeedInfo, boolean autoreload, boolean hideRead) { super(context, R.layout.entrylistitem, createManagedCursor(context, uri, hideRead), autoreload); this.hideRead = hideRead; this.context = context; this.uri = uri; Cursor cursor = getCursor(); titleColumnPosition = cursor.getColumnIndex(FeedData.EntryColumns.TITLE); dateColumn = cursor.getColumnIndex(FeedData.EntryColumns.DATE); readDateColumn = cursor.getColumnIndex(FeedData.EntryColumns.READDATE); favoriteColumn = cursor.getColumnIndex(FeedData.EntryColumns.FAVORITE); idColumn = cursor.getColumnIndex(FeedData.EntryColumns._ID); linkColumn = cursor.getColumnIndex(FeedData.EntryColumns.LINK); this.showFeedInfo = showFeedInfo; if (showFeedInfo) { feedIconColumn = cursor.getColumnIndex(FeedData.FeedColumns.ICON); feedNameColumn = cursor.getColumnIndex(FeedData.FeedColumns.NAME); } forcedState = STATE_NEUTRAL; markedAsRead = new Vector<Long>(); markedAsUnread = new Vector<Long>(); favorited = new Vector<Long>(); unfavorited = new Vector<Long>(); dateFormat = android.text.format.DateFormat.getDateFormat(context); timeFormat = android.text.format.DateFormat.getTimeFormat(context); } @Override public void bindView(View view, final Context context, Cursor cursor) { TextView textView = (TextView) view.findViewById(android.R.id.text1); String link = cursor.getString(linkColumn); String title = cursor.getString(titleColumnPosition); textView.setText(title == null || title.length() == 0 ? link : title); TextView dateTextView = (TextView) view.findViewById(android.R.id.text2); final ImageView imageView = (ImageView) view.findViewById(android.R.id.icon); final long id = cursor.getLong(idColumn); view.setTag(link); final boolean favorite = !unfavorited.contains(id) && (cursor.getInt(favoriteColumn) == 1 || favorited.contains(id)); imageView.setImageResource(favorite ? android.R.drawable.star_on : android.R.drawable.star_off); imageView.setTag(favorite ? Strings.TRUE : Strings.FALSE); imageView.setOnClickListener(new OnClickListener() { public void onClick(View view) { boolean newFavorite = !Strings.TRUE.equals(view.getTag()); if (newFavorite) { view.setTag(Strings.TRUE); imageView.setImageResource(android.R.drawable.star_on); favorited.add(id); unfavorited.remove(id); } else { view.setTag(Strings.FALSE); imageView.setImageResource(android.R.drawable.star_off); unfavorited.add(id); favorited.remove(id); } ContentValues values = new ContentValues(); values.put(FeedData.EntryColumns.FAVORITE, newFavorite ? 1 : 0); view.getContext().getContentResolver().update(uri, values, new StringBuilder(FeedData.EntryColumns._ID).append(Strings.DB_ARG).toString(), new String[] {Long.toString(id)}); context.getContentResolver().notifyChange(FeedData.EntryColumns.FAVORITES_CONTENT_URI, null); } }); Date date = new Date(cursor.getLong(dateColumn)); if (showFeedInfo && feedIconColumn > -1 && feedNameColumn > -1) { byte[] iconBytes = cursor.getBlob(feedIconColumn); if (iconBytes != null && iconBytes.length > 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null) { int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18f, context.getResources().getDisplayMetrics()); if (bitmap.getHeight() != bitmapSizeInDip) { bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false); } dateTextView.setText(new StringBuilder().append(' ').append(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(cursor.getString(feedNameColumn))); // bad style } else { dateTextView.setText(new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(cursor.getString(feedNameColumn))); } dateTextView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(bitmap), null, null, null); } else { dateTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); dateTextView.setText(new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(cursor.getString(feedNameColumn))); } } else { dateTextView.setText(new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date))); } if (forcedState == STATE_ALLUNREAD && !markedAsRead.contains(id) || (forcedState != STATE_ALLREAD && cursor.isNull(readDateColumn) && !markedAsRead.contains(id)) || markedAsUnread.contains(id)) { textView.setEnabled(true); } else { textView.setEnabled(false); } } public boolean isHideRead() { return hideRead; } public void setHideRead(boolean hideRead) { if (hideRead != this.hideRead) { this.hideRead = hideRead; reloadCursor(); } } public void reloadCursor() { markedAsRead.clear(); markedAsUnread.clear(); favorited.clear(); unfavorited.clear(); context.stopManagingCursor(getCursor()); forcedState = STATE_NEUTRAL; changeCursor(createManagedCursor(context, uri, hideRead)); notifyDataSetInvalidated(); } private static Cursor createManagedCursor(Activity context, Uri uri, boolean hideRead) { return context.managedQuery(uri, null, hideRead ? READDATEISNULL : null, null, new StringBuilder(PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Strings.SETTINGS_PRIORITIZE, false) ? SQLREAD : Strings.EMPTY).append(FeedData.EntryColumns.DATE).append(Strings.DB_DESC).toString()); } public void markAsRead() { if (hideRead) { reloadCursor(); // well, the cursor should be empty } else { forcedState = STATE_ALLREAD; markedAsRead.clear(); markedAsUnread.clear(); notifyDataSetInvalidated(); } } public void markAsUnread() { forcedState = STATE_ALLUNREAD; markedAsRead.clear(); markedAsUnread.clear(); notifyDataSetInvalidated(); } public void neutralizeReadState() { forcedState = STATE_NEUTRAL; } public void markAsRead(long id) { if (hideRead) { reloadCursor(); } else { markedAsRead.add(id); markedAsUnread.remove(id); notifyDataSetInvalidated(); } } public void markAsUnread(long id) { markedAsUnread.add(id); markedAsRead.remove(id); notifyDataSetInvalidated(); } }
025003b-gfgfgf
src/de/shandschuh/sparserss/EntriesListAdapter.java
Java
mit
9,341
/** * Sparse rss * * Copyright (c) 2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; public abstract class SimpleTask implements Runnable { private boolean canceled = false; private int postCount = 0; public abstract void runControlled(); public void cancel() { canceled = true; } public boolean isCanceled() { return canceled; } public void post() { post(1); } public synchronized void post(int count) { postCount += count; canceled = false; } public boolean isPosted() { return postCount > 0; } public int getPostCount() { return postCount; } public final synchronized void run() { if (!canceled) { runControlled(); } postRun(); postCount--; } /** * Override to use */ public void postRun() { } public void enable() { canceled = false; } }
025003b-gfgfgf
src/de/shandschuh/sparserss/SimpleTask.java
Java
mit
1,912
/** * Sparse rss * * Copyright (c) 2010-2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.widget; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.view.View; import android.view.View.OnClickListener; import de.shandschuh.sparserss.R; import de.shandschuh.sparserss.provider.FeedData; public class WidgetConfigActivity extends PreferenceActivity { private int widgetId; private static final String NAMECOLUMN = new StringBuilder("ifnull(").append(FeedData.FeedColumns.NAME).append(',').append(FeedData.FeedColumns.URL).append(") as title").toString(); public static final String ZERO = "0"; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setResult(RESULT_CANCELED); Bundle extras = getIntent().getExtras(); if (extras != null) { widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); } addPreferencesFromResource(R.layout.widgetpreferences); setContentView(R.layout.widgetconfig); final ListPreference entryCountPreference = (ListPreference) findPreference("widget.entrycount"); final PreferenceCategory feedsPreferenceCategory = (PreferenceCategory) findPreference("widget.visiblefeeds"); Cursor cursor = this.getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, new String[] {FeedData.FeedColumns._ID, NAMECOLUMN}, null, null, null); if (cursor.moveToFirst()) { int[] ids = new int[cursor.getCount()+1]; CheckBoxPreference checkboxPreference = new CheckBoxPreference(this); checkboxPreference.setTitle(R.string.all_feeds); feedsPreferenceCategory.addPreference(checkboxPreference); checkboxPreference.setKey(ZERO); checkboxPreference.setDisableDependentsState(true); ids[0] = 0; for (int n = 1; !cursor.isAfterLast(); cursor.moveToNext(), n++) { checkboxPreference = new CheckBoxPreference(this); checkboxPreference.setTitle(cursor.getString(1)); ids[n] = cursor.getInt(0); checkboxPreference.setKey(Integer.toString(ids[n])); feedsPreferenceCategory.addPreference(checkboxPreference); checkboxPreference.setDependency(ZERO); } cursor.close(); findViewById(R.id.save_button).setOnClickListener(new OnClickListener() { public void onClick(View view) { SharedPreferences.Editor preferences = getSharedPreferences(SparseRSSAppWidgetProvider.class.getName(), 0).edit(); boolean hideRead = false;//((CheckBoxPreference) getPreferenceManager().findPreference("widget.hideread")).isChecked(); preferences.putBoolean(widgetId+".hideread", hideRead); StringBuilder builder = new StringBuilder(); for (int n = 0, i = feedsPreferenceCategory.getPreferenceCount(); n < i; n++) { CheckBoxPreference preference = (CheckBoxPreference) feedsPreferenceCategory.getPreference(n); if (preference.isChecked()) { if (n == 0) { break; } else { if (builder.length() > 0) { builder.append(','); } builder.append(preference.getKey()); } } } String feedIds = builder.toString(); String entryCount = entryCountPreference.getValue(); preferences.putString(widgetId+".feeds", feedIds); preferences.putString(widgetId+".entrycount", entryCount); int color = getPreferenceManager().getSharedPreferences().getInt("widget.background", SparseRSSAppWidgetProvider.STANDARD_BACKGROUND); preferences.putInt(widgetId+".background", color); preferences.commit(); SparseRSSAppWidgetProvider.updateAppWidget(WidgetConfigActivity.this, widgetId, hideRead, entryCount, feedIds, color); setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)); finish(); } }); } else { // no feeds found --> use all feeds, no dialog needed cursor.close(); setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)); } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/widget/WidgetConfigActivity.java
Java
mit
5,480
/** * Sparse rss * * Copyright (c) 2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.widget; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import de.shandschuh.sparserss.R; public class ColorPickerDialogPreference extends DialogPreference { private SeekBar redSeekBar; private SeekBar greenSeekBar; private SeekBar blueSeekBar; private SeekBar transparencySeekBar; int color; public ColorPickerDialogPreference(Context context, AttributeSet attrs) { super(context, attrs); color = SparseRSSAppWidgetProvider.STANDARD_BACKGROUND; } @Override protected View onCreateDialogView() { final View view = super.onCreateDialogView(); view.setBackgroundColor(color); redSeekBar = (SeekBar) view.findViewById(R.id.seekbar_red); greenSeekBar = (SeekBar) view.findViewById(R.id.seekbar_green); blueSeekBar = (SeekBar) view.findViewById(R.id.seekbar_blue); transparencySeekBar = (SeekBar) view.findViewById(R.id.seekbar_transparency); int _color = color; transparencySeekBar.setProgress(((_color / 0x01000000)*100)/255); _color %= 0x01000000; redSeekBar.setProgress(((_color / 0x00010000)*100)/255); _color %= 0x00010000; greenSeekBar.setProgress(((_color / 0x00000100)*100)/255); _color %= 0x00000100; blueSeekBar.setProgress((_color*100)/255); OnSeekBarChangeListener onSeekBarChangeListener = new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int red = (redSeekBar.getProgress()*255) / 100; int green = (greenSeekBar.getProgress()*255) / 100; int blue = (blueSeekBar.getProgress()*255) / 100; int transparency = (transparencySeekBar.getProgress()*255) / 100; color = transparency*0x01000000 + red*0x00010000 + green*0x00000100 + blue; view.setBackgroundColor(color); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } }; redSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); greenSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); blueSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); transparencySeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); return view; } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { persistInt(color); } super.onDialogClosed(positiveResult); } }
025003b-gfgfgf
src/de/shandschuh/sparserss/widget/ColorPickerDialogPreference.java
Java
mit
3,708
/** * Sparse rss * * Copyright (c) 2010-2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.widget.RemoteViews; import de.shandschuh.sparserss.MainTabActivity; import de.shandschuh.sparserss.R; import de.shandschuh.sparserss.Strings; import de.shandschuh.sparserss.provider.FeedData; public class SparseRSSAppWidgetProvider extends AppWidgetProvider { private static final String LIMIT = " limit "; private static final int[] IDS = {R.id.news_1, R.id.news_2, R.id.news_3, R.id.news_4, R.id.news_5, R.id.news_6, R.id.news_7, R.id.news_8, R.id.news_9, R.id.news_10}; private static final int[] ICON_IDS = {R.id.news_icon_1, R.id.news_icon_2, R.id.news_icon_3, R.id.news_icon_4, R.id.news_icon_5, R.id.news_icon_6, R.id.news_icon_7, R.id.news_icon_8, R.id.news_icon_9, R.id.news_icon_10}; public static final int STANDARD_BACKGROUND = 0x7c000000; @Override public void onReceive(Context context, Intent intent) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); onUpdate(context, appWidgetManager, appWidgetManager.getAppWidgetIds(new ComponentName(context, SparseRSSAppWidgetProvider.class))); } public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { SharedPreferences preferences = context.getSharedPreferences(SparseRSSAppWidgetProvider.class.getName(), 0); for (int n = 0, i = appWidgetIds.length; n < i; n++) { updateAppWidget(context, appWidgetManager, appWidgetIds[n], preferences.getBoolean(appWidgetIds[n]+".hideread", false), preferences.getString(appWidgetIds[n]+".entrycount", "10"), preferences.getString(appWidgetIds[n]+".feeds", Strings.EMPTY), preferences.getInt(appWidgetIds[n]+".background", STANDARD_BACKGROUND)); } } static void updateAppWidget(Context context, int appWidgetId, boolean hideRead, String entryCount, String feedIds, int backgroundColor) { updateAppWidget(context, AppWidgetManager.getInstance(context), appWidgetId, hideRead, entryCount, feedIds, backgroundColor); } private static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, boolean hideRead, String entryCount, String feedIds, int backgroundColor) { StringBuilder selection = new StringBuilder(); if (hideRead) { selection.append(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL); } if (feedIds.length() > 0) { if (selection.length() > 0) { selection.append(Strings.DB_AND); } selection.append(FeedData.EntryColumns.FEED_ID).append(" IN ("+feedIds).append(')'); } Cursor cursor = context.getContentResolver().query(FeedData.EntryColumns.CONTENT_URI, new String[] {FeedData.EntryColumns.TITLE, FeedData.EntryColumns._ID, FeedData.FeedColumns.ICON}, selection.toString(), null, new StringBuilder(FeedData.EntryColumns.DATE).append(Strings.DB_DESC).append(LIMIT).append(entryCount).toString()); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.homescreenwidget); views.setOnClickPendingIntent(R.id.feed_icon, PendingIntent.getActivity(context, 0, new Intent(context, MainTabActivity.class), 0)); int k = 0; while (cursor.moveToNext() && k < IDS.length) { views.setViewVisibility(IDS[k], View.VISIBLE); if (!cursor.isNull(2)) { try { byte[] iconBytes = cursor.getBlob(2); if (iconBytes != null && iconBytes.length > 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null) { views.setBitmap(ICON_IDS[k], "setImageBitmap", bitmap); views.setViewVisibility(ICON_IDS[k], View.VISIBLE); views.setTextViewText(IDS[k], " "+cursor.getString(0)); // bad style } else { views.setViewVisibility(ICON_IDS[k], View.GONE); views.setTextViewText(IDS[k], cursor.getString(0)); } } else { views.setViewVisibility(ICON_IDS[k], View.GONE); views.setTextViewText(IDS[k], cursor.getString(0)); } } catch (Throwable e) { views.setViewVisibility(ICON_IDS[k], View.GONE); views.setTextViewText(IDS[k], cursor.getString(0)); } } else { views.setViewVisibility(ICON_IDS[k], View.GONE); views.setTextViewText(IDS[k], cursor.getString(0)); } views.setOnClickPendingIntent(IDS[k++], PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.ENTRY_CONTENT_URI(cursor.getString(1))), PendingIntent.FLAG_CANCEL_CURRENT)); } cursor.close(); for (; k < IDS.length; k++) { views.setViewVisibility(ICON_IDS[k], View.GONE); views.setViewVisibility(IDS[k], View.GONE); views.setTextViewText(IDS[k], Strings.EMPTY); } views.setInt(R.id.widgetlayout, "setBackgroundColor", backgroundColor); appWidgetManager.updateAppWidget(appWidgetId, views); } }
025003b-gfgfgf
src/de/shandschuh/sparserss/widget/SparseRSSAppWidgetProvider.java
Java
mit
6,295
/** * Sparse rss * * Copyright (c) 2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * ============================================================================== * This helper class is needed for older Android versions that verify all * existing references on startup. */ package de.shandschuh.sparserss; import android.app.Activity; import android.graphics.drawable.Drawable; import android.webkit.WebView; public class CompatibilityHelper { private static final String METHOD_GETACTIONBAR = "getActionBar"; private static final String METHOD_SETICON = "setIcon"; private static final String METHOD_ONRESUME = "onResume"; private static final String METHOD_ONPAUSE = "onPause"; public static void setActionBarDrawable(Activity activity, Drawable drawable) { try { Object actionBar = Activity.class.getMethod(METHOD_GETACTIONBAR).invoke(activity); actionBar.getClass().getMethod(METHOD_SETICON, Drawable.class).invoke(actionBar, drawable); } catch (Exception e) { } } public static void onResume(WebView webView) { try { WebView.class.getMethod(METHOD_ONRESUME).invoke(webView); } catch (Exception e) { } } public static void onPause(WebView webView) { try { WebView.class.getMethod(METHOD_ONPAUSE).invoke(webView); } catch (Exception e) { } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/CompatibilityHelper.java
Java
mit
2,382
/** * Sparse rss * * Copyright (c) 2010-2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import de.shandschuh.sparserss.service.RefreshService; public class ApplicationPreferencesActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { if (MainTabActivity.isLightTheme(this)) { setTheme(R.style.Theme_Light); } super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.preferences); Preference preference = (Preference) findPreference(Strings.SETTINGS_REFRESHENABLED); preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (Boolean.TRUE.equals(newValue)) { new Thread() { public void run() { startService(new Intent(ApplicationPreferencesActivity.this, RefreshService.class)); } }.start(); } else { getPreferences(MODE_PRIVATE).edit().putLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, 0).commit(); stopService(new Intent(ApplicationPreferencesActivity.this, RefreshService.class)); } return true; } }); preference = (Preference) findPreference(Strings.SETTINGS_SHOWTABS); preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (MainTabActivity.INSTANCE != null ) { MainTabActivity.INSTANCE.setTabWidgetVisible(Boolean.TRUE.equals(newValue)); } return true; } }); preference = (Preference) findPreference(Strings.SETTINGS_LIGHTTHEME); preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { Editor editor = PreferenceManager.getDefaultSharedPreferences(ApplicationPreferencesActivity.this).edit(); editor.putBoolean(Strings.SETTINGS_LIGHTTHEME, Boolean.TRUE.equals(newValue)); editor.commit(); android.os.Process.killProcess(android.os.Process.myPid()); // this return statement will never be reached return true; } }); preference = (Preference) findPreference(Strings.SETTINGS_EFFICIENTFEEDPARSING); preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(final Preference preference, Object newValue) { if (newValue.equals(Boolean.FALSE)) { AlertDialog.Builder builder = new AlertDialog.Builder(ApplicationPreferencesActivity.this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(android.R.string.dialog_alert_title); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Editor editor = PreferenceManager.getDefaultSharedPreferences(ApplicationPreferencesActivity.this).edit(); editor.putBoolean(Strings.SETTINGS_EFFICIENTFEEDPARSING, Boolean.FALSE); editor.commit(); ((CheckBoxPreference) preference).setChecked(false); dialog.dismiss(); } }); builder.setNegativeButton(android.R.string.cancel, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setMessage(R.string.warning_moretraffic); builder.show(); return false; } else { return true; } } }); } }
025003b-gfgfgf
src/de/shandschuh/sparserss/ApplicationPreferencesActivity.java
Java
mit
5,020
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import de.shandschuh.sparserss.provider.FeedData; public final class Strings { public static final String PACKAGE = "de.shandschuh.sparserss"; public static final String SETTINGS_REFRESHINTERVAL = "refresh.interval"; public static final String SETTINGS_NOTIFICATIONSENABLED = "notifications.enabled"; public static final String SETTINGS_REFRESHENABLED = "refresh.enabled"; public static final String SETTINGS_REFRESHONPENENABLED = "refreshonopen.enabled"; public static final String SETTINGS_NOTIFICATIONSRINGTONE = "notifications.ringtone"; public static final String SETTINGS_NOTIFICATIONSVIBRATE = "notifications.vibrate"; public static final String SETTINGS_PRIORITIZE = "contentpresentation.prioritize"; public static final String SETTINGS_SHOWTABS = "tabs.show"; public static final String SETTINGS_FETCHPICTURES = "pictures.fetch"; public static final String SETTINGS_PROXYENABLED = "proxy.enabled"; public static final String SETTINGS_PROXYPORT = "proxy.port"; public static final String SETTINGS_PROXYHOST = "proxy.host"; public static final String SETTINGS_PROXYWIFIONLY = "proxy.wifionly"; public static final String SETTINGS_PROXYTYPE = "proxy.type"; public static final String SETTINGS_KEEPTIME = "keeptime"; public static final String SETTINGS_BLACKTEXTONWHITE = "blacktextonwhite"; public static final String SETTINGS_LIGHTTHEME = "lighttheme"; public static final String SETTINGS_FONTSIZE = "fontsize"; public static final String SETTINGS_STANDARDUSERAGENT = "standarduseragent"; public static final String SETTINGS_DISABLEPICTURES = "pictures.disable"; public static final String SETTINGS_HTTPHTTPSREDIRECTS = "httphttpsredirects"; public static final String SETTINGS_OVERRIDEWIFIONLY = "overridewifionly"; public static final String SETTINGS_GESTURESENABLED = "gestures.enabled"; public static final String SETTINGS_ENCLOSUREWARNINGSENABLED = "enclosurewarnings.enabled"; public static final String SETTINGS_EFFICIENTFEEDPARSING = "efficientfeedparsing"; public static final String ACTION_REFRESHFEEDS = "de.shandschuh.sparserss.REFRESH"; public static final String ACTION_STOPREFRESHFEEDS = "de.shandschuh.sparserss.STOPREFRESH"; public static final String ACTION_UPDATEWIDGET = "de.shandschuh.sparserss.FEEDUPDATED"; public static final String ACTION_RESTART = "de.shandschuh.sparserss.RESTART"; public static final String FEEDID = "feedid"; public static final String DB_ISNULL = " IS NULL"; public static final String DB_DESC = " DESC"; public static final String DB_ARG = "=?"; public static final String DB_AND = " AND "; public static final String DB_EXCUDEFAVORITE = new StringBuilder(FeedData.EntryColumns.FAVORITE).append(Strings.DB_ISNULL).append(" OR ").append(FeedData.EntryColumns.FAVORITE).append("=0").toString(); public static final String EMPTY = ""; public static final String HTTP = "http://"; public static final String HTTPS = "https://"; public static final String _HTTP = "http"; public static final String _HTTPS = "https"; public static final String PROTOCOL_SEPARATOR = "://"; public static final String FILE_FAVICON = "/favicon.ico"; public static final String SPACE = " "; public static final String TWOSPACE = " "; public static final String HTML_TAG_REGEX = "<(.|\n)*?>"; public static final String FILEURL = "file://"; public static final String IMAGEFILE_IDSEPARATOR = "__"; public static final String IMAGEID_REPLACEMENT = "##ID##"; public static final String DEFAULTPROXYPORT = "8080"; public static final String URL_SPACE = "%20"; public static final String HTML_SPAN_REGEX = "<[/]?[ ]?span(.|\n)*?>"; public static final String HTML_IMG_REGEX = "<[/]?[ ]?img(.|\n)*?>"; public static final String ONE = "1"; public static final Object THREENEWLINES = "\n\n\n"; public static final String PREFERENCE_LICENSEACCEPTED = "license.accepted"; public static final String PREFERENCE_LASTSCHEDULEDREFRESH = "lastscheduledrefresh"; public static final String PREFERENCE_LASTTAB = "lasttab"; public static final String HTML_LT = "&lt;"; public static final String HTML_GT = "&gt;"; public static final String LT = "<"; public static final String GT = ">"; protected static final String TRUE = "true"; protected static final String FALSE = "false"; public static final String READDATE_GREATERZERO = FeedData.EntryColumns.READDATE+">0"; public static final String COUNT = "count"; public static final String ENCLOSURE_SEPARATOR = "[@]"; // exactly three characters! public static final String QUESTIONMARKS = "'??'"; public static final String HTML_QUOT = "&quot;"; public static final String QUOT = "\""; public static final String HTML_APOS = "&apos;"; public static final String APOSTROPHE = "'"; public static final String AMP = "&"; public static final String AMP_SG = "&amp;"; public static final String SLASH = "/"; public static final String COMMASPACE = ", "; public static final String SCHEDULED = "scheduled"; }
025003b-gfgfgf
src/de/shandschuh/sparserss/Strings.java
Java
mit
6,270
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.provider; import java.io.File; import de.shandschuh.sparserss.handler.PictureFilenameFilter; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public class FeedData { public static final String CONTENT = "content://"; public static final String AUTHORITY = "de.shandschuh.sparserss.provider.FeedData"; private static final String TYPE_PRIMARY_KEY = "INTEGER PRIMARY KEY AUTOINCREMENT"; protected static final String TYPE_TEXT = "TEXT"; protected static final String TYPE_DATETIME = "DATETIME"; protected static final String TYPE_INT = "INT"; protected static final String TYPE_BOOLEAN = "INTEGER(1)"; public static final String FEED_DEFAULTSORTORDER = FeedColumns.PRIORITY; public static class FeedColumns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds").toString()); public static final String URL = "url"; public static final String NAME = "name"; public static final String LASTUPDATE = "lastupdate"; public static final String ICON = "icon"; public static final String ERROR = "error"; public static final String PRIORITY = "priority"; public static final String FETCHMODE = "fetchmode"; public static final String REALLASTUPDATE = "reallastupdate"; public static final String WIFIONLY = "wifionly"; public static final String IMPOSE_USERAGENT = "impose_useragent"; public static final String HIDE_READ = "hide_read"; public static final String[] COLUMNS = new String[] {_ID, URL, NAME, LASTUPDATE, ICON, ERROR, PRIORITY, FETCHMODE, REALLASTUPDATE, WIFIONLY, IMPOSE_USERAGENT, HIDE_READ}; public static final String[] TYPES = new String[] {TYPE_PRIMARY_KEY, "TEXT UNIQUE", TYPE_TEXT, TYPE_DATETIME, "BLOB", TYPE_TEXT, TYPE_INT, TYPE_INT, TYPE_DATETIME, TYPE_BOOLEAN, TYPE_BOOLEAN, TYPE_BOOLEAN}; public static final Uri CONTENT_URI(String feedId) { return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds/").append(feedId).toString()); } public static final Uri CONTENT_URI(long feedId) { return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds/").append(feedId).toString()); } } public static class EntryColumns implements BaseColumns { public static final String FEED_ID = "feedid"; public static final String TITLE = "title"; public static final String ABSTRACT = "abstract"; public static final String DATE = "date"; public static final String READDATE = "readdate"; public static final String LINK = "link"; public static final String FAVORITE = "favorite"; public static final String ENCLOSURE = "enclosure"; public static final String GUID = "guid"; public static final String AUTHOR = "author"; public static final String[] COLUMNS = new String[] {_ID, FEED_ID, TITLE, ABSTRACT, DATE, READDATE, LINK, FAVORITE, ENCLOSURE, GUID, AUTHOR}; public static final String[] TYPES = new String[] {TYPE_PRIMARY_KEY, "INTEGER(7)", TYPE_TEXT, TYPE_TEXT, TYPE_DATETIME, TYPE_DATETIME, TYPE_TEXT, TYPE_BOOLEAN, TYPE_TEXT, TYPE_TEXT, TYPE_TEXT}; public static Uri CONTENT_URI = Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/entries").toString()); public static Uri FAVORITES_CONTENT_URI = Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/favorites").toString()); public static Uri CONTENT_URI(String feedId) { return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds/").append(feedId).append("/entries").toString()); } public static Uri ENTRY_CONTENT_URI(String entryId) { return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/entries/").append(entryId).toString()); } public static Uri PARENT_URI(String path) { return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append(path.substring(0, path.lastIndexOf('/'))).toString()); } } private static String[] IDPROJECTION = new String[] {FeedData.EntryColumns._ID}; public static void deletePicturesOfFeedAsync(final Context context, final Uri entriesUri, final String selection) { if (FeedDataContentProvider.IMAGEFOLDER_FILE.exists()) { new Thread() { public void run() { deletePicturesOfFeed(context, entriesUri, selection); } }.start(); } } public static synchronized void deletePicturesOfFeed(Context context, Uri entriesUri, String selection) { if (FeedDataContentProvider.IMAGEFOLDER_FILE.exists()) { PictureFilenameFilter filenameFilter = new PictureFilenameFilter(); Cursor cursor = context.getContentResolver().query(entriesUri, IDPROJECTION, selection, null, null); while (cursor.moveToNext()) { filenameFilter.setEntryId(cursor.getString(0)); File[] files = FeedDataContentProvider.IMAGEFOLDER_FILE.listFiles(filenameFilter); for (int n = 0, i = files != null ? files.length : 0; n < i; n++) { files[n].delete(); } } cursor.close(); } } public static synchronized void deletePicturesOfEntry(String entryId) { if (FeedDataContentProvider.IMAGEFOLDER_FILE.exists()) { PictureFilenameFilter filenameFilter = new PictureFilenameFilter(entryId); File[] files = FeedDataContentProvider.IMAGEFOLDER_FILE.listFiles(filenameFilter); for (int n = 0, i = files != null ? files.length : 0; n < i; n++) { files[n].delete(); } } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/provider/FeedData.java
Java
mit
6,679
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.provider; import java.io.File; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; import android.text.TextUtils; import de.shandschuh.sparserss.Strings; public class FeedDataContentProvider extends ContentProvider { private static final String FOLDER = Environment.getExternalStorageDirectory()+"/sparserss/"; private static final String DATABASE_NAME = "sparserss.db"; private static final int DATABASE_VERSION = 13; private static final int URI_FEEDS = 1; private static final int URI_FEED = 2; private static final int URI_ENTRIES = 3; private static final int URI_ENTRY= 4; private static final int URI_ALLENTRIES = 5; private static final int URI_ALLENTRIES_ENTRY = 6; private static final int URI_FAVORITES = 7; private static final int URI_FAVORITES_ENTRY = 8; protected static final String TABLE_FEEDS = "feeds"; private static final String TABLE_ENTRIES = "entries"; private static final String ALTER_TABLE = "ALTER TABLE "; private static final String ADD = " ADD "; private static final String EQUALS_ONE = "=1"; public static final String IMAGEFOLDER = Environment.getExternalStorageDirectory()+"/sparserss/images/"; // faster than FOLDER+"images/" public static final File IMAGEFOLDER_FILE = new File(IMAGEFOLDER); private static final String BACKUPOPML = Environment.getExternalStorageDirectory()+"/sparserss/backup.opml"; private static UriMatcher URI_MATCHER; private static final String[] PROJECTION_PRIORITY = new String[] {FeedData.FeedColumns.PRIORITY}; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds", URI_FEEDS); URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds/#", URI_FEED); URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds/#/entries", URI_ENTRIES); URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds/#/entries/#", URI_ENTRY); URI_MATCHER.addURI(FeedData.AUTHORITY, "entries", URI_ALLENTRIES); URI_MATCHER.addURI(FeedData.AUTHORITY, "entries/#", URI_ALLENTRIES_ENTRY); URI_MATCHER.addURI(FeedData.AUTHORITY, "favorites", URI_FAVORITES); URI_MATCHER.addURI(FeedData.AUTHORITY, "favorites/#", URI_FAVORITES_ENTRY); IMAGEFOLDER_FILE.mkdirs(); // Create .nomedia file, that will prevent Android image gallery from showing random parts of webpages we've saved File nomedia = new File(IMAGEFOLDER+".nomedia"); try { if (!nomedia.exists()) { nomedia.createNewFile(); } } catch (Exception e) { } } private static class DatabaseHelper extends SQLiteOpenHelper { private Context context; public DatabaseHelper(Context context, String name, int version) { super(context, name, null, version); // the constructor just sets the values and returns, therefore context cannot be null this.context = context; context.sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET)); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(createTable(TABLE_FEEDS, FeedData.FeedColumns.COLUMNS, FeedData.FeedColumns.TYPES)); database.execSQL(createTable(TABLE_ENTRIES, FeedData.EntryColumns.COLUMNS, FeedData.EntryColumns.TYPES)); File backupFile = new File(BACKUPOPML); if (backupFile.exists()) { /** Perform an automated import of the backup */ OPML.importFromFile(backupFile, database); } } private String createTable(String tableName, String[] columns, String[] types) { if (tableName == null || columns == null || types == null || types.length != columns.length || types.length == 0) { throw new IllegalArgumentException("Invalid parameters for creating table "+tableName); } else { StringBuilder stringBuilder = new StringBuilder("CREATE TABLE "); stringBuilder.append(tableName); stringBuilder.append(" ("); for (int n = 0, i = columns.length; n < i; n++) { if (n > 0) { stringBuilder.append(", "); } stringBuilder.append(columns[n]).append(' ').append(types[n]); } return stringBuilder.append(");").toString(); } } @Override public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { if (oldVersion < 2) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.PRIORITY).append(' ').append(FeedData.TYPE_INT).toString()); } if (oldVersion < 3) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.FAVORITE).append(' ').append(FeedData.TYPE_BOOLEAN).toString()); } if (oldVersion < 4) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.FETCHMODE).append(' ').append(FeedData.TYPE_INT).toString()); } if (oldVersion < 5) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.REALLASTUPDATE).append(' ').append(FeedData.TYPE_DATETIME).toString()); } if (oldVersion < 6) { Cursor cursor = database.query(TABLE_FEEDS, new String[] {FeedData.FeedColumns._ID}, null, null, null, null, FeedData.FeedColumns._ID); int count = 0; while (cursor.moveToNext()) { executeCatchedSQL(database, new StringBuilder("UPDATE ").append(TABLE_FEEDS).append(" SET ").append(FeedData.FeedColumns.PRIORITY).append('=').append(count++).append(" WHERE _ID=").append(cursor.getLong(0)).toString()); } cursor.close(); } if (oldVersion < 7) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.WIFIONLY).append(' ').append(FeedData.TYPE_BOOLEAN).toString()); } // we simply leave the "encoded" column untouched if (oldVersion < 9) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.ENCLOSURE).append(' ').append(FeedData.TYPE_TEXT).toString()); } if (oldVersion < 10) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.GUID).append(' ').append(FeedData.TYPE_TEXT).toString()); } if (oldVersion < 11) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.AUTHOR).append(' ').append(FeedData.TYPE_TEXT).toString()); } if (oldVersion < 12) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.IMPOSE_USERAGENT).append(' ').append(FeedData.TYPE_BOOLEAN).toString()); if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Strings.SETTINGS_STANDARDUSERAGENT, true)) { // no "DEFAULT" syntax executeCatchedSQL(database, new StringBuilder("UPDATE ").append(TABLE_FEEDS).append(" SET ").append(FeedData.FeedColumns.IMPOSE_USERAGENT).append("='1'").toString()); } } if (oldVersion < 13) { executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.HIDE_READ).append(' ').append(FeedData.TYPE_BOOLEAN).toString()); } } private void executeCatchedSQL(SQLiteDatabase database, String query) { try { database.execSQL(query); } catch (Exception e) { } } @Override public synchronized SQLiteDatabase getWritableDatabase() { File oldDatabaseFile = new File(Environment.getExternalStorageDirectory()+"/sparserss/sparserss.db"); if (oldDatabaseFile.exists()) { // get rid of the old structure SQLiteDatabase newDatabase = super.getWritableDatabase(); try { SQLiteDatabase oldDatabase = SQLiteDatabase.openDatabase(Environment.getExternalStorageDirectory()+"/sparserss/sparserss.db", null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY); Cursor cursor = oldDatabase.query(TABLE_ENTRIES, null, null, null, null, null, null); newDatabase.beginTransaction(); String[] columnNames = cursor.getColumnNames(); int i = columnNames.length; int[] columnIndices = new int[i]; for (int n = 0; n < i; n++) { columnIndices[n] = cursor.getColumnIndex(columnNames[n]); } while (cursor.moveToNext()) { ContentValues values = new ContentValues(); for (int n = 0; n < i; n++) { if (!cursor.isNull(columnIndices[n])) { values.put(columnNames[n], cursor.getString(columnIndices[n])); } } newDatabase.insert(TABLE_ENTRIES, null, values); } cursor.close(); cursor = oldDatabase.query(TABLE_FEEDS, null, null, null, null, null, FeedData.FeedColumns._ID); columnNames = cursor.getColumnNames(); i = columnNames.length; columnIndices = new int[i]; for (int n = 0; n < i; n++) { columnIndices[n] = cursor.getColumnIndex(columnNames[n]); } int count = 0; while (cursor.moveToNext()) { ContentValues values = new ContentValues(); for (int n = 0; n < i; n++) { if (!cursor.isNull(columnIndices[n])) { if (FeedData.FeedColumns.ICON.equals(columnNames[n])) { values.put(FeedData.FeedColumns.ICON, cursor.getBlob(columnIndices[n])); } else { values.put(columnNames[n], cursor.getString(columnIndices[n])); } } } values.put(FeedData.FeedColumns.PRIORITY, count++); newDatabase.insert(TABLE_FEEDS, null, values); } cursor.close(); oldDatabase.close(); oldDatabaseFile.delete(); newDatabase.setTransactionSuccessful(); newDatabase.endTransaction(); OPML.exportToFile(BACKUPOPML, newDatabase); } catch (Exception e) { } return newDatabase; } else { return super.getWritableDatabase(); } } } private DatabaseHelper databaseHelper; private String[] MAXPRIORITY = new String[] {"MAX("+FeedData.FeedColumns.PRIORITY+")"}; @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int option = URI_MATCHER.match(uri); String table = null; StringBuilder where = new StringBuilder(); SQLiteDatabase database = databaseHelper.getWritableDatabase(); switch(option) { case URI_FEED : { table = TABLE_FEEDS; final String feedId = uri.getPathSegments().get(1); new Thread() { public void run() { delete(FeedData.EntryColumns.CONTENT_URI(feedId), null, null); } }.start(); where.append(FeedData.FeedColumns._ID).append('=').append(feedId); /** Update the priorities */ Cursor priorityCursor = database.query(TABLE_FEEDS, PROJECTION_PRIORITY, FeedData.FeedColumns._ID+"="+feedId, null, null, null, null); if (priorityCursor.moveToNext()) { database.execSQL("UPDATE "+TABLE_FEEDS+" SET "+FeedData.FeedColumns.PRIORITY+" = "+FeedData.FeedColumns.PRIORITY+"-1 WHERE "+FeedData.FeedColumns.PRIORITY+" > "+priorityCursor.getInt(0)); priorityCursor.close(); } else { priorityCursor.close(); } break; } case URI_FEEDS : { table = TABLE_FEEDS; break; } case URI_ENTRY : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(3)); break; } case URI_ENTRIES : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns.FEED_ID).append('=').append(uri.getPathSegments().get(1)); break; } case URI_ALLENTRIES : { table = TABLE_ENTRIES; break; } case URI_FAVORITES_ENTRY : case URI_ALLENTRIES_ENTRY : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(1)); break; } case URI_FAVORITES : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns.FAVORITE).append(EQUALS_ONE); break; } } if (!TextUtils.isEmpty(selection)) { if (where.length() > 0) { where.append(Strings.DB_AND); } where.append(selection); } int count = database.delete(table, where.toString(), selectionArgs); if (table == TABLE_FEEDS) { // == is ok here OPML.exportToFile(BACKUPOPML, database); } if (count > 0) { getContext().getContentResolver().notifyChange(uri, null); getContext().sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET)); } return count; } @Override public String getType(Uri uri) { int option = URI_MATCHER.match(uri); switch(option) { case URI_FEEDS : return "vnd.android.cursor.dir/vnd.feeddata.feed"; case URI_FEED : return "vnd.android.cursor.item/vnd.feeddata.feed"; case URI_FAVORITES : case URI_ALLENTRIES : case URI_ENTRIES : return "vnd.android.cursor.dir/vnd.feeddata.entry"; case URI_FAVORITES_ENTRY : case URI_ALLENTRIES_ENTRY : case URI_ENTRY : return "vnd.android.cursor.item/vnd.feeddata.entry"; default : throw new IllegalArgumentException("Unknown URI: "+uri); } } @Override public Uri insert(Uri uri, ContentValues values) { long newId = -1; int option = URI_MATCHER.match(uri); SQLiteDatabase database = databaseHelper.getWritableDatabase(); switch (option) { case URI_FEEDS : { Cursor cursor = database.query(TABLE_FEEDS, MAXPRIORITY, null, null, null, null, null, null); if (cursor.moveToNext()) { values.put(FeedData.FeedColumns.PRIORITY, cursor.getInt(0)+1); } else { values.put(FeedData.FeedColumns.PRIORITY, 1); } cursor.close(); newId = database.insert(TABLE_FEEDS, null, values); OPML.exportToFile(BACKUPOPML, database); break; } case URI_ENTRIES : { values.put(FeedData.EntryColumns.FEED_ID, uri.getPathSegments().get(1)); newId = database.insert(TABLE_ENTRIES, null, values); break; } case URI_ALLENTRIES : { newId = database.insert(TABLE_ENTRIES, null, values); break; } default : throw new IllegalArgumentException("Illegal insert"); } if (newId > -1) { getContext().getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, newId); } else { throw new SQLException("Could not insert row into "+uri); } } @Override public boolean onCreate() { try { File folder = new File(FOLDER); folder.mkdir(); // maybe we use the boolean return value later } catch (Exception e) { } databaseHelper = new DatabaseHelper(getContext(), DATABASE_NAME, DATABASE_VERSION); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); int option = URI_MATCHER.match(uri); if ((option == URI_FEED || option == URI_FEEDS) && sortOrder == null) { sortOrder = FeedData.FEED_DEFAULTSORTORDER; } switch(option) { case URI_FEED : { queryBuilder.setTables(TABLE_FEEDS); queryBuilder.appendWhere(new StringBuilder(FeedData.FeedColumns._ID).append('=').append(uri.getPathSegments().get(1))); break; } case URI_FEEDS : { queryBuilder.setTables(TABLE_FEEDS); break; } case URI_ENTRY : { queryBuilder.setTables(TABLE_ENTRIES); queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(3))); break; } case URI_ENTRIES : { queryBuilder.setTables(TABLE_ENTRIES); queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns.FEED_ID).append('=').append(uri.getPathSegments().get(1))); break; } case URI_ALLENTRIES : { queryBuilder.setTables("entries join (select name, icon, _id as feed_id from feeds) as F on (entries.feedid = F.feed_id)"); break; } case URI_FAVORITES_ENTRY : case URI_ALLENTRIES_ENTRY : { queryBuilder.setTables(TABLE_ENTRIES); queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(1))); break; } case URI_FAVORITES : { queryBuilder.setTables("entries join (select name, icon, _id as feed_id from feeds) as F on (entries.feedid = F.feed_id)"); queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns.FAVORITE).append(EQUALS_ONE)); break; } } SQLiteDatabase database = databaseHelper.getReadableDatabase(); Cursor cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int option = URI_MATCHER.match(uri); String table = null; StringBuilder where = new StringBuilder(); SQLiteDatabase database = databaseHelper.getWritableDatabase(); switch(option) { case URI_FEED : { table = TABLE_FEEDS; long feedId = Long.parseLong(uri.getPathSegments().get(1)); where.append(FeedData.FeedColumns._ID).append('=').append(feedId); if (values != null && values.containsKey(FeedData.FeedColumns.PRIORITY)) { int newPriority = values.getAsInteger(FeedData.FeedColumns.PRIORITY); Cursor priorityCursor = database.query(TABLE_FEEDS, PROJECTION_PRIORITY, FeedData.FeedColumns._ID+"="+feedId, null, null, null, null); if (priorityCursor.moveToNext()) { int oldPriority = priorityCursor.getInt(0); priorityCursor.close(); if (newPriority > oldPriority) { database.execSQL("UPDATE "+TABLE_FEEDS+" SET "+FeedData.FeedColumns.PRIORITY+" = "+FeedData.FeedColumns.PRIORITY+"-1 WHERE "+FeedData.FeedColumns.PRIORITY+" BETWEEN "+(oldPriority+1)+" AND "+newPriority); } else if (newPriority < oldPriority) { database.execSQL("UPDATE "+TABLE_FEEDS+" SET "+FeedData.FeedColumns.PRIORITY+" = "+FeedData.FeedColumns.PRIORITY+"+1 WHERE "+FeedData.FeedColumns.PRIORITY+" BETWEEN "+newPriority+" AND "+(oldPriority-1)); } } else { priorityCursor.close(); } } break; } case URI_FEEDS : { table = TABLE_FEEDS; // maybe this should be disabled break; } case URI_ENTRY : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(3)); break; } case URI_ENTRIES : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns.FEED_ID).append('=').append(uri.getPathSegments().get(1)); break; } case URI_ALLENTRIES: { table = TABLE_ENTRIES; break; } case URI_FAVORITES_ENTRY : case URI_ALLENTRIES_ENTRY : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(1)); break; } case URI_FAVORITES : { table = TABLE_ENTRIES; where.append(FeedData.EntryColumns.FAVORITE).append(EQUALS_ONE); break; } } if (!TextUtils.isEmpty(selection)) { if (where.length() > 0) { where.append(Strings.DB_AND).append(selection); } else { where.append(selection); } } int count = database.update(table, values, where.toString(), selectionArgs); if (table == TABLE_FEEDS && (values.containsKey(FeedData.FeedColumns.NAME) || values.containsKey(FeedData.FeedColumns.URL) || values.containsKey(FeedData.FeedColumns.PRIORITY))) { // == is ok here OPML.exportToFile(BACKUPOPML, database); } if (count > 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } }
025003b-gfgfgf
src/de/shandschuh/sparserss/provider/FeedDataContentProvider.java
Java
mit
21,165
/** * Sparse rss * * Copyright (c) 2010-2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss.provider; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Xml; import de.shandschuh.sparserss.Strings; public class OPML { private static final String START = "<?xml version=\"1.0\" encoding=\"utf-8\"?><opml version=\"1.1\"><head><title>Sparse RSS export</title><dateCreated>"; private static final String AFTERDATE = "</dateCreated></head><body>"; private static final String OUTLINE_TITLE = "<outline title=\""; private static final String OUTLINE_XMLURL = "\" type=\"rss\" xmlUrl=\""; private static final String ATTRIBUTE_CATEGORY_VALUE = "/"+FeedData.FeedColumns.WIFIONLY; private static final String OUTLINE_CATEGORY = "\" category=\""; private static final String OUTLINE_CLOSING = "\" />"; private static final String CLOSING = "</body></opml>\n"; private static OPMLParser parser = new OPMLParser(); public static void importFromFile(String filename, Context context) throws FileNotFoundException, IOException, SAXException { parser.context = context; parser.database = null; Xml.parse(new InputStreamReader(new FileInputStream(filename)), parser); } protected static void importFromInputStream(InputStream inputStream, SQLiteDatabase database) { parser.context = null; parser.database = database; try { database.beginTransaction(); Xml.parse(new InputStreamReader(inputStream), parser); /** This is ok since the database is empty */ database.execSQL(new StringBuilder("UPDATE ").append(FeedDataContentProvider.TABLE_FEEDS).append(" SET ").append(FeedData.FeedColumns.PRIORITY).append('=').append(FeedData.FeedColumns._ID).append("-1").toString()); database.setTransactionSuccessful(); } catch (Exception e) { } finally { database.endTransaction(); } } protected static void importFromFile(File file, SQLiteDatabase database) { try { importFromInputStream(new FileInputStream(file), database); } catch (FileNotFoundException e) { // do nothing } } public static void exportToFile(String filename, Context context) throws IOException { Cursor cursor = context.getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, new String[] {FeedData.FeedColumns._ID, FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.WIFIONLY}, null, null, null); try { writeData(filename, cursor); } finally { cursor.close(); } } protected static void exportToFile(String filename, SQLiteDatabase database) { Cursor cursor = database.query(FeedDataContentProvider.TABLE_FEEDS, new String[] {FeedData.FeedColumns._ID, FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.WIFIONLY}, null, null, null, null, FeedData.FEED_DEFAULTSORTORDER); try { writeData(filename, cursor); } catch (Exception e) { } cursor.close(); } private static void writeData(String filename, Cursor cursor) throws IOException { StringBuilder builder = new StringBuilder(START); builder.append(System.currentTimeMillis()); builder.append(AFTERDATE); while(cursor.moveToNext()) { builder.append(OUTLINE_TITLE); builder.append(cursor.isNull(1) ? Strings.EMPTY : TextUtils.htmlEncode(cursor.getString(1))); builder.append(OUTLINE_XMLURL); builder.append(TextUtils.htmlEncode(cursor.getString(2))); if (cursor.getInt(3) == 1) { builder.append(OUTLINE_CATEGORY); builder.append(ATTRIBUTE_CATEGORY_VALUE); } builder.append(OUTLINE_CLOSING); } builder.append(CLOSING); BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write(builder.toString()); writer.close(); } private static class OPMLParser extends DefaultHandler { private static final String TAG_BODY = "body"; private static final String TAG_OUTLINE = "outline"; private static final String ATTRIBUTE_TITLE = "title"; private static final String ATTRIBUTE_XMLURL = "xmlUrl"; private static final String ATTRIBUTE_CATEGORY = "category"; private boolean bodyTagEntered; private boolean probablyValidElement = false; private Context context; private SQLiteDatabase database; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (!bodyTagEntered) { if (TAG_BODY.equals(localName)) { bodyTagEntered = true; probablyValidElement = true; } } else if (TAG_OUTLINE.equals(localName)) { String url = attributes.getValue(Strings.EMPTY, ATTRIBUTE_XMLURL); if (url != null) { String title = attributes.getValue(Strings.EMPTY, ATTRIBUTE_TITLE); ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.URL, url); values.put(FeedData.FeedColumns.NAME, title != null && title.length() > 0 ? title : null); values.put(FeedData.FeedColumns.WIFIONLY, ATTRIBUTE_CATEGORY_VALUE.equals(attributes.getValue(Strings.EMPTY, ATTRIBUTE_CATEGORY)) ? 1 : 0); if (context != null) { Cursor cursor = context.getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, null, new StringBuilder(FeedData.FeedColumns.URL).append(Strings.DB_ARG).toString(), new String[] {url}, null); if (!cursor.moveToFirst()) { context.getContentResolver().insert(FeedData.FeedColumns.CONTENT_URI, values); } cursor.close(); } else { // this happens only, if the db is new and therefore empty database.insert(FeedDataContentProvider.TABLE_FEEDS, null, values); } } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (bodyTagEntered && TAG_BODY.equals(localName)) { bodyTagEntered = false; } } @Override public void endDocument() throws SAXException { if (!probablyValidElement) { throw new SAXException(); } else { super.endDocument(); } } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/provider/OPML.java
Java
mit
7,557
/** * Sparse rss * * Copyright (c) 2010-2012 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.preference.PreferenceManager; import de.shandschuh.sparserss.service.RefreshService; public class BootCompletedBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.createPackageContext(Strings.PACKAGE, 0)); preferences.edit().putLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, 0).commit(); if (preferences.getBoolean(Strings.SETTINGS_REFRESHENABLED, false)) { context.startService(new Intent(context, RefreshService.class)); } context.sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET)); } catch (NameNotFoundException e) { } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/BootCompletedBroadcastReceiver.java
Java
mit
2,124
/** * Sparse rss * * Copyright (c) 2012, 2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import de.shandschuh.sparserss.provider.FeedData; public class FeedConfigActivity extends Activity { private static final String WASACTIVE = "wasactive"; private static final String[] PROJECTION = new String[] {FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.WIFIONLY, FeedData.FeedColumns.IMPOSE_USERAGENT, FeedData.FeedColumns.HIDE_READ}; private EditText nameEditText; private EditText urlEditText; private CheckBox refreshOnlyWifiCheckBox; private CheckBox standardUseragentCheckBox; private CheckBox hideReadCheckBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.feedsettings); setResult(RESULT_CANCELED); Intent intent = getIntent(); nameEditText = (EditText) findViewById(R.id.feed_title); urlEditText = (EditText) findViewById(R.id.feed_url); refreshOnlyWifiCheckBox = (CheckBox) findViewById(R.id.wifionlycheckbox); standardUseragentCheckBox = (CheckBox) findViewById(R.id.standarduseragentcheckbox); hideReadCheckBox = (CheckBox) findViewById(R.id.hidereadcheckbox); if (intent.getAction().equals(Intent.ACTION_INSERT)) { setTitle(R.string.newfeed_title); restoreInstanceState(savedInstanceState); ((Button) findViewById(R.id.button_ok)).setOnClickListener(new OnClickListener() { public void onClick(View v) { String url = urlEditText.getText().toString(); if (!url.startsWith(Strings.HTTP) && !url.startsWith(Strings.HTTPS)) { url = Strings.HTTP+url; } Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, null, new StringBuilder(FeedData.FeedColumns.URL).append(Strings.DB_ARG).toString(), new String[] {url}, null); if (cursor.moveToFirst()) { cursor.close(); Toast.makeText(FeedConfigActivity.this, R.string.error_feedurlexists, Toast.LENGTH_LONG).show(); } else { cursor.close(); ContentValues values = new ContentValues(); values.put(FeedData.FeedColumns.WIFIONLY, refreshOnlyWifiCheckBox.isChecked() ? 1 : 0); values.put(FeedData.FeedColumns.IMPOSE_USERAGENT, standardUseragentCheckBox.isChecked() ? 0 : 1); values.put(FeedData.FeedColumns.HIDE_READ, hideReadCheckBox.isChecked() ? 1 : 0); values.put(FeedData.FeedColumns.URL, url); values.put(FeedData.FeedColumns.ERROR, (String) null); String name = nameEditText.getText().toString(); if (name.trim().length() > 0) { values.put(FeedData.FeedColumns.NAME, name); } getContentResolver().insert(FeedData.FeedColumns.CONTENT_URI, values); setResult(RESULT_OK); finish(); } } }); } else { setTitle(R.string.editfeed_title); if (!restoreInstanceState(savedInstanceState)) { Cursor cursor = getContentResolver().query(intent.getData(), PROJECTION, null, null, null); if (cursor.moveToNext()) { nameEditText.setText(cursor.getString(0)); urlEditText.setText(cursor.getString(1)); refreshOnlyWifiCheckBox.setChecked(cursor.getInt(2) == 1); standardUseragentCheckBox.setChecked(cursor.isNull(3) || cursor.getInt(3) == 0); hideReadCheckBox.setChecked(cursor.getInt(4) == 1); cursor.close(); } else { cursor.close(); Toast.makeText(FeedConfigActivity.this, R.string.error, Toast.LENGTH_LONG).show(); finish(); } } ((Button) findViewById(R.id.button_ok)).setOnClickListener(new OnClickListener() { public void onClick(View v) { String url = urlEditText.getText().toString(); Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, new String[] {FeedData.FeedColumns._ID}, new StringBuilder(FeedData.FeedColumns.URL).append(Strings.DB_ARG).toString(), new String[] {url}, null); if (cursor.moveToFirst() && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) { cursor.close(); Toast.makeText(FeedConfigActivity.this, R.string.error_feedurlexists, Toast.LENGTH_LONG).show(); } else { cursor.close(); ContentValues values = new ContentValues(); if (!url.startsWith(Strings.HTTP) && !url.startsWith(Strings.HTTPS)) { url = Strings.HTTP+url; } values.put(FeedData.FeedColumns.URL, url); String name = nameEditText.getText().toString(); values.put(FeedData.FeedColumns.NAME, name.trim().length() > 0 ? name : null); values.put(FeedData.FeedColumns.FETCHMODE, 0); values.put(FeedData.FeedColumns.WIFIONLY, refreshOnlyWifiCheckBox.isChecked() ? 1 : 0); values.put(FeedData.FeedColumns.IMPOSE_USERAGENT, standardUseragentCheckBox.isChecked() ? 0 : 1); values.put(FeedData.FeedColumns.HIDE_READ, hideReadCheckBox.isChecked() ? 1 : 0); values.put(FeedData.FeedColumns.ERROR, (String) null); getContentResolver().update(getIntent().getData(), values, null, null); setResult(RESULT_OK); finish(); } } }); } ((Button) findViewById(R.id.button_cancel)).setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); } private boolean restoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null && savedInstanceState.getBoolean(WASACTIVE, false)) { nameEditText.setText(savedInstanceState.getCharSequence(FeedData.FeedColumns.NAME)); urlEditText.setText(savedInstanceState.getCharSequence(FeedData.FeedColumns.URL)); refreshOnlyWifiCheckBox.setChecked(savedInstanceState.getBoolean(FeedData.FeedColumns.WIFIONLY)); standardUseragentCheckBox.setChecked(!savedInstanceState.getBoolean(FeedData.FeedColumns.IMPOSE_USERAGENT)); // we don't have to negate this here, if we would not negate it in the OnSaveInstanceStage, but lets do it for the sake of readability return true; } else { return false; } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(WASACTIVE, true); outState.putCharSequence(FeedData.FeedColumns.NAME, nameEditText.getText()); outState.putCharSequence(FeedData.FeedColumns.URL, urlEditText.getText()); outState.putBoolean(FeedData.FeedColumns.WIFIONLY, refreshOnlyWifiCheckBox.isChecked()); outState.putBoolean(FeedData.FeedColumns.IMPOSE_USERAGENT, !standardUseragentCheckBox.isChecked()); } }
025003b-gfgfgf
src/de/shandschuh/sparserss/FeedConfigActivity.java
Java
mit
7,939
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import de.shandschuh.sparserss.service.FetcherService; public class RefreshBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Strings.ACTION_REFRESHFEEDS.equals(intent.getAction())) { context.startService(new Intent(context, FetcherService.class).putExtras(intent)); // a thread would mark the process as inactive } else if (Strings.ACTION_STOPREFRESHFEEDS.equals(intent.getAction())) { context.stopService(new Intent(context, FetcherService.class)); } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/RefreshBroadcastReceiver.java
Java
mit
1,827
/** * Sparse rss * * Copyright (c) 2010-2013 Stefan Handschuh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package de.shandschuh.sparserss; import java.text.DateFormat; import java.util.Date; import java.util.Vector; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.util.TypedValue; import android.view.View; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import de.shandschuh.sparserss.provider.FeedData; public class RSSOverviewListAdapter extends ResourceCursorAdapter { private static final String COUNT_UNREAD = "COUNT(*) - COUNT(readdate)"; private static final String COUNT = "COUNT(*)"; private String COLON; private int nameColumnPosition; private int lastUpdateColumn; private int idPosition; private int linkPosition; private int errorPosition; private int iconPosition; private Handler handler; private SimpleTask updateTask; private boolean feedSort; private Vector<View> sortViews; private DateFormat dateFormat; private DateFormat timeFormat; public RSSOverviewListAdapter(Activity activity) { super(activity, R.layout.feedlistitem, activity.managedQuery(FeedData.FeedColumns.CONTENT_URI, null, null, null, null)); nameColumnPosition = getCursor().getColumnIndex(FeedData.FeedColumns.NAME); lastUpdateColumn = getCursor().getColumnIndex(FeedData.FeedColumns.LASTUPDATE); idPosition = getCursor().getColumnIndex(FeedData.FeedColumns._ID); linkPosition = getCursor().getColumnIndex(FeedData.FeedColumns.URL); errorPosition = getCursor().getColumnIndex(FeedData.FeedColumns.ERROR); iconPosition = getCursor().getColumnIndex(FeedData.FeedColumns.ICON); COLON = activity.getString(R.string.colon); handler = new Handler(); updateTask = new SimpleTask() { @Override public void runControlled() { RSSOverviewListAdapter.super.onContentChanged(); cancel(); // cancel the task such that it does not run more than once without explicit intention } @Override public void postRun() { if (getPostCount() > 1) { // enforce second run even if task is canceled handler.postDelayed(updateTask, 1500); } } }; sortViews = new Vector<View>(); dateFormat = android.text.format.DateFormat.getDateFormat(activity); timeFormat = android.text.format.DateFormat.getTimeFormat(activity); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textView = ((TextView) view.findViewById(android.R.id.text1)); textView.setSingleLine(); Cursor countCursor = context.getContentResolver().query(FeedData.EntryColumns.CONTENT_URI(cursor.getString(idPosition)), new String[] {COUNT_UNREAD, COUNT}, null, null, null); countCursor.moveToFirst(); int unreadCount = countCursor.getInt(0); int count = countCursor.getInt(1); countCursor.close(); long timestamp = cursor.getLong(lastUpdateColumn); TextView updateTextView = ((TextView) view.findViewById(android.R.id.text2));; if (cursor.isNull(errorPosition)) { Date date = new Date(timestamp); updateTextView.setText(new StringBuilder(context.getString(R.string.update)).append(COLON).append(timestamp == 0 ? context.getString(R.string.never) : new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(unreadCount).append('/').append(count).append(' ').append(context.getString(R.string.unread)))); } else { updateTextView.setText(new StringBuilder(context.getString(R.string.error)).append(COLON).append(cursor.getString(errorPosition))); } textView.setEnabled(unreadCount > 0); byte[] iconBytes = cursor.getBlob(iconPosition); if (iconBytes != null && iconBytes.length > 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length); if (bitmap != null && bitmap.getHeight() > 0 && bitmap.getWidth() > 0) { int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18f, context.getResources().getDisplayMetrics()); if (bitmap.getHeight() != bitmapSizeInDip) { bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false); } textView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(bitmap), null, null, null); textView.setText(" " + (cursor.isNull(nameColumnPosition) ? cursor.getString(linkPosition) : cursor.getString(nameColumnPosition))); } else { textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); textView.setText(cursor.isNull(nameColumnPosition) ? cursor.getString(linkPosition) : cursor.getString(nameColumnPosition)); } } else { view.setTag(null); textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); textView.setText(cursor.isNull(nameColumnPosition) ? cursor.getString(linkPosition) : cursor.getString(nameColumnPosition)); } View sortView = view.findViewById(R.id.sortitem); if (!sortViews.contains(sortView)) { // as we are reusing views, this is fine sortViews.add(sortView); } sortView.setVisibility(feedSort ? View.VISIBLE : View.GONE); } @Override protected synchronized void onContentChanged() { /* * we delay the second(!) content change by 1.5 second such that it gets called at most once per 1.5 seconds * to take stress away from the UI and avoid not needed updates */ if (!updateTask.isPosted()) { super.onContentChanged(); updateTask.post(2); // we post 2 tasks handler.postDelayed(updateTask, 1500); // waits one second until the task gets unposted updateTask.cancel(); // put the canceled task in the queue to enable it again optionally } else { if (updateTask.getPostCount() < 2) { updateTask.post(); // enables the task and adds a new one } else { updateTask.enable(); } } } public void setFeedSortEnabled(boolean enabled) { feedSort = enabled; /* we do not want to call notifyDataSetChanged as this requeries the cursor*/ int visibility = feedSort ? View.VISIBLE : View.GONE; for (View sortView : sortViews) { sortView.setVisibility(visibility); } } }
025003b-gfgfgf
src/de/shandschuh/sparserss/RSSOverviewListAdapter.java
Java
mit
7,361
# Adjust to your local settings SDK_DIR = /home/android/android-sdks API_LEVEL = 15 KEYALIAS = rss # From here on, the file should be left unchanged AAPT = $(SDK_DIR)/platform-tools/aapt ANDROID_JAR = $(SDK_DIR)/platforms/android-$(API_LEVEL)/android.jar DX_JAR = $(SDK_DIR)/platform-tools/lib/dx.jar SDKLIB_JAR = $(SDK_DIR)/tools/lib/sdklib.jar ZIPALIGN = $(SDK_DIR)/tools/zipalign all: zipalign icons: res/drawable/icon.png res/drawable/feed.png res/drawable/feed_grey.png res/drawable/ic_statusbar_rss.png res/drawable-v9/ic_statusbar_rss.png res/drawable-v11/ic_statusbar_rss.png res/drawable/icon.png: launcher.svg mkdir -p res/drawable convert launcher.svg -resize 60x60 -background Transparent -bordercolor Transparent -border 4x6 \( +clone -background Transparent -shadow 40x1+0+3 \) +swap -layers merge +repage res/drawable/icon.png convert -extract 72x72+0+0 +repage res/drawable/icon.png res/drawable/icon.png res/drawable/feed.png: launcher.svg mkdir -p res/drawable convert launcher.svg -resize 19x19 -background Transparent -bordercolor Transparent -border 23x23 res/drawable/feed.png convert -extract 44x44+0+21 +repage res/drawable/feed.png res/drawable/feed.png res/drawable/feed_grey.png: launcher.svg mkdir -p res/drawable convert launcher.svg -resize 19x19 -background Transparent -type Grayscale -bordercolor Transparent -border 23x23 res/drawable/feed_grey.png convert -extract 44x44+0+21 +repage res/drawable/feed_grey.png res/drawable/feed_grey.png res/drawable/ic_statusbar_rss.png: status_icon.svg mkdir -p res/drawable convert status_icon.svg -background Transparent -resize 21x21 -bordercolor Transparent -border 2 res/drawable/ic_statusbar_rss.png res/drawable-v9/ic_statusbar_rss.png: status_icon_23.svg mkdir -p res/drawable-v9 convert status_icon_23.svg -background Transparent -resize 21x21 -bordercolor Transparent -border 2 res/drawable-v9/ic_statusbar_rss.png res/drawable-v11/ic_statusbar_rss.png: status_icon_30.svg mkdir -p res/drawable-v11 convert status_icon_30.svg -background Transparent -resize 21x21 -bordercolor Transparent -border 2 res/drawable-v11/ic_statusbar_rss.png aapt: icons AndroidManifest.xml res mkdir -p gen/de/shandschuh/sparserss/ mkdir -p bin $(AAPT) p -f -M AndroidManifest.xml -F bin/resources.ap_ -I $(ANDROID_JAR) -S res -m -J gen javac: aapt mkdir -p bin/classes javac -d bin/classes -sourcepath gen gen/de/shandschuh/sparserss/*.java javac -cp bin/classes:$(ANDROID_JAR) -d bin/classes -sourcepath src `find src -name *.java -print` bin/classes.dex: javac java -jar $(DX_JAR) --dex --output=bin/classes.dex bin/classes bin/SparseRSS_unsigned.apk: bin/classes.dex java -cp $(SDKLIB_JAR) com.android.sdklib.build.ApkBuilderMain bin/SparseRSS_unsigned.apk -u -z bin/resources.ap_ -f bin/classes.dex bin/SparseRSS_signed.apk: bin/SparseRSS_unsigned.apk jarsigner -keystore keystore -signedjar bin/SparseRSS_signed.apk bin/SparseRSS_unsigned.apk $(KEYALIAS) zipalign: bin/SparseRSS_signed.apk $(ZIPALIGN) 4 bin/SparseRSS_signed.apk bin/SparseRSS_signed_aligned.apk clean: rm -fr res/drawable* rm -fr gen rm -fr bin
025003b-gfgfgf
Makefile
Makefile
mit
3,124
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("BUS")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("BUS")> <Assembly: AssemblyCopyright("Copyright © 2010")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("55bc6486-e938-45f7-a30a-7fad4fa87009")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/My Project/AssemblyInfo.vb
Visual Basic .NET
gpl2
1,159
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class VeBus
 Shared dao As New VeDao Public Shared Function LayDanhSachVe() As DataTable Return dao.LayDanhSachVe() End Function Public Shared Function TimVe(ByVal ve As VeDto) As DataTable Return dao.TimVe(ve) End Function Public Shared Function TimVeTheoMaLichGan(ByVal maLichGan As Integer) As DataTable Return dao.TimVeTheoMaLichGan(maLichGan) End Function Public Shared Function ThemVe(ByVal ve As VeDto) As Integer Return dao.ThemVe(ve) End Function Public Shared Function CapNhatVe(ByVal ve As VeDto) As Integer Return dao.CapNhatVe(ve) End Function Public Shared Function XoaVe(ByVal maCanXoa As Long) As Integer 'Return dao.XoaVe(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/VeBus.vb
Visual Basic .NET
gpl2
895
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LoaiVeBus
 Shared dao As New LoaiVeDao Public Shared Function LayDanhSachLoaiVe() As DataTable Return dao.LayDanhSachLoaiVe() End Function Public Shared Function LayDanhSachLoaiVeTheoMaTuyen(ByVal maTuyen As Long) As DataTable Return dao.LayDanhSachLoaiVeTheoMaTuyen(maTuyen) End Function Public Shared Function ThemLoaiVe(ByVal loaive As LoaiVeDto) As Integer Return dao.ThemLoaiVe(loaive) End Function Public Shared Function CapNhatLoaiVe(ByVal loaive As LoaiVeDto) As Integer Return dao.CapNhatLoaiVe(loaive) End Function Public Shared Function XoaLoaiVe(ByVal maCanXoa As Long) As Integer Return dao.XoaLoaiVe(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/LoaiVeBus.vb
Visual Basic .NET
gpl2
853
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LichGanLapBus Shared dao As New LichGanLapDao Public Shared Function LayDanhSachXeDuocLap() As DataTable Return dao.LayDanhSachXeDuocLap() End Function Public Shared Function LayLichGanLap(ByVal maLichGan As Long) As DataTable Return dao.LayLichGanLap(maLichGan) End Function Public Shared Function ThemMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer Return dao.ThemMotLichGanLap(lgLap) End Function Public Shared Function CapNhatMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer Return dao.CapNhatMotLichGanLap(lgLap) End Function Public Shared Function XoaMotLichGanLap(ByVal maLichGan As Long) As Integer Return dao.XoaMotLichGanLap(maLichGan) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/LichGanLapBus.vb
Visual Basic .NET
gpl2
886
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LichGanBus
 Shared dao As New LichGanDao Public Shared Function LayDanhSachLichGan() As DataTable Return dao.LayDanhSachLichGan() End Function Public Shared Function TimLichGan(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal thoiDiemKhoiHanh As String, ByVal maXe As Long) As DataTable Return dao.TimLichGan(maTuyen, ngayKhoiHanh, thoiDiemKhoiHanh, maXe) End Function Public Shared Function TimLichGanTheoMa(ByVal maCanTim As Integer) As DataTable Return dao.TimLichGanTheoMa(maCanTim) End Function Public Shared Function ThemMotLichGan(ByVal lg As LichGanDto) As Integer Return dao.ThemMotLichGan(lg) End Function Public Shared Function ThemLichGan(ByVal lg As LichGanDto) As Integer Return dao.ThemMotLichGan(lg) End Function Public Shared Function CapNhatLichGan(ByVal lg As LichGanDto) As Integer Return dao.CapNhatLichGan(lg) End Function Public Shared Function XoaMotLichGan(ByVal maCanXoa As Long) As Integer Return dao.XoaMotLichGan(maCanXoa) End Function 'Tìm ngày khởi hành Public Shared Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable Return dao.TimNgayKhoiHanh(maTuyen) End Function 'Tìm giờ khởi hành Public Shared Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable Return dao.TimThoiDiemKhoiHanh(maTuyen, ngayKhoiHanh) End Function 'Lấy danh sách xe đang Public Shared Function DanhSachXeDangRanh(ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable Return dao.DanhSachXeDangRanh(ngayKhoiHanh, ThoiDiemKhoiHanh) End Function 'Lấy mã lịch gán vừa thêm vào Public Shared Function LayMaLichGanVuaThem() As Long Return dao.LayMaLichGanVuaThem() End Function 'Bán vé... 'Tìm xe theo tuyến, thời điểm Public Shared Function DanhSachXe_TheoTuyen_ThoiDiem(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable Return dao.DanhSachXe_TheoTuyen_ThoiDiem(maTuyen, ngayKhoiHanh, ThoiDiemKhoiHanh) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/LichGanBus.vb
Visual Basic .NET
gpl2
2,377
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class ChungBus Shared dao As New CHUNG 'Public Function KiemTraKetNoi_CSDL_CoDuocKhong() As String ' Dim loiKetNoi As String = "" ' If provider.Connect Is Nothing Then ' loiKetNoi = "Không tìm thấy cơ sở dữ liệu!!!" ' End If ' Return loiKetNoi 'End Function Public Shared Function LayDanhSach() As DataTable Return dao.LayDanhSach() End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/ChungBus.vb
Visual Basic .NET
gpl2
538
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class XeBus
 Shared dao As New XeDao Public Shared Function LayDanhSachXe() As DataTable Return dao.LayDanhSachXe() End Function Public Shared Function TimXe(ByVal xe As XeDto) As DataTable Return dao.TimXe(xe) End Function Public Shared Function TimXeTheoMaXe(ByVal maXe As Integer) As DataTable Return dao.TimXeTheoMaXe(maXe) End Function Public Shared Function LaySoChoNgoi_TheoMaXe(ByVal maXe As Integer) As Integer Return dao.LaySoChoNgoi_TheoMaXe(maXe) End Function Public Shared Function ThemXe(ByVal xe As XeDto) As Integer Return dao.ThemXe(xe) End Function Public Shared Function CapNhatXe(ByVal xe As XeDto) As Integer Return dao.CapNhatXe(xe) End Function Public Shared Function XoaXe(ByVal maCanXoa As Long) As Integer Return dao.XoaXe(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/XeBus.vb
Visual Basic .NET
gpl2
1,026
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class NhanVienBus Shared dao As New NhanVienDao Public Shared Function LayNguoiDangNhap(ByVal tenDangNhap As String, ByVal matKhau As String) As Integer Return dao.LayNguoiDangNhap(tenDangNhap, matKhau) End Function Public Shared Function LayNguoiDung(ByVal tenDangNhap As String, ByVal matKhau As String) As DataTable Return dao.LayNguoiDung(tenDangNhap, matKhau) End Function Public Shared Function LayNguoiDungTheoMa(ByVal maNhanVien As Long) As DataTable Return dao.LayNguoiDungTheoMa(maNhanVien) End Function Public Shared Function LayNguoiDung() As DataTable Return dao.LayNguoiDung() End Function Public Shared Function LayQuyen() As DataTable Return dao.LayQuyen() End Function Public Shared Function LayDanhSachNguoiDung() As DataTable Return dao.LayDanhSachNguoiDung() End Function Public Shared Function ThemNhanVien(ByVal nhanVien As NhanVienDto) As Integer Return dao.ThemNhanVien(nhanVien) End Function Public Shared Function CapNhatNhanVien(ByVal nhanVien As NhanVienDto) As Integer Return dao.CapNhatNhanVien(nhanVien) End Function Public Shared Function TimKiemNhanVien(ByVal nhanVien As NhanVienDto) As DataTable Return dao.TimKiemNhanVien(nhanVien) End Function Public Shared Function XoaNhanVien(ByVal nhanVien As NhanVienDto) As String Return dao.XoaNhanVien(nhanVien) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/NhanVienBus.vb
Visual Basic .NET
gpl2
1,606
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class XL_Chung Shared dao As New XL_Chung_dao Public Shared Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable Return dao.TimNgayKhoiHanh(maTuyen) End Function Public Shared Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable Return dao.TimThoiDiemKhoiHanh(maTuyen, ngayKhoiHanh) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/XL_Chung.vb
Visual Basic .NET
gpl2
499
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LichTuyenBus Shared daoLichTuyen As New LichTuyenLapDao Shared daoLichTuyenKhongLap As New LichTuyenKhongLapDao Public Shared Function LayDanhSachLichTuyen() As DataTable Return daoLichTuyen.LayDanhSachLichTuyenLap() End Function Public Shared Function LayDanhSachLichTuyenLapThu() As DataTable Return daoLichTuyen.LayDanhSachLichTuyenLapThu() End Function Public Shared Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenDto) As Integer Return daoLichTuyen.ThemThoiDiemKhoiHanh(thoiDiem) End Function Public Shared Function CapNhatThoiDiemKhoiHanh(ByRef data As DataTable) As Integer Return daoLichTuyen.CapNhatThoiDiemKhoiHanh(data) End Function Public Shared Function CapNhatThuLap(ByVal data As DataRow) As Integer Return daoLichTuyen.CapNhatThuLap(data) End Function Public Shared Function XoaThoiDiemKhoiHanh(ByVal data As DataRow) As Integer Return daoLichTuyen.XoaThoiDiemKhoiHanh(data) End Function Public Shared Function LayDanhSachLichTuyenKhongLap() As DataTable Return daoLichTuyenKhongLap.LayDanhSachLichTuyenKhongLap() End Function Public Shared Function LayDanhSachLichTuyenKhongLapThoiDiem() As DataTable Return daoLichTuyenKhongLap.LayDanhSachLichTuyenKhongLapThoiDiem() End Function Public Shared Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenKhongLapDto) As Integer Return daoLichTuyenKhongLap.ThemThoiDiemKhoiHanh(thoiDiem) End Function Public Shared Function CapNhatThoiDiemKhoiHanhKhongLap(ByRef data As DataTable) As Integer Return daoLichTuyenKhongLap.CapNhatThoiDiemKhoiHanh(data) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/LichTuyenBus.vb
Visual Basic .NET
gpl2
1,851
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class TuyenBus Shared dao As New TuyenDao Public Shared Function LayDanhSachTuyen() As DataTable Return dao.LayDanhSachTuyen() End Function Public Shared Function TimTuyen(ByVal tuyen As TuyenDto) As DataTable Return dao.TimTuyen(tuyen) End Function Public Shared Function TimTuyenTheoMaTuyen(ByVal maTuyen As Integer) As DataTable Return dao.TimTuyenTheoMaTuyen(maTuyen) End Function Public Shared Function ThemTuyen(ByVal tuyen As TuyenDto) As Integer Return dao.ThemTuyen(tuyen) End Function Public Shared Function CapNhatTuyen(ByVal tuyen As TuyenDto) As Integer Return dao.CapNhatTuyen(tuyen) End Function Public Shared Function XoaTuyen(ByVal maCanXoa As Long) As Integer Return dao.XoaTuyen(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/BUS/TuyenBus.vb
Visual Basic .NET
gpl2
955
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("DTO")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("DTO")> <Assembly: AssemblyCopyright("Copyright © 2010")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("84ab580b-e875-4d64-89f9-64f5640d4f9d")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/My Project/AssemblyInfo.vb
Visual Basic .NET
gpl2
1,159
Public Class LichTuyenDto Dim _MaTuyen As Integer Dim _MaNhanVien As Integer Dim _ThoiDiemKhoiHanh As String Dim _ThuHai As Boolean Dim _ThuBa As Boolean Dim _ThuTu As Boolean Dim _ThuNam As Boolean Dim _ThuSau As Boolean Dim _ThuBay As Boolean Dim _ChuNhat As Boolean Sub New() _MaTuyen = 0 _MaNhanVien = 0 _ThoiDiemKhoiHanh = "00:00" _ThuHai = False _ThuBa = False _ThuTu = False _ThuNam = False _ThuSau = False _ThuBay = False _ChuNhat = False End Sub Public Property MaTuyen() Get Return _MaTuyen End Get Set(ByVal value) _MaTuyen = value End Set End Property Public Property MaNhanVien() Get Return _MaNhanVien End Get Set(ByVal value) _MaNhanVien = value End Set End Property Public Property ThoiDiemKhoiHanh() Get Return _ThoiDiemKhoiHanh End Get Set(ByVal value) _ThoiDiemKhoiHanh = value End Set End Property Public Property ThuHai() Get Return _ThuHai End Get Set(ByVal value) _ThuHai = value End Set End Property Public Property ThuBa() Get Return _ThuBa End Get Set(ByVal value) _ThuBa = value End Set End Property Public Property ThuTu() Get Return _ThuTu End Get Set(ByVal value) _ThuTu = value End Set End Property Public Property ThuNam() Get Return _ThuNam End Get Set(ByVal value) _ThuNam = value End Set End Property Public Property ThuSau() Get Return _ThuSau End Get Set(ByVal value) _ThuSau = value End Set End Property Public Property ThuBay() Get Return _ThuBay End Get Set(ByVal value) _ThuBay = value End Set End Property Public Property ChuNhat() Get Return _ChuNhat End Get Set(ByVal value) _ChuNhat = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/LichTuyenDto.vb
Visual Basic .NET
gpl2
2,456
Public Class XeDto Dim _MaXe As Long Dim _SoXe As String Dim _HieuXe As String Dim _DoiXe As Integer Dim _SoChoNgoi As Integer Sub New() _MaXe = 0 _SoXe = "" _HieuXe = "" _DoiXe = 0 _SoChoNgoi = 0 End Sub Public Property MaXe() As Long Get Return Me._MaXe End Get Set(ByVal value As Long) Me._MaXe = value End Set End Property Public Property SoXe() As String Get Return Me._SoXe End Get Set(ByVal value As String) Me._SoXe = value End Set End Property Public Property HieuXe() As String Get Return Me._HieuXe End Get Set(ByVal value As String) Me._HieuXe = value End Set End Property Public Property DoiXe() As Integer Get Return Me._DoiXe End Get Set(ByVal value As Integer) Me._DoiXe = value End Set End Property Public Property SoChoNgoi() As Integer Get Return Me._SoChoNgoi End Get Set(ByVal value As Integer) Me._SoChoNgoi = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/XeDto.vb
Visual Basic .NET
gpl2
1,334
Public Class LichKhoiHanhDto Dim _MaLap As Long Dim _ThuLap As String Sub New() _MaLap = 0 _ThuLap = "" End Sub Public Property MaLap() As Long Get Return Me._MaLap End Get Set(ByVal value As Long) Me._MaLap = value End Set End Property Public Property ThuLap() As String Get Return Me._ThuLap End Get Set(ByVal value As String) Me._ThuLap = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/LichKhoiHanhDto.vb
Visual Basic .NET
gpl2
572
Public Class VeDto Dim _MaGhe As Integer Dim _MaLich As Long Dim _TinhTrang As Boolean Dim _LoaiVe As Long Sub New() _MaGhe = 0 _MaLich = 0 _TinhTrang = False _LoaiVe = 0 End Sub Public Property MaGhe() As Integer Get Return Me._MaGhe End Get Set(ByVal value As Integer) Me._MaGhe = value End Set End Property Public Property MaLich() As Long Get Return Me._MaLich End Get Set(ByVal value As Long) Me._MaLich = value End Set End Property Public Property TinhTrang() As Boolean Get Return Me._TinhTrang End Get Set(ByVal value As Boolean) Me._TinhTrang = value End Set End Property Public Property LoaiVe() As Long Get Return Me._LoaiVe End Get Set(ByVal value As Long) Me._LoaiVe = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/VeDto.vb
Visual Basic .NET
gpl2
1,096
Public Class NhanVienDto Dim _MaNhanVien As Integer Dim _TenDangNhap As String Dim _MatKhau As String Dim _HoTen As String Dim _NgaySinh As Date Dim _GioiTinh As Integer Dim _DiaChi As String Dim _DienThoai As String Dim _LoaiNhanVien As Integer Sub New() _MaNhanVien = 0 _TenDangNhap = "" _MatKhau = "" _HoTen = "" _DiaChi = "" _DienThoai = "" _LoaiNhanVien = -1 _GioiTinh = 0 _NgaySinh = New DateTime(1, 1, 1) End Sub Public Property MaNhanVien() Get Return _MaNhanVien End Get Set(ByVal value) _MaNhanVien = value End Set End Property Public Property TenDangNhap() Get Return _TenDangNhap End Get Set(ByVal value) _TenDangNhap = value End Set End Property Public Property MatKhau() Get Return _MatKhau End Get Set(ByVal value) _MatKhau = value End Set End Property Public Property HoTen() Get Return _HoTen End Get Set(ByVal value) _HoTen = value End Set End Property Public Property NgaySinh() As Date Get Return _NgaySinh End Get Set(ByVal value As Date) _NgaySinh = value End Set End Property Public Property GioiTinh() Get Return _GioiTinh End Get Set(ByVal value) _GioiTinh = value End Set End Property Public Property DiaChi() Get Return _DiaChi End Get Set(ByVal value) _DiaChi = value End Set End Property Public Property DienThoai() Get Return _DienThoai End Get Set(ByVal value) _DienThoai = value End Set End Property Public Property LoaiNhanVien() Get Return _LoaiNhanVien End Get Set(ByVal value) _LoaiNhanVien = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/NhanVienDto.vb
Visual Basic .NET
gpl2
2,275
Public Class LoaiVeDto Dim _MaLoai As Long Dim _MaTuyen As Long Dim _GiaVe As Decimal Sub New() _MaLoai = 0 _MaTuyen = 0 _GiaVe = 0 End Sub Public Property MaLoai() As Long Get Return Me._MaLoai End Get Set(ByVal value As Long) Me._MaLoai = value End Set End Property Public Property MaTuyen() As Long Get Return Me._MaTuyen End Get Set(ByVal value As Long) Me._MaTuyen = value End Set End Property Public Property GiaVe() As Decimal Get Return Me._GiaVe End Get Set(ByVal value As Decimal) Me._GiaVe = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/LoaiVeDto.vb
Visual Basic .NET
gpl2
825
Public Class TuyenDto Dim _MaTuyeXe As Integer Dim _TenTuyenXe As String Dim _DiaDiemDi As String Dim _DiaDiemDen As String Sub New() _MaTuyeXe = 0 _TenTuyenXe = "" _DiaDiemDi = "" _DiaDiemDen = "" End Sub Public Property MaTuyenXe() Get Return _MaTuyeXe End Get Set(ByVal value) _MaTuyeXe = value End Set End Property Public Property TenTuyenXe() Get Return _TenTuyenXe End Get Set(ByVal value) _TenTuyenXe = value End Set End Property Public Property DiaDiemDi() Get Return _DiaDiemDi End Get Set(ByVal value) _DiaDiemDi = value End Set End Property Public Property DiaDiemDen() Get Return _DiaDiemDen End Get Set(ByVal value) _DiaDiemDen = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/TuyenDto.vb
Visual Basic .NET
gpl2
1,051
Public Class LichTuyenKhongLapDto Dim _MaTuyen As Integer Dim _MaNhanVien As Integer Dim _ThoiDiemKhoiHanh As String Dim _NgayKhoiHanh As Date Sub New() _MaTuyen = 0 _MaNhanVien = 0 _ThoiDiemKhoiHanh = "00:00 AM" _NgayKhoiHanh = New DateTime(1, 1, 1) End Sub Public Property MaTuyen() Get Return _MaTuyen End Get Set(ByVal value) _MaTuyen = value End Set End Property Public Property MaNhanVien() Get Return _MaNhanVien End Get Set(ByVal value) _MaNhanVien = value End Set End Property Public Property ThoiDiemKhoiHanh() Get Return _ThoiDiemKhoiHanh End Get Set(ByVal value) _ThoiDiemKhoiHanh = value End Set End Property Public Property NgayKhoiHanh() Get Return _NgayKhoiHanh End Get Set(ByVal value) _NgayKhoiHanh = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/LichTuyenKhongLapDto.vb
Visual Basic .NET
gpl2
1,131
Public Class LichGanLapDto Dim _MaLichGan As Long Dim _ThuHai As Boolean Dim _ThuBa As Boolean Dim _ThuTu As Boolean Dim _ThuNam As Boolean Dim _ThuSau As Boolean Dim _ThuBay As Boolean Dim _ChuNhat As Boolean Sub New() _MaLichGan = 0 _ThuHai = False _ThuBa = False _ThuTu = False _ThuNam = False _ThuSau = False _ThuBay = False _ChuNhat = False End Sub Public Property MaLichGan() As Long Get Return _MaLichGan End Get Set(ByVal value As Long) _MaLichGan = value End Set End Property Public Property ThuHai() As Boolean Get Return _ThuHai End Get Set(ByVal value As Boolean) _ThuHai = value End Set End Property Public Property ThuBa() As Boolean Get Return _ThuBa End Get Set(ByVal value As Boolean) _ThuBa = value End Set End Property Public Property ThuTu() As Boolean Get Return _ThuTu End Get Set(ByVal value As Boolean) _ThuTu = value End Set End Property Public Property ThuNam() As Boolean Get Return _ThuNam End Get Set(ByVal value As Boolean) _ThuNam = value End Set End Property Public Property ThuSau() As Boolean Get Return _ThuSau End Get Set(ByVal value As Boolean) _ThuSau = value End Set End Property Public Property ThuBay() As Boolean Get Return _ThuBay End Get Set(ByVal value As Boolean) _ThuBay = value End Set End Property Public Property ChuNhat() As Boolean Get Return _ChuNhat End Get Set(ByVal value As Boolean) _ChuNhat = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/LichGanLapDto.vb
Visual Basic .NET
gpl2
2,103
Public Class LichGanDto Dim _MaLichGan As Long Dim _MaTuyen As Long Dim _ThoiDiemKhoiHanh As String Dim _NgayKhoiHanh As Date Dim _MaXe As Long Dim _MaNV As Long Sub New() _MaLichGan = 0 _MaTuyen = 0 _ThoiDiemKhoiHanh = Convert.ToDateTime("0:0") _NgayKhoiHanh = "1/1/111" _MaXe = 0 _MaNV = 0 End Sub Public Property MaLichGan() As Long Get Return Me._MaLichGan End Get Set(ByVal value As Long) Me._MaLichGan = value End Set End Property Public Property MaTuyen() As Long Get Return Me._MaTuyen End Get Set(ByVal value As Long) Me._MaTuyen = value End Set End Property Public Property ThoiDiemKhoiHanh() As String Get Return Me._ThoiDiemKhoiHanh End Get Set(ByVal value As String) Me._ThoiDiemKhoiHanh = value End Set End Property Public Property NgayKhoiHanh() As Date Get Return Me._NgayKhoiHanh End Get Set(ByVal value As Date) Me._NgayKhoiHanh = value End Set End Property Public Property MaXe() As Long Get Return Me._MaXe End Get Set(ByVal value As Long) Me._MaXe = value End Set End Property Public Property MaNhanVien() As Long Get Return Me._MaNV End Get Set(ByVal value As Long) Me._MaNV = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/DTO/LichGanDto.vb
Visual Basic .NET
gpl2
1,679
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("BUS")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("BUS")> <Assembly: AssemblyCopyright("Copyright © 2010")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("55bc6486-e938-45f7-a30a-7fad4fa87009")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/My Project/AssemblyInfo.vb
Visual Basic .NET
gpl2
1,159
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class VeBus
 Shared dao As New VeDao Public Shared Function LayDanhSachVe() As DataTable Return dao.LayDanhSachVe() End Function Public Shared Function TimVe(ByVal ve As VeDto) As DataTable Return dao.TimVe(ve) End Function Public Shared Function TimVeTheoMaLichGan(ByVal maLichGan As Integer) As DataTable Return dao.TimVeTheoMaLichGan(maLichGan) End Function Public Shared Function ThemVe(ByVal ve As VeDto) As Integer Return dao.ThemVe(ve) End Function Public Shared Function CapNhatVe(ByVal ve As VeDto) As Integer Return dao.CapNhatVe(ve) End Function Public Shared Function XoaVe(ByVal maCanXoa As Long) As Integer 'Return dao.XoaVe(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/VeBus.vb
Visual Basic .NET
gpl2
895
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LoaiVeBus
 Shared dao As New LoaiVeDao Public Shared Function LayDanhSachLoaiVe() As DataTable Return dao.LayDanhSachLoaiVe() End Function Public Shared Function LayDanhSachLoaiVeTheoMaTuyen(ByVal maTuyen As Long) As DataTable Return dao.LayDanhSachLoaiVeTheoMaTuyen(maTuyen) End Function Public Shared Function ThemLoaiVe(ByVal loaive As LoaiVeDto) As Integer Return dao.ThemLoaiVe(loaive) End Function Public Shared Function CapNhatLoaiVe(ByVal loaive As LoaiVeDto) As Integer Return dao.CapNhatLoaiVe(loaive) End Function Public Shared Function XoaLoaiVe(ByVal maCanXoa As Long) As Integer Return dao.XoaLoaiVe(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/LoaiVeBus.vb
Visual Basic .NET
gpl2
853
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LichGanLapBus Shared dao As New LichGanLapDao Public Shared Function LayDanhSachXeDuocLap() As DataTable Return dao.LayDanhSachXeDuocLap() End Function Public Shared Function LayLichGanLap(ByVal maLichGan As Long) As DataTable Return dao.LayLichGanLap(maLichGan) End Function Public Shared Function ThemMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer Return dao.ThemMotLichGanLap(lgLap) End Function Public Shared Function CapNhatMotLichGanLap(ByVal lgLap As LichGanLapDto) As Integer Return dao.CapNhatMotLichGanLap(lgLap) End Function Public Shared Function XoaMotLichGanLap(ByVal maLichGan As Long) As Integer Return dao.XoaMotLichGanLap(maLichGan) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/LichGanLapBus.vb
Visual Basic .NET
gpl2
886
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LichGanBus
 Shared dao As New LichGanDao Public Shared Function LayDanhSachLichGan() As DataTable Return dao.LayDanhSachLichGan() End Function Public Shared Function TimLichGan(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal thoiDiemKhoiHanh As String, ByVal maXe As Long) As DataTable Return dao.TimLichGan(maTuyen, ngayKhoiHanh, thoiDiemKhoiHanh, maXe) End Function Public Shared Function TimLichGanTheoMa(ByVal maCanTim As Integer) As DataTable Return dao.TimLichGanTheoMa(maCanTim) End Function Public Shared Function ThemMotLichGan(ByVal lg As LichGanDto) As Integer Return dao.ThemMotLichGan(lg) End Function Public Shared Function ThemLichGan(ByVal lg As LichGanDto) As Integer Return dao.ThemMotLichGan(lg) End Function Public Shared Function CapNhatLichGan(ByVal lg As LichGanDto) As Integer Return dao.CapNhatLichGan(lg) End Function Public Shared Function XoaMotLichGan(ByVal maCanXoa As Long) As Integer Return dao.XoaMotLichGan(maCanXoa) End Function 'Tìm ngày khởi hành Public Shared Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable Return dao.TimNgayKhoiHanh(maTuyen) End Function 'Tìm giờ khởi hành Public Shared Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable Return dao.TimThoiDiemKhoiHanh(maTuyen, ngayKhoiHanh) End Function 'Lấy danh sách xe đang Public Shared Function DanhSachXeDangRanh(ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable Return dao.DanhSachXeDangRanh(ngayKhoiHanh, ThoiDiemKhoiHanh) End Function 'Lấy mã lịch gán vừa thêm vào Public Shared Function LayMaLichGanVuaThem() As Long Return dao.LayMaLichGanVuaThem() End Function 'Bán vé... 'Tìm xe theo tuyến, thời điểm Public Shared Function DanhSachXe_TheoTuyen_ThoiDiem(ByVal maTuyen As Long, ByVal ngayKhoiHanh As Date, ByVal ThoiDiemKhoiHanh As String) As DataTable Return dao.DanhSachXe_TheoTuyen_ThoiDiem(maTuyen, ngayKhoiHanh, ThoiDiemKhoiHanh) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/LichGanBus.vb
Visual Basic .NET
gpl2
2,377
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class ChungBus
 Shared dao As New CHUNG 'Public Function KiemTraKetNoi_CSDL_CoDuocKhong() As String ' Dim loiKetNoi As String = "" ' If provider.Connect Is Nothing Then ' loiKetNoi = "Không tìm thấy cơ sở dữ liệu!!!" ' End If ' Return loiKetNoi 'End Function Public Shared Function LayDanhSach() As DataTable Return dao.LayDanhSach() End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/ChungBus.vb
Visual Basic .NET
gpl2
539
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class XeBus
 Shared dao As New XeDao Public Shared Function LayDanhSachXe() As DataTable Return dao.LayDanhSachXe() End Function Public Shared Function TimXe(ByVal xe As XeDto) As DataTable Return dao.TimXe(xe) End Function Public Shared Function TimXeTheoMaXe(ByVal maXe As Integer) As DataTable Return dao.TimXeTheoMaXe(maXe) End Function Public Shared Function LaySoChoNgoi_TheoMaXe(ByVal maXe As Integer) As Integer Return dao.LaySoChoNgoi_TheoMaXe(maXe) End Function Public Shared Function ThemXe(ByVal xe As XeDto) As Integer Return dao.ThemXe(xe) End Function Public Shared Function CapNhatXe(ByVal xe As XeDto) As Integer Return dao.CapNhatXe(xe) End Function Public Shared Function XoaXe(ByVal maCanXoa As Long) As Integer Return dao.XoaXe(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/XeBus.vb
Visual Basic .NET
gpl2
1,026
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class NhanVienBus Shared dao As New NhanVienDao Public Shared Function LayNguoiDangNhap(ByVal tenDangNhap As String, ByVal matKhau As String) As Integer Return dao.LayNguoiDangNhap(tenDangNhap, matKhau) End Function Public Shared Function LayNguoiDung(ByVal tenDangNhap As String, ByVal matKhau As String) As DataTable Return dao.LayNguoiDung(tenDangNhap, matKhau) End Function Public Shared Function LayNguoiDungTheoMa(ByVal maNhanVien As Long) As DataTable Return dao.LayNguoiDungTheoMa(maNhanVien) End Function Public Shared Function LayNguoiDung() As DataTable Return dao.LayNguoiDung() End Function Public Shared Function LayQuyen() As DataTable Return dao.LayQuyen() End Function Public Shared Function LayDanhSachNguoiDung() As DataTable Return dao.LayDanhSachNguoiDung() End Function Public Shared Function ThemNhanVien(ByVal nhanVien As NhanVienDto) As Integer Return dao.ThemNhanVien(nhanVien) End Function Public Shared Function CapNhatNhanVien(ByVal nhanVien As NhanVienDto) As Integer Return dao.CapNhatNhanVien(nhanVien) End Function Public Shared Function TimKiemNhanVien(ByVal nhanVien As NhanVienDto) As DataTable Return dao.TimKiemNhanVien(nhanVien) End Function Public Shared Function XoaNhanVien(ByVal nhanVien As NhanVienDto) As String Return dao.XoaNhanVien(nhanVien) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/NhanVienBus.vb
Visual Basic .NET
gpl2
1,606
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class XL_Chung 
 Shared dao As New XL_Chung_dao Public Shared Function TimNgayKhoiHanh(ByVal maTuyen As Integer) As DataTable Return dao.TimNgayKhoiHanh(maTuyen) End Function Public Shared Function TimThoiDiemKhoiHanh(ByVal maTuyen As Integer, ByVal ngayKhoiHanh As Date) As DataTable Return dao.TimThoiDiemKhoiHanh(maTuyen, ngayKhoiHanh) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/XL_Chung.vb
Visual Basic .NET
gpl2
500
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class LichTuyenBus Shared daoLichTuyen As New LichTuyenLapDao Shared daoLichTuyenKhongLap As New LichTuyenKhongLapDao Public Shared Function LayDanhSachLichTuyen() As DataTable Return daoLichTuyen.LayDanhSachLichTuyenLap() End Function Public Shared Function LayDanhSachLichTuyenLapThu() As DataTable Return daoLichTuyen.LayDanhSachLichTuyenLapThu() End Function Public Shared Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenDto) As Integer Return daoLichTuyen.ThemThoiDiemKhoiHanh(thoiDiem) End Function Public Shared Function CapNhatThoiDiemKhoiHanh(ByRef data As DataTable) As Integer Return daoLichTuyen.CapNhatThoiDiemKhoiHanh(data) End Function Public Shared Function CapNhatThuLap(ByVal data As DataRow) As Integer Return daoLichTuyen.CapNhatThuLap(data) End Function Public Shared Function XoaThoiDiemKhoiHanh(ByVal data As DataRow) As Integer Return daoLichTuyen.XoaThoiDiemKhoiHanh(data) End Function Public Shared Function LayDanhSachLichTuyenKhongLap() As DataTable Return daoLichTuyenKhongLap.LayDanhSachLichTuyenKhongLap() End Function Public Shared Function LayDanhSachLichTuyenKhongLapThoiDiem() As DataTable Return daoLichTuyenKhongLap.LayDanhSachLichTuyenKhongLapThoiDiem() End Function Public Shared Function ThemThoiDiemKhoiHanh(ByVal thoiDiem As LichTuyenKhongLapDto) As Integer Return daoLichTuyenKhongLap.ThemThoiDiemKhoiHanh(thoiDiem) End Function Public Shared Function CapNhatThoiDiemKhoiHanhKhongLap(ByRef data As DataTable) As Integer Return daoLichTuyenKhongLap.CapNhatThoiDiemKhoiHanh(data) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/LichTuyenBus.vb
Visual Basic .NET
gpl2
1,851
Imports System.Data Imports System.Data.OleDb Imports DAO Imports DTO Public Class TuyenBus Shared dao As New TuyenDao Public Shared Function LayDanhSachTuyen() As DataTable Return dao.LayDanhSachTuyen() End Function Public Shared Function TimTuyen(ByVal tuyen As TuyenDto) As DataTable Return dao.TimTuyen(tuyen) End Function Public Shared Function TimTuyenTheoMaTuyen(ByVal maTuyen As Integer) As DataTable Return dao.TimTuyenTheoMaTuyen(maTuyen) End Function Public Shared Function ThemTuyen(ByVal tuyen As TuyenDto) As Integer Return dao.ThemTuyen(tuyen) End Function Public Shared Function CapNhatTuyen(ByVal tuyen As TuyenDto) As Integer Return dao.CapNhatTuyen(tuyen) End Function Public Shared Function XoaTuyen(ByVal maCanXoa As Long) As Integer Return dao.XoaTuyen(maCanXoa) End Function End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/BUS/TuyenBus.vb
Visual Basic .NET
gpl2
955
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("DTO")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("DTO")> <Assembly: AssemblyCopyright("Copyright © 2010")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("84ab580b-e875-4d64-89f9-64f5640d4f9d")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/My Project/AssemblyInfo.vb
Visual Basic .NET
gpl2
1,159
Public Class LichTuyenDto Dim _MaTuyen As Integer Dim _MaNhanVien As Integer Dim _ThoiDiemKhoiHanh As String Dim _ThuHai As Boolean Dim _ThuBa As Boolean Dim _ThuTu As Boolean Dim _ThuNam As Boolean Dim _ThuSau As Boolean Dim _ThuBay As Boolean Dim _ChuNhat As Boolean Sub New() _MaTuyen = 0 _MaNhanVien = 0 _ThoiDiemKhoiHanh = "00:00" _ThuHai = False _ThuBa = False _ThuTu = False _ThuNam = False _ThuSau = False _ThuBay = False _ChuNhat = False End Sub Public Property MaTuyen() Get Return _MaTuyen End Get Set(ByVal value) _MaTuyen = value End Set End Property Public Property MaNhanVien() Get Return _MaNhanVien End Get Set(ByVal value) _MaNhanVien = value End Set End Property Public Property ThoiDiemKhoiHanh() Get Return _ThoiDiemKhoiHanh End Get Set(ByVal value) _ThoiDiemKhoiHanh = value End Set End Property Public Property ThuHai() Get Return _ThuHai End Get Set(ByVal value) _ThuHai = value End Set End Property Public Property ThuBa() Get Return _ThuBa End Get Set(ByVal value) _ThuBa = value End Set End Property Public Property ThuTu() Get Return _ThuTu End Get Set(ByVal value) _ThuTu = value End Set End Property Public Property ThuNam() Get Return _ThuNam End Get Set(ByVal value) _ThuNam = value End Set End Property Public Property ThuSau() Get Return _ThuSau End Get Set(ByVal value) _ThuSau = value End Set End Property Public Property ThuBay() Get Return _ThuBay End Get Set(ByVal value) _ThuBay = value End Set End Property Public Property ChuNhat() Get Return _ChuNhat End Get Set(ByVal value) _ChuNhat = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/LichTuyenDto.vb
Visual Basic .NET
gpl2
2,456
Public Class XeDto Dim _MaXe As Long Dim _SoXe As String Dim _HieuXe As String Dim _DoiXe As Integer Dim _SoChoNgoi As Integer Sub New() _MaXe = 0 _SoXe = "" _HieuXe = "" _DoiXe = 0 _SoChoNgoi = 0 End Sub Public Property MaXe() As Long Get Return Me._MaXe End Get Set(ByVal value As Long) Me._MaXe = value End Set End Property Public Property SoXe() As String Get Return Me._SoXe End Get Set(ByVal value As String) Me._SoXe = value End Set End Property Public Property HieuXe() As String Get Return Me._HieuXe End Get Set(ByVal value As String) Me._HieuXe = value End Set End Property Public Property DoiXe() As Integer Get Return Me._DoiXe End Get Set(ByVal value As Integer) Me._DoiXe = value End Set End Property Public Property SoChoNgoi() As Integer Get Return Me._SoChoNgoi End Get Set(ByVal value As Integer) Me._SoChoNgoi = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/XeDto.vb
Visual Basic .NET
gpl2
1,334
Public Class LichKhoiHanhDto Dim _MaLap As Long Dim _ThuLap As String Sub New() _MaLap = 0 _ThuLap = "" End Sub Public Property MaLap() As Long Get Return Me._MaLap End Get Set(ByVal value As Long) Me._MaLap = value End Set End Property Public Property ThuLap() As String Get Return Me._ThuLap End Get Set(ByVal value As String) Me._ThuLap = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/LichKhoiHanhDto.vb
Visual Basic .NET
gpl2
572
Public Class VeDto Dim _MaGhe As Integer Dim _MaLich As Long Dim _TinhTrang As Boolean Dim _LoaiVe As Long Sub New() _MaGhe = 0 _MaLich = 0 _TinhTrang = False _LoaiVe = 0 End Sub Public Property MaGhe() As Integer Get Return Me._MaGhe End Get Set(ByVal value As Integer) Me._MaGhe = value End Set End Property Public Property MaLich() As Long Get Return Me._MaLich End Get Set(ByVal value As Long) Me._MaLich = value End Set End Property Public Property TinhTrang() As Boolean Get Return Me._TinhTrang End Get Set(ByVal value As Boolean) Me._TinhTrang = value End Set End Property Public Property LoaiVe() As Long Get Return Me._LoaiVe End Get Set(ByVal value As Long) Me._LoaiVe = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/VeDto.vb
Visual Basic .NET
gpl2
1,096
Public Class NhanVienDto Dim _MaNhanVien As Integer Dim _TenDangNhap As String Dim _MatKhau As String Dim _HoTen As String Dim _NgaySinh As Date Dim _GioiTinh As Integer Dim _DiaChi As String Dim _DienThoai As String Dim _LoaiNhanVien As Integer Sub New() _MaNhanVien = 0 _TenDangNhap = "" _MatKhau = "" _HoTen = "" _DiaChi = "" _DienThoai = "" _LoaiNhanVien = -1 _GioiTinh = 0 _NgaySinh = New DateTime(1, 1, 1) End Sub Public Property MaNhanVien() Get Return _MaNhanVien End Get Set(ByVal value) _MaNhanVien = value End Set End Property Public Property TenDangNhap() Get Return _TenDangNhap End Get Set(ByVal value) _TenDangNhap = value End Set End Property Public Property MatKhau() Get Return _MatKhau End Get Set(ByVal value) _MatKhau = value End Set End Property Public Property HoTen() Get Return _HoTen End Get Set(ByVal value) _HoTen = value End Set End Property Public Property NgaySinh() As Date Get Return _NgaySinh End Get Set(ByVal value As Date) _NgaySinh = value End Set End Property Public Property GioiTinh() Get Return _GioiTinh End Get Set(ByVal value) _GioiTinh = value End Set End Property Public Property DiaChi() Get Return _DiaChi End Get Set(ByVal value) _DiaChi = value End Set End Property Public Property DienThoai() Get Return _DienThoai End Get Set(ByVal value) _DienThoai = value End Set End Property Public Property LoaiNhanVien() Get Return _LoaiNhanVien End Get Set(ByVal value) _LoaiNhanVien = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/NhanVienDto.vb
Visual Basic .NET
gpl2
2,275
Public Class LoaiVeDto Dim _MaLoai As Long Dim _MaTuyen As Long Dim _GiaVe As Decimal Sub New() _MaLoai = 0 _MaTuyen = 0 _GiaVe = 0 End Sub Public Property MaLoai() As Long Get Return Me._MaLoai End Get Set(ByVal value As Long) Me._MaLoai = value End Set End Property Public Property MaTuyen() As Long Get Return Me._MaTuyen End Get Set(ByVal value As Long) Me._MaTuyen = value End Set End Property Public Property GiaVe() As Decimal Get Return Me._GiaVe End Get Set(ByVal value As Decimal) Me._GiaVe = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/LoaiVeDto.vb
Visual Basic .NET
gpl2
825
Public Class TuyenDto Dim _MaTuyeXe As Integer Dim _TenTuyenXe As String Dim _DiaDiemDi As String Dim _DiaDiemDen As String Sub New() _MaTuyeXe = 0 _TenTuyenXe = "" _DiaDiemDi = "" _DiaDiemDen = "" End Sub Public Property MaTuyenXe() Get Return _MaTuyeXe End Get Set(ByVal value) _MaTuyeXe = value End Set End Property Public Property TenTuyenXe() Get Return _TenTuyenXe End Get Set(ByVal value) _TenTuyenXe = value End Set End Property Public Property DiaDiemDi() Get Return _DiaDiemDi End Get Set(ByVal value) _DiaDiemDi = value End Set End Property Public Property DiaDiemDen() Get Return _DiaDiemDen End Get Set(ByVal value) _DiaDiemDen = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/TuyenDto.vb
Visual Basic .NET
gpl2
1,051
Public Class LichTuyenKhongLapDto Dim _MaTuyen As Integer Dim _MaNhanVien As Integer Dim _ThoiDiemKhoiHanh As String Dim _NgayKhoiHanh As Date Sub New() _MaTuyen = 0 _MaNhanVien = 0 _ThoiDiemKhoiHanh = "00:00 AM" _NgayKhoiHanh = New DateTime(1, 1, 1) End Sub Public Property MaTuyen() Get Return _MaTuyen End Get Set(ByVal value) _MaTuyen = value End Set End Property Public Property MaNhanVien() Get Return _MaNhanVien End Get Set(ByVal value) _MaNhanVien = value End Set End Property Public Property ThoiDiemKhoiHanh() Get Return _ThoiDiemKhoiHanh End Get Set(ByVal value) _ThoiDiemKhoiHanh = value End Set End Property Public Property NgayKhoiHanh() Get Return _NgayKhoiHanh End Get Set(ByVal value) _NgayKhoiHanh = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/LichTuyenKhongLapDto.vb
Visual Basic .NET
gpl2
1,131
Public Class LichGanLapDto Dim _MaLichGan As Long Dim _ThuHai As Boolean Dim _ThuBa As Boolean Dim _ThuTu As Boolean Dim _ThuNam As Boolean Dim _ThuSau As Boolean Dim _ThuBay As Boolean Dim _ChuNhat As Boolean Sub New() _MaLichGan = 0 _ThuHai = False _ThuBa = False _ThuTu = False _ThuNam = False _ThuSau = False _ThuBay = False _ChuNhat = False End Sub Public Property MaLichGan() As Long Get Return _MaLichGan End Get Set(ByVal value As Long) _MaLichGan = value End Set End Property Public Property ThuHai() As Boolean Get Return _ThuHai End Get Set(ByVal value As Boolean) _ThuHai = value End Set End Property Public Property ThuBa() As Boolean Get Return _ThuBa End Get Set(ByVal value As Boolean) _ThuBa = value End Set End Property Public Property ThuTu() As Boolean Get Return _ThuTu End Get Set(ByVal value As Boolean) _ThuTu = value End Set End Property Public Property ThuNam() As Boolean Get Return _ThuNam End Get Set(ByVal value As Boolean) _ThuNam = value End Set End Property Public Property ThuSau() As Boolean Get Return _ThuSau End Get Set(ByVal value As Boolean) _ThuSau = value End Set End Property Public Property ThuBay() As Boolean Get Return _ThuBay End Get Set(ByVal value As Boolean) _ThuBay = value End Set End Property Public Property ChuNhat() As Boolean Get Return _ChuNhat End Get Set(ByVal value As Boolean) _ChuNhat = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/LichGanLapDto.vb
Visual Basic .NET
gpl2
2,103
Public Class LichGanDto Dim _MaLichGan As Long Dim _MaTuyen As Long Dim _ThoiDiemKhoiHanh As String Dim _NgayKhoiHanh As Date Dim _MaXe As Long Dim _MaNV As Long Sub New() _MaLichGan = 0 _MaTuyen = 0 _ThoiDiemKhoiHanh = Convert.ToDateTime("0:0") _NgayKhoiHanh = "1/1/111" _MaXe = 0 _MaNV = 0 End Sub Public Property MaLichGan() As Long Get Return Me._MaLichGan End Get Set(ByVal value As Long) Me._MaLichGan = value End Set End Property Public Property MaTuyen() As Long Get Return Me._MaTuyen End Get Set(ByVal value As Long) Me._MaTuyen = value End Set End Property Public Property ThoiDiemKhoiHanh() As String Get Return Me._ThoiDiemKhoiHanh End Get Set(ByVal value As String) Me._ThoiDiemKhoiHanh = value End Set End Property Public Property NgayKhoiHanh() As Date Get Return Me._NgayKhoiHanh End Get Set(ByVal value As Date) Me._NgayKhoiHanh = value End Set End Property Public Property MaXe() As Long Get Return Me._MaXe End Get Set(ByVal value As Long) Me._MaXe = value End Set End Property Public Property MaNhanVien() As Long Get Return Me._MaNV End Get Set(ByVal value As Long) Me._MaNV = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/DTO/LichGanDto.vb
Visual Basic .NET
gpl2
1,679
Imports System.Data.OleDb Imports BUS Imports DTO Public Class frmQuanLyNhanVien Dim vtClick As Integer = 0 Dim dtNHANVIEN As DataTable Dim flagInsert As Boolean Private Sub frmQuanLy_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cbxLoaiNguoiDung.SelectedIndex = 0 Try If sessionNhanVien.LoaiNhanVien = 0 Then dgvNhanVien.DataSource = NhanVienBus.LayNguoiDungTheoMa(sessionNhanVien.MaNhanVien) Else dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung() End If Dim nhanVien As New NhanVienDto nhanVien = LayNguoiDung_DataGridView(0) HienThiLenTextboxs(nhanVien) Catch ex As Exception MessageBox.Show(ex.Message) End Try If sessionNhanVien.LoaiNhanVien = 0 Then txtTenDangNhap.Enabled = False btnThem.Enabled = False btnXoa.Enabled = False End If End Sub Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click dgvNhanVien.Rows(0).Selected = False dgvNhanVien.Rows(dgvNhanVien.Rows.Count - 1).Selected = True If (dgvNhanVien.Rows(dgvNhanVien.Rows.Count - 1).Selected = True) Then 'ResetTextboxs() End If Dim kt As String = KiemTra_NhapLieu_Them() If (kt <> "") Then MessageBox.Show(kt, "Thong bao") Exit Sub End If Dim kq As Integer = NhanVienBus.ThemNhanVien(Me.NhapNhanVien()) If (kq = 0) Then MessageBox.Show("đã có trong dữ liệu", "Thông báo") Else dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung() dgvNhanVien.Rows(dgvNhanVien.Rows.Count - 1).Selected = True Dim nhanVien As NhanVienDto = LayNguoiDung_DataGridView(dgvNhanVien.Rows.Count - 2) HienThiLenTextboxs(nhanVien) End If End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Close() End Sub Public Sub ResetTextboxs() txtMaNhanVien.Text = "" txtTenDangNhap.Text = "" txtMatKhau.Text = "" txtHoTen.Text = "" txtDiaChi.Text = "" txtDienThoai.Text = "" End Sub Public Sub HienThiLenTextboxs(ByVal nhanVien As NhanVienDto) txtMaNhanVien.Text = nhanVien.MaNhanVien txtTenDangNhap.Text = nhanVien.TenDangNhap txtMatKhau.Text = nhanVien.MatKhau txtHoTen.Text = nhanVien.HoTen dtpNgaySinh.Value = nhanVien.NgaySinh.Date If (nhanVien.GioiTinh = 1) Then rdbNu.Checked = True Else rdbNam.Checked = True End If txtDiaChi.Text = nhanVien.DiaChi txtDienThoai.Text = nhanVien.DienThoai cbxLoaiNguoiDung.SelectedIndex = nhanVien.LoaiNhanVien End Sub Public Sub xl_Button(ByVal b As Boolean) btnThem.Enabled = b btnXoa.Enabled = b btnSua.Enabled = b btnTim.Enabled = Not b End Sub Public Function NhapNhanVien() As NhanVienDto Dim nhanVien As New NhanVienDto If IsNumeric(txtMaNhanVien.Text) Then nhanVien.MaNhanVien = txtMaNhanVien.Text End If nhanVien.TenDangNhap = txtTenDangNhap.Text nhanVien.MatKhau = txtMatKhau.Text nhanVien.HoTen = txtHoTen.Text nhanVien.NgaySinh = dtpNgaySinh.Value If rdbNu.Checked = True Then nhanVien.GioiTinh = 1 Else nhanVien.GioiTinh = 0 End If nhanVien.DiaChi = txtDiaChi.Text nhanVien.DienThoai = txtDienThoai.Text nhanVien.LoaiNhanVien = cbxLoaiNguoiDung.SelectedIndex Return nhanVien End Function Private Sub dgvNhanVien_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvNhanVien.MouseClick vtClick = dgvNhanVien.CurrentRow.Index If vtClick = dgvNhanVien.Rows.Count - 1 Then ResetTextboxs() Exit Sub End If Try Dim nhanVien As NhanVienDto nhanVien = LayNguoiDung_DataGridView(vtClick) HienThiLenTextboxs(nhanVien) Catch ex As Exception End Try End Sub Public Function LayNguoiDung_DataGridView(ByVal vtdong As Integer) As NhanVienDto Dim nhanVien As New NhanVienDto nhanVien.MaNhanVien = dgvNhanVien.Rows(vtdong).Cells("MaNhanVien").Value nhanVien.TenDangNhap = dgvNhanVien.Rows(vtdong).Cells("TenDangNhap").Value nhanVien.MatKhau = dgvNhanVien.Rows(vtdong).Cells("MatKhau").Value nhanVien.HoTen = dgvNhanVien.Rows(vtdong).Cells("HoTen").Value nhanVien.NgaySinh = dgvNhanVien.Rows(vtdong).Cells("NgaySinh").Value Dim phai As String = dgvNhanVien.Rows(vtdong).Cells("Phai").Value If (phai = "Nam") Then nhanVien.GioiTinh = 0 Else nhanVien.GioiTinh = 1 End If nhanVien.DiaChi = dgvNhanVien.Rows(vtdong).Cells("DiaChi").Value nhanVien.DienThoai = dgvNhanVien.Rows(vtdong).Cells("DienThoai").Value nhanVien.LoaiNhanVien = dgvNhanVien.Rows(vtdong).Cells("LoaiNhanVien").Value Return nhanVien End Function Public Function KiemTra_NhapLieu_Them() As String Dim str As String = "" If KT_TenDangNhap(txtTenDangNhap.Text) <> "" Then str = KT_TenDangNhap(txtTenDangNhap.Text) txtTenDangNhap.Focus() Return str ElseIf KT_MatKhau(txtMatKhau.Text) <> "" Then str = KT_MatKhau(txtMatKhau.Text) txtMatKhau.Focus() Return str ElseIf txtHoTen.Text = "" Then str = "Ho ten khong duoc rong !!" txtHoTen.Focus() Return str ElseIf txtDienThoai.Text = "" Then ' str = "Điện thoại không được rỗng !!" 'txtDienThoai.Focus() 'Return str ElseIf txtDiaChi.Text = "" Then str = "Địa chỉ không được rỗng !!" txtDiaChi.Focus() Return str End If Return str End Function Private Sub dgvNhanVien_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvNhanVien.SelectionChanged vtClick = dgvNhanVien.CurrentRow.Index If vtClick = dgvNhanVien.Rows.Count - 1 Then 'ResetTextboxs() Exit Sub End If Try Dim nhanVien As NhanVienDto nhanVien = LayNguoiDung_DataGridView(vtClick) HienThiLenTextboxs(nhanVien) Catch ex As Exception End Try End Sub Private Sub btnTim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTim.Click Dim nhanVien As New NhanVienDto nhanVien.TenDangNhap = txtTenDangNhap.Text nhanVien.HoTen = txtHoTen.Text nhanVien.DienThoai = txtDienThoai.Text If rdbNam.Checked = True Then nhanVien.GioiTinh = 0 ElseIf rdbNu.Checked = True Then nhanVien.GioiTinh = 1 End If dgvNhanVien.DataSource = NhanVienBus.TimKiemNhanVien(nhanVien) End Sub Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click If vtClick = 0 Then ResetTextboxs() End If If vtClick = dgvNhanVien.Rows.Count - 1 Then MessageBox.Show("Chọn dòng có dữ liệu cần xoá !!", "Thông báo") Exit Sub End If Dim nhanVien As New NhanVienDto nhanVien.MaNhanVien = dgvNhanVien.Rows(vtClick).Cells("MaNhanVien").Value NhanVienBus.XoaNhanVien(nhanVien) dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung() nhanVien = LayNguoiDung_DataGridView(0) HienThiLenTextboxs(nhanVien) End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click If vtClick = dgvNhanVien.Rows.Count - 1 Then MessageBox.Show("Chọn dòng dữ liệu cần sửa !!", "Thông báo") Exit Sub End If Dim nhanVien As New NhanVienDto nhanVien = NhapNhanVien() NhanVienBus.CapNhatNhanVien(nhanVien) If sessionNhanVien.LoaiNhanVien = 0 Then dgvNhanVien.DataSource = NhanVienBus.LayNguoiDungTheoMa(sessionNhanVien.MaNhanVien) Else dgvNhanVien.DataSource = NhanVienBus.LayDanhSachNguoiDung() End If nhanVien = LayNguoiDung_DataGridView(0) HienThiLenTextboxs(nhanVien) End Sub End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/frmQuanLyNhanVien.vb
Visual Basic .NET
gpl2
9,057
Public Class sessionNhanVien Shared _maNhanVien As Long Shared _loaiNhanVien As Integer Public Shared Property MaNhanVien() As Long Get Return _maNhanVien End Get Set(ByVal value As Long) _maNhanVien = value End Set End Property Public Shared Property LoaiNhanVien() As Integer Get Return _loaiNhanVien End Get Set(ByVal value As Integer) _loaiNhanVien = value End Set End Property End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/sessionNhanVien.vb
Visual Basic .NET
gpl2
555
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("GiaoDien")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("GiaoDien")> <Assembly: AssemblyCopyright("Copyright © 2010")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("06b73687-555f-488a-8489-25e993fd1587")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/My Project/AssemblyInfo.vb
Visual Basic .NET
gpl2
1,169
Imports System.Data.OleDb Imports BUS Imports DTO Public Class frmBanVe Private Sub frmBanVe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cbxTuyenXe.DataSource = TuyenBus.LayDanhSachTuyen() cbxTuyenXe.DisplayMember = "TenTuyen" cbxTuyenXe.ValueMember = "MaTuyen" End Sub Private Sub cbxTuyenXe_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxTuyenXe.SelectedIndexChanged cbxNgayKhoiHanh.Text = "" cbxTuyenXe.ValueMember = "MaTuyen" Dim maTuyen As Long = cbxTuyenXe.SelectedValue cbxNgayKhoiHanh.DataSource = LichGanBus.TimNgayKhoiHanh(maTuyen) cbxNgayKhoiHanh.DisplayMember = "NgayKhoiHanh" End Sub Private Sub cbxNgayKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxNgayKhoiHanh.SelectedIndexChanged, cbxNgayKhoiHanh.TextChanged cbxGioKhoiHanh.Text = "" cbxTuyenXe.ValueMember = "MaTuyen" cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh" Dim maTuyen As Long = cbxTuyenXe.SelectedValue Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue cbxGioKhoiHanh.DataSource = LichGanBus.TimThoiDiemKhoiHanh(maTuyen, ngayKH) cbxGioKhoiHanh.DisplayMember = "ThoiDiemKhoiHanh" cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh" End Sub Private Sub cbxGioKhoiHanh_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxGioKhoiHanh.SelectedIndexChanged, cbxGioKhoiHanh.TextChanged cbxTuyenXe.ValueMember = "MaTuyen" cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh" cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh" Dim maTuyen As Long = cbxTuyenXe.SelectedValue Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue Dim thoiDiemKH As String = cbxGioKhoiHanh.SelectedValue dgvXe.DataSource = LichGanBus.DanhSachXe_TheoTuyen_ThoiDiem(maTuyen, ngayKH, thoiDiemKH) End Sub Private Sub HienThiVe() cbxTuyenXe.ValueMember = "MaTuyen" cbxNgayKhoiHanh.ValueMember = "NgayKhoiHanh" cbxGioKhoiHanh.ValueMember = "ThoiDiemKhoiHanh" Dim maTuyen As Long = cbxTuyenXe.SelectedValue Dim ngayKH As Date = cbxNgayKhoiHanh.SelectedValue Dim thoiDiemKH As String = cbxGioKhoiHanh.SelectedValue Dim vitri, MaXe As Integer Try vitri = dgvXe.CurrentRow.Index MaXe = dgvXe.Rows(vitri).Cells("MaXe").Value Catch ex As Exception End Try Dim maLichGan As Long Try Dim dt As DataTable = LichGanBus.TimLichGan(maTuyen, ngayKH, thoiDiemKH, MaXe) maLichGan = dt.Rows(0).Item("MaLichGan") Catch ex As Exception '....... End Try dgvVe.DataSource = VeBus.TimVeTheoMaLichGan(maLichGan) End Sub Private Sub dgvXe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvXe.MouseClick HienThiVe() End Sub Private Sub dgvXe_DataSourceChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvXe.DataSourceChanged HienThiVe() End Sub Dim vitriClick As Integer Private Sub dgvVe_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvVe.MouseClick Try vitriClick = dgvVe.CurrentRow.Index Catch ex As Exception End Try End Sub Dim ve As New VeDto Private Sub btnBanVe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBanVe.Click Dim maGhe As Integer Dim maLichGan As Long Dim tinhTrang As Boolean If vitriClick = dgvVe.Rows.Count - 1 Then MessageBox.Show("Chọn dòng có dữ liệu!!!", "THÔNG BÁO") Exit Sub End If Try maGhe = dgvVe.Rows(vitriClick).Cells("MaGhe").Value maLichGan = dgvVe.Rows(vitriClick).Cells("MaLich").Value tinhTrang = dgvVe.Rows(vitriClick).Cells("TinhTrang").Value Catch ex As Exception MessageBox.Show("Chọn một chỗ ngồi (mã ghế)!", "THÔNG BÁO") Exit Sub End Try If tinhTrang Then MessageBox.Show("Vé này đã bán!", "THÔNG BÁO") Exit Sub End If ve.MaGhe = maGhe ve.MaLich = maLichGan ve.TinhTrang = True 'dgvVe.Columns("MaLoaiVe").Visible = False ve.LoaiVe = dgvVe.Rows(vitriClick).Cells("MaLoaiVe").Value VeBus.CapNhatVe(ve) HienThiVe() dgvVe.Rows(0).Selected = False dgvVe.Rows(vitriClick).Selected = True btnHuy.Enabled = True End Sub Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click ve.TinhTrang = False VeBus.CapNhatVe(ve) HienThiVe() dgvVe.Rows(0).Selected = False dgvVe.Rows(vitriClick).Selected = True btnHuy.Enabled = False End Sub Private Sub btnDong_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDong.Click Close() End Sub End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/frmBanVe.vb
Visual Basic .NET
gpl2
5,416
Imports System.Data.OleDb Imports BUS Imports DTO Public Class frmQuyen Dim dataset As DataSet Dim quyenBindingSource As BindingSource Dim quyenNguoiDungBindingSource As BindingSource Private Sub frmQuyen_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load LoadData() BindingSource() End Sub Public Sub LoadData() dataset = New DataSet dataset.Tables.Add(NhanVienBus.LayNguoiDung()) dataset.Tables.Add(NhanVienBus.LayQuyen()) dataset.Tables(0).TableName = "NguoiDung" dataset.Tables(1).TableName = "Quyen" quyenBindingSource.DataSource = dataset quyenBindingSource.DataMember = "Quyen" dataset.Relations.Add("QuyenNguoiDung", dataset.Tables(0).Columns("Maquyen"), dataset.Tables(1).Columns("MaQuyen")) quyenNguoiDungBindingSource.DataSource = quyenBindingSource quyenNguoiDungBindingSource.DataMember = "QuyenNguoiDung" End Sub Public Sub BindingSource() dgvQuyen.DataSource = quyenBindingSource dgvNguoiDung.DataSource = quyenNguoiDungBindingSource End Sub End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/frmQuyen.vb
Visual Basic .NET
gpl2
1,222
Imports System.Data.OleDb Imports BUS Imports DTO Public Class frmDangNhap Public kqDangNhap As Boolean = False Public Function KT_DangNhap() As Boolean Dim tenDangNhap As String = txtTenDangNhap.Text Dim matKhau As String = txtMatKhau.Text ' Dim loaiNhanVien As Integer= NhanVienBus.LayNguoiDangNhap(tenDangNhap, matKhau) Dim dt As DataTable = NhanVienBus.LayNguoiDung(tenDangNhap, matKhau) If (dt.Rows.Count = 0) Then Return False End If sessionNhanVien.MaNhanVien = dt.Rows(0).Item("MaNhanVien") sessionNhanVien.LoaiNhanVien = dt.Rows(0).Item("LoaiNhanVien") Return True 'Try ' If loaiNhanVien <> -1 Then ' ' MessageBox.Show("Đăng nhập thành công !", "Thông báo", MessageBoxButtons.OK) ' Return True ' End If 'Catch ex As Exception ' '..... 'End Try 'Return False End Function Private Sub btnDangNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDangNhap.Click kqDangNhap = KT_DangNhap() If kqDangNhap Then Close() Else txtMatKhau.Text = "" MessageBox.Show("Nhập sai tên hoặc mật khẩu!", "Thông báo", MessageBoxButtons.OK) End If End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub Private Sub frmDangNhap_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed txtTenDangNhap.Text = "" txtMatKhau.Text = "" End Sub Private Sub frmDangNhap_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/frmDangNhap.vb
Visual Basic .NET
gpl2
1,935
Imports System.Data.OleDb Imports BUS Imports DTO Public Class frmLapLich Dim datasrrc As DataSet Dim tuyenBindingSource As New BindingSource Dim tuyenLichLapBindingSource As New BindingSource Dim tuyenThuLapBindingSource As New BindingSource Friend WithEvents tuyenNgayKhongLapBindingSource As New BindingSource Dim tuyenThoiDiemKhongLapBindingSource As New BindingSource Private Sub LICHLAP_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load LoadData() BindingData() End Sub Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click Try If xl_kiemtraThem() = True Then Dim row As DataRowView = tuyenLichLapBindingSource.AddNew() row.Row.SetField(1, txtGio.Text + ":" + txtPhut.Text) End If Catch ex As Exception End Try End Sub Private Sub btnCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhat.Click If (tuyenThuLapBindingSource.Position = -1) Then Dim row As DataRowView = tuyenThuLapBindingSource.AddNew() row.Row.SetField("ThuHai", cbxThuHai.Checked) row.Row.SetField("ThuBa", cbxThuBa.Checked) row.Row.SetField("ThuTu", cbxThuTu.Checked) row.Row.SetField("ThuNam", cbxThuNam.Checked) row.Row.SetField("ThuSau", cbxThuSau.Checked) row.Row.SetField("ThuBay", cbxThuBay.Checked) row.Row.SetField("ChuNhat", cbxChuNhat.Checked) End If EndEdit() LichTuyenBus.CapNhatThoiDiemKhoiHanh(datasrrc.Tables(1)) LichTuyenBus.CapNhatThuLap(CType(tuyenThuLapBindingSource.Current, DataRowView).Row) datasrrc.Tables(2).AcceptChanges() RefreshBindingCheckBox() End Sub Private Sub btnHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuy.Click CancelEdit() End Sub Private Sub btnThemThoiDiem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemThoiDiem.Click Try If xl_kiemtraThemKhongLap() = True Then If (tuyenNgayKhongLapBindingSource.Position = -1) Then Return End If Dim row As DataRowView = tuyenThoiDiemKhongLapBindingSource.AddNew() row.Row.SetField("ThoiDiemKhoiHanh", txtGioKhongLap.Text + ":" + txtPhutKhongLap.Text) Dim dt As DataRowView = tuyenNgayKhongLapBindingSource.Current row.Row.SetField("MaTuyen", dt.Row.Field(Of Integer)("MaTuyen")) row.Row.SetField("NgayKhoiHanh", dt.Row.Field(Of Date)("NgayKhoiHanh")) tuyenThoiDiemKhongLapBindingSource.EndEdit() End If Catch ex As Exception End Try End Sub Private Sub btnThemNgay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemNgay.Click If xl_kiemtraNgayKhoiHanh() = True Then Dim row As DataRowView = tuyenNgayKhongLapBindingSource.AddNew() row.Row.SetField("NgayKhoiHanh", dtpNgayKhoiHanh.Value) tuyenNgayKhongLapBindingSource.EndEdit() datasrrc.Tables(3).AcceptChanges() End If End Sub Private Sub btnCapNhatThoiDiem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhatThoiDiem.Click EndEdit() LichTuyenBus.CapNhatThoiDiemKhoiHanhKhongLap(datasrrc.Tables(4)) End Sub Private Sub dgvDanhSachLichLap_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDanhSachLichLap.CellContentClick If (dgvDanhSachLichLap.Columns(e.ColumnIndex).Name = "colXoa") Then tuyenLichLapBindingSource.RemoveAt(e.RowIndex) End If End Sub Private Sub NgayKhoiHanh_PositionChanged(ByVal sender As System.Object, ByVal e As EventArgs) Handles tuyenNgayKhongLapBindingSource.CurrentItemChanged If (tuyenNgayKhongLapBindingSource.Position = -1) Then Return End If Dim rowView As DataRowView = tuyenNgayKhongLapBindingSource.Current If (rowView.Row.ItemArray.Length > 3) Then Return End If Dim filter As String = String.Format("NgayKhoiHanh = #{1:MM/dd/yyyy}# AND MaTuyen= {0}", _ rowView.Row.Field(Of Integer)("MaTuyen"), _ rowView.Row.Field(Of Date)("NgayKhoiHanh")) tuyenThoiDiemKhongLapBindingSource.Filter = filter datasrrc.Tables(4).DefaultView.RowFilter = "" End Sub Sub ClearBindingCheckBox() cbxThuHai.DataBindings.Clear() cbxThuBa.DataBindings.Clear() cbxThuTu.DataBindings.Clear() cbxThuNam.DataBindings.Clear() cbxThuSau.DataBindings.Clear() cbxThuBay.DataBindings.Clear() cbxChuNhat.DataBindings.Clear() End Sub Sub RefreshBindingCheckBox() ClearBindingCheckBox() cbxThuHai.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuHai") cbxThuBa.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBa") cbxThuTu.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuTu") cbxThuNam.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuNam") cbxThuSau.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuSau") cbxThuBay.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBay") cbxChuNhat.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ChuNhat") End Sub Public Sub LoadData() datasrrc = New DataSet datasrrc.Tables.Add(TuyenBus.LayDanhSachTuyen()) datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyen()) datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyenLapThu()) datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyenKhongLap()) datasrrc.Tables.Add(LichTuyenBus.LayDanhSachLichTuyenKhongLapThoiDiem()) datasrrc.Tables(0).TableName = "Tuyen" datasrrc.Tables(1).TableName = "LichLap" datasrrc.Tables(2).TableName = "ThuLap" datasrrc.Tables(3).TableName = "TuyenKhongLap" datasrrc.Tables(4).TableName = "ThoiDiemKhongLap" tuyenBindingSource.DataSource = datasrrc tuyenBindingSource.DataMember = "Tuyen" 'Tuyến lập datasrrc.Relations.Add("TuyenLichLap", datasrrc.Tables(0).Columns("MaTuyen"), datasrrc.Tables(1).Columns("MaTuyen")) datasrrc.Relations.Add("TuyenThuLap", datasrrc.Tables(0).Columns("MaTuyen"), datasrrc.Tables(2).Columns("MaTuyen")) tuyenLichLapBindingSource.DataSource = tuyenBindingSource tuyenLichLapBindingSource.DataMember = "TuyenLichLap" tuyenThuLapBindingSource.DataSource = tuyenBindingSource tuyenThuLapBindingSource.DataMember = "TuyenThuLap" 'Tuyến không lập datasrrc.Relations.Add("TuyenLichKhongLap", datasrrc.Tables(0).Columns("MaTuyen"), datasrrc.Tables(3).Columns("MaTuyen")) tuyenNgayKhongLapBindingSource.DataSource = tuyenBindingSource tuyenNgayKhongLapBindingSource.DataMember = "TuyenLichKhongLap" tuyenThoiDiemKhongLapBindingSource.DataSource = datasrrc tuyenThoiDiemKhongLapBindingSource.DataMember = "ThoiDiemKhongLap" End Sub Public Sub BindingData() cbxTenTuyen.DataSource = tuyenBindingSource cbxTenTuyen.DisplayMember = "TenTuyen" cbxTenTuyen.ValueMember = "MaTuyen" dgvDanhSachLichLap.DataSource = tuyenLichLapBindingSource dgvNgayKhoiHanh.DataSource = tuyenNgayKhongLapBindingSource dgvDanhSachLichKhongLap.DataSource = tuyenThoiDiemKhongLapBindingSource cbxThuHai.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuHai") cbxThuBa.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBa") cbxThuTu.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuTu") cbxThuNam.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuNam") cbxThuSau.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuSau") cbxThuBay.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ThuBay") cbxChuNhat.DataBindings.Add("Checked", tuyenThuLapBindingSource, "ChuNhat") End Sub Public Function xl_kiemtraThem() As Boolean Dim temp As String = txtGio.Text & ":" & txtPhut.Text If txtGio.Text = "" Or Not IsNumeric(txtGio.Text) Then txtGio.Focus() MessageBox.Show("Giờ không hợp lệ!", "Thông báo") Return False ElseIf CType(txtGio.Text, Integer) < 0 Or CType(txtGio.Text, Integer) > 24 Then txtGio.Focus() MessageBox.Show("24 Giờ không hợp lệ!", "Thông báo") Return False ElseIf txtPhut.Text = "" Or Not IsNumeric(txtPhut.Text) Then txtPhut.Focus() MessageBox.Show("Phút Không hợp lệ !", "Thông báo") Return False ElseIf CType(txtPhut.Text, Integer) < 0 Or CType(txtPhut.Text, Integer) > 60 Then txtPhut.Focus() MessageBox.Show("60 phút không hợp lệ!", "Thông báo") Return False Else For i As Integer = 0 To dgvDanhSachLichLap.Rows.Count - 1 If temp = dgvDanhSachLichLap.Rows(i).Cells(2).Value Then MessageBox.Show("Thời điểm hợp lệ !", "Thông báo") Return False End If Next End If Return True End Function Public Function xl_kiemtraNgayKhoiHanh() As Boolean Dim ngayKhoiHanh As Date = dtpNgayKhoiHanh.Value For i As Integer = 0 To dgvNgayKhoiHanh.Rows.Count - 1 If ngayKhoiHanh = CType(dgvNgayKhoiHanh.Rows(i).Cells(1).Value, Date) Then MessageBox.Show("Ngày khởi hành không lệ !", "Thông báo") Return False End If Next Return True End Function Public Function xl_kiemtraThemKhongLap() As Boolean Dim temp As String = txtGioKhongLap.Text & ":" & txtPhutKhongLap.Text If txtGioKhongLap.Text = "" Or Not IsNumeric(txtGioKhongLap.Text) Then txtGioKhongLap.Focus() MessageBox.Show("Giờ không hợp lệ!", "Thông báo") Return False ElseIf CType(txtGioKhongLap.Text, Integer) < 0 Or CType(txtGioKhongLap.Text, Integer) > 24 Then txtGioKhongLap.Focus() MessageBox.Show("24 Giờ không hợp lệ!", "Thông báo") Return False ElseIf txtPhutKhongLap.Text = "" Or Not IsNumeric(txtPhutKhongLap.Text) Then txtPhutKhongLap.Focus() MessageBox.Show("Phút Không hợp lệ !", "Thông báo") Return False ElseIf CType(txtPhutKhongLap.Text, Integer) < 0 Or CType(txtPhutKhongLap.Text, Integer) > 60 Then txtPhutKhongLap.Focus() MessageBox.Show("60 phút không hợp lệ!", "Thông báo") Return False Else For i As Integer = 0 To dgvDanhSachLichKhongLap.Rows.Count - 1 If temp = dgvDanhSachLichKhongLap.Rows(i).Cells(3).Value Then MessageBox.Show("Thời điểm hợp lệ !", "Thông báo") Return False End If Next Return True End If Return True End Function Private Sub EndEdit() tuyenLichLapBindingSource.EndEdit() tuyenThuLapBindingSource.EndEdit() tuyenNgayKhongLapBindingSource.EndEdit() tuyenThoiDiemKhongLapBindingSource.EndEdit() End Sub Private Sub CancelEdit() tuyenLichLapBindingSource.CancelEdit() tuyenThuLapBindingSource.CancelEdit() tuyenNgayKhongLapBindingSource.CancelEdit() tuyenThoiDiemKhongLapBindingSource.CancelEdit() End Sub Private Sub btnHuyThoiDiem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuyThoiDiem.Click tuyenThoiDiemKhongLapBindingSource.CancelEdit() tuyenNgayKhongLapBindingSource.CancelEdit() End Sub Private Sub dgvDanhSachLichKhongLap_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDanhSachLichKhongLap.CellContentClick If (dgvDanhSachLichKhongLap.Columns(e.ColumnIndex).Name = "colXoaThoiDiem") Then tuyenThoiDiemKhongLapBindingSource.RemoveAt(e.RowIndex) End If End Sub End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/frmLapLich.vb
Visual Basic .NET
gpl2
13,072
Imports System.Data.OleDb Imports BUS Imports DTO Public Class frmTuyenXe Dim dtTUYEN As DataTable Dim vtClick As Integer = 0 Private Sub TuyenXe_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Try dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen() Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(0) HienThiThongTinTUYEN(tuyen) Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Public Function KT_NhapLieu_Them() As String Dim str As String = "" If txtMaTuyen.Text <> "" AndAlso Not IsNumeric(txtMaTuyen.Text) Then str = "Mã tuyến là số!!!" txtMaTuyen.Focus() ElseIf txtTenTuyen.Text = "" Then str = "Tên tuyến không được rỗng!!!" txtTenTuyen.Focus() ElseIf txtDiaDiemDi.Text = "" Then str = "Diem diem di không được rỗng!!!" txtDiaDiemDi.Focus() ElseIf txtDiaDiemDen.Text = "" Then str = "Diem diem den không được rỗng!!!" txtDiaDiemDen.Focus() End If Return str End Function Public Function LayTuyenTuTextboxs() As TuyenDto Dim tuyen As New TuyenDto If IsNumeric(txtMaTuyen.Text) Then tuyen.MaTuyenXe = txtMaTuyen.Text End If tuyen.TenTuyenXe = txtTenTuyen.Text tuyen.DiaDiemDi = txtDiaDiemDi.Text tuyen.DiaDiemDen = txtDiaDiemDen.Text Return tuyen End Function Public Function LayTuyenTu_DataGridView(ByVal vtdong As Integer) As TuyenDto Dim tuyen As New TuyenDto tuyen.MaTuyenXe = dgvTuyen.Rows(vtdong).Cells("MaTuyen").Value tuyen.TenTuyenXe = dgvTuyen.Rows(vtdong).Cells("TenTuyen").Value tuyen.DiaDiemDi = dgvTuyen.Rows(vtdong).Cells("DiaDiemDi").Value tuyen.DiaDiemDen = dgvTuyen.Rows(vtdong).Cells("DiaDiemDen").Value Return tuyen End Function Public Sub HienThiThongTinTUYEN(ByVal tuyen As TuyenDto) txtMaTuyen.Text = tuyen.MaTuyenXe txtTenTuyen.Text = tuyen.TenTuyenXe txtDiaDiemDi.Text = tuyen.DiaDiemDi txtDiaDiemDen.Text = tuyen.DiaDiemDen End Sub Public Sub ResetTextboxs() txtMaTuyen.Text = "" txtTenTuyen.Text = "" txtDiaDiemDi.Text = "" txtDiaDiemDen.Text = "" End Sub Private Sub btnTimTuyen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTimTuyen.Click dgvTuyen.DataSource = TuyenBus.TimTuyen(Me.LayTuyenTuTextboxs()) End Sub Private Sub btnThemTuyen_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemTuyen.Click Dim ktNhapLieu As String = KT_NhapLieu_Them() If (ktNhapLieu <> "") Then MessageBox.Show(ktNhapLieu, "THÔNG BÁO") Exit Sub End If Dim kq As Integer = TuyenBus.ThemTuyen(Me.LayTuyenTuTextboxs()) If (kq = 0) Then MessageBox.Show("Tên tuyến xe đã có trong dữ liệu!!!", "THÔNG BÁO") Else dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen() dgvTuyen.Rows(0).Selected = False dgvTuyen.Rows(dgvTuyen.Rows.Count - 2).Selected = True Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(dgvTuyen.Rows.Count - 2) HienThiThongTinTUYEN(tuyen) End If End Sub Private Sub btnXoaTuyen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoaTuyen.Click If vtClick = dgvTuyen.Rows.Count - 1 Then MessageBox.Show("Chọn dòng có dữ liệu cần xóa!!!", "THÔNG BÁO") Exit Sub End If Dim ma As Integer = dgvTuyen.Rows(vtClick).Cells("MaTuyen").Value Dim kq As Integer = TuyenBus.XoaTuyen(ma) dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen() Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(0) HienThiThongTinTuyen(tuyen) End Sub Private Sub btnCapNhaTuyen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapNhaTuyen.Click Dim ktNhapLieu As String = KT_NhapLieu_Them() If (ktNhapLieu <> "") Then MessageBox.Show(ktNhapLieu, "THÔNG BÁO") Exit Sub End If Dim kq As Integer = TuyenBus.CapNhatTuyen(Me.LayTuyenTuTextboxs()) If (kq = 0) Then MessageBox.Show("Ten Tuyen đã có trong dữ liệu!!!", "THÔNG BÁO") Else dgvTuyen.DataSource = TuyenBus.LayDanhSachTuyen() dgvTuyen.Rows(0).Selected = False dgvTuyen.Rows(vtClick).Selected = True Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(vtClick) HienThiThongTinTUYEN(tuyen) End If End Sub Private Sub dgvTuyen_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgvTuyen.MouseClick vtClick = dgvTuyen.CurrentRow.Index() If vtClick = dgvTuyen.Rows.Count - 1 Then ResetTextboxs() Exit Sub End If Dim tuyen As TuyenDto = LayTuyenTu_DataGridView(vtClick) HienThiThongTinTUYEN(tuyen) End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Close() End Sub End Class
10650251065124quanlyhocsinh
trunk/QuảnLyXe/QuanLyXe/Backup/GiaoDien/frmTuyenXe.vb
Visual Basic .NET
gpl2
5,577