code
stringlengths
3
1.18M
language
stringclasses
1 value
package XML; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.xml.sax.SAXException; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author PC */ public class Form extends javax.swing.JFrame { /** * Creates new form Form */ public Form() { 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() { jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea3 = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea4 = new javax.swing.JTextArea(); jButton2 = new javax.swing.JButton(); jScrollPane5 = new javax.swing.JScrollPane(); jTextArea5 = new javax.swing.JTextArea(); jScrollPane6 = new javax.swing.JScrollPane(); jTextArea6 = new javax.swing.JTextArea(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextArea2.setColumns(20); jTextArea2.setRows(5); jScrollPane2.setViewportView(jTextArea2); jTextArea3.setColumns(20); jTextArea3.setRows(5); jScrollPane3.setViewportView(jTextArea3); jTextArea4.setColumns(20); jTextArea4.setRows(5); jScrollPane4.setViewportView(jTextArea4); jButton2.setText("OK"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextArea5.setColumns(20); jTextArea5.setRows(5); jScrollPane5.setViewportView(jTextArea5); jTextArea6.setColumns(20); jTextArea6.setRows(5); jScrollPane6.setViewportView(jTextArea6); jButton3.setText("OK"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE) .addComponent(jScrollPane2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .addComponent(jScrollPane4)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .addComponent(jScrollPane6) .addGroup(layout.createSequentialGroup() .addComponent(jButton3) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE) .addComponent(jScrollPane3) .addComponent(jScrollPane5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jButton3)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE) .addComponent(jScrollPane4) .addComponent(jScrollPane6)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String th=""; Table dl=new Table(); XuLyChuoi xl=new XuLyChuoi(); xl.TaoBang(jTextArea1.getText(), dl); for(int i=0;i<dl.Kieu.length;i++) { th+=dl.TenBien[i]+"\t"+dl.Kieu[i]+"\n"; } th+=dl.TenKhoaChinh; jTextArea2.setText(dl.TenBang+"\n\n"+th); Create cr=new Create(); try { cr.CreateTable(dl); } catch (ParserConfigurationException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: Condition ct=new Condition(); XuLyChuoi xl=new XuLyChuoi(); xl.XoaDong(jTextArea3.getText(),ct); String th=ct.TenBang+"\n"; for(int i=0;i<ct.Bien.length;i++) { th+=ct.Bien[i]+"\t"+ct.DauSoSanh[i]+"\t"+ct.GiaTri[i]+"\n"; } for(int i=0;i<ct.DauNoi.length;i++) { th+=ct.DauNoi[i]+"\n"; } jTextArea4.setText(th); Delete dl=new Delete(); dl.DeleteRecord(ct); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: Records rs=new Records(); Attributes tt=new Attributes(); Condition ct=new Condition(); Condition dk=new Condition(); XuLyChuoi xl=new XuLyChuoi(); xl.ChonDong(jTextArea5.getText(),tt); ct=tt.DieuKien1; dk=tt.DieuKien2; String th=new String(); if(ct!=null) { th = ct.TenBang + "\n"; for (int i = 0; i < ct.Bien.length; i++) { th += ct.Bien[i] + "\t" + ct.DauSoSanh[i] + "\t" + ct.GiaTri[i] + "\n"; } for (int i = 0; i < ct.DauNoi.length; i++) { th += ct.DauNoi[i] + "\n"; } } if(dk!=null) { th = dk.TenBang + "\n"; for (int i = 0; i < dk.Bien.length; i++) { th += dk.Bien[i] + "\t" + dk.DauSoSanh[i] + "\t" + dk.GiaTri[i] + "\n"; } for (int i = 0; i < dk.DauNoi.length; i++) { th += dk.DauNoi[i] + "\n"; } } jTextArea6.setText(th); Select sl=new Select(); sl.SelectRecord(tt,rs); }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Form().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; private javax.swing.JTextArea jTextArea3; private javax.swing.JTextArea jTextArea4; private javax.swing.JTextArea jTextArea5; private javax.swing.JTextArea jTextArea6; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.util.List; /** * * @author PC */ public class Record { public List<String> record; public Record() { } public Record(List<String> record) { this.record=record; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ public class Temp { /** * @param args the command line arguments */ public static void main(String[] args) { Delete dl=new Delete(); Condition ct=new Condition(); ct.TenBang="HOCSINH"; ct.Bien=new String[4]; ct.GiaTri=new String[4]; ct.DauSoSanh=new String[4]; ct.DauNoi=new String[3]; ct.Bien[0]="dtb"; ct.GiaTri[0]="0"; ct.DauSoSanh[0]=">"; ct.Bien[1]="dtb"; ct.GiaTri[1]="5"; ct.DauSoSanh[1]="<"; ct.Bien[2]="dtb"; ct.GiaTri[2]="7"; ct.DauSoSanh[2]=">"; ct.Bien[3]="dtb"; ct.GiaTri[3]="10"; ct.DauSoSanh[3]="<"; ct.DauNoi[0]="and"; ct.DauNoi[1]="or"; ct.DauNoi[2]="and"; dl.DeleteRecord(ct); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author TanAnh */ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class NewClass { public static void main(String argv[]) { try { File fXmlFile = new File("c:\\test.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("staff"); System.out.println("-----------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("First Name : " + getTagValue("firstname", eElement)); System.out.println("Last Name : " + getTagValue("lastname", eElement)); System.out.println("Nick Name : " + getTagValue("nickname", eElement)); System.out.println("Salary : " + getTagValue("salary", eElement)); } } } catch (Exception e) { System.err.println(e.getMessage()); } } private static String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ public class Attributes { public String Bang1; public String Bang2; public String[] ThuocTinh1; public String[] ThuocTinh2; public Condition DieuKien1; public Condition DieuKien2; public String BienNoi1; public String BienNoi2; public boolean SoSanh; public Attributes() { } public Attributes(String Bang1, String Bang2, String[] ThuocTinh1, String[] ThuocTinh2, Condition DieuKien1, Condition DieuKien2, String BienNoi1, String BienNoi2, boolean SoSanh) { this.Bang1=Bang1; this.Bang2=Bang2; this.ThuocTinh1=ThuocTinh1; this.ThuocTinh2=ThuocTinh2; this.DieuKien1=DieuKien1; this.DieuKien2=DieuKien2; this.BienNoi1=BienNoi1; this.BienNoi2=BienNoi2; this.SoSanh=SoSanh; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; /** * * @author PC */ public class Create { public void CreateTable(Table dl) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { File directory = new File(""); String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml"; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(filepath); Element database=doc.getDocumentElement(); Element table=doc.createElement("Table"); table.setAttribute("Ten", dl.TenBang); //table.setAttribute("pk", dl.TenKhoaChinh); Element record =doc.createElement("Record"); Element[] col=new Element[dl.TenBien.length]; for (int i = 0; i < dl.TenBien.length; i++) { col[i] = doc.createElement("Col"); col[i].setAttribute("Ten", dl.TenBien[i]); col[i].setAttribute("Type", dl.Kieu[i]); record.appendChild(col[i]); } table.appendChild(record); database.appendChild(table); TransformerFactory tff = TransformerFactory.newInstance(); Transformer transformer = tff.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource xmlSource = new DOMSource(doc); StreamResult outputTarget = new StreamResult(filepath); transformer.transform(xmlSource, outputTarget); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Delete { public void DeleteRecord(Condition ct) { try { File directory = new File(""); String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(filepath); XPathFactory xfactory = XPathFactory.newInstance(); javax.xml.xpath.XPath xpath = xfactory.newXPath(); String reg="//Table[@Ten='"+ct.TenBang+"']/Record[Col["; for (int i = 0; i < ct.Bien.length - 1; i++) { reg += "@Ten='" + ct.Bien[i] + "' and ." + ct.DauSoSanh[i] + "'" + ct.GiaTri[i] + "' " + ct.DauNoi[i] + " "; } reg += "@Ten='" + ct.Bien[ct.Bien.length - 1] + "' and ." + ct.DauSoSanh[ct.Bien.length - 1] + "'" + ct.GiaTri[ct.Bien.length - 1] + "']]"; System.out.println(reg); XPathExpression expr = xpath.compile(reg); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node item=nodes.item(i); item.getParentNode().removeChild(item); } TransformerFactory tff = TransformerFactory.newInstance(); Transformer transformer = tff.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource xmlSource = new DOMSource(doc); StreamResult outputTarget = new StreamResult(filepath); transformer.transform(xmlSource, outputTarget); } catch (Exception ex) { } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * * @author TanAnh */ public class XPath { public static void main(String args[]) { String a; try { String filePath = "C:\\file.xml"; Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filePath)); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/company/staff"; Node widgetNode = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE); NodeList listnod = widgetNode.getChildNodes(); for (int i = 0; i < listnod.getLength(); i++) { a = listnod.item(i).getTextContent(); System.out.print("-" + a); } System.out.println(); System.out.println("----------------"); expression = "nickname"; Node newnode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE); System.err.println(newnode.getTextContent()); } catch (XPathExpressionException ex) { Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(XPath.class.getName()).log(Level.SEVERE, null, ex); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Select { public void SelectRecord(Attributes tt, Records rs) { try { rs = new Records(); File directory = new File(""); String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(filepath); XPathFactory xfactory = XPathFactory.newInstance(); javax.xml.xpath.XPath xpath = xfactory.newXPath(); String reg1 = new String(); String reg2 = new String(); if (tt.DieuKien1 != null) { reg1 = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) { reg1 += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " "; } reg1 += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]"; } if (tt.DieuKien2 != null) { reg2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) { reg2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " "; } reg2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]"; } System.out.println(reg1); System.out.println(reg2); String rx = new String(); String rx1 = new String(); String rx2 = new String(); if (tt.Bang2 == null && tt.DieuKien2 == null) { if (tt.DieuKien1 == null)//Khong where { rx = "//Table[@Ten='" + tt.Bang1 + "']/Record"; XPathExpression expr = xpath.compile(rx); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { NodeList nl = nodes.item(i).getChildNodes(); for (int j = 0; j < nl.getLength(); j++)//chon ra Col { Node it = nl.item(j); if (it.getNodeType() == Node.ELEMENT_NODE) { for (int k = 0; k < tt.ThuocTinh1.length; k++) { if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) { System.out.println(nl.item(j).getTextContent()); } } } } } } else//Co where khong long khong ket { rx = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) { rx += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " "; } rx += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]"; XPathExpression expr = xpath.compile(rx); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { NodeList nl = nodes.item(i).getChildNodes(); for (int j = 0; j < nl.getLength(); j++)//chon ra Col { Node it = nl.item(j); if (it.getNodeType() == Node.ELEMENT_NODE) { for (int k = 0; k < tt.ThuocTinh1.length; k++) { if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) { System.out.println(nl.item(j).getTextContent()); } } } } } } } else//tt.Bang2!=null || tt.DieuKien2!=null { if (tt.DieuKien1 == null) { if (tt.DieuKien2 == null)//Ket khong long { rx1 = "//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='" + tt.BienNoi1 + "']"; rx2 = "//Table[@Ten='" + tt.Bang2 + "']/Record/Col[@Ten='" + tt.BienNoi2 + "']"; XPathExpression expr1 = xpath.compile(rx1); Object result1 = expr1.evaluate(doc, XPathConstants.NODESET); NodeList nodes1 = (NodeList) result1; XPathExpression expr2 = xpath.compile(rx2); Object result2 = expr2.evaluate(doc, XPathConstants.NODESET); NodeList nodes2 = (NodeList) result2; List<String> giao = new ArrayList<String>(); for (int i = 0; i < nodes1.getLength(); i++) { Node i1 = nodes1.item(i); for (int j = 0; j < nodes2.getLength(); j++) { Node i2 = nodes2.item(j); if (i1.getTextContent().compareTo(i2.getTextContent()) == 0) { NodeList pr1 = i1.getParentNode().getChildNodes(); for (int l = 0; l < pr1.getLength(); l++) { if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE) { for (int m = 0; m < tt.ThuocTinh1.length; m++) { if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0) System.out.println(pr1.item(l).getTextContent()); } } } NodeList pr2 = i2.getParentNode().getChildNodes(); for (int l = 0; l < pr2.getLength(); l++) { if(pr2.item(l).getNodeType()==Node.ELEMENT_NODE) { for (int m = 0; m < tt.ThuocTinh2.length; m++) { if(pr2.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh2[m])==0) System.out.println(pr2.item(l).getTextContent()); } } } } } } } else { if (tt.Bang2 != null)//Long khong ket { //Chon Col rx1="//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='"+tt.BienNoi1+"']"; XPathExpression expr1 = xpath.compile(rx1); Object result1 = expr1.evaluate(doc, XPathConstants.NODESET); NodeList nodes1 = (NodeList) result1; //Chon Record rx2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) { rx2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " "; } rx2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]"; XPathExpression expr2 = xpath.compile(rx2); Object result2 = expr2.evaluate(doc, XPathConstants.NODESET); NodeList nodes2 = (NodeList) result2; for (int i = 0; i < nodes2.getLength(); i++) { NodeList nl2 = nodes2.item(i).getChildNodes(); for (int j = 0; j < nl2.getLength(); j++)//chon ra Col { Node it2 = nl2.item(j); if (it2.getNodeType() == Node.ELEMENT_NODE) { if (it2.getAttributes().item(0).getNodeValue().compareTo(tt.BienNoi2) == 0) { System.out.println(nl2.item(j).getTextContent()); } } } } } } } } } catch (Exception ex) { } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; /** * * @author TanAnh */ public class WriteXMLFile { public static void main(String argv[]) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // staff elements Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // firstname elements Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); // lastname elements Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); // nickname elements Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); // salary elements Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\file.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } }
Java
package XML; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author PC */ import java.lang.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class XuLyChuoi { public String XoaMoiKhoangTrang(String chuoi) { return chuoi.replaceAll("\\s", ""); } public void TaoBang(String chuoi, Table dl) { String[] h = chuoi.split("\\("); String c1 = XoaMoiKhoangTrang(h[0]); String ct = c1.substring(0, 11); ct = ct.toLowerCase(); if (ct.contains("createtable")) { dl.TenBang = c1.substring(11, c1.length()); } String c2 = XoaMoiKhoangTrang(h[1]); if (c2.contains("primarykey")) { c2 = c2.substring(0, c2.length() - 1); String[] tt = c2.split(","); dl.Kieu = new String[tt.length - 1]; dl.TenBien = new String[tt.length - 1]; for (int i = 0; i < tt.length - 1; i++) { if (tt[i].contains("int")) { dl.Kieu[i] = "int"; dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 3); } if (tt[i].contains("varchar")) { dl.Kieu[i] = "string"; dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 7); } } h[2] = XoaMoiKhoangTrang(h[2]); dl.TenKhoaChinh = h[2].substring(0, h[2].length() - 2); } else { c2 = c2.substring(0, c2.length() - 1); String[] tt = c2.split(","); dl.Kieu = new String[tt.length]; dl.TenBien = new String[tt.length]; for (int i = 0; i < tt.length; i++) { if (tt[i].contains("int")) { dl.Kieu[i] = "int"; dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 3); } if (tt[i].contains("varchar")) { dl.Kieu[i] = "string"; dl.TenBien[i] = tt[i].substring(0, tt[i].length() - 7); } } dl.TenKhoaChinh = null; } } public void XoaDong(String chuoi, Condition ct) { String regex = null; if (chuoi.contains("where")) { regex = "where"; } if (chuoi.contains("WHERE")) { regex = "WHERE"; } String[] h = chuoi.split(regex); h[0] = XoaMoiKhoangTrang(h[0]); ct.TenBang = h[0].substring(10); char[] s = h[1].toCharArray(); List<String> d = new ArrayList<String>(); List<String> n = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { if (s[i] == '<' || s[i] == '=' || s[i] == '>') { d.add(Character.toString(s[i])); } } for (int i = 0; i < s.length - 4; i++) { if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) { n.add("and"); } if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) { n.add("or"); } } String tokens[] = null; String splitPattern = "<|>|=|AND|OR|and|or"; Pattern p = Pattern.compile(splitPattern); tokens = p.split(h[1].trim()); ct.Bien = new String[tokens.length / 2]; ct.GiaTri = new String[tokens.length / 2]; ct.DauNoi = new String[(tokens.length / 2) - 1]; for (int i = 0; i < tokens.length / 2; i++) { ct.Bien[i] = tokens[2 * i].trim(); if (tokens[2 * i + 1].trim().contains("'")) { ct.GiaTri[i] = tokens[2 * i + 1].trim().replaceAll("'", " ").trim(); } else { ct.GiaTri[i] = tokens[2 * i + 1].trim(); } } ct.DauNoi = n.toArray(new String[0]); ct.DauSoSanh = d.toArray(new String[0]); } public void ChonDong(String chuoi, Attributes tt) { chuoi = chuoi.trim(); chuoi = chuoi.replaceAll("\n", " "); chuoi = chuoi.replaceAll("\t", " "); System.out.println(chuoi); String tokens[] = null; String splitPattern = "select |SELECT | FROM | from "; if (!(chuoi.contains(" WHERE ") || chuoi.contains(" where "))) { Pattern p = Pattern.compile(splitPattern); tokens = p.split(chuoi); tokens[1] = XoaMoiKhoangTrang(tokens[1]); String c[] = tokens[1].split(","); tt.Bang1 = tokens[2].trim(); tt.Bang2 = null; tt.ThuocTinh1 = new String[c.length]; for (int i = 0; i < c.length; i++) { tt.ThuocTinh1[i] = c[i]; } } else { splitPattern += "| WHERE | where "; Pattern p = Pattern.compile(splitPattern); tokens = p.split(chuoi); if (tokens[2].contains(",")) //co 2 bang { tokens[2] = XoaMoiKhoangTrang(tokens[2]); tt.Bang1 = tokens[2].substring(0, tokens[2].indexOf(",")).trim(); tt.Bang2 = tokens[2].substring(tokens[2].indexOf(",") + 1, tokens[2].length()).trim(); String[] at = tokens[1].split(","); List<String> tt1 = new ArrayList<String>(); List<String> tt2 = new ArrayList<String>(); for (int i = 0; i < at.length; i++) { if (at[i].contains(tt.Bang1)) { tt1.add(at[i].substring(tt.Bang1.length() + 1)); } if (at[i].contains(tt.Bang2)) { tt2.add(at[i].substring(tt.Bang2.length() + 1)); } } tt.ThuocTinh1 = tt1.toArray(new String[0]); tt.ThuocTinh2 = tt2.toArray(new String[0]); System.out.println(tt.Bang1); for (int i = 0; i < tt.ThuocTinh1.length; i++) { System.out.println(tt.ThuocTinh1[i]); } System.out.println("\n" + tt.Bang2); for (int i = 0; i < tt.ThuocTinh2.length; i++) { System.out.println(tt.ThuocTinh2[i]); } String[] bn = tokens[3].split("="); for (int i = 0; i < bn.length; i++) { if (bn[i].contains(tt.Bang1)) { tt.BienNoi1 = bn[i].substring(tt.Bang1.length() + 1); } if (bn[i].contains(tt.Bang2)) { tt.BienNoi2 = bn[i].substring(tt.Bang2.length() + 1); } } tt.SoSanh = true; System.out.println(tt.BienNoi1); System.out.println(tt.BienNoi2); } else //Khong co 2 bang { tokens[1] = XoaMoiKhoangTrang(tokens[1]); String c[] = tokens[1].split(","); tt.Bang1 = tokens[2].trim(); tt.ThuocTinh1 = new String[c.length]; for (int i = 0; i < c.length; i++) { tt.ThuocTinh1[i] = c[i]; } if (tokens.length == 4) //Khong long nhau { tt.Bang2 = null; for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } tt.DieuKien1=new Condition(); tt.DieuKien1.TenBang=tt.Bang1; char[] s = tokens[3].toCharArray(); List<String> d = new ArrayList<String>(); List<String> n = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { if (s[i] == '<' || s[i] == '=' || s[i] == '>') { d.add(Character.toString(s[i])); } } for (int i = 0; i < s.length - 4; i++) { if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) { n.add("and"); } if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) { n.add("or"); } } String tks[] = null; String sp = "<|>|=|AND|OR|and|or"; Pattern pt = Pattern.compile(sp); tks = pt.split(tokens[3].trim()); tt.DieuKien1.Bien = new String[tks.length / 2]; tt.DieuKien1.GiaTri = new String[tks.length / 2]; tt.DieuKien1.DauNoi = new String[(tks.length / 2) - 1]; for (int i = 0; i < tks.length / 2; i++) { tt.DieuKien1.Bien[i] = tks[2 * i].trim(); if (tks[2 * i + 1].trim().contains("'")) { tt.DieuKien1.GiaTri[i]=tks[2 * i + 1].trim().replaceAll("'", " ").trim(); } else { tt.DieuKien1.GiaTri[i] = tks[2 * i + 1].trim(); } } tt.DieuKien1.DauNoi = n.toArray(new String[0]); tt.DieuKien1.DauSoSanh = d.toArray(new String[0]); } else //Long Nhau { tt.Bang2 = tokens[5].trim(); tt.BienNoi2 = tokens[4].trim(); System.out.println(tt.Bang2); System.out.println(tt.BienNoi2); for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } tokens[6]=tokens[6].trim().substring(0,tokens[6].length()-1); tt.DieuKien2=new Condition(); tt.DieuKien2.TenBang=tt.Bang2; char[] s = tokens[6].toCharArray(); List<String> d = new ArrayList<String>(); List<String> n = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { if (s[i] == '<' || s[i] == '=' || s[i] == '>') { d.add(Character.toString(s[i])); } } for (int i = 0; i < s.length - 4; i++) { if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) { n.add("and"); } if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) { n.add("or"); } } String tks[] = null; String sp = "<|>|=|AND|OR|and|or"; Pattern pt = Pattern.compile(sp); tks = pt.split(tokens[6].trim()); tt.DieuKien2.Bien = new String[tks.length / 2]; tt.DieuKien2.GiaTri = new String[tks.length / 2]; tt.DieuKien2.DauNoi = new String[(tks.length / 2) - 1]; for (int i = 0; i < tks.length / 2; i++) { tt.DieuKien2.Bien[i] = tks[2 * i].trim(); if (tks[2 * i + 1].trim().contains("'")) { tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim().replaceAll("'", " ").trim(); } else { tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim(); } } tt.DieuKien2.DauNoi = n.toArray(new String[0]); tt.DieuKien2.DauSoSanh = d.toArray(new String[0]); tokens[3]=tokens[3].trim(); tt.BienNoi1=tokens[3].substring(0,tokens[3].indexOf(" ")); if(tokens[3].contains(" not ") || tokens[3].contains(" NOT ")) tt.SoSanh=false; else tt.SoSanh=true; } } } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author TanAnh */ import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ModifyXMLFile { public static void main(String argv[]) { try { String filepath = "c:\\file.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); // Get the root element Node company = doc.getFirstChild(); // Get the staff element , it may not working if tag has spaces, or // whatever weird characters in front...it's better to use // getElementsByTagName() to get it directly. // Node staff = company.getFirstChild(); // Get the staff element by tag name directly Node staff = doc.getElementsByTagName("staff").item(0); // update staff attribute NamedNodeMap attr = staff.getAttributes(); Node nodeAttr = attr.getNamedItem("id"); nodeAttr.setTextContent("3"); // append a new node to staff Element age = doc.createElement("age"); age.appendChild(doc.createTextNode("28")); staff.appendChild(age); // loop the staff child node NodeList list = staff.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); // get the salary element, and update the value if ("salary".equals(node.getNodeName())) { node.setTextContent("2000000"); } //remove firstname if ("firstname".equals(node.getNodeName())) { staff.removeChild(node); } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filepath)); transformer.transform(source, result); System.out.println("Done"); } catch (ParserConfigurationException pce) { } catch (TransformerException tfe) { } catch (IOException ioe) { } catch (SAXException sae) { } } }
Java
import java.util.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class Parentheses { void display(String s) { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Parentheses.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); } }
Java
package edu.gatech.oad.antlab.pkg2; /** * CS2335 Ant Lab * * AntLab11.java helper class * * @author Robert * @version 1.0 */ public class AntLab22 { /** * retrieves a pre-stored string message * @return the string */ public String getMessage() { return " a"; } }
Java
package edu.gatech.oad.antlab.pkg2; /** * CS2340 Ant Lab * * AntLab11.java helper class * * @author Robert * @version 1.0 */ public class AntLab21 { /** * retrieves a pre-stored string message * @return the string */ public String getMessage() { return " deserve"; } }
Java
package edu.gatech.oad.antlab.person; /** * A simple class for person 1 * returns their name and a * modified string * * @author Bob * @version 1.1 */ public class Person4 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person4(String pname) { name = pname; } /** * This method should take the string * input and return its characters rotated * 2 positions. * given "gtg123b" it should return * "g123bgt". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //use the substring method to move the first two characters to the end of the string return input.substring(2)+input.substring(0,2); } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
Java
package edu.gatech.oad.antlab.person; import java.util.ArrayList; import java.util.Collections; /** * A simple class for person 2 * returns their name and a * modified string * * @author Bob * @version 1.1 */ public class Person2 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person2(String pname) { name = pname; } /** * This method should take the string * input and return its characters in * random order. * given "gtg123b" it should return * something like "g3tb1g2". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //initializes variables int index = 0; String mod = ""; ArrayList<Character> characters = new ArrayList<Character>(); //adds characters into ArrayList while(index < input.length()){ characters.add(input.charAt(index)); index++; } //shuffles the indexes of ArrayList Collections.shuffle(characters); //Creates new String using indexes of Character ArrayList index = 0; while(index < input.length()){ mod = mod + characters.get(index); index++; } return mod; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
Java
package edu.gatech.oad.antlab.person; /** * A simple class for person 5 * returns their name and a * modified string * * @author Bob * @version 1.1 */ public class Person5 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person5(String pname) { name = pname; } /** * This method should take the string * input and return its characters rotated * 4 positions. * given "gtg123b" it should return * "23bgtg1". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //Person 5 put your implementation here return null; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
Java
package edu.gatech.oad.antlab.person; /** * A simple class for person 3 * returns their name and a * reversed string * * @author Bob * @version 1.1 */ public class Person3 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person3(String pname){ name = pname; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } /** * This method should take the string * input and return its reverse. * given "gtg123b" it should return * b321gtg. * * @param input the string to be reversed * @return the reversed string */ private String calc(String input) { String ans = ""; for (char c:input.toCharArray()){ ans=c+ans; } return ans; } }
Java
package edu.gatech.oad.antlab.person; /** * A simple class for person 1 * returns their name and a * modified string * * @author Bob * @version 1.1 */ public class Person1 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person1(String pname) { name = pname; } /** * This method should take the string * input and return its characters rotated * 2 positions. * given "gtg123b" it should return * "g123bgt". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //Person 1 put your implementation here return input.substring(2)+input.substring(0,2); } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
Java
package edu.gatech.oad.antlab.pkg1; /** * CS2335 Ant Lab * * AntLab12.java helper class */ public class AntLab12 { /** * retrieves a pre-stored string message * @return the string */ public String getMessage() { return " You"; } }
Java
package edu.gatech.oad.antlab.pkg1; //if you get an error on this import //you do not have resources.jar on the classpath import edu.cs2335.antlab.pkg3.*; import edu.gatech.oad.antlab.person.*; import edu.gatech.oad.antlab.pkg2.*; /** * CS2335 Ant Lab * * Prints out a simple message gathered from all of the other classes * in the package structure */ public class AntLabMain { /**antlab11.java message class*/ private AntLab11 ant11; /**antlab12.java message class*/ private AntLab12 ant12; /**antlab21.java message class*/ private AntLab21 ant21; /**antlab22.java message class*/ private AntLab22 ant22; /**antlab31 java message class which is contained in a jar resource file*/ private AntLab31 ant31; /** * the constructor that initializes all the helper classes */ public AntLabMain () { ant11 = new AntLab11(); ant12 = new AntLab12(); ant21 = new AntLab21(); ant22 = new AntLab22(); //if you get an error here, you do not have resources.jar on the classpath ant31 = new AntLab31(); } /** * gathers a string from all the other classes and prints the message * out to the console * */ public void printOutMessage() { String toPrint = ant11.getMessage() + ant12.getMessage() + ant21.getMessage() + ant22.getMessage() + ant31.getMessage(); //Person1 replace P1 with your name //and ggg000x with your gt num Person1 p1 = new Person1("Cameron Smith"); toPrint += p1.toString("csmith330"); //Person2 replace P2 with your name //and ggg000x with your gt num Person2 p2 = new Person2("Michael Dang"); toPrint += p2.toString("mdang3"); //Person3 replace P3 with your name //and ggg000x with your gt num Person3 p3 = new Person3("W Scott Johnson"); toPrint += p3.toString("wjohnson38"); //Person4 replace P4 with your name //and ggg000x with your gt num Person4 p4 = new Person4("Seth Pearce"); toPrint += p4.toString("spearce3"); //Person5 replace P5 with your name //and ggg000x with your gt num Person5 p5 = new Person5("P5"); toPrint += p5.toString("ggg005x"); System.out.println(toPrint); } /** * entry point for the program */ public static void main(String[] args) { new AntLabMain().printOutMessage(); } }
Java
package edu.gatech.oad.antlab.pkg1; /** * CS2340 Ant Lab * * AntLab11.java helper class * @author Robert * @version 1.0 */ public class AntLab11 { /** * retrieves a pre-stored string message * @return the string */ public String getMessage() { return "Congrats!"; } }
Java
package com.syh.appshare.modules.history; import android.app.Activity; public class ShareHistoryActivity extends Activity{ }
Java
package com.syh.appshare.modules.share; import com.syh.appshare.R; import android.app.Activity; import android.os.Bundle; public class ShareDetailActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_share_detail); } }
Java
package com.syh.appshare.modules.share; import android.app.Activity; public class ShareActivity extends Activity { }
Java
package com.syh.appshare.modules.search; import android.app.Activity; public class SearchActivity extends Activity { }
Java
package com.syh.appshare.modules.news; import android.app.Activity; public class NewsActivity extends Activity { }
Java
package com.syh.appshare.services; import java.util.List; import com.syh.appshare.Constants; import com.syh.appshare.Memory; import com.syh.appshare.common.utils.LogUtil; import com.syh.appshare.common.utils.Utils; import com.syh.appshare.objects.InstalledApkInfo; import android.app.ActivityManager; import android.app.Service; import android.app.ActivityManager.RunningTaskInfo; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; /** * 检测当前程序的后台服务 * @author shenyh * */ public class ShareServices extends Service { private final String tag="service"; private final int MAX_TASK=1,NOTIFY=2; private ActivityManager activityManager; /** * 正在运行的程序 */ private List<RunningTaskInfo> runningTasks; /** * 上一个应用程序包名 */ private String lastPackageName=null; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch(msg.what){ case NOTIFY:{ String packageName=msg.getData().getString(Constants.PACKAGE_NAME_TAG); String className=msg.getData().getString(Constants.CLASS_NAME_TAG); Utils.notifyShare(getApplicationContext(), packageName, className); break; } } } }; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { activityManager=(ActivityManager) getSystemService(ACTIVITY_SERVICE); new Thread(){ @Override public void run() { try { while(true){ LogUtil.debug(tag, "ShareServices is running. lastPackageName:"+lastPackageName); //检测栈 // 获取当前正在运行的任务 runningTasks = activityManager.getRunningTasks(MAX_TASK); if(runningTasks!=null){ String packageName=runningTasks.get(0).baseActivity.getPackageName(); if(isWhiteList(packageName)){ String className=runningTasks.get(0).baseActivity.getClassName(); if(!packageName.equals(lastPackageName)){ lastPackageName=packageName; Message msg=new Message(); msg.what=NOTIFY; Bundle data=new Bundle(); data.putString(Constants.PACKAGE_NAME_TAG, packageName); data.putString(Constants.CLASS_NAME_TAG, className); msg.setData(data); handler.sendMessage(msg); } } } Thread.sleep(1000); } } catch (InterruptedException e) { LogUtil.error(tag, "check app InterruptedException e:"+e.toString()); e.printStackTrace(); } catch (Exception e) { LogUtil.error(tag, "check app Exception e:"+e.toString()); e.printStackTrace(); } } }.start(); return super.onStartCommand(intent, flags, startId); } /** * 包名是否在白名单中(白名单为非系统应用) * @param packageName * @return */ private boolean isWhiteList(String packageName){ List<InstalledApkInfo> installedApkList=Memory.getInstance(ShareServices.this).getInstalledApkList(); for(int i=0;i<installedApkList.size();i++){ if(installedApkList.get(i).packageName.equals(packageName)){ return true; } } return false; } }
Java
package com.syh.appshare; import java.util.List; import android.content.Context; import com.syh.appshare.common.utils.Utils; import com.syh.appshare.objects.InstalledApkInfo; public class Memory { private static Memory INSTANCE = null; private static Context context; private Memory() { } public static synchronized Memory getInstance(Context c) { if (INSTANCE == null) { INSTANCE = new Memory(); } context=c; return INSTANCE; } private List<InstalledApkInfo> installedApkList=null; public List<InstalledApkInfo> getInstalledApkList(){ if(installedApkList==null){ installedApkList=Utils.getInstalledApkList(context); } return installedApkList; } }
Java
package com.syh.appshare; public class Constants { public final static int LogError=4,LogDebug=3,LogInfo=2; public final static int LogLevel=LogDebug; public final static int SHARE_NOTIFY_TAG=1; public final static String PACKAGE_NAME_TAG="PACKAGE_NAME_TAG"; public final static String CLASS_NAME_TAG="CLASS_NAME_TAG"; }
Java
package com.syh.appshare.objects; import java.io.Serializable; /** * 分享的应用对象 * @author shenyh * */ public class APP implements Serializable{ private static final long serialVersionUID = -2372314353808592795L; //必要属性 /** * 包名 */ public String packageName; /** * versionCode */ public String versionCode; /** * versionName */ public String versionName; //其他属性 /** * 图标Url */ public String iconUrl; /** * 分类 */ public String type; /** * 分享次数 */ public String shareCount; /** * 分享理由 */ public String shareReason; /** * 是否已安装,默认为false */ public boolean hasInstalled=false; /** * 分享的时间 */ public long shareTime; }
Java
package com.syh.appshare.objects; import java.io.Serializable; import android.graphics.drawable.Drawable; /** * @作者:沈扬红 * @日期:2011-4-15 * @描述:封装已安装软件数据 */ public class InstalledApkInfo implements Serializable { public static final long serialVersionUID = 1L; public Drawable apk_icon;//程序图标 public String apk_name;//程序名称 public String apk_version;//程序版本 public String packageName;//程序包名称 public boolean needUpdate;//是否需要更新 public String version_code;//版本code public String className;//main activity class public InstalledApkInfo(Drawable apk_icon,String apk_name, String apk_version, String packageName) { this.apk_icon = apk_icon; this.apk_name = apk_name; this.apk_version = apk_version; this.packageName = packageName; } public InstalledApkInfo(Drawable apk_icon,String apk_name, String apk_version, String packageName, boolean needUpdate,String apk_version_code,String className) { this.apk_icon = apk_icon; this.apk_name = apk_name; this.apk_version = apk_version; this.packageName = packageName; this.needUpdate = needUpdate; this.version_code=apk_version_code; this.className=className; } }
Java
package com.syh.appshare; import java.util.ArrayList; import java.util.List; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.TabHost; import com.syh.appshare.common.utils.LogUtil; import com.syh.appshare.modules.news.NewsActivity; import com.syh.appshare.services.ShareServices; public class MainActivity extends TabActivity { public final String tag="main"; public static MainActivity instance; public TabHost tabHost; /** * 保存tabActivity中activity标签 */ private List<String> tabList=new ArrayList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initActivity(); } private void initActivity(){ //启动服务 startService(new Intent(this,ShareServices.class)); instance=MainActivity.this; tabHost=getTabHost(); Intent intent=new Intent(MainActivity.this,NewsActivity.class); setCrurentTab("SourceCatalog", intent); try { //隐藏标签栏 getTabWidget().setVisibility(View.GONE); } catch (Exception e) { e.printStackTrace(); } } public void setCrurentTab(String tabSpec,Intent intent){ if(!tabList.contains(tabSpec)){ tabHost.addTab(tabHost.newTabSpec(tabSpec) .setIndicator(tabSpec, getResources().getDrawable(R.drawable.icon)) .setContent(intent)); tabList.add(tabSpec); } tabHost.setCurrentTabByTag(tabSpec); } @Override protected void onDestroy() { super.onDestroy(); instance=null; } /** * 返回当前tab标签的前一个标签 * @return @return true:返回成功 false:返回失败 * @author wangweiwei * 2012-3-15 */ public boolean backPrevTab() { if(tabList.size()>1) { tabList.remove(tabList.size()-1); tabHost.setCurrentTabByTag(tabList.get(tabList.size()-1)); return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { LogUtil.debug(tag, "MainActivity onKeyDown."); return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { LogUtil.debug(tag, "MainActivity onKeyUp."); if(keyCode==KeyEvent.KEYCODE_BACK ){ if(goBack()){ LogUtil.debug(tag, "goBack is true"); return true; }else{ LogUtil.debug(tag, "goBack is false"); finish(); } return true; } return super.onKeyUp(keyCode, event); } /** * 是否消耗掉返回事件 * @return */ private boolean goBack(){ return backPrevTab(); } }
Java
package com.syh.appshare.common.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import com.syh.appshare.Constants; import com.syh.appshare.R; import com.syh.appshare.objects.InstalledApkInfo; public class Utils { private final static String tag="util"; /** * * @param context * @param packageName * @param className */ public static void notifyShare(Context context, String packageName,String className) { try { LogUtil.debug(tag, "notifyShare packageName:" + packageName+"className:"+className); NotificationManager nfm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); String appName=getAppName(context,packageName); String hint = context.getString(R.string.share_hint).replace("**", appName); String title = hint; String content=appName+" 版本号:"+getVersionName(context,packageName); Notification notification = new Notification(R.drawable.icon_small, hint,System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL;// 点击自动清除通知 Intent openintent = new Intent(); openintent.setClassName(context.getPackageName(), "com.syh.appshare.modules.share.ShareDetailActivity"); Bundle data = new Bundle(); data.putString(Constants.PACKAGE_NAME_TAG, packageName); data.putString(Constants.CLASS_NAME_TAG, className); openintent.putExtras(data); PendingIntent contentIntent = PendingIntent.getActivity(context,Constants.SHARE_NOTIFY_TAG, openintent, 0); notification.setLatestEventInfo(context, title, content, contentIntent); nfm.notify(Constants.SHARE_NOTIFY_TAG, notification); } catch (Exception e) { e.printStackTrace(); LogUtil.error(tag, "notifyShare e:" + e.toString()); } } /** * 获取应用名称 * @param context * @param packageName * @return */ public static String getAppName(Context context,String packageName){ try { return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.loadLabel(context.getPackageManager()).toString(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取VersionName * @param context * @param packageName * @return */ public static String getVersionName(Context context,String packageName){ try { return context.getPackageManager().getPackageInfo(packageName, 0).versionName; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取已安装APK列表 * @param context * @return */ public static List<InstalledApkInfo> getInstalledApkList(Context context){ LinkedList<InstalledApkInfo> installedApkList = new LinkedList<InstalledApkInfo>(); PackageManager pManager = context.getPackageManager(); List<PackageInfo> appList = getAllInstalledApplications(context); Drawable apk_icon; String apk_ame; String apk_version; String packageName; String apk_version_code;// syh 2011-06-29 boolean needUpdate; List<ResolveInfo> infoList = getLocalApps(context); // syh Map<String, String> infoMap = new HashMap<String, String>(); for (int i = 0; i < infoList.size(); i++) { infoMap.put(infoList.get(i).activityInfo.packageName, infoList .get(i).activityInfo.name); } for (int i = 0; i < appList.size(); i++) { PackageInfo pinfo = appList.get(i); apk_icon = pManager.getApplicationIcon(pinfo.applicationInfo); apk_ame = pManager.getApplicationLabel(pinfo.applicationInfo).toString(); apk_version = pinfo.versionName; packageName = pinfo.applicationInfo.packageName; apk_version_code = pinfo.versionCode + ""; String className = infoMap.get(packageName); needUpdate = false; installedApkList.add(new InstalledApkInfo(apk_icon,apk_ame, apk_version, packageName, needUpdate, apk_version_code, className)); } return installedApkList; } /** * 获取已安装apk包信息 * @param context * @return */ private static List<PackageInfo> getAllInstalledApplications(Context context) { List<PackageInfo> apps = new ArrayList<PackageInfo>(); PackageManager pm = context.getPackageManager(); // 获取手机内所有应用 List<PackageInfo> packageInfoList = pm.getInstalledPackages(0); for (int i = 0; i < packageInfoList.size(); i++) { PackageInfo packageInfo = (PackageInfo) packageInfoList.get(i); // 判断是否为非系统预装的应用程序 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) { // 去除非本资源包的安装包 if (!packageInfo.packageName.equalsIgnoreCase(context .getPackageName())) { apps.add(packageInfo); } } } return apps; } /** * 获取已安装系统启动信息 * @param context * @return */ private static List<ResolveInfo> getLocalApps(Context context) { List<ResolveInfo> mApps = new LinkedList<ResolveInfo>(); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); mApps = context.getPackageManager().queryIntentActivities(intent, 0); return mApps; } }
Java
package com.syh.appshare.common.utils; import android.util.Log; import com.syh.appshare.Constants; public class LogUtil { public static void error(String tag,String msg){ if(Constants.LogLevel<=Constants.LogError){ Log.e(tag, msg); } } public static void debug(String tag,String msg){ if(Constants.LogLevel<=Constants.LogDebug){ Log.d(tag, msg); } } public static void info(String tag,String msg){ if(Constants.LogLevel<=Constants.LogInfo){ Log.i(tag, msg); } } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.net; import java.net.Socket; import java.net.ServerSocket; import java.io.IOException; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.MDC; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.net.SocketNode; import org.apache.log4j.net.SocketServer; /** * This SocketServer exits after certain number of connections from a * client. This number is determined the totalsTest parameter, that is * the first argument on the commmand line. The second argument, * prefix, determines the prefix of the configuration file to * use. Each run of the server will use a different properties * file. For the i-th run, the path to the file is * (prefix+i+".properties"). * * @author Ceki Gulcu */ public class ShortSocketServer { static Logger cat = Logger.getLogger(ShortSocketServer.class); public static void main(String args[]) throws Exception { int totalTests = 0; String prefix = null; if(args.length == 2) { totalTests = Integer.parseInt(args[0]); prefix = args[1]; } else { usage("Wrong number of arguments."); } int port = Integer.valueOf(System.getProperty("port", "12345")); LogLog.debug("Listening on port " + port); ServerSocket serverSocket = new ServerSocket(port); MDC.put("hostID", "shortSocketServer"); for(int i = 1; i <= totalTests; i++) { PropertyConfigurator.configure(prefix+i+".properties"); LogLog.debug("Waiting to accept a new client."); Socket socket = serverSocket.accept(); LogLog.debug("Connected to client at " + socket.getInetAddress()); LogLog.debug("Starting new socket node."); SocketNode sn = new SocketNode(socket, LogManager.getLoggerRepository()); Thread t = new Thread(sn); t.start(); t.join(); } } static void usage(String msg) { System.err.println(msg); System.err.println( "Usage: java " +ShortSocketServer.class.getName() + " totalTests configFilePrefix"); System.exit(1); } }
Java
package zing.com; import android.app.Activity; import android.os.Bundle; public class ZingActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.interfaces; import android.os.Environment; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public interface IDDBB { //For the sdcard io public final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath(); public final String QUITESLEEP_PATH = "quitesleep"; //For the sdcard & internal data app public final String DDBB_DIR = "ddbb"; public final String DDBB_FILE = "quitesleep.db"; //Constante para especificar el nivel de profundidad de busqueda en un //objeto public final int DEEP = 3; public static final String SEMAPHORE = "SEMAPHORE"; }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.syncData; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Mail; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.dialogs.SyncContactsDialog; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.TokenizerUtils; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class SyncContactsNew extends Thread { final private String CLASS_NAME = getClass().getName(); private final Context context; private int insertContact = 0; private SyncContactsDialog syncDialog; //-------------- Getters & Setters -------------------------// public int getInsertContact() { return insertContact; } public void setInsertContact(int insertContact) { this.insertContact = insertContact; } public SyncContactsDialog getSyncDialog() { return syncDialog; } public void setSyncDialog(SyncContactsDialog syncDialog) { this.syncDialog = syncDialog; } //----------------------------------------------------------------------// /** * Constructor with all the three obligatory params for run the synchronization * use for the first time running the application (empty db4o database * contacts data) or for any other synchronization. * * @param context * @param syncDialog */ public SyncContactsNew ( Context context, SyncContactsDialog syncDialog) { this.context = context; this.syncDialog = syncDialog; } /** * This funcion check if the db4o database is full contacts empty, so indicate * that is the first time too run the application. * * @return True or false if the db4o is contact empty or not * @see boolean * @throws Exception */ public boolean isTheFirstTime () throws Exception{ try { ClientDDBB clientDDBB = new ClientDDBB(); List<Contact> contactList = clientDDBB.getSelects().selectAllContacts(); clientDDBB.close(); if (contactList != null && contactList.size()>0) return false; else return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(); } } /** * Synchronize the SQLite data contacts, with at least one phone number, * with the DB4O database. * * @param context * @see insertsContacts after run and finish this function for * check how many contacts are synchronized. */ public void run () { try { if (context != null) { //int insertContact = 0; ClientDDBB clientDDBB = new ClientDDBB(); //get all contacts from de ddbb Cursor contactCursor = context.getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, // Which columns to return. null, // WHERE clause. null, // WHERE clause value substitution null); // Sort order. if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Num contacts: " + contactCursor.getCount()); //Whule startCursor has content while (contactCursor.moveToNext()) { String contactName = contactCursor.getString(contactCursor.getColumnIndex( ContactsContract.Data.DISPLAY_NAME)); String contactId = contactCursor.getString(contactCursor.getColumnIndex( ContactsContract.Contacts._ID)); String hasPhone = contactCursor.getString(contactCursor.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)); //------- for debug only -------------------// if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Name: " + contactName + "\tId: " + contactId + "\thasPhone: " + hasPhone); boolean res = Boolean.parseBoolean(hasPhone); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "boolean: " + res); //---------------------------------------------------// //If the used contact has at least one phone number, we //insert it in the db4o ddbb, else not insert. if (hasPhone.equals("1")) { //Create the db4o contact object. Contact contact = new Contact(contactId, contactName); //insert the contact object clientDDBB.getInserts().insertContact(contact); insertContact ++; //where clausule String where = ContactsContract.Data.CONTACT_ID + " = " + contactId + " AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'"; Cursor phonesCursor = context.getContentResolver().query( ContactsContract.Data.CONTENT_URI, null, where, null, null); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "count: " + phonesCursor.getCount()); List<String> phonesList = new ArrayList<String>(phonesCursor.getCount()); //While the phonesCursor has content while (phonesCursor.moveToNext()) { String phoneNumber = phonesCursor.getString( phonesCursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); phonesList.add(phoneNumber); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "phone: " + phoneNumber); } //close the phones cursor phonesCursor.close(); //create the phones object asociated to contacts createPhoneObjects(contact, phonesList, clientDDBB); //Get all mail from the contact Cursor mailCursor = context.getContentResolver().query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null); if (mailCursor.getCount() > 0) { List<String> mailsList = new ArrayList<String>(mailCursor.getColumnCount()); //While the emailsCursor has content while (mailCursor.moveToNext()) { //This would allow you get several email addresses String emailAddress = mailCursor.getString( mailCursor.getColumnIndex( ContactsContract.CommonDataKinds.Email.DATA)); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "email: " + emailAddress); mailsList.add(emailAddress); } //Create the mail objects asociated to every contact createMailObjects(contact, mailsList, clientDDBB); } //close the email cursor mailCursor.close(); }//end hasPhone //create the Schedule object if not have been created previously createSchedule(clientDDBB); //Commit the transaction clientDDBB.commit(); }//end contact cursor //return insertContact; }//end context!=null else //return -1; insertContact = -1; //this.sleep(5000); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); //return -1; insertContact = -1; }finally { //Hide and dismiss de synchronization dialog syncDialog.stopDialog(context); } } /** * * @param contact * @param phonesList * @param clientDDBB * @return the number of phones created * @see int */ private int createPhoneObjects ( Contact contact, List<String> phonesList, ClientDDBB clientDDBB) { try { int numPhones = 0; for (int i=0; i<phonesList.size(); i++) { /* Here parse the original phone number, wich, by default * contains x dash by other wich contains nothing delim. */ String newPhone = TokenizerUtils.tokenizerPhoneNumber(phonesList.get(i), null); Phone phone = new Phone(contact, newPhone); numPhones ++; clientDDBB.getInserts().insertPhone(phone); } return numPhones; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * * @param contact * @param mailsList * @param clientDDBB * @return the number of mails created (inserted) * @see int */ private int createMailObjects ( Contact contact, List<String> mailsList, ClientDDBB clientDDBB) { try { int numMails = 0; for (int i=0; i<mailsList.size(); i++) { Mail mail = new Mail(contact, mailsList.get(i)); numMails ++; clientDDBB.getInserts().insertMail(mail); } return numMails; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * Create the Schedule object if not was created previously. This object * is an empty Schedule. * * @param clientDDBB * @return true if Schedule object is created or false is not * @see boolean */ private boolean createSchedule (ClientDDBB clientDDBB) { try { Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule == null) { schedule = new Schedule(); clientDDBB.getInserts().insertSchedule(schedule); return true; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.syncData; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import android.util.Log; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Mail; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.dialogs.SyncContactsDialog; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.TokenizerUtils; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class SyncContactsRefresh extends Thread { final private String CLASS_NAME = getClass().getName(); private final Context context; private int insertContact = 0; private SyncContactsDialog syncDialog; //-------------- Getters & Setters -------------------------// public int getInsertContact() { return insertContact; } public void setInsertContact(int insertContact) { this.insertContact = insertContact; } public SyncContactsDialog getSyncDialog() { return syncDialog; } public void setSyncDialog(SyncContactsDialog syncDialog) { this.syncDialog = syncDialog; } //----------------------------------------------------------------------// /** * Constructor with all the three obligatory params for run the synchronization * use for the first time running the application (empty db4o database * contacts data) or for any other synchronization. * * @param context * @param syncDialog */ public SyncContactsRefresh ( Context context, SyncContactsDialog syncDialog) { this.context = context; this.syncDialog = syncDialog; } /** * Delete all objects associated to Contacts, Mail, Phones, and Banned. * @return */ public boolean deleteAll () { try { ClientDDBB clientDDBB = new ClientDDBB(); int deleteContacts = clientDDBB.getDeletes().deleteAllContacts(); int deletePhones = clientDDBB.getDeletes().deleteAllPhones(); int deleteMails = clientDDBB.getDeletes().deleteAllMails(); int deleteBanned = clientDDBB.getDeletes().deleteAllBanned(); int deleteCallLog = clientDDBB.getDeletes().deleteAllCallLog(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteContacts: " + deleteContacts); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deletePhones: " + deletePhones); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteMails: " + deleteMails); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteBanned: " + deleteBanned); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteCallLog:" + deleteCallLog); clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Synchronize the SQLite data contacts, with at least one phone number, * with the DB4O database. * * @param context * @see insertsContacts after run and finish this function for * check how many contacts are synchronized. */ public void run () { try { if (deleteAll()) syncContacts(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); }finally { //Hide and dismiss de synchronization dialog syncDialog.stopDialog(context); } } /** * Sync contacts from the ddbb SQLite to the DB4O ddbb */ private void syncContacts () { try { if (context != null) { //int insertContact = 0; ClientDDBB clientDDBB = new ClientDDBB(); //get all contacts from de ddbb Cursor contactCursor = context.getContentResolver().query( ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Num contacts: " + contactCursor.getCount()); //Whule startCursor has content while (contactCursor.moveToNext()) { String contactName = contactCursor.getString(contactCursor.getColumnIndex( ContactsContract.Data.DISPLAY_NAME)); String contactId = contactCursor.getString(contactCursor.getColumnIndex( ContactsContract.Contacts._ID)); String hasPhone = contactCursor.getString(contactCursor.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)); //------- for debug only -------------------// if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Name: " + contactName + "\tId: " + contactId + "\thasPhone: " + hasPhone); boolean res = Boolean.parseBoolean(hasPhone); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "boolean: " + res); //---------------------------------------------------// //If the used contact has at least one phone number, we //insert it in the db4o ddbb, else not insert. if (hasPhone.equals("1")) { //Create the db4o contact object. Contact contact = new Contact(contactId, contactName); //insert the contact object clientDDBB.getInserts().insertContact(contact); insertContact ++; //where clausule String where = ContactsContract.Data.CONTACT_ID + " = " + contactId + " AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'"; Cursor phonesCursor = context.getContentResolver().query( ContactsContract.Data.CONTENT_URI, null, where, null, null); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "count: " + phonesCursor.getCount()); List<String> phonesList = new ArrayList<String>(phonesCursor.getCount()); //While the phonesCursor has content while (phonesCursor.moveToNext()) { String phoneNumber = phonesCursor.getString( phonesCursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); phonesList.add(phoneNumber); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "phone: " + phoneNumber); } //close the phones cursor phonesCursor.close(); //create the phones object asociated to contacts createPhoneObjects(contact, phonesList, clientDDBB); //Get all mail from the contact Cursor mailCursor = context.getContentResolver().query( ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null); if (mailCursor.getCount() > 0) { List<String> mailsList = new ArrayList<String>(mailCursor.getColumnCount()); //While the emailsCursor has content while (mailCursor.moveToNext()) { //This would allow you get several email addresses String emailAddress = mailCursor.getString( mailCursor.getColumnIndex( ContactsContract.CommonDataKinds.Email.DATA)); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "email: " + emailAddress); mailsList.add(emailAddress); } //Create the mail objects asociated to every contact createMailObjects(contact, mailsList, clientDDBB); } //close the email cursor mailCursor.close(); }//end hasPhone //create the Schedule object if not have been created previously createSchedule(clientDDBB); //Commit the transaction clientDDBB.commit(); }//end contact cursor }//end context!=null else //return -1; insertContact = -1; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); insertContact = -1; } } /** * * @param contact * @param phonesList * @param clientDDBB * @return the number of phones created * @see int */ private int createPhoneObjects ( Contact contact, List<String> phonesList, ClientDDBB clientDDBB) { try { int numPhones = 0; for (int i=0; i<phonesList.size(); i++) { /* Here parse the original phone number, wich, by default * contains x dash by other wich contains nothing delim. */ String newPhone = TokenizerUtils.tokenizerPhoneNumber(phonesList.get(i), null); Phone phone = new Phone(contact, newPhone); numPhones ++; clientDDBB.getInserts().insertPhone(phone); } return numPhones; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * * @param contact * @param mailsList * @param clientDDBB * @return the number of mails created (inserted) * @see int */ private int createMailObjects ( Contact contact, List<String> mailsList, ClientDDBB clientDDBB) { try { int numMails = 0; for (int i=0; i<mailsList.size(); i++) { Mail mail = new Mail(contact, mailsList.get(i)); numMails ++; clientDDBB.getInserts().insertMail(mail); } return numMails; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * Create the Schedule object if not was created previously. This object * is an empty Schedule. * * @param clientDDBB * @return true if Schedule object is created or false is not * @see boolean */ private boolean createSchedule (ClientDDBB clientDDBB) { try { Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule == null) { schedule = new Schedule(); clientDDBB.getInserts().insertSchedule(schedule); return true; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.activities; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import es.cesar.quitesleep.R; import es.cesar.quitesleep.dialogs.WarningDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.subactivities.About; import es.cesar.quitesleep.subactivities.AddBanned; import es.cesar.quitesleep.subactivities.DeleteBanned; import es.cesar.quitesleep.subactivities.Help; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ContactsTab extends Activity implements OnClickListener { final private String CLASS_NAME = getClass().getName(); final private int WARNING_DIALOG = 1; //Ids for the button widgets private final int addBannedId = R.id.contacts_button_addBanned; private final int deleteBannedId = R.id.contacts_button_deleteBanned; private final int syncContactsID = R.id.contacts_button_syncContacts; //Ids for option menu final int aboutMenuId = R.id.menu_information_about; final int helpMenuId = R.id.menu_information_help; //Ids for warning dialog private WarningDialog warningDialog; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contactstab); try { //Instanciate all buttons Button addBannedButton = (Button)findViewById(addBannedId); Button deleteBannedButton = (Button)findViewById(deleteBannedId); Button syncContactsButton = (Button)findViewById(syncContactsID); //Define the buttons listener addBannedButton.setOnClickListener(this); deleteBannedButton.setOnClickListener(this); syncContactsButton.setOnClickListener(this); warningDialog = new WarningDialog(this, ConfigAppValues.WARNING_SYNC_CONTACTS); }catch (Exception e) { e.printStackTrace(); if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, e.toString()); } } /** * onClick method for the view widgets * * @param view View of the used widget */ public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case addBannedId: Intent intentAddContacts = new Intent(this, AddBanned.class); startActivityForResult(intentAddContacts, ConfigAppValues.REQCODE_ADD_BANNED); break; case deleteBannedId: Intent intentViewContacts = new Intent(this, DeleteBanned.class); startActivityForResult(intentViewContacts, ConfigAppValues.REQCODE_DELETE_BANNED); break; case syncContactsID: showDialog(WARNING_DIALOG); break; } } /** * Create the activity dialogs used for it * * @param id * @return the dialog for the option specified * @see Dialog */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case WARNING_DIALOG: if (QSLog.DEBUG_D) QSLog.d(CLASS_NAME, "Create the WarningDialog for 1st time"); dialog = warningDialog.getAlertDialog(); break; default: dialog = null; } return dialog; } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { //TODO if (QSLog.DEBUG_D) QSLog.d(CLASS_NAME, "RequestCode: " + requestCode + "\nResultCode: " + resultCode); } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.informationmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case aboutMenuId: Intent intentAbout = new Intent(this, About.class); startActivityForResult(intentAbout, ConfigAppValues.LAUNCH_ABOUT); break; case helpMenuId: Intent intentHelp = new Intent(this, Help.class); startActivityForResult(intentHelp, ConfigAppValues.LAUNCH_ABOUT); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.activities; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import es.cesar.quitesleep.R; import es.cesar.quitesleep.dialogs.SyncContactsDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.syncData.SyncContactsNew; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * @version 1.0, 02-21-2010 * * Main class for start QuiteSleep App, this class implement the tabs wigets * to show them. * */ public class Main extends TabActivity { final String CLASS_NAME = getClass().getName(); @Override public void onCreate (Bundle savedInstanceState) { try { //Set the min api level for the application, used for choice differents //api methods for differents api levels. ConfigAppValues.setMinApiLevel(getApplicationInfo().targetSdkVersion); //Set the app context for get the ddbb file and other file access if (ConfigAppValues.getContext() == null) ConfigAppValues.setContext(this); if (QSLog.DEBUG_I)QSLog.i(CLASS_NAME, "SDK Version: " + String.valueOf(ConfigAppValues.getMinApiLevel())); super.onCreate(savedInstanceState); //Create the app top bar createAppBar(); //Sync the databases if the db4o database is empty (first time run the app) syncDatabases(); //Resource object to get Drawables Resources resources = getResources(); //The activity tabHost final TabHost tabHost = getTabHost(); //Reusable TabSpec for each tab final TabHost.TabSpec tabSpec = null; //Reusable intent for each tab final Intent intent = null; //------------ Contacts Tab ------------------------------// createContactsTab(intent, tabSpec, tabHost, resources); //------------ Schedule Tab --------------------------// createScheduleTab(intent, tabSpec, tabHost, resources); //------------ Settings Tab --------------------------// createSettingsTab(intent, tabSpec, tabHost, resources); //------------- Logs Tab -----------------------------// createLogsTab(intent, tabSpec, tabHost, resources); //Set the init (main) tab tabHost.setCurrentTab(0); }catch (Exception e) { Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Create the Application Title Bar in top of the activity * * @throws Exception */ private void createAppBar () throws Exception { try { //Put an app icon to the upper left of the screen Window window = getWindow(); window.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.group_tabs); window.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.quitesleep); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(); } } /** * Sync the contacts data between SQLite and DB4O databases the first time * if the db4o database is empty. * It is done used one thread for it. */ private void syncDatabases () { try { SyncContactsDialog syncDialog = new SyncContactsDialog(); SyncContactsNew syncContacts = new SyncContactsNew(this, syncDialog); //Only if the db4o database is empty, we proceed //with the synchronization, otherwise we don't anything if (syncContacts.isTheFirstTime()) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Proceed with the synchronization for the first time"); syncDialog.showDialogFirstTime(this); syncContacts.start(); }else if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "The db4o database already contains data contacts"); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(); } } /** * Create the Contacts Tab * * @param intent * @param tabSpec * @param tabHost * @param resources * @throws Exception */ private void createContactsTab ( Intent intent, TabSpec tabSpec, TabHost tabHost, Resources resources) throws Exception { try { //--------------- Contacts Tab ----------------------// //Create an intent to launch an Activiy for the tab (to be reused) intent = new Intent().setClass(this, ContactsTab.class); //Get the string resource from the string xml set constants CharSequence contactsLabel = getString(R.string.contacts_tab_label); //Initialize a TabSpec for each tab and add it to the TabHost. Also //we add the intent to the tab for when it push, use the intent added //(go to the clock tab) tabSpec = tabHost.newTabSpec(contactsLabel.toString()).setIndicator( contactsLabel, resources.getDrawable(R.drawable.contactstab)).setContent(intent); //Add the TabSpec to the TabHost tabHost.addTab(tabSpec); }catch (Exception e) { e.printStackTrace(); if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(e.toString()); } } /** * Create the Schedule Tab * * @param intent * @param tabSpec * @param tabHost * @param resources * @throws Exception */ private void createScheduleTab ( Intent intent, TabSpec tabSpec, TabHost tabHost, Resources resources) throws Exception { try { //------------ Schedule Tab --------------------------// intent = new Intent().setClass(this, ScheduleTab.class); CharSequence scheduleLabel = getString(R.string.schedule_tab_label); tabSpec = tabHost.newTabSpec(scheduleLabel.toString()).setIndicator( scheduleLabel, resources.getDrawable(R.drawable.scheduletab)).setContent(intent); tabHost.addTab(tabSpec); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(e.toString()); } } /** * * @param intent * @param tabSpec * @param tabHost * @param resources * @throws Exception */ private void createSettingsTab ( Intent intent, TabSpec tabSpec, TabHost tabHost, Resources resources) throws Exception { try { //------------ Settings Tab --------------------------// intent = new Intent().setClass(this, SettingsTab.class); CharSequence messageLabel = getString(R.string.settings_tab_label); tabSpec = tabHost.newTabSpec(messageLabel.toString()).setIndicator( messageLabel, resources.getDrawable(R.drawable.settingstab)).setContent(intent); tabHost.addTab(tabSpec); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(e.toString()); } } /** * * @param intent * @param tabSpec * @param tabHost * @param resources * @throws Exception */ private void createLogsTab ( Intent intent, TabSpec tabSpec, TabHost tabHost, Resources resources) throws Exception { try { //------------ Logs Tab --------------------------// intent = new Intent().setClass(this, LogsTab.class); CharSequence messageLabel = getString(R.string.logs_tab_label); tabSpec = tabHost.newTabSpec(messageLabel.toString()).setIndicator( messageLabel, resources.getDrawable(R.drawable.logstab)).setContent(intent); tabHost.addTab(tabSpec); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(e.toString()); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.widget.ToggleButton; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.notifications.QuiteSleepNotification; import es.cesar.quitesleep.operations.StartStopServicesOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.subactivities.About; import es.cesar.quitesleep.subactivities.Help; import es.cesar.quitesleep.subactivities.MailSettings; import es.cesar.quitesleep.subactivities.SmsSettings; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@mgail.com * */ public class SettingsTab extends Activity implements OnClickListener { private final String CLASS_NAME = getClass().getName(); //Ids for the button widgets final int mailButtonId = R.id.settings_button_mail; final int smsButtonId = R.id.settings_button_sms; final int serviceToggleButtonId = R.id.settings_togglebutton_service; //Ids for option menu final int aboutMenuId = R.id.menu_information_about; final int helpMenuId = R.id.menu_information_help; //Activity buttons private Button mailButton; private Button smsButton; private ToggleButton serviceToggleButton; //Notification //private NotificationManager notificationManager; //final private int notificationId = R.layout.quitesleep_notification; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settingstab); //All Activity buttons mailButton = (Button)findViewById(mailButtonId); smsButton = (Button)findViewById(smsButtonId); serviceToggleButton = (ToggleButton)findViewById(serviceToggleButtonId); //Define all button listeners mailButton.setOnClickListener(this); smsButton.setOnClickListener(this); serviceToggleButton.setOnClickListener(this); //Get the notification manager service //notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); /* Set the previous saved state in the ddbb in the widgets that need * the saved state, such as toggle button. */ setDefaultSavedData(); } /** * Listener for all buttons in this Activity */ public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case mailButtonId: Intent intentMailSettings = new Intent(this, MailSettings.class); startActivityForResult(intentMailSettings, ConfigAppValues.REQCODE_MAIL_SETTINGS); break; case smsButtonId: Intent intentSmsSettings = new Intent(this, SmsSettings.class); startActivityForResult(intentSmsSettings, ConfigAppValues.REQCODE_SMS_SETTINGS); break; case serviceToggleButtonId: startStopServiceProcess(); QuiteSleepNotification.showNotification( this, serviceToggleButton.isChecked()); break; default: break; } } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.informationmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case aboutMenuId: Intent intentAbout = new Intent(this, About.class); startActivityForResult(intentAbout, ConfigAppValues.LAUNCH_ABOUT); break; case helpMenuId: Intent intentHelp = new Intent(this, Help.class); startActivityForResult(intentHelp, ConfigAppValues.LAUNCH_ABOUT); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Put the ddbb saved data in the activity widgets if someone need to * chage this state using a previous save data. */ private void setDefaultSavedData () { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { serviceToggleButton.setChecked(settings.isQuiteSleepServiceState()); }else serviceToggleButton.setChecked(false); clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that depends the serviceToggleButton state try to start the * QuiteSleep incoming call service or stop it. */ private void startStopServiceProcess () { try { boolean result = StartStopServicesOperations.startStopQuiteSleepService( serviceToggleButton.isChecked()); if (serviceToggleButton.isChecked()) { /* Deactivate the notification toast because now use the * status bar notification */ /* if (result) //All right, start the service was ok! Toast.makeText( this, this.getString( R.string.settings_toast_start_service), Toast.LENGTH_SHORT).show(); else //An error has ocurred!! Toast.makeText( this, this.getString( R.string.settings_toast_fail_service), Toast.LENGTH_SHORT).show(); */ }else { if (result) //All right, stop the service was ok! if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.settings_toast_stop_service), Toast.LENGTH_SHORT); else //An error has ocurred!! if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.settings_toast_fail_service), Toast.LENGTH_SHORT); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /* @Override public void onActivityResult (int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } */ }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.activities; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.dialogs.EndTimeDialog; import es.cesar.quitesleep.dialogs.StartTimeDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.subactivities.About; import es.cesar.quitesleep.subactivities.Help; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ScheduleTab extends Activity implements OnClickListener { private final String CLASS_NAME = getClass().getName(); private final int START_TIME_DIALOG = 0; private final int END_TIME_DIALOG = 1; //Ids for the button widgets private final int startTimeButtonId = R.id.schedule_button_startTime; private final int endTimeButtonId = R.id.schedule_button_endTime; private final int daysWeekButtonId = R.id.schedule_button_daysweek; //Ids for thextViews widgets private final int startTimeLabelId = R.id.schedule_textview_startTime; private final int endTimeLabelId = R.id.schedule_textview_endTime; //Days of the week checkboxes Ids private final int mondayCheckId = R.id.schedule_checkbox_monday; private final int tuesdayCheckId = R.id.schedule_checkbox_tuesday; private final int wednesdayCheckId = R.id.schedule_checkbox_wednesday; private final int thursdayCheckId = R.id.schedule_checkbox_thursday; private final int fridayCheckId = R.id.schedule_checkbox_friday; private final int saturdayCheckId = R.id.schedule_checkbox_saturday; private final int sundayCheckId = R.id.schedule_checkbox_sunday; //Used dialogs in this activity private StartTimeDialog startTimeDialog; private EndTimeDialog endTimeDialog; //labels for start and end times private TextView startTimeLabel; private TextView endTimeLabel; //Days of the week checkboxes private CheckBox mondayCheck; private CheckBox tuesdayCheck; private CheckBox wednesdayCheck; private CheckBox thursdayCheck; private CheckBox fridayCheck; private CheckBox saturdayCheck; private CheckBox sundayCheck; //Ids for option menu final int aboutMenuId = R.id.menu_information_about; final int helpMenuId = R.id.menu_information_help; final private String CALCULATOR_FONT = "fonts/calculator_script_mt.ttf"; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scheduletab); startTimeDialog = new StartTimeDialog(this); endTimeDialog = new EndTimeDialog(this); Button startTimeButton = (Button)findViewById(startTimeButtonId); Button endTimeButton = (Button)findViewById(endTimeButtonId); Button daysWeekButton = (Button)findViewById(daysWeekButtonId); //--------- Define our own text style used a custom font ------// startTimeLabel = (TextView)findViewById(startTimeLabelId); endTimeLabel = (TextView)findViewById(endTimeLabelId); Typeface face = Typeface.createFromAsset(getAssets(), CALCULATOR_FONT); startTimeLabel.setTypeface(face); endTimeLabel.setTypeface(face); //-------------------------------------------------------------------// //Sets the timeLabes into start and end time dialogs for update the changes startTimeDialog.setStartTimeLabel(startTimeLabel); endTimeDialog.setEndTimeLabel(endTimeLabel); //Instantiate the days of the week checkboxes mondayCheck = (CheckBox)findViewById(mondayCheckId); tuesdayCheck = (CheckBox)findViewById(tuesdayCheckId); wednesdayCheck = (CheckBox)findViewById(wednesdayCheckId); thursdayCheck = (CheckBox)findViewById(thursdayCheckId); fridayCheck = (CheckBox)findViewById(fridayCheckId); saturdayCheck = (CheckBox)findViewById(saturdayCheckId); sundayCheck = (CheckBox)findViewById(sundayCheckId); //Define the onClick listeners startTimeButton.setOnClickListener(this); endTimeButton.setOnClickListener(this); daysWeekButton.setOnClickListener(this); /* Set the default saved data when this activity is run for first time * (not for first time globally, else for all times that we run * the application and show this activity for first time) */ setDefaultSavedData(); } /** * Listener for all buttons in this Activity */ public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case startTimeButtonId: showDialog(START_TIME_DIALOG); break; case endTimeButtonId: showDialog(END_TIME_DIALOG); break; case daysWeekButtonId: saveDayWeeksSelection(); break; } } /** * For the first time that create the dialogs */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case START_TIME_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the StartTimeDialog for 1st time"); dialog = startTimeDialog.getTimePickerDialog(); break; case END_TIME_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the EndTimeDialog for 1st time"); dialog = endTimeDialog.getTimePickerDialog(); break; default: dialog = null; } return dialog; } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case START_TIME_DIALOG: break; case END_TIME_DIALOG: break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { //TODO if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "en onActiviryResult"); } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.informationmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case aboutMenuId: Intent intentAbout = new Intent(this, About.class); startActivityForResult(intentAbout, ConfigAppValues.LAUNCH_ABOUT); break; case helpMenuId: Intent intentHelp = new Intent(this, Help.class); startActivityForResult(intentHelp, ConfigAppValues.LAUNCH_ABOUT); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Save the days of the weeks checkboxes state into a Schedule object from the * database. If the Schedule object isn't create, we don't do nothing, not save the * checkboxes state. * * @return true or false if the schedule save was good or not * @see boolean */ private boolean saveDayWeeksSelection () { try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule != null) { schedule.setMonday(mondayCheck.isChecked()); schedule.setTuesday(tuesdayCheck.isChecked()); schedule.setWednesday(wednesdayCheck.isChecked()); schedule.setThursday(thursdayCheck.isChecked()); schedule.setFriday(fridayCheck.isChecked()); schedule.setSaturday(saturdayCheck.isChecked()); schedule.setSunday(sundayCheck.isChecked()); clientDDBB.getInserts().insertSchedule(schedule); clientDDBB.commit(); clientDDBB.close(); if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.schedule_toast_daysweek_ok), Toast.LENGTH_SHORT); return true; }else { if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.schedule_toast_daysweek_ko), Toast.LENGTH_SHORT); return false; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(e.toString()); } } /** * Set the default saved data in the start and end time labels and * all checkboxes associated to a day of the week. */ private void setDefaultSavedData () { try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); if (schedule != null) { if (schedule.getStartFormatTime()!= null && !schedule.getStartFormatTime().equals("")) startTimeLabel.setText(schedule.getStartFormatTime()); if (schedule.getEndFormatTime() != null && !schedule.getEndFormatTime().equals("")) endTimeLabel.setText(schedule.getEndFormatTime()); mondayCheck.setChecked(schedule.isMonday()); tuesdayCheck.setChecked(schedule.isTuesday()); wednesdayCheck.setChecked(schedule.isWednesday()); thursdayCheck.setChecked(schedule.isThursday()); fridayCheck.setChecked(schedule.isFriday()); saturdayCheck.setChecked(schedule.isSaturday()); sundayCheck.setChecked(schedule.isSunday()); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.activities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ListActivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.CallLog; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.dialogs.WarningDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class LogsTab extends ListActivity { //Constants final private String CLASS_NAME = this.getClass().getName(); final private int WARNING_REMOVE_DIALOG = 0; final private int WARNING_REFRESH_DIALOG = 1; //Widgets Ids private final int removeCallLogMenuId = R.id.menu_calllog_remove; private final int refreshCallLogMenuId = R.id.menu_calllog_refresh; //Widgets private WarningDialog warningRemoveDialog; private WarningDialog warningRefreshDialog; private ArrayAdapter<String> arrayAdapter; //this activity private Activity thisActivity = this; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); warningRemoveDialog = new WarningDialog( this, ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS); warningRefreshDialog = new WarningDialog( this, ConfigAppValues.WARNING_REFRESH_CALL_LOG); getAllCallLogList(); } /** * Get all CallLog list from de ddbb */ private void getAllCallLogList () { try { ClientDDBB clientDDBB = new ClientDDBB(); List<CallLog> callLogList = clientDDBB.getSelects().selectAllCallLog(); List<String> callLogListString = convertCallLogList(callLogList); if (callLogListString != null) { arrayAdapter = new ArrayAdapter<String>( this, R.layout.logstab, R.id.logstab_textview_contact, callLogListString); setListAdapter(arrayAdapter); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * * @param contactList * @return The contactList but only the list with the name contacts * @see List<String> */ private List<String> convertCallLogList (List<CallLog> callLogList) throws Exception { try { if (callLogList != null && callLogList.size()>0) { List<String> callLogListString = new ArrayList<String>(); for (int i=0; i<callLogList.size(); i++) { String callLogString = callLogList.get(i).toString(); if (callLogString != null) callLogListString.add(callLogString); } return callLogListString; } return null; }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(); } } /** * Create the activity dialogs used for it * * @param id * @return the dialog for the option specified * @see Dialog */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case WARNING_REMOVE_DIALOG: dialog = warningRemoveDialog.getAlertDialog(); break; case WARNING_REFRESH_DIALOG: dialog = warningRefreshDialog.getAlertDialog(); break; default: dialog = null; } return dialog; } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case WARNING_REMOVE_DIALOG: warningRemoveDialog.setContext(this); warningRemoveDialog.setArrayAdapter(arrayAdapter); warningRemoveDialog.setHandler(handlerRemove); break; case WARNING_REFRESH_DIALOG: warningRefreshDialog.setContext(this); warningRefreshDialog.setArrayAdapter(arrayAdapter); warningRefreshDialog.setHandler(handlerRefresh); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.calllogmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case removeCallLogMenuId: showDialog(WARNING_REMOVE_DIALOG); break; case refreshCallLogMenuId: showDialog(WARNING_REFRESH_DIALOG); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Handler for clear the listView and the array adapter once we have been * add all contacts to the banned list */ public final Handler handlerRemove = new Handler() { public void handleMessage(Message message) { if (arrayAdapter != null && arrayAdapter.getCount()>0) { //int count = arrayAdapter.getCount(); int numRemoveCallLogs = message.getData().getInt( ConfigAppValues.NUM_REMOVE_CALL_LOGS); //clear the arrayAdapter arrayAdapter.clear(); //Show the toast message Toast.makeText( ConfigAppValues.getContext(), numRemoveCallLogs + " " + ConfigAppValues.getContext().getString( R.string.menu_calllog_remove_toast), Toast.LENGTH_SHORT).show(); } } }; /** * Handler for clear the listView and the array adapter once we have been * add all contacts to the banned list */ public final Handler handlerRefresh = new Handler() { public void handleMessage(Message message) { ArrayList<String> callLogListString = null; if (arrayAdapter != null) { callLogListString = message.getData().getStringArrayList( ConfigAppValues.REFRESH_CALL_LOG); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "callLoglistString: " + callLogListString); //set the array adapter if (callLogListString != null) { //first delete the previous content list arrayAdapter.clear(); //Second, add all call logs to the list for (int i=0; i<callLogListString.size(); i++) { String callLog = callLogListString.get(i); Log.d(CLASS_NAME, "callLog:" ) ; arrayAdapter.add(callLog); } } //Show the toast message if (QSToast.RELEASE) QSToast.r( ConfigAppValues.getContext(), ConfigAppValues.getContext().getString( R.string.menu_calllog_refresh_toast), Toast.LENGTH_SHORT); } /* If the arrayAdapter previously doesn't have any call log, this * not been initialized, so initialize now. */ else { callLogListString = message.getData().getStringArrayList( ConfigAppValues.REFRESH_CALL_LOG); Log.d(CLASS_NAME, "inicializando arrayAdapter. " + "CallLogListString: " + callLogListString); arrayAdapter = new ArrayAdapter<String>( thisActivity, R.layout.logstab, R.id.logstab_textview_contact, callLogListString); setListAdapter(arrayAdapter); } } }; }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.receivers; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsManager; import android.util.Log; import android.widget.Toast; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * Class that implements the sms receiver action for listen the send action message * */ public class SendActionSMSReceiver extends BroadcastReceiver{ private String CLASS_NAME = getClass().getName(); final String SENT_SMS_ACTION = "SENT_SMS_ACTION"; @Override public void onReceive(Context context, Intent intent) { switch (getResultCode()) { case Activity.RESULT_OK: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Successful transmission!!"); if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext(), "Successful transmission!!", Toast.LENGTH_SHORT); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Nonspecific Failure!!"); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Intent extra: " + intent.getExtras().getInt("errorCode")); if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext(), "Nonspecific Failure!!", Toast.LENGTH_SHORT); break; case SmsManager.RESULT_ERROR_RADIO_OFF: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Radio is turned Off!!"); if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext(), "Radio is turned Off!!", Toast.LENGTH_SHORT); break; case SmsManager.RESULT_ERROR_NULL_PDU: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "PDU Failure"); if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext(), "PDU Failure", Toast.LENGTH_SHORT); break; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.receivers; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.os.PowerManager; import android.os.Vibrator; import android.telephony.PhoneStateListener; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.telephony.TelephonyManager; import android.util.Log; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.listeners.MyPhoneStateListener; import es.cesar.quitesleep.notifications.QuiteSleepNotification; import es.cesar.quitesleep.operations.IncomingCallOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class PhoneStateReceiver extends BroadcastReceiver { private final String CLASS_NAME = getClass().getName(); //Constants for all broadcastreceiver types used in the app private final String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED"; private final String PHONE_STATE = "android.intent.action.PHONE_STATE"; private final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; //Other constants used private final String PDUS = "pdus"; @Override public void onReceive (Context context, Intent intent) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "BroadcastReceive. Tipo: " + intent.getAction()); //------------- LISTEN FOR BOOT COMPLETED ------------------// if (intent.getAction().equals(BOOT_COMPLETED)) { listenBootCompleted(context); } //---------- LISTEN FOR INCOMING CALLS ------------------// else if (intent.getAction().equals(PHONE_STATE)) { listenIncomingCalls(context); } //----------- LISTEN FOR INCOMING SMS ----------------------// else if (intent.getAction().equals(SMS_RECEIVED)) { //listenIncomingSMS(context, intent); } } /** * Listen for BOOT_COMPLETED event and show the QuiteSleep status bar * notification if the QuiteSleep service is previously configured to start * Also initialize things like ConfigAppValues.setContext() * * @param context */ private void listenBootCompleted (Context context) { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "en Boot_Completed!!"); if (ConfigAppValues.getContext() == null) ConfigAppValues.setContext(context); if (ConfigAppValues.getQuiteSleepServiceState() != null) { if (ConfigAppValues.getQuiteSleepServiceState()) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Show notification x ConfigAppValues: " + ConfigAppValues.getQuiteSleepServiceState()); QuiteSleepNotification.showNotification(context, true); } } else { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { ConfigAppValues.setQuiteSleepServiceState(settings.isQuiteSleepServiceState()); if (settings.isQuiteSleepServiceState()) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Show notification x Settings: " + settings.isQuiteSleepServiceState()); QuiteSleepNotification.showNotification(context, true); } } else { ConfigAppValues.setQuiteSleepServiceState(false); settings = new Settings(false); clientDDBB.getInserts().insertSettings(settings); clientDDBB.commit(); } clientDDBB.close(); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Listen for incoming calls and use the listener for. * @param context */ private synchronized void listenIncomingCalls (Context context) { try { MyPhoneStateListener phoneListener = new MyPhoneStateListener(context); TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Listen the incoming SMS. * * @param context * @param intent */ /* private void listenIncomingSMS (Context context, Intent intent) { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SMS RECEIVED!!!!!"); SmsManager sms = SmsManager.getDefault(); Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[])bundle.get(PDUS); SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i=0; i<pdus.length; i++) messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); for (SmsMessage message:messages) { String messageText = message.getMessageBody(); String phoneSender = message.getOriginatingAddress(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SMS Msg: " + messageText); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SMS From: " + phoneSender); if (IncomingCallOperations.ringerMode() != AudioManager.RINGER_MODE_SILENT) IncomingCallOperations.silentIncomingCall(phoneSender); } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } */ }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * Class that implements the sms delivery action for listen the send action message * */ public class DeliveredActionSMSReceiver extends BroadcastReceiver { private String CLASS_NAME = getClass().getName(); final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "The user have been receive the SMS message!!"); if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext(), "The user have been receive the SMS message!!", Toast.LENGTH_SHORT);; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.notifications; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import es.cesar.quitesleep.R; import es.cesar.quitesleep.activities.Main; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class QuiteSleepNotification { private final static String CLASS_NAME = "es.cesar.quitesleep.notifications.QuiteSleepNotification"; //Notification private static NotificationManager notificationManager = null; final private static int notificationId = R.layout.quitesleep_notification; /** * Create the intent that is used when the user touch the QuiteSleep * notification, and then go to the Main class application. * * @return the PendingIntent * @see PendingIntent */ private static PendingIntent notificationIntent (Context context) { // The PendingIntent to launch our activity if the user selects this // notification. Note the use of FLAG_UPDATE_CURRENT so that if there // is already an active matching pending intent, we will update its // extras to be the ones passed in here. PendingIntent contentIntent = PendingIntent.getActivity( context, 0, new Intent( context, Main.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT); return contentIntent; } /** * Show the QuiteSleep service running notification. If is the stop * action, cancel the notification and hide. */ public static void showNotification (Context context, boolean showNotification) { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "notifiactionId: " + notificationId); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "showNotification: " + showNotification); if (showNotification) { //Get the notification manager service if (notificationManager == null) notificationManager = (NotificationManager)context. getSystemService(Context.NOTIFICATION_SERVICE); CharSequence title = context.getText(R.string.app_name); CharSequence message; message = ConfigAppValues.getContext().getText( R.string.quitesleep_notification_start_message); Notification notification = new Notification( R.drawable.quitesleep_statusbar, message, System.currentTimeMillis()); notification.setLatestEventInfo( context, title, message, notificationIntent(context)); /* For the led flash custom notification.ledARGB = 0xff00ff00; notification.ledOnMS = 300; notification.ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS; */ notificationManager.notify(notificationId, notification); }else if (notificationManager != null){ if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Cancelando la notificacion"); notificationManager.cancel(notificationId); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.callServices; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.IBinder; import android.os.Vibrator; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class NormalModeCallService extends Service { private final String CLASS_NAME = getClass().getName(); //------------ Inherited method re-implement ----------------------// @Override public void onCreate () { } @Override public IBinder onBind (Intent intent) { return null; } @Override public int onStartCommand (Intent intent, int flags, int startId) { /* if ((flags & START_FLAG_RETRY) == 0) { //TODO If it's a restart, do something }else { //TODO Alternative background process } */ putRingerModeNormal(); stopSelf(); return Service.START_NOT_STICKY; } //------------------------------------------------------------------------// /** * Put the mobile in normal mode (audio and vibrate), important: normal mode * such the user defined previously (before to put the mobile in silence) * */ private void putRingerModeNormal () { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Poniendo el movil en modo normal"); AudioManager audioManager = (AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE); audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); ConfigAppValues.processIdleCall = false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put the vibrator in mode On */ private void vibrateOn () { try { String vibratorService = Context.VIBRATOR_SERVICE; Vibrator vibrator = (Vibrator)ConfigAppValues.getContext(). getSystemService(vibratorService); vibrator.vibrate(1000); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.callServices; import android.app.Service; import android.content.Intent; import android.os.IBinder; import es.cesar.quitesleep.operations.IncomingCallOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class SilentModeCallService extends Service { private final String CLASS_NAME = getClass().getName(); //------------ Inherited method re-implement ----------------------// @Override public void onCreate () { } @Override public IBinder onBind (Intent intent) { return null; } @Override public int onStartCommand (Intent intent, int flags, int startId) { /* if ((flags & START_FLAG_RETRY) == 0) { //TODO If it's a restart, do something }else { //TODO Alternative background process } */ String incomingCallNumber = intent.getExtras().getString(ConfigAppValues.INCOMING_CALL_NUMBER); IncomingCallOperations incomingCallOperations = new IncomingCallOperations(incomingCallNumber); //If i use threads incomingCallOperations.start(); //I i don't use threads //incomingCallOperations.silentIncomingCall(); //Stop the service by self way stopSelf(); //before i used start_sticky return Service.START_NOT_STICKY; } //------------------------------------------------------------------------// }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Settings extends Id { public final String CLASS_NAME = getClass().getName(); //Attribute Settings QuiteSleep service private boolean quiteSleepServiceState = false; //Attribute Mail Settings private String user; private String passwd; private String subject; private String body; private boolean mailService = false; //Attribute SMS Settings private String smsText; private boolean smsService = false; //--------------- Getters & Setters --------------------------// //@@@@@@@@@ QuiteSleep service @@@@@@@@@@@@@@@// public boolean isQuiteSleepServiceState() { return quiteSleepServiceState; } public void setQuiteSleepServiceState(boolean quiteSleepServiceState) { this.quiteSleepServiceState = quiteSleepServiceState; } //@@@@@@@@@@ Mail Service @@@@@@@@@@@@@@@@@@// public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public boolean isMailService() { return mailService; } public void setMailService(boolean mailService) { this.mailService = mailService; } //@@@@@@@@@@@@ SMS service @@@@@@@@@@@@@@@@@@@@// public boolean isSmsService() { return smsService; } public void setSmsService(boolean smsService) { this.smsService = smsService; } public String getSmsText() { return smsText; } public void setSmsText(String smsText) { this.smsText = smsText; } //------------------------------------------------------------------------// /** * Constructor without parameters */ public Settings () { super(); } /** * Constructor with the basic paramters * @param quiteSleepServiceState */ public Settings (boolean quiteSleepServiceState) { super(); this.quiteSleepServiceState = quiteSleepServiceState; } @Override public String toString () { return "Settings: \tquiteSleepServiceState: " + quiteSleepServiceState; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Phone extends Id { private Contact contact; private String contactPhone; private boolean usedToSend; //------- Getters & Setters --------------// public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } public boolean isUsedToSend() { return usedToSend; } public void setUsedToSend(boolean usedToSend) { this.usedToSend = usedToSend; } //---------------------------------------------// /** * Constructor without parameters */ public Phone () { super(); } /** * Constructor with basic paramters * * @param contact * @param contactPhone */ public Phone (Contact contact, String contactPhone) { super(); this.contact = contact; this.contactPhone = contactPhone; } public Phone (Contact contact, String contactPhone, boolean usedToSend) { super(); this.contact = contact; this.contactPhone = contactPhone; this.usedToSend = usedToSend; } @Override public String toString () { return "Contact: " + contact + "\nPhone: " + contactPhone + "\tUsedToSend: " + usedToSend; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import java.text.DateFormat; import java.util.Date; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Schedule extends Id { //--- Time in Calendar format -----// private Date startTime; private Date endTime; //---- Time formatted ----------------// private String startFormatTime; private String endFormatTime; //---------- Week days ------------------// private boolean monday = false; private boolean tuesday = false; private boolean wednesday = false; private boolean thursday = false; private boolean friday = false; private boolean saturday = false; private boolean sunday = false; //--------------------------------------------------// //------ Getters & Setters --------------// public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getStartFormatTime() { return startFormatTime; } public void setStartFormatTime(String startFormatTime) { this.startFormatTime = startFormatTime; } public String getEndFormatTime() { return endFormatTime; } public void setEndFormatTime(String endFormatTime) { this.endFormatTime = endFormatTime; } //---------------- Week days ---------------------------// public boolean isMonday() { return monday; } public void setMonday(boolean monday) { this.monday = monday; } public boolean isTuesday() { return tuesday; } public void setTuesday(boolean tuesday) { this.tuesday = tuesday; } public boolean isWednesday() { return wednesday; } public void setWednesday(boolean wednesday) { this.wednesday = wednesday; } public boolean isThursday() { return thursday; } public void setThursday(boolean thursday) { this.thursday = thursday; } public boolean isFriday() { return friday; } public void setFriday(boolean friday) { this.friday = friday; } public boolean isSaturday() { return saturday; } public void setSaturday(boolean saturday) { this.saturday = saturday; } public boolean isSunday() { return sunday; } public void setSunday(boolean sunday) { this.sunday = sunday; } //------------- StartTimes ----------------------------------// public void setAllStartTime (Date startTime, String startFormatTime) { this.startTime = startTime; this.startFormatTime = startFormatTime; } public void setAllEndTime (Date endTime, String endFormatTime) { this.endTime = endTime; this.endFormatTime = endFormatTime; } //--------------------------------------------------------------------// /** * Constructor without parameters */ public Schedule () { super(); } /** * Constructor with the basic parameters * @param startTime * @param endTime */ public Schedule (Date startTime, Date endTime) { super(); this.startTime = startTime; this.endTime = endTime; //Convert all calendar schedules to format strings schedules DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT); this.startFormatTime = dateFormat.format(startTime); this.endFormatTime = dateFormat.format(endTime); } /** * * @param startTime * @param endTime * @param startFormatTime * @param endFormatTime */ public Schedule ( Date startTime, Date endTime, String startFormatTime, String endFormatTime) { super(); this.startTime = startTime; this.endTime = endTime; this.startFormatTime = startFormatTime; this.endFormatTime = endFormatTime; } @Override public String toString () { return "StartTime: " + startFormatTime + "\tEndTime: " + endFormatTime + "\nMonday: " + monday + "\tTuesday: " + tuesday + "\tWednesday: " + wednesday + "\tThursday:" + thursday + "\tFriday: " + friday + "\tSaturday: " + saturday + "\tSunday: " + sunday; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Banned extends Id { private Contact contact; private Schedule schedule; //-------- Getters & Setters ---------------// public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public Schedule getSchedule() { return schedule; } public void setSchedule(Schedule schedule) { this.schedule = schedule; } //----------------------------------------------// /** * Constructor without parameters */ public Banned () { super(); } /** * Contacts with all parameters * * @param contact * @param schedule */ public Banned (Contact contact, Schedule schedule) { super(); this.contact = contact; this.schedule = schedule; } @Override public String toString () { return "Contact: " + contact + "\nSchedule: " + schedule; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class CallLog extends Id { private int numOrder; private Contact contact; private String phoneNumber; private boolean sendSms = false; private int numSendMail; private String timeCall; //------------------------------------------------------------------------// public void setNumOrder(int numOrder) { this.numOrder = numOrder; } public void setContact(Contact contact) { this.contact = contact; } public Contact getContact() { return contact; } public int getNumOrder() { return numOrder; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public boolean isSendSms() { return sendSms; } public void setSendSms(boolean sendSms) { this.sendSms = sendSms; } public int getNumSendMail() { return numSendMail; } public void setNumSendMail(int numSendMail) { this.numSendMail = numSendMail; } public String getTimeCall() { return timeCall; } public void setTimeCall(String timeCall) { this.timeCall = timeCall; } //------------------------------------------------------------------------// /** * Constructor without parameters */ public CallLog () { super(); } /** * Constructor with the first paramter to get usually * * @param phone */ public CallLog (String phone) { super(); this.phoneNumber = phone; } /** * Constructor with all parameters * * @param contact * @param phone * @param numSendSms * @param sendMail * @param timeCall * @param timeCallLong */ public CallLog ( Contact contact, String phone, boolean sendSms, int numSendMail, String timeCall) { super(); this.contact = contact; this.phoneNumber = phone; this.sendSms = sendSms; this.numSendMail = numSendMail; this.timeCall = timeCall; } @Override public String toString () { return contact.getContactName() + "\t(" + phoneNumber + ")" + "\n" + timeCall + "\t\tSms: " + (sendSms ? 1:0) + "\tEmail: " + numSendMail; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import java.io.Serializable; import es.cesar.quitesleep.utils.SHA1Utils; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Id implements Serializable { /** * */ private static final long serialVersionUID = 1L; protected String id = ""; public String getId () { return id; } public void setId (String id) { this.id = id; } /** * Constructor that create an unique Identificator Id for any object * in the DDBB. */ public Id () { //get the actual system time in nanoseconds String time = String.valueOf(System.nanoTime()); //Create a sha1 string for the time previously got this.id = SHA1Utils.generateSHA1toString(time); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import java.util.List; import android.util.Log; import com.db4o.ObjectContainer; import com.db4o.ext.StoredClass; import com.db4o.query.Query; import es.cesar.quitesleep.interfaces.IDDBB; import es.cesar.quitesleep.staticValues.DDBBValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Selects implements IDDBB { private final String CLASS_NAME = getClass().getName(); private ObjectContainer db; /** * Constructor * * @param db */ public Selects (ObjectContainer db) { this.db = db; } /** * Select all Contact objects from the DDBB and return it. * * @return All Contact objects from the DDBB * @see List<Contact> */ public List<Contact> selectAllContacts () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Contact.class); //Ordered by name (first A....last Z) query.descend(DDBBValues.CONTACT_NAME).orderAscending(); List<Contact> contactList = query.execute(); return contactList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Select one Contact that is the same with the name passed * * @param contactName * @return The contact match with the passed name * @see Contact */ public Contact selectContactForName (String contactName) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Contact.class); query.descend(DDBBValues.CONTACT_NAME).constrain(contactName); List<Contact> contactList = query.execute(); if (contactList != null && contactList.size() == 1) return contactList.get(0); else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString()); return null; } } /** * Select Contact object match with the passed phoneNumber, search * along all contact's phone numbers. * * @param phoneContact * @return Contact that match with the passed phone number * any contact's phone number * @see Contact */ public Contact selectContactForPhoneNumber (String phoneContact) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Phone.class); query.descend(DDBBValues.CONTACT_PHONE).constrain(phoneContact); List<Phone> contactList = query.execute(); if (contactList != null && contactList.size() == 1) { Phone phone = contactList.get(0); return phone.getContact(); } else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString()); return null; } } /** * Select Contact object match with the passed phoneNumber, search * along all contact's phone numbers. * * @param phoneNumber * @return Contact that match with the passed phone number * any contact's phone number * @see Contact */ public Contact selectContactForMail (String mailContact) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Mail.class); query.descend(DDBBValues.CONTACT_MAIL).constrain(mailContact); List<Mail> contactList = query.execute(); if (contactList != null && contactList.size() == 1) { Mail mail = contactList.get(0); return mail.getContact(); } else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString()); return null; } } /** * Get all phones of the selected contact * @param contactName * @return All phones about the selected contact * @see List<Phone> */ public List<Phone> selectAllContactPhonesForName (String contactName) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Phone.class); query.descend(DDBBValues.CONTACT).descend( DDBBValues.CONTACT_NAME).constrain(contactName); List<Phone> phonesList = query.execute(); return phonesList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Get all mails from the selected contact * @param contactName * @return List with all contact's mails * @see List<Mail> */ public List<Mail> selectAllContactMailsForName (String contactName) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Mail.class); query.descend(DDBBValues.CONTACT).descend( DDBBValues.CONTACT_NAME).constrain(contactName); List<Mail> mailsList = query.execute(); return mailsList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * * @param contact * @return */ public List<Mail> selectAllContactMailForContact (Contact contact) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Mail.class); query.descend(DDBBValues.CONTACT).constrain(contact); List<Mail> mailList = query.execute(); return mailList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Get all banned contacts from the database * * @return List with all contacts or null if there any exception * @see List<Banned> */ public List<Banned> selectAllBannedContacts () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Banned.class); //Ordered by name (first A....last Z) query.descend(DDBBValues.CONTACT). descend(DDBBValues.CONTACT_NAME).orderAscending(); List<Banned> bannedList = query.execute(); return bannedList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Get all not banned contacts from the database * * @return */ public List<Contact> selectAllNotBannedContacts () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Contact.class); query.descend(DDBBValues.BANNED).constrain(false); query.descend(DDBBValues.CONTACT_NAME).orderAscending(); List<Contact> contactList = query.execute(); return contactList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Get the banned contact associate to the phone number passed to the * function. Check if the contact name associate to the phone is in the * ddbb and if the contact has the flag banned to true. * * @param phoneNumber * @return contact if exists one contact banned who has * the incoming number passed * @see Contact */ public Contact selectBannedContactForPhoneNumber (String phoneNumber) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Phone.class); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "PhoneNumber: " + phoneNumber); query.descend(DDBBValues.CONTACT_PHONE).constrain(phoneNumber).and( query.descend(DDBBValues.CONTACT).descend(DDBBValues.BANNED).constrain(true)); List<Phone> phoneBannedList = query.execute(); if (phoneBannedList != null && phoneBannedList.size() == 1) { Phone phone = phoneBannedList.get(0); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Phone: " + phone); return phone.getContact(); } else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Get the banned object that match with the contactName passed. * * @param contactName * @return The banned object matches with the contactName passed. * @see Banned */ public Banned selectBannedContactForName (String contactName) { try { synchronized(SEMAPHORE) { Query query = db.query(); query.constrain(Banned.class); query.descend(DDBBValues.CONTACT).descend( DDBBValues.CONTACT_NAME).constrain(contactName); List<Banned> bannedList = query.execute(); if (bannedList != null && bannedList.size() == 1) return bannedList.get(0); else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Get the (for the moment) the one Schedule object in the database. * For now (04-17-2010) in this application version of quitesleep, must be * only one Schedule object in the database, so all banned objects have to * use the same Schedule object. * * @return The (for the moment) only Schedule object in the database * @see Schedule */ public Schedule selectSchedule () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Schedule.class); List<Schedule> scheduleList = query.execute(); if (scheduleList != null && scheduleList.size() == 1) return scheduleList.get(0); else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Return the settings object only if is the one in the ddbb, else * return null because have to be an error, only must be one Settings object * in the ddbb. * * @return The settings object * @see Settings */ public Settings selectSettings () { try { synchronized(SEMAPHORE) { Query query = db.query(); query.constrain(Settings.class); List<Settings> settingsList = query.execute(); if (settingsList != null && settingsList.size()==1) return settingsList.get(0); else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * * @param phoneNumber * @return */ public Phone selectPhoneForPhoneNumber (String phoneNumber) { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Phone.class); query.descend(DDBBValues.CONTACT_PHONE).constrain(phoneNumber); List<Phone> phoneList = query.execute(); if (phoneList != null) return phoneList.get(0); else return null; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * * @return */ public List<CallLog> selectAllCallLog () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(CallLog.class); //Order by the most new to the most older query.descend(DDBBValues.NUM_ORDER).orderDescending(); List<CallLog> callLogList = query.execute(); return callLogList; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * * @return */ public int countCallLog () { try { synchronized (SEMAPHORE) { StoredClass storedClass = db.ext().storedClass(CallLog.class); return storedClass.getIDs().length; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import android.util.Log; import com.db4o.ObjectContainer; import es.cesar.quitesleep.interfaces.IDDBB; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * @note This class is also used as update parent class, because the operations * are the same in both cases * */ public class Inserts implements IDDBB{ private final String CLASS_NAME = getClass().getName(); //The link with the database for can does operations protected ObjectContainer db; /** * Constructor * * @param db */ public Inserts (ObjectContainer db) { this.db = db; } /** * Insert one Contact object in the DDBB. * * @param contact * @return true or false depends the operation result * @see boolean */ public boolean insertContact (Contact contact) { try { synchronized(SEMAPHORE) { db.store(contact); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param phone * @return boolean */ public boolean insertPhone (Phone phone) { try { synchronized (SEMAPHORE) { db.store(phone); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param mail * @return */ public boolean insertMail (Mail mail) { try { synchronized (SEMAPHORE) { db.store(mail); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param banned * @return */ public boolean insertBanned (Banned banned) { try { synchronized (SEMAPHORE) { db.store(banned); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param schedule * @return */ public boolean insertSchedule (Schedule schedule) { try { synchronized(SEMAPHORE) { db.store(schedule); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param settings * @return */ public boolean insertSettings (Settings settings) { try { synchronized (SEMAPHORE) { db.store(settings); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param callLog * @return */ public boolean insertCallLog (CallLog callLog) { try { synchronized (SEMAPHORE) { db.store(callLog); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import java.util.List; import android.util.Log; import com.db4o.ObjectContainer; import com.db4o.query.Query; import es.cesar.quitesleep.interfaces.IDDBB; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Deletes implements IDDBB { final String CLASS_NAME = getClass().getName(); private ObjectContainer db; /** * Constructor * * @param db */ public Deletes (ObjectContainer db) { this.db = db; } /** * Delete one Contact object in the DDBB that matches with the passed * * @param contact * @return true or false with the operation result * @see boolean */ public boolean deleteContact (Contact contact) { try { synchronized (SEMAPHORE) { db.delete(contact); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Delete the banned object passed * * @param banned * @return true or false of the banned object delete sucessfully * @see boolean */ public boolean deleteBanned (Banned banned) { try { synchronized (SEMAPHORE) { db.delete(banned); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @param settings * @return */ public boolean deleteSettings (Settings settings) { try { synchronized(SEMAPHORE) { db.delete(settings); return true; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * * @return */ public int deleteAllContacts () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Contact.class); List<Contact> contactList = query.execute(); int deletes = 0; if (contactList != null) for (int i=0; i<contactList.size(); i++){ Contact contact = contactList.get(i); db.delete(contact); deletes ++; } return deletes; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * * @return */ public int deleteAllPhones () { try { synchronized(SEMAPHORE) { Query query = db.query(); query.constrain(Phone.class); List<Phone> phoneList = query.execute(); int deletes = 0; if (phoneList != null) for (int i=0; i<phoneList.size(); i++) { Phone phone = phoneList.get(i); db.delete(phone); deletes ++; } return deletes; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * * @return */ public int deleteAllMails () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(Mail.class); List<Mail> mailList = query.execute(); int deletes = 0; if (mailList != null) for (int i=0; i<mailList.size(); i++) { Mail mail = mailList.get(i); db.delete(mail); deletes++; } return deletes; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * * @return */ public int deleteAllBanned () { try { Query query = db.query(); query.constrain(Banned.class); List<Banned> bannedList = query.execute(); int deletes = 0; if (bannedList != null) for (int i=0; i<bannedList.size(); i++) { Banned banned = bannedList.get(i); db.delete(banned); deletes++; } return deletes; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * * @return */ public int deleteAllCallLog () { try { synchronized (SEMAPHORE) { Query query = db.query(); query.constrain(CallLog.class); List<CallLog> callLogList = query.execute(); int deletes = 0; if (callLogList != null) for (int i=0; i<callLogList.size(); i++) { CallLog callLog = callLogList.get(i); db.delete(callLog); deletes ++; } return deletes; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Contact extends Id { private String contactId; private String contactName; private boolean banned = false; //------------- Getters & Setters ------------------------------// public String getContactId() { return contactId; } public void setContactId(String contactId) { this.contactId = contactId; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public boolean isBanned() { return banned; } public void setBanned(boolean banned) { this.banned = banned; } //------------------------------------------------------------------------// /** * Constructor without parameters */ public Contact () { super(); } /** * Complete constructor with two essential properties, contact id and contact name * * @param contactId * @param contactName */ public Contact (String contactId, String contactName) { super(); this.contactId = contactId; this.contactName = contactName; } /** * Function return toString */ public String toString () { return "ContactId: " + contactId + "\tContactName: " + contactName + "\tBanned: " + banned; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import android.util.Log; import com.db4o.ObjectContainer; import com.db4o.ObjectServer; import es.cesar.quitesleep.interfaces.IDDBB; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ClientDDBB implements IDDBB{ final String CLASS_NAME = getClass().getName(); protected ObjectContainer clientDDBB; protected Selects selects; protected Inserts inserts; protected Updates updates; protected Deletes deletes; /** * This function return the ObjectContainer ised like as clientDDBB for * the application. * * @return The ObjectContainer used like as clientDDBB * @see ObjectContainer */ public ObjectContainer getObjectContainer () { return clientDDBB; } /** * Otro cliente para conectarse al servidor de forma embebida, pero * a diferencia del anterior, usamos una clase estática que lo lanza. */ public ClientDDBB () { try { synchronized (SEMAPHORE) { clientDDBB = ServerDDBB.getServer().openClient(); selects = new Selects(clientDDBB); inserts = new Inserts(clientDDBB); updates = new Updates(clientDDBB); deletes = new Deletes(clientDDBB); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * * @param cliente */ public ClientDDBB (ObjectContainer clientDDBB) { try { synchronized (SEMAPHORE) { selects = new Selects(clientDDBB); inserts = new Inserts(clientDDBB); updates = new Updates(clientDDBB); deletes = new Deletes(clientDDBB); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Constructor al que le pasamos un servidor para que lo utilice en vez * de utilizar el que pone en memoria la clase ServerBBDDEmbebido. * * Este constructor esta creado para ser utilizado en la Migración de BBDD. * * @param server */ public ClientDDBB (ObjectServer serverDDBB) { try { synchronized (SEMAPHORE) { clientDDBB = serverDDBB.openClient(); selects = new Selects(clientDDBB); inserts = new Inserts(clientDDBB); updates = new Updates(clientDDBB); deletes = new Deletes(clientDDBB); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that close the ClientDDBB if it's opened previously */ public void close () { if (!isClosed()) // close the ObjectContainer clientDDBB.close(); } /** * Function that said if the client is closed * @return true or false if the clientDDBB is closed or not * @see boolean */ public boolean isClosed () { if (clientDDBB != null) return clientDDBB.ext().isClosed(); else return true; } public void commit () { clientDDBB.commit(); } public ObjectContainer getClientDDBB() { return clientDDBB; } public void setClientDDBB(ObjectContainer clientDDBB) { this.clientDDBB = clientDDBB; } public Selects getSelects() { return selects; } public void setSelects(Selects selects) { this.selects = selects; } public Inserts getInserts() { return inserts; } public void setInserts(Inserts inserts) { this.inserts = inserts; } public Updates getUpdates() { return updates; } public void setUpdates(Updates updates) { this.updates = updates; } public Deletes getDeletes() { return deletes; } public void setDeletes(Deletes deletes) { this.deletes = deletes; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Mail extends Id { private Contact contact; private String contactMail; private boolean usedToSend; //------ Getters & Setters ---------------// public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public String getContactMail() { return contactMail; } public void setContactMail(String contactMail) { this.contactMail = contactMail; } public boolean isUsedToSend() { return usedToSend; } public void setUsedToSend(boolean usedToSend) { this.usedToSend = usedToSend; } //------------------------------------------------// /** * Constructor without parameters */ public Mail () { super(); } /** * Constructor with basic parameters * @param contact * @param contactMail */ public Mail (Contact contact, String contactMail) { super(); this.contact = contact; this.contactMail = contactMail; } /** * Constructor with all parameters * @param contact * @param contactMail * @param usedToSend */ public Mail (Contact contact, String contactMail, boolean usedToSend) { super(); this.contact = contact; this.contactMail = contactMail; this.usedToSend = usedToSend; } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import android.util.Log; import com.db4o.ObjectServer; import com.db4o.cs.Db4oClientServer; import com.db4o.cs.config.ServerConfiguration; import es.cesar.quitesleep.interfaces.IDDBB; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ServerDDBB implements IDDBB { private final static String CLASS_NAME = "es.cesar.quitesleep.ddbb.ServerDDBB"; /** * This object is for get only one Singleton object and create ONLY inside * of this class mode. */ private static ServerDDBB SINGLETON = null; /** * This object is the server DDBB file properly said */ private static ObjectServer server = null; /** * Constructor for the ServerDDBB */ private ServerDDBB () { try { if (QSLog.DEBUG_I)QSLog.i(CLASS_NAME, "Before to open the DDBB"); ServerConfiguration configuration = Db4oClientServer.newServerConfiguration(); configuration.common().allowVersionUpdates(true); configuration.common().activationDepth(DEEP); server = Db4oClientServer.openServer( configuration, getDDBBFile(DDBB_FILE), 0); if (server == null) if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Server Null!!!!"); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Create the server instance if the server doesn't create before */ private synchronized static void createInstance () { if (server == null) SINGLETON = new ServerDDBB(); } /** * Get the server DDBB instance, if the singleton object doesn't create * before, we create for use it. * * @return The server object * @see ObjectsServer */ public static ObjectServer getServer() { if (SINGLETON == null) createInstance(); return server; } /** * Function for logs only */ public static void checkServer () { if (SINGLETON == null) if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Singleton Nul!!!"); else if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Singleton Not Null!!!"); if (server == null) if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Server Null!!!"); else if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Server Not Null!!!"); } /** * Destructor class function */ protected void finalize () { if (server != null) { server.close(); server = null; } } /** * Function that defrag de Server DDBB File for get free space */ public static void defrag () { try { if (server != null) com.db4o.defragment.Defragment.defrag( getDDBBFile(DDBB_FILE), getDDBBFile(DDBB_FILE + ".old")); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that returns the ddbb file string from the app * * @param ddbb_file * @return The ddbb filename * @see String */ private static String getDDBBFile(String ddbb_file) { //ConfigAppValues.getContext(); if (ConfigAppValues.getContext() != null) if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "getContext != null"); else if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "getContext == null"); return ConfigAppValues.getContext().getDir( DDBB_DIR, ConfigAppValues.getContext().MODE_PRIVATE) + "/" + ddbb_file; //NOTA: Para escribir en la sdcard, no se utiliza getContext().getDir() //Se utiliza FileOutputStream y las funciones normales de java.io } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.ddbb; import com.db4o.ObjectContainer; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class Updates extends Inserts { private final String CLASS_NAME = getClass().getName(); public Updates (ObjectContainer db) { super(db); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.listeners; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.Toast; import es.cesar.quitesleep.callServices.NormalModeCallService; import es.cesar.quitesleep.callServices.SilentModeCallService; import es.cesar.quitesleep.operations.CheckSettingsOperations; import es.cesar.quitesleep.operations.IncomingCallOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class MyPhoneStateListener extends PhoneStateListener { private final String CLASS_NAME = getClass().getName(); /** * Constructor with the context parameter for use if the application * not run and is the BOOT_COMPLETED BroadcastReceiver that is launch * this. * @param context */ public MyPhoneStateListener (Context context) { super(); if (ConfigAppValues.getContext() == null) ConfigAppValues.setContext(context); } /** * Function that receive the state id for the phone state type * (idle, offhook and ringing), and the incoming number that is doing * the call. */ public void onCallStateChanged (int state, String incomingNumber) { try { switch (state) { //------------- CALL_STATE_IDLE ----------------------// case TelephonyManager.CALL_STATE_IDLE: processCallStateIdle(); break; //----------------- CALL_STATE_OFFHOOK --------------// case TelephonyManager.CALL_STATE_OFFHOOK: processCallStateOffhook(); break; //----------------- CALL_STATE_RINGING --------------// case TelephonyManager.CALL_STATE_RINGING: processCallStateRinging(incomingNumber); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Proces the CALL_STATE_IDLE signal from PhoneReceiver */ private void processCallStateIdle () { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "IDLE"); ConfigAppValues.processRingCall = false; if (ringerMode() == AudioManager.RINGER_MODE_SILENT && CheckSettingsOperations.checkQuiteSleepServiceState() && !ConfigAppValues.processIdleCall) { /* Put one pause of 1 second for wait before put the * ringer mode to normal again */ //Thread.sleep(1000); ConfigAppValues.processIdleCall = true; //-- If u choose use Android Service for process incoming call use this --// ConfigAppValues.getContext().startService( new Intent( ConfigAppValues.getContext(), NormalModeCallService.class)); //------------------------------------------------------------// if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext().getApplicationContext(), "IDLE!!!!!!!!", Toast.LENGTH_SHORT); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e( CLASS_NAME, ExceptionUtils.exceptionTraceToString(e.toString(), e.getStackTrace())); } } /** * Proces the CALL_STATE_OFFHOOK signal from PhoneReceiver */ private void processCallStateOffhook () { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "OFFHOOK"); ConfigAppValues.processRingCall = false; if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext().getApplicationContext(), "OFFHOOK!!!!!!!!", Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Proces the CALL_STATE_RINGING signal from PhoneReceiver */ private void processCallStateRinging (String incomingNumber) { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "RINGING"); /* Put the device in silent mode if the inc.oming number is * from contact banned and in schedule interval */ if (ringerMode() != AudioManager.RINGER_MODE_SILENT && CheckSettingsOperations.checkQuiteSleepServiceState() && !ConfigAppValues.processRingCall) { ConfigAppValues.processRingCall = true; //-- If u choose use Android Service for send SMS use this --// ConfigAppValues.getContext().startService( new Intent( ConfigAppValues.getContext(), SilentModeCallService.class).putExtra( ConfigAppValues.INCOMING_CALL_NUMBER, incomingNumber)); //------------------------------------------------------------// if (QSToast.DEBUG) QSToast.d( ConfigAppValues.getContext().getApplicationContext(), "RINGING!!!!!!!!", Toast.LENGTH_SHORT); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Get what ringer mode is at the moment. * * @return return RINGER_MODE_SILENT(0), RINGER_MODE_NORMAL(2), RINGER_MODE_VIBRATE(1) * @see int * @throws Exception */ private int ringerMode () throws Exception { try { AudioManager audioManager = (AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE); //Only for traces switch (audioManager.getRingerMode()) { case AudioManager.RINGER_MODE_SILENT: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Ringer_Mode_Silent"); break; case AudioManager.RINGER_MODE_NORMAL: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Ringer_Mode_Normal"); break; case AudioManager.RINGER_MODE_VIBRATE: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Ringer_Mode_Vibrate"); break; default: break; } return audioManager.getRingerMode(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import java.util.StringTokenizer; import android.util.Log; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class TokenizerUtils { private final static String CLASS_NAME = "es.cesar.quitesleep.utils.TokenizerUtils"; public static void main (String[] args) { final String PHONE = "6-76-10--4-15-9"; String newPhone = tokenizerPhoneNumber(PHONE, null); //Log.e("tokens", "OldPhone: " + PHONE + "NewPhone: " + newPhone); System.out.println("OldPhone: " + PHONE + " NewPhone: " + newPhone); } /** * Tokenize the passed phoneNumber erasing the string separator and return * the phone number whitout these. * * @param phoneNumber * @param delim * @return the new String without the delim chars * @see String */ public static String tokenizerPhoneNumber ( String phoneNumber, String delim) { final String DEFAULT_DELIM = "-"; try { //If not delim has been specified, put the default delim if (delim == null) delim = DEFAULT_DELIM; //If phone number is different from null we parse it. if (phoneNumber != null) { /* Separate the phone number into tokens which the delim string * is the "separate word" */ StringTokenizer tokenizer = new StringTokenizer(phoneNumber, delim); String phoneNumberWithoutDelim = ""; while (tokenizer.hasMoreTokens()) phoneNumberWithoutDelim = phoneNumberWithoutDelim + tokenizer.nextToken(); return phoneNumberWithoutDelim; } return null; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Add an increase of hours to the time passed, if the delim parameter is null * we use the default parameter ":" * * @param time * @param increase * @param delim * @return the new time with the increase done * @see String */ public static String addIncreaseDate (String time, int increase, String delim) { try { final String DEFAULT_DELIM = ":"; if (delim == null) delim = DEFAULT_DELIM; if (time != null) { /* Separate the time into tokens which the delim string * is the "separate word" */ StringTokenizer tokenizer = new StringTokenizer(time, delim); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "count tokens: " + tokenizer.countTokens()); if (tokenizer.countTokens() == 2) { String hourString = tokenizer.nextToken(); String minStrig = tokenizer.nextToken(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "hourString: " + hourString + "\tminString: " + minStrig); int hour = Integer.valueOf(hourString); String completeNewTime = String.valueOf(hour + increase) + ":" + minStrig; if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "new time: " + completeNewTime); return completeNewTime; } } else { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "time == null"); return null; } return null; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import android.content.Context; import android.widget.Toast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * Class for show or not Toast notificactions * Two levels: * - Debug mode (for develop process) * - Release mode (for release app) * */ public class QSToast { private final static String CLASS_NAME = "es.cesar.quitelseep.utils.QSToast"; public static final boolean DEBUG = true; public static final boolean RELEASE = true; /** * Toast for debug (d) mode * * @param context * @param message * @param length */ public static void d(Context context, String message, int length) { Toast.makeText( context, message, length).show(); } /** * Toast for release (r) mode * * @param context * @param message * @param length */ public static void r(Context context, String message, int length) { Toast.makeText( context, message, length).show(); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.activation.DataSource; /** * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * @codefrom http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-ap * */ public class ByteArrayDataSource implements DataSource { private byte[] data; private String type; public ByteArrayDataSource(byte[] data, String type) { super(); this.data = data; this.type = type; } public ByteArrayDataSource(byte[] data) { super(); this.data = data; } public void setType(String type) { this.type = type; } public String getContentType() { if (type == null) return "application/octet-stream"; else return type; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public String getName() { return "ByteArrayDataSource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Not Supported"); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import android.util.Log; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class QSLog { public static final boolean DEBUG_V = true; public static final boolean DEBUG_D = true; public static final boolean DEBUG_I = true; public static final boolean DEBUG_W = true; public static final boolean DEBUG_E = true; public static void v(String className, String msg) { Log.v(className, msg); } public static void d(String className, String msg) { Log.d(className, msg); } public static void i(String className, String msg) { Log.i(className, msg); } public static void w(String className, String msg) { Log.w(className, msg); } public static void e(String className, String msg) { Log.e(className, msg); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.MessageDigest; import java.util.Arrays; import android.util.Log; /** * * @author Cesar Valiente Gordo y Eduardo Coca Sola * @mail cesar.valiente@gmail.com * */ public class SHA1Utils { final static String CLASS_NAME = "SHA1Util"; // Genera SHA-1 de un char[] public static byte[] generateSHA1 (char chars[]) { return generateSHA1(new String(chars)); } // Genera SHA-1 de un String public static byte[] generateSHA1 (String str) { return generateSHA1(str.getBytes()); } // Genera SHA-1 de un InputStream public static byte[] generateSHA1 (InputStream is) { try { return generateSHA1(InputStreamUtils.InputStreamTOByte(is)); } catch (Exception e) { return null; } } public static String generateSHA1toString (String str) { try { byte[] datos = generateSHA1(str.getBytes()); return byteArrayToHexString(datos); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } public static String generateSHA1toString (InputStream is) { try { return InputStreamUtils.byteToString(generateSHA1(InputStreamUtils.InputStreamTOByte(is))); } catch (Exception e) { return null; } } // Genera SHA-1 de un File public static byte[] generateSHA1 (File file) { try { return generateSHA1(new FileInputStream (file)); } catch (Exception e) { return null; } } // Genera SHA-1 de un byte[] public static byte[] generateSHA1 (byte[] bytes) { byte[] encryted = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(bytes); encryted = digest.digest(); } catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } return encryted; } // Codifica un byte[] en hexadecimal public static String byteArrayToHexString(byte[] b){ if (b==null) return null; StringBuffer sb = new StringBuffer(b.length * 2); for (int i = 0; i < b.length; i++){ int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toUpperCase(); } // Codifica String hexadecimal en byte[] public static byte[] hexStringToByteArray(String s) { if (s==null) return null; byte[] b = new byte[s.length() / 2]; for (int i = 0; i < b.length; i++){ int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte)v; } return b; } // Compara dos byte[] elemento a elemento public static boolean compareByteArrays (byte[] b1, byte[] b2) { return b1!=null && b2!=null && Arrays.equals(b1, b2) ; } // Compara dos String public static boolean compareHexString (String s1, String s2) { return s1!=null && s2!=null && s1.equalsIgnoreCase(s2); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * * @author Cesar Valiente Gordo y Eduardo Coca Sola * @mail cesar.valiente@gmail.com * */ public class InputStreamUtils { final static int BUFFER_SIZE = 4096; // Tamaño de los bloques a leer/escribir al comprimir en ZIP /************************************************************************** * * @param in InputStream * @return String * @throws Exception * * Funci�n que pasa de InputStream a String **************************************************************************/ public static String InputStreamTOString (InputStream in) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; // Bytes leidos por bloque while ( (count = in.read(data,0,BUFFER_SIZE)) != -1 ) outStream.write(data,0,count); data=null; return new String (outStream.toByteArray(),"ISO-8859-1"); } /** * * @param in * @param encoding * @return * @throws Exception */ public static String InputStreamTOString (InputStream in, String encoding) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; // Bytes leidos por bloque while ( (count = in.read(data,0,BUFFER_SIZE)) != -1 ) outStream.write(data,0,count); data=null; return new String (outStream.toByteArray(),encoding); } /************************************************************************** * * @param in String * @return InputStream * @throws Exception * * Funci�n que pasa de String a InputStream **************************************************************************/ public static InputStream StringTOInputStream (String in) throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("ISO-8859-1")); return is; } /************************************************************************** * * @param in InputStream * @return byte[] * @throws IOException * * Funci�n que pasa convierte un InputStream a un array de bytes (byte[]) **************************************************************************/ public static byte[] InputStreamTOByte (InputStream in) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; // Bytes leidos por bloque while ( (count = in.read(data,0,BUFFER_SIZE)) != -1 ) outStream.write(data,0,count); data=null; return outStream.toByteArray(); } //TODO revisar este metodo public static InputStream byteTOInputStream (byte[] in) throws Exception { ByteArrayInputStream resultado = new ByteArrayInputStream(in); return resultado; } public static String byteToString (byte[] in) throws Exception { InputStream ins = byteTOInputStream(in); return InputStreamTOString(ins); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.utils; import android.util.Log; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ExceptionUtils { public static final String CLASS_NAME = "es.cesar.quitesleep.utils.ExceptionUtils"; /** * * @param stackTrace * @return */ public static String exceptionTraceToString ( String exception, StackTraceElement[] stackTrace) { try { String completeTrace = ""; for (int i=0; i<stackTrace.length; i++) { if (completeTrace.equals("")) completeTrace = exception + "\n\t" + stackTrace[i].toString() + "\n"; else completeTrace = completeTrace + "\t" + stackTrace[i] + "\n"; } return completeTrace; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString()); return ""; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.mailmessages; import java.security.Security; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import android.util.Log; import es.cesar.quitesleep.ddbb.CallLog; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Mail; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.utils.ByteArrayDataSource; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * @mostcodefrom http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-ap * */ public class SendMail extends Authenticator implements Runnable { private final String CLASS_NAME = getClass().getName(); private String user; private String passwd; private String subject; private String body; private String incomingCallNumber; private List<String> receiverMailList; private CallLog callLog; //--------------- Getters & Setters --------------------------// public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getIncomingCallNumber() { return incomingCallNumber; } public void setIncomingCallNumber(String incomingCallNumber) { this.incomingCallNumber = incomingCallNumber; } public List<String> getReceiverMailList() { return receiverMailList; } public void setReceiverMailList (List<String> receiverMailList) { this.receiverMailList = receiverMailList; } public CallLog getCallLog() { return callLog; } public void setCallLog(CallLog callLog) { this.callLog = callLog; } //------------------------------------------------------------------------// static { Security.addProvider(new JSSEProvider()); } /** * Constructor with all parameters * * @param user * @param passwd * @param subject * @param body * @param incomingCallNumber */ public SendMail ( String user, String passwd, String subject, String body, String incomingCallNumber) { this.user = user; this.passwd = passwd; this.subject = subject; this.body = body; this.incomingCallNumber = incomingCallNumber; getReceiverMailList(incomingCallNumber); } /** * Constructor empty */ public SendMail (String incomingCallNumber, CallLog callLog) { this.incomingCallNumber = incomingCallNumber; this.callLog = callLog; getAllData(); getReceiverMailList(incomingCallNumber); } /** * Get all mail data form the ddbb. Assume that previously have been check * if mail service is activated. */ private void getAllData () { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { user = settings.getUser(); passwd = settings.getPasswd(); subject = settings.getSubject(); body = settings.getBody(); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that obtains the mail asociated to the phone number passed * * @param incomingCallNumber */ private void getReceiverMailList (String incomingCallNumber){ try { ClientDDBB clientDDBB = new ClientDDBB(); Phone phone = clientDDBB.getSelects().selectPhoneForPhoneNumber(incomingCallNumber); if (phone != null) { Contact contact = phone.getContact(); List<Mail> mailList = clientDDBB.getSelects().selectAllContactMailForContact(contact); clientDDBB.close(); //We don't check if is a banned contact because previously must be done receiverMailList = new ArrayList<String>(); boolean findAtLeastOne = false; for (int i=0; i<mailList.size(); i++) { Mail mail = mailList.get(i); if (mail.isUsedToSend()) { receiverMailList.add(mail.getContactMail()); findAtLeastOne = true; } } if (!findAtLeastOne) receiverMailList = null; //--- Used when only one of all mail list was used for send email ----/ /* int i=0; boolean find = false; Mail mail = null; while (i<mailList.size() && !find) { mail = mailList.get(i); if (mail.isUsedToSend()) find = true; i++; } if (find) receiverMailList = mail.getContactMail(); else receiverMailList = null; */ //------------------------------------------------------------// } /* The else case mustn't be never, because previously we have check * that this receiver is in the banned list */ }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); receiverMailList = null; } } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, passwd); } @Override public void run () { int numShipments = sendMail(); saveNumShipments(numShipments); } /** * Send an email to the receiver associated to the phone number who has been * do the call. * * @return true or false depends of the result action * @see boolean */ public synchronized int sendMail () { try { if (receiverMailList != null) { if (MailConfig.getProperties() == null) MailConfig.initProperties(); int numShipments = 0; Properties properties = MailConfig.getProperties(); Session session = Session.getDefaultInstance(properties, this); MimeMessage message = new MimeMessage(session); DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(body.getBytes(), "text/plain")); message.setSender(new InternetAddress(user)); message.setSubject(subject); message.setDataHandler(dataHandler); for (int i=0; i<receiverMailList.size(); i++) { String mailToSend = receiverMailList.get(i); message.setRecipient( Message.RecipientType.TO, new InternetAddress(mailToSend)); Transport.send(message); numShipments ++; } return numShipments; } return 0; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return -1; } } /** * Save the CallLog object if the numShipments is greater than 0. * @param numShipments */ private void saveNumShipments (int numShipments) { try { if (numShipments > 0) { /* ClientDDBB clientDDBB = new ClientDDBB(); clientDDBB.getUpdates().insertCallLog(callLog); clientDDBB.commit(); clientDDBB.close(); */ //Use when join all threads finish callLog.setNumSendMail(numShipments); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package es.cesar.quitesleep.mailmessages; import java.security.AccessController; import java.security.Provider; /** * @author Alexander Y. Kleymenov * @version $Revision$ * * @codefrom http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-ap */ public final class JSSEProvider extends Provider { /** * Constructor */ public JSSEProvider() { super("HarmonyJSSE", 1.0, "Harmony JSSE Provider"); AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() { public Void run() { put("SSLContext.TLS", "org.apache.harmony.xnet.provider.jsse.SSLContextImpl"); put("Alg.Alias.SSLContext.TLSv1", "TLS"); put("KeyManagerFactory.X509", "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl"); put("TrustManagerFactory.X509", "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl"); return null; } }); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.mailmessages; import java.util.Properties; import android.util.Log; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class MailConfig { private static String CLASS_NAME = "es.cesar.quitesleep.sendmessages.MailConfig"; private static Properties properties = null; //------------- Getters & Setters ------------------------------// public static Properties getProperties() { return properties; } public static void setProperties(Properties properties) { MailConfig.properties = properties; } //------------------------------------------------------------------------// public static void initProperties () { try { properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", "smtp.gmail.com"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smpt.port", "465"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.quitwait", "false"); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.staticValues; public class DDBBValues { //------ Contact -------------------------------// public static final String CONTACT_ID = "contactId"; public static final String CONTACT_NAME = "contactName"; public static final String BANNED = "banned"; //-------- Phone -----------------------------------// public static final String CONTACT = "contact"; public static final String CONTACT_PHONE = "contactPhone"; public static final String USED_TO_SEND = "usedToSend"; //-------- Mail --------------------------------// public static final String CONTACT_MAIL = "contactMail"; //Also used here: CONTACT and USED_TO_SEND //-------- Schedule --------------------------------// public static final String START_SCHEDULE = "startSchedule"; public static final String END_SCHEDULE = "endSchedule"; public static final String START_FORMAT_SCHEDULE = "startFormatSchedule"; public static final String END_FORMAT_SCHEDULE = "endFormatSchedule"; //-------- Banned --------------------------------------// public static final String SCHEDULE = "schedule"; //Also used here: CONTACT //-------- CallLog ---------------------------------// public static final String PHONE = "phone"; public static final String NUM_ORDER = "numOrder"; public static final String NUM_SEND_SMS = "numSendSms"; public static final String NUM_SEND_MAIL = "numSendMail"; }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.staticValues; import java.util.concurrent.Semaphore; import android.content.Context; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ConfigAppValues { //------------- FINAL VALUES (Constants) --------------------------// public static final String CONTACT_NAME = "CONTACT_NAME"; //--------------- req Codes for return activities ------------------// public static final int REQCODE_ADD_BANNED = 1; public static final int REQCODE_DELETE_BANNED = 2; public static final int REQCODE_SMS_SETTINGS = 3; public static final int REQCODE_MAIL_SETTINGS = 4; public static final int REQCODE_SYNC_CONTACTS = 5; public static final int REQCODE_CONTACT_DETAILS = 6; public static final int REQCODE_EDIT_CONTACT = 7; public static final int reqTest = 100; //------------------------------------------------------------------------// //------------ Codes for dialog actions ------------------------------// public static final int WARNING_SYNC_CONTACTS = 1; public static final int WARNING_ADD_ALL_CONTACTS = 2; public static final int WARNING_REMOVE_ALL_CONTACTS = 3; public static final int WARNING_SMS_ACTION = 4; public static final int WARNING_MAIL_ACTION = 5; public static final int WARNING_REMOVE_ALL_CALL_LOGS = 6; public static final int WARNING_REFRESH_CALL_LOG = 7; //------------------------------------------------------------------------// //---------- Codes for informaton through intents ----------// public static final String NUM_REMOVE_CONTACTS = "NUM_REMOVE_CONTACTS"; public static final String NUM_REMOVE_CALL_LOGS = "NUM_REMOVE_CALL_LOGS"; public static final String REFRESH_CALL_LOG = "REFRESH_CALL_LOG"; //------------ Other response codes ------------------------------// public static final int LAUNCH_ABOUT = 1; public static final int LAUNCH_HELP = 2; //Min Api level used in this app private static int minApiLevel = 1; //General context used in this app private static Context context = null; /* Used for check without need to use the ddbb if the service * QuiteSleep must be running or not. */ private static Boolean quiteSleepServiceState = null; private static Boolean mailServiceState = null; private static Boolean smsServiceState = null; //Constant string for get the incomingCallNumber public static String INCOMING_CALL_NUMBER = "INCOMING_CALL_NUMBER"; //For use as semaphores in a producer-consumer way public static boolean processRingCall = false; public static boolean processIdleCall = false; //---------- Getters & Setters -----------------------------------// public static int getMinApiLevel() { return minApiLevel; } public static void setMinApiLevel(int minApiLevel) { ConfigAppValues.minApiLevel = minApiLevel; } public static Context getContext () { return context; } public static void setContext (Context context) { ConfigAppValues.context = context; } public static Boolean getQuiteSleepServiceState() { return quiteSleepServiceState; } public static void setQuiteSleepServiceState(Boolean quiteSleepServiceState) { ConfigAppValues.quiteSleepServiceState = quiteSleepServiceState; } public static Boolean getMailServiceState() { return mailServiceState; } public static void setMailServiceState(Boolean mailServiceState) { ConfigAppValues.mailServiceState = mailServiceState; } public static Boolean getSmsServiceState() { return smsServiceState; } public static void setSmsServiceState(Boolean smsServiceState) { ConfigAppValues.smsServiceState = smsServiceState; } //------------------------------------------------------------------------// }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import android.util.Log; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class SmsOperations { private static final String CLASS_NAME = "es.cesar.quitesleep.operations.SmsOperations"; /** * Save the smsText body in the ddbb. * @param smsText * @return true or false if depends of the successfully operation */ public static boolean saveSmsSettings (String smsText) { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) settings.setSmsText(smsText); else { settings = new Settings(false); settings.setSmsText(smsText); } clientDDBB.getInserts().insertSettings(settings); clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import java.util.List; import android.util.Log; import android.widget.CheckBox; import es.cesar.quitesleep.ddbb.Banned; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Mail; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ContactOperations { private final static String CLASS_NAME = "es.cesar.quitesleep.operations.AddContact"; /** * Update the contact object, create the associated Banned object and * updates the phones and mail objects putting the flag useToSend to true * or false for send messages when incoming calls that not respond. * * @param contactName * @param phoneCheckboxList * @param mailCheckboxList * @return true or false depends for the operation successfully * @see boolean */ public static boolean addContact ( String contactName, List<CheckBox> phoneCheckboxList, List<CheckBox> mailCheckboxList) { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "EN addContact"); ClientDDBB clientDDBB = new ClientDDBB(); //-------- Update Contact --------------------------// Contact contact = clientDDBB.getSelects().selectContactForName(contactName); contact.setBanned(true); clientDDBB.getUpdates().insertContact(contact); //---------- Create and insert Banned ------------------// Schedule schedule = clientDDBB.getSelects().selectSchedule(); Banned banned = new Banned(contact, schedule); clientDDBB.getInserts().insertBanned(banned); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Updated Contact and Banned"); //--------------- Update Phone --------------------------// List<Phone> phoneList = clientDDBB.getSelects().selectAllContactPhonesForName(contactName); for (int i=0; i<phoneList.size(); i++) { Phone phone = phoneList.get(i); int j=0; boolean find = false; while (j<phoneCheckboxList.size() && !find) { CheckBox checkbox = phoneCheckboxList.get(j); if (checkbox.getText().equals(phone.getContactPhone())) { phone.setUsedToSend(checkbox.isChecked()); clientDDBB.getUpdates().insertPhone(phone); find = true; } j++; } } //----------------- Update Mail --------------------------// List<Mail> mailList = clientDDBB.getSelects().selectAllContactMailsForName(contactName); for (int i=0; i<mailList.size(); i++) { Mail mail = mailList.get(i); int j=0; boolean find = false; while (j<mailCheckboxList.size() && !find) { CheckBox checkbox = mailCheckboxList.get(j); if (checkbox.getText().equals(mail.getContactMail())) { mail.setUsedToSend(checkbox.isChecked()); clientDDBB.getUpdates().insertMail(mail); find = true; } j++; } } //---------- Commit and close --------------------------// clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Remove contact from the banned list, updating the contact object and * remove the banned object. * * @param contactName * @return true or false depends for the operation successfully * @see boolean */ public static boolean removeContact (String contactName) { try { ClientDDBB clientDDBB = new ClientDDBB(); //--------- Update Contact ------------------------------// Contact contact = clientDDBB.getSelects().selectContactForName(contactName); contact.setBanned(false); clientDDBB.getUpdates().insertContact(contact); //--------- Delete Banned --------------------------// Banned banned = clientDDBB.getSelects().selectBannedContactForName(contactName); clientDDBB.getDeletes().deleteBanned(banned); //---------- Commit and close ----------------------// clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Update all edit attributes from the contact passed as its phone numbers * and mail addresses used for send messages when incomig call is here * and the contact is banned. * * @param contactName * @param phoneCheckboxList * @param mailCheckboxList * * @return true or false depends for the operation successfully * @see boolean */ public static boolean editContact ( String contactName, List<CheckBox> phoneCheckboxList, List<CheckBox> mailCheckboxList) { try { ClientDDBB clientDDBB = new ClientDDBB(); //----------------- Update all edit phones ------------------// List<Phone> phoneList = clientDDBB.getSelects().selectAllContactPhonesForName(contactName); for (int i=0; i<phoneList.size(); i++) { Phone phone = phoneList.get(i); int j=0; boolean find = false; while (j<phoneCheckboxList.size() && !find) { CheckBox checkbox = phoneCheckboxList.get(j); if (checkbox.getText().equals(phone.getContactPhone())) { phone.setUsedToSend(checkbox.isChecked()); clientDDBB.getUpdates().insertPhone(phone); find = true; } j++; } } //------------- Update all edit mails ------------------// List<Mail> mailList = clientDDBB.getSelects().selectAllContactMailsForName(contactName); for (int i=0; i<mailList.size(); i++) { Mail mail = mailList.get(i); int j=0; boolean find = false; while (j<mailCheckboxList.size() && !find) { CheckBox checkbox = mailCheckboxList.get(j); if (checkbox.getText().equals(mail.getContactMail())) { mail.setUsedToSend(checkbox.isChecked()); clientDDBB.getUpdates().insertMail(mail); find = true; } j++; } } //---------------- Commit and close ------------------// clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import android.util.Log; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class MailOperations { private final static String CLASS_NAME = "es.cesar.quitesleep.operations.MailOperations"; /** * Function that save the mail settings into Settings object from the ddbb, * if the Settings object doesn't exists we create it, and if it exists, * update one. * * @param user * @param passwd * @param subject * @param body * * @return true or false if the operation was sucessfully or not * @see boolean */ public static boolean saveMailSettings ( String user, String passwd, String subject, String body) { try { ClientDDBB clientDDBB = new ClientDDBB(); /* ------- Save the mail settings, both if Settings object not * exists or if exists ------------------------------------- */ Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { settings.setUser(user); settings.setPasswd(passwd); settings.setSubject(subject); settings.setBody(body); clientDDBB.getUpdates().insertSettings(settings); } /* Never must be used this else because in onCreate, if the Settings * object isn't created previously, then there we create it. * But we i leave post because previously i already coded it. */ else { settings = new Settings(false); settings.setUser(user); settings.setPasswd(passwd); settings.setSubject(subject); settings.setBody(body); clientDDBB.getInserts().insertSettings(settings); } //------------ Commit & close -------------------------// clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Function that save the mailService sending state, in both, the Settings * object in the ddbb and the static variable for more fast access later. * * @param mailServiceState * * @return true or false depends of sucessfully operation * @see boolean */ public static boolean saveMailServiceState (boolean mailServiceState) { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { settings.setMailService(mailServiceState); clientDDBB.getUpdates().insertSettings(settings); } /* Never must be used this else because in onCreate, if the Settings * object isn't created previously, then there we create it. * But we i leave post because previously i already coded it. */ else { settings = new Settings(false); settings.setMailService(mailServiceState); clientDDBB.getUpdates().insertSettings(settings); } //Update the global static variable for fast access later ConfigAppValues.setMailServiceState(mailServiceState); //Comit & close clientDDBB.commit(); clientDDBB.close(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import android.content.Context; import android.media.AudioManager; import android.os.Vibrator; import es.cesar.quitesleep.ddbb.CallLog; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.mailmessages.SendMail; import es.cesar.quitesleep.smsmessages.SendSMSThread; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.TokenizerUtils; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class IncomingCallOperations extends Thread { private static final String CLASS_NAME = "es.cesar.quitesleep.utils.operations.IncomingCallOperations"; private String incomingCallNumber; //---------------- Getters & Setters ----------------------------------// public String getIncomingCallNumber() { return incomingCallNumber; } public void setIncomingCallNumber(String incomingCallNumber) { this.incomingCallNumber = incomingCallNumber; } //------------------------------------------------------------------------// /** * Constructor * @param incomingCallNumber */ public IncomingCallOperations(String incomingCallNumber) { this.incomingCallNumber = incomingCallNumber; } @Override public void run () { silentIncomingCall(); } /** * Function that check if the incoming call number is from a banned contact, * if is true, put the mobile to silent mode (sound and vibrate), if is * false do nothing. * * UPDATE 05-05-2010: now, we puts always the phone in silent mode when incoming * call, but, then, quitesleep check if the contact is banned and if is in the * schedule time, if is true, creates a new CallLog object, and we don't nothing * with the phone mode, so it was put in silent mode at beginning. * But if the incoming phone not is from a banned contact and/or if not * is in the schedule time, put the mobile phone in normal mode. * I have done this, because, is the only manner i get, that the phone never ring * one sec when an incoming call from a banned contact arrives and the only way * to put the mobile phone with vibrator off, one time the mobile phone is in normal * mode the ring is too on. * The inconvenience is that whatever incoming call the first tone the mobile * phone silence it, not is the perfect way but is the only and the best way * that i have reached with >Android 2.0 at day. * */ public void silentIncomingCall () { try { /* Put the mobile phone in silent mode (sound+vibration) * Here i put this for silent all incoming call for salomonic decision * that silent all calls for later if the contact is banned let this * silent mode and if the contact isn't banned put in normal mode. * I use this because sometimes a ring second sound when an incoming call. */ //putRingerModeSilent(); ClientDDBB clientDDBB = new ClientDDBB(); String phoneNumberWhithoutDashes = TokenizerUtils.tokenizerPhoneNumber(incomingCallNumber, null); Contact contactBanned = clientDDBB.getSelects().selectBannedContactForPhoneNumber( phoneNumberWhithoutDashes); //If the contact is in the banned list if (contactBanned != null) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Contact: " + contactBanned.getContactName() + "\t isBanned: " + contactBanned.isBanned()); //create the CallLog object for log calls. CallLog callLog = new CallLog(); //check if the call is in the interval time boolean isInInterval = checkSchedule(callLog, clientDDBB); if (isInInterval) { //Put the mobile phone in silent mode (sound+vibration) putRingerModeSilent(); /* Check if the mail service is running, if it is true * create a SendMail object for try to send one or more * email to the contact with the incoming number */ sendMail(incomingCallNumber, callLog, clientDDBB); /* Check if the sms service is running, if it is true * create a SendSMS object for try to send a SMS to * the contact with the incoming number */ sendSMS(incomingCallNumber, callLog, clientDDBB); //get the nomOrder for the new CallLog int numOrder = clientDDBB.getSelects().countCallLog(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "CallLog numOrder: " + numOrder); //Set the parameters and save it callLog.setPhoneNumber(phoneNumberWhithoutDashes); callLog.setContact(contactBanned); callLog.setNumOrder(numOrder+1); clientDDBB.getInserts().insertCallLog(callLog); clientDDBB.commit(); clientDDBB.close(); } //If the call isn't in the interval time else { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "No está en el intervalo"); //putRingerModeNormal(); clientDDBB.close(); } } //If the incoming call number isn't of the any banned contact else { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "ContactBanned == NULL!!!!"); //putRingerModeNormal(); clientDDBB.close(); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Compare the present time with the schedule start and end times (interval) * * @return true if the present time is in the interval or false * if isn't * @see boolean */ private boolean checkSchedule (CallLog callLog, ClientDDBB clientDDBB) { try { //ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); //clientDDBB.close(); if (schedule != null && CheckSettingsOperations.checkDayWeek(schedule)) { return isInInterval(callLog, schedule); } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Function that check if the call incoming with the now time, is between the * twho hours specified as start and end of the interval specified by the user. * * @param callLog * @param schedule * @return true or false if the incoming call with the actual hour * is in an interval delimit by the start and end hours * @see boolean */ private boolean isInInterval (CallLog callLog, Schedule schedule) { try { DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); Calendar dateAndTime = Calendar.getInstance(); String timeNow = timeFormat.format(dateAndTime.getTime()); String timeStart = schedule.getStartFormatTime(); String timeEnd = schedule.getEndFormatTime(); String timeNowComplete = getCompleteDate(dateAndTime); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "time now: " + timeNowComplete); callLog.setTimeCall(timeNowComplete); SimpleDateFormat parser = new SimpleDateFormat("HH:mm"); Date start = parser.parse(timeStart); Date end = parser.parse(timeEnd); Date now = parser.parse(timeNow); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "start: " + start + "\ttimeStart: " + timeStart); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "end: " + end + "\ttimeEnd: " + timeEnd); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "now: " + now + "\timeNow: " + timeNow); String dayCompleteString = "24:00"; Date dayComplete = parser.parse(dayCompleteString); String dayInitString = "00:00"; Date dayInit = parser.parse(dayInitString); final int INCREASE = 24; boolean isInInterval; //If both times are equals (24h) (si 8:00 = 8:00) if (start.compareTo(end) == 0) isInInterval = true; //(Si start=10:00 end=21:00)) //If end time is after than start time (ie: start=10:00 end=21:00) else if (end.after(start) && (now.after(start) && now.before(end))) isInInterval = true; /* If end time is before than start time (ie: start=22:00 end=3:00) * then, we must be add 24 to the end time. (so ie: start=22:00 end:27:00) */ //(Si start=22:00 end=3:00 ==> newEnd=3:00+24=27:00) else if (end.before(start)) { String newEndTimeString = TokenizerUtils.addIncreaseDate( timeEnd, INCREASE, null); Date newEndTime = parser.parse(newEndTimeString); /* (Si start=22:00 now=23:00 dayComplete=24:00, antes * hemos comprobado que end<start==> end: 3:00) */ if (now.after(start) && now.before(dayComplete)) isInInterval = true; /* (Si now>00:00==> now=2:00 now<newEnd(27:00) ==> now=2:00+24=26:00) * así que ahora queda start=23:00 end=27:00 y now=26:00 */ else if (now.after(dayInit) && now.before(newEndTime)) { String newNowTimeString = TokenizerUtils.addIncreaseDate( timeNow, INCREASE, null); Date newNowTime = parser.parse(newNowTimeString); if (newNowTime.after(start) && newNowTime.before(newEndTime)) isInInterval = true; else isInInterval = false; }else isInInterval = false; }else isInInterval = false; if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Está en el intervalo: " + isInInterval); return isInInterval; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Get the compelte format date in English mode * * @param now * @return the complete format date * @see String */ private String getCompleteDate (Calendar now) { try { return (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR) + " " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } /** * Put the vibrator in mode off */ private void vibrateOff () { try { String vibratorService = Context.VIBRATOR_SERVICE; Vibrator vibrator = (Vibrator)ConfigAppValues.getContext(). getSystemService(vibratorService); vibrator.cancel(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Send mail to the contact caller * @param incomingNumber * @param callLog * @param clientDDBB */ private void sendMail (String incomingNumber, CallLog callLog, ClientDDBB clientDDBB) { try { if (CheckSettingsOperations.checkMailService(clientDDBB)) { //------------------------------------------------------------// //Send mail using Threads SendMail sendMail = new SendMail(incomingNumber, callLog); Thread threadMail = new Thread(sendMail); threadMail.start(); threadMail.join(); //------------------------------------------------------------// //------------------------------------------------------------// //Send mail without use Threads /* SendMail sendMail = new SendMail(incomingNumber, callLog); sendMail.sendMail(); */ } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Send SMS message to the contact caller * * @param incomingNumber * @param callLog * @param clientDDBB */ private void sendSMS (String incomingNumber, CallLog callLog, ClientDDBB clientDDBB) { try { if (CheckSettingsOperations.checkSmsService(clientDDBB)) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "antes de enviar el sms"); //-- If u choose use Android Service for send SMS use this --// /* ConfigAppValues.getContext().startService( new Intent( ConfigAppValues.getContext(), SendSMSService.class).putExtra( ConfigAppValues.RECEIVER, incomingNumber)); */ //------------------------------------------------------------// //----- If u choose Java Thread for send SMS use this -----// SendSMSThread sendSMS = new SendSMSThread(incomingNumber, callLog); sendSMS.start(); sendSMS.join(); //------------------------------------------------------------// //------------------------------------------------------------// //Use without using threads /* SendSMSThread sendSMS = new SendSMSThread(incomingNumber); sendSMS.sendSms(); */ //------------------------------------------------------------// } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put the mobile in silence mode (audio and vibrate) * */ private void putRingerModeSilent () { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Poniendo el movil en modo silencio"); AudioManager audioManager = (AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE); audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } private void putRingerModeNormal () { try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Poniendo el movil en modo normal"); AudioManager audioManager = (AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE); audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import android.content.Context; import android.os.Handler; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.dialogs.AddAllDialog; import es.cesar.quitesleep.dialogs.CallLogDialog; import es.cesar.quitesleep.dialogs.RemoveAllDialog; import es.cesar.quitesleep.dialogs.SyncContactsDialog; import es.cesar.quitesleep.menus.AddAllMenu; import es.cesar.quitesleep.menus.RefreshCallLogMenu; import es.cesar.quitesleep.menus.RemoveAllMenu; import es.cesar.quitesleep.menus.RemoveCallLogMenu; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.syncData.SyncContactsRefresh; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class DialogOperations { private final static String CLASS_NAME = "es.cesar.quitesleep.operations.DialogOperations"; /** * Sync the contacts data between SQLite and DB4O databases the first time * if the db4o database is empty. * It is done used one thread for it. */ public static void syncContactsRefresh () { try { SyncContactsDialog syncDialog = new SyncContactsDialog(); SyncContactsRefresh syncContacts = new SyncContactsRefresh(ConfigAppValues.getContext(), syncDialog); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Refreshing the database"); syncDialog.showDialogRefreshList(ConfigAppValues.getContext()); syncContacts.start(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(); } } /** * Function that add all contacts to the banned list in one separated thread, * and show a progressDialog fow wait for it, and an handler for clear the * arrayAdapter one habe been finished. */ public static void addAllContacts ( Context context, ArrayAdapter<String> arrayAdapter, Handler handler) { try { /* Only can selectAll contacts if the arrayAdapter is != null and * have content, that is the state of it when prevously we add all * contacts. */ if (arrayAdapter != null && arrayAdapter.getCount()>0) { //Create the progressDialog used while the system add all contacts AddAllDialog addAllDialog = new AddAllDialog(); //Create the object that this thread will do the process AddAllMenu addAllMenu = new AddAllMenu(arrayAdapter, addAllDialog, handler); //Show the progress dialog and run the thread for add all contacts addAllDialog.showDialog(context); addAllMenu.start(); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(); } } /** * Function that start the remove banned contacts from the banned list * in a separated thread and use a progressDialog for wait for it, and * handler for clear the arrayAdapter once have finished. */ public static void removeAllContacts ( Context context, ArrayAdapter<String> arrayAdapter, Handler handler) { try { /* Only can selectAll contacts if the arrayAdapter is != null and * have content, that is the state of it when prevously we add all * contacts. */ if (arrayAdapter != null && arrayAdapter.getCount()>0) { //Create the progressDialog used while the system add all contacts RemoveAllDialog removeAllDialog = new RemoveAllDialog(); //Create the object that this thread will do the process RemoveAllMenu removeAllMenu = new RemoveAllMenu(arrayAdapter, removeAllDialog, handler); //Show the progress dialog and run the thread for add all contacts removeAllDialog.showDialog(context); removeAllMenu.start(); } }catch (Exception e) { Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(); } } /** * Function that does the operations about start and stop the sms service */ public static void checkSmsService (Context context, boolean isChecked) { try { boolean result = StartStopServicesOperations.startStopSmsService(isChecked); if (isChecked) { if (result) //All right, start the service was ok! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.smssettings_toast_start_service), Toast.LENGTH_SHORT); else //An error has ocurred!! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.smssettings_toast_fail_service), Toast.LENGTH_SHORT); }else { if (result) //All right, stop the service was ok! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.smssettings_toast_stop_service), Toast.LENGTH_SHORT); else //An error has ocurred!! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.smssettings_toast_fail_service), Toast.LENGTH_SHORT); } }catch (Exception e) { Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that does the operations about start and stop the mail service */ public static void checkMailService (Context context, boolean isChecked) { try { boolean result = StartStopServicesOperations.startStopMailService(isChecked); if (isChecked) { if (result) //All right, start the service was ok! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.mailsettings_toast_start_service), Toast.LENGTH_SHORT); else //An error has ocurred!! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.mailsettings_toast_fail_service), Toast.LENGTH_SHORT); }else { if (result) //All right, stop the service was ok! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.mailsettings_toast_stop_service), Toast.LENGTH_SHORT); else //An error has ocurred!! if (QSToast.RELEASE) QSToast.r( context, context.getString( R.string.mailsettings_toast_fail_service), Toast.LENGTH_SHORT); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Remove all call log objects from the ddbb for clean the call log information * list. * * @param context * @param arrayAdapter * @param handler */ public static void removeAllCallLogs ( Context context, ArrayAdapter<String> arrayAdapter, Handler handler) { try { /* Only can selectAll contacts if the arrayAdapter is != null and * have content, that is the state of it when prevously we add all * contacts. */ if (arrayAdapter != null && arrayAdapter.getCount()>0) { //Create the progressDialog used while the system add all contacts CallLogDialog callLogDialog = new CallLogDialog(); //Create the object that this thread will do the process RemoveCallLogMenu callLogMenu = new RemoveCallLogMenu(arrayAdapter, callLogDialog, handler); //Show the progress dialog and run the thread for add all contacts callLogDialog.showDialog(context, ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS); callLogMenu.start(); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(); } } public static void refreshAllCallLogs ( Context context, ArrayAdapter<String> arrayAdapter, Handler handler) { try { //Create the progressDialog used while the system add all contacts CallLogDialog callLogDialog = new CallLogDialog(); //Create the object that this thread will do the process RefreshCallLogMenu refreshCallLogMenu = new RefreshCallLogMenu(arrayAdapter, callLogDialog, handler); //Show the progress dialog and run the thread for add all contacts callLogDialog.showDialog(context, ConfigAppValues.WARNING_REFRESH_CALL_LOG); refreshCallLogMenu.start(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import java.util.Calendar; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class CheckSettingsOperations { private static final String CLASS_NAME = "es.cesar.quitesleep.operations.CheckServicesOperations"; /** * Check if the Settings object is created in the ddbb. If it's created * check this attribute serviceState for check if the service is up * or is down. * * @return true if the service is running or false if not. */ public static boolean checkQuiteSleepServiceState () { try { boolean serviceState = false; if (ConfigAppValues.getQuiteSleepServiceState() != null) serviceState = ConfigAppValues.getQuiteSleepServiceState(); else { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); clientDDBB.close(); if (settings != null) serviceState = settings.isQuiteSleepServiceState(); } return serviceState; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Check if today is a selected day for use the banned contacts list and schedule. * * @param schedule * @return true if today is one "banned day" or false if isn't * @see boolean */ public static boolean checkDayWeek (Schedule schedule) { try { Calendar dateAndTime = Calendar.getInstance(); int dayWeek = dateAndTime.get(Calendar.DAY_OF_WEEK); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Day Week: " + dayWeek); switch (dayWeek) { case Calendar.SUNDAY: return schedule.isSunday(); case Calendar.MONDAY: return schedule.isMonday(); case Calendar.TUESDAY: return schedule.isTuesday(); case Calendar.WEDNESDAY: return schedule.isWednesday(); case Calendar.THURSDAY: return schedule.isThursday(); case Calendar.FRIDAY: return schedule.isFriday(); case Calendar.SATURDAY: return schedule.isSaturday(); } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Check if the mail service for send email is activated or not * * @param clientDDBB * @return true or false if it is activated or not */ public static boolean checkMailService (ClientDDBB clientDDBB) { try { if (ConfigAppValues.getMailServiceState() != null) return ConfigAppValues.getMailServiceState(); else { //ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { ConfigAppValues.setMailServiceState(settings.isMailService()); //clientDDBB.close(); return ConfigAppValues.getMailServiceState(); } /* Mustn't be never this case because previously the settings object * must be created */ else { settings = new Settings(false); clientDDBB.getInserts().insertSettings(settings); clientDDBB.commit(); //clientDDBB.close(); return false; } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e( CLASS_NAME, ExceptionUtils.exceptionTraceToString(e.toString(), e.getStackTrace())); return false; } } /** * Check if the sms service for send sms is activated or not * * @param clientDDBB * @return true or false depends of the state * @see boolean */ public static boolean checkSmsService (ClientDDBB clientDDBB) { try { if (ConfigAppValues.getSmsServiceState() != null) return ConfigAppValues.getSmsServiceState(); else { //ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { ConfigAppValues.setSmsServiceState(settings.isSmsService()); //clientDDBB.close(); return ConfigAppValues.getSmsServiceState(); }else { settings = new Settings(false); clientDDBB.getInserts().insertSettings(settings); clientDDBB.commit(); //clientDDBB.close(); return false; } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.operations; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class StartStopServicesOperations { private static final String CLASS_NAME = "es.cesar.quitesleep.operations.StartStopService"; /** * Start or Stop the QuiteSleep incoming call service. If the service is already started * nothing to do and return true, if the service isn't active, return true * saving the state in the Settings object in the ddbb. * * @param stateQuiteSleepService * @return True if the operation was sucessfully. False if an exception occurred. * @see boolean */ public static boolean startStopQuiteSleepService ( boolean stateQuiteSleepService) { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { settings.setQuiteSleepServiceState(stateQuiteSleepService); }else { settings = new Settings(); settings.setQuiteSleepServiceState(stateQuiteSleepService); } clientDDBB.getUpdates().insertSettings(settings); clientDDBB.commit(); clientDDBB.close(); //Put true or false if the start service was ok ConfigAppValues.setQuiteSleepServiceState(stateQuiteSleepService); //IncomingCallOperations.vibrateOff(); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Function that update the ddbb with the state of mailService * * @param mailServiceState * @return true if the operation was sucessfully or false if some * exception occurred * @see boolean */ public static boolean startStopMailService (boolean mailServiceState) { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) settings.setMailService(mailServiceState); else { settings = new Settings(false); settings.setMailService(mailServiceState); } clientDDBB.getUpdates().insertSettings(settings); clientDDBB.commit(); clientDDBB.close(); //Put the mail state service in the static attribute ConfigAppValues.setMailServiceState(mailServiceState); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Function that update the ddbb with the state of smsService * * @param smsServiceState * @return true if the operation was sucessfully or false if not * @see boolean */ public static boolean startStopSmsService (boolean smsServiceState) { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) settings.setSmsService(smsServiceState); else { settings = new Settings(false); settings.setSmsService(smsServiceState); } clientDDBB.getInserts().insertSettings(settings); clientDDBB.commit(); clientDDBB.close(); //Put the sms state service in the static attribute ConfigAppValues.setSmsServiceState(smsServiceState); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import android.app.ProgressDialog; import android.content.Context; import es.cesar.quitesleep.R; import es.cesar.quitesleep.staticValues.ConfigAppValues; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class CallLogDialog { private String CLASS_NAME = getClass().getName(); private ProgressDialog progressDialog; //-------- Getters & Setters --------------------------------------// public ProgressDialog getProgressDialog() { return progressDialog; } public void setProgressDialog(ProgressDialog progressDialog) { this.progressDialog = progressDialog; } //--------------------------------------------------------------------// /** * Constructor without parameters. */ public CallLogDialog () { } /** * Show the synchronization message */ public void showDialog (Context context, int typeDialog) { if (typeDialog == ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS) progressDialog = ProgressDialog.show( context, "", context.getString(R.string.calllogdialog_dialog_remove_label), true); else if (typeDialog == ConfigAppValues.WARNING_REFRESH_CALL_LOG) progressDialog = ProgressDialog.show( context, "", context.getString(R.string.calllogdialog_dialog_refresh_label), true); } /** * Hide and dismiss the synchronization message * @param context */ public void stopDialog (Context context) { //progressDialog.cancel(); progressDialog.dismiss(); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Handler; import android.util.Log; import android.widget.ArrayAdapter; import es.cesar.quitesleep.R; import es.cesar.quitesleep.operations.DialogOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class WarningDialog { private final String CLASS_NAME = getClass().getName(); private int alertDialogImage = R.drawable.dialog_warning; private AlertDialog alertDialog; private int operationType; //Use for addAll, removeAll, smsService and mailService private Context context; //Use for addAll and removeAll private ArrayAdapter<String> arrayAdapter; private Handler handler; //Use for smsService and mailService private boolean toggleButtonIsChecked; private int title; private int message; //------------------ Getters & Setters ----------------------// public AlertDialog getAlertDialog() { return alertDialog; } public void setAlertDialog(AlertDialog alertDialog) { this.alertDialog = alertDialog; } public int getOperationType() { return operationType; } public void setOperationType(int operationType) { this.operationType = operationType; } public int getTitle() { return title; } public void setTitle(int title) { this.title = title; } public int getMessage() { return message; } public void setMessage(int message) { this.message = message; } public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } public ArrayAdapter<String> getArrayAdapter() { return arrayAdapter; } public void setArrayAdapter(ArrayAdapter<String> arrayAdapter) { this.arrayAdapter = arrayAdapter; } public Handler getHandler() { return handler; } public void setHandler(Handler handler) { this.handler = handler; } public boolean isToggleButtonIsChecked() { return toggleButtonIsChecked; } public void setToggleButtonIsChecked(boolean toggleButtonIsChecked) { this.toggleButtonIsChecked = toggleButtonIsChecked; } //------------------------------------------------------------------------// /** * Get the title and message for each type of operation */ private void getLabelsOperationType () { try { title = R.string.warningdialog_caution_label; switch (operationType) { case ConfigAppValues.WARNING_ADD_ALL_CONTACTS: message = R.string.warningdialog_contactOperations_label; break; case ConfigAppValues.WARNING_REMOVE_ALL_CONTACTS: message = R.string.warningdialog_contactOperations_label; break; case ConfigAppValues.WARNING_SYNC_CONTACTS: message = R.string.warningdialog_synccontact_label; break; case ConfigAppValues.WARNING_SMS_ACTION: message = R.string.warningdialog_sms_label; break; case ConfigAppValues.WARNING_MAIL_ACTION: message = R.string.warningdialog_mail_label; break; case ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS: message = R.string.warningdialog_calllog_remove_label; break; case ConfigAppValues.WARNING_REFRESH_CALL_LOG: message = R.string.warningdialog_calllog_refresh_label; break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * */ private void callOperationType () { try { switch (operationType) { case ConfigAppValues.WARNING_ADD_ALL_CONTACTS: DialogOperations.addAllContacts(context, arrayAdapter, handler); break; case ConfigAppValues.WARNING_REMOVE_ALL_CONTACTS: DialogOperations.removeAllContacts(context, arrayAdapter, handler); break; case ConfigAppValues.WARNING_SYNC_CONTACTS: DialogOperations.syncContactsRefresh(); break; case ConfigAppValues.WARNING_SMS_ACTION: DialogOperations.checkSmsService(context, toggleButtonIsChecked); break; case ConfigAppValues.WARNING_MAIL_ACTION: DialogOperations.checkMailService(context, toggleButtonIsChecked); break; case ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS: DialogOperations.removeAllCallLogs(context, arrayAdapter, handler); break; case ConfigAppValues.WARNING_REFRESH_CALL_LOG: DialogOperations.refreshAllCallLogs(context, arrayAdapter, handler); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Constructor with the basic parameter * @param activity */ public WarningDialog (final Activity activity, int operationType) { this.operationType = operationType; getLabelsOperationType(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setIcon(alertDialogImage); builder.setTitle(title) .setMessage(message); if ((operationType != ConfigAppValues.WARNING_SMS_ACTION) && (operationType != ConfigAppValues.WARNING_MAIL_ACTION)) { builder.setCancelable(false); builder.setPositiveButton( R.string.warningdialog_yes_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Log.d(CLASS_NAME, "YES"); callOperationType(); } }); builder.setNegativeButton( R.string.warningdialog_no_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Log.d(CLASS_NAME, "NO"); dialog.cancel(); //no debemos hacer nada extra. } }); }else { builder.setNeutralButton( R.string.warningdialog_ok_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Log.d(CLASS_NAME, "OK"); callOperationType(); } }); } alertDialog = builder.create(); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import android.app.ProgressDialog; import android.content.Context; import es.cesar.quitesleep.R; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class RemoveAllDialog { private String CLASS_NAME = getClass().getName(); private ProgressDialog progressDialog; //-------- Getters & Setters --------------------------------------// public ProgressDialog getProgressDialog() { return progressDialog; } public void setProgressDialog(ProgressDialog progressDialog) { this.progressDialog = progressDialog; } //--------------------------------------------------------------------// /** * Constructor without parameters. */ public RemoveAllDialog () { } /** * Show the synchronization message */ public void showDialog (Context context) { progressDialog = ProgressDialog.show( context, "", context.getString(R.string.removealldialog_dialog_label), true); } /** * Hide and dismiss the synchronization message * @param context */ public void stopDialog (Context context) { //progressDialog.cancel(); progressDialog.dismiss(); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import android.app.ProgressDialog; import android.content.Context; import es.cesar.quitesleep.R; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class SyncContactsDialog { private String CLASS_NAME = getClass().getName(); final int FIRST_TIME_SYNC = R.string.synccontactsdialog_message_firsttime_label; final int ANY_TIME_SYNC = R.string.synccontactsdialog_message_anytime_label; final int REFRESH_LIST = R.string.synccontactsdialog_message_refresh_label; private ProgressDialog progressDialog; private String messageDialog = ""; //-------- Getters & Setters --------------------------------------// public ProgressDialog getProgressDialog() { return progressDialog; } public void setProgressDialog(ProgressDialog progressDialog) { this.progressDialog = progressDialog; } public String getMessageDialog () { return messageDialog; } public void setMessageDialog (String messageDialog) { this.messageDialog = messageDialog; } //--------------------------------------------------------------------// /** * Constructor without parameters. */ public SyncContactsDialog () { } /** * Show the dialog with the first time synchronization message * @param context */ public void showDialogFirstTime (Context context) { messageDialog = context.getString(FIRST_TIME_SYNC); showDialog(context); } /** * Show the dialog with the any time synchronization message * @param context */ public void showDialogAnyTime (Context context) { messageDialog = context.getString(ANY_TIME_SYNC); showDialog(context); } public void showDialogRefreshList (Context context) { messageDialog = context.getString(REFRESH_LIST); showDialog(context); } /** * Show the dialog with other synchronization message that we like * @param context * @param messageDialg */ public void showDialogOtherMessage (Context context, String messageDialg) { this.messageDialog = messageDialg; showDialog(context); } /** * Show the synchronization message * @param context */ private void showDialog (Context context) { progressDialog = ProgressDialog.show(context, "", messageDialog, true); } /** * Hide and dismiss the synchronization message * @param context */ public void stopDialog (Context context) { //progressDialog.cancel(); progressDialog.dismiss(); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import java.text.DateFormat; import java.util.Calendar; import android.app.Activity; import android.app.TimePickerDialog; import android.util.Log; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class EndTimeDialog { private String CLASS_NAME = getClass().getName(); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); Calendar dateAndTime = Calendar.getInstance(); private TimePickerDialog timePickerDialog; private TextView endTimeLabel; private Activity activity; //-------------- Getters & Setters -----------------------// public TimePickerDialog getTimePickerDialog() { return timePickerDialog; } public void setTimePickerDialog(TimePickerDialog timePickerDialog) { this.timePickerDialog = timePickerDialog; } public TextView getEndTimeLabel() { return endTimeLabel; } public void setEndTimeLabel(TextView endTimeLabel) { this.endTimeLabel = endTimeLabel; } //-----------------------------------------------------------------------// TimePickerDialog.OnTimeSetListener timerPickerEnd = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { view.setIs24HourView(true); dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay); dateAndTime.set(Calendar.MINUTE, minute); //Update operations updateSchedule(); updateEndTimeLabel(); } }; /** * Constructor * * @param activity */ public EndTimeDialog (Activity activity) { timePickerDialog = new TimePickerDialog( activity, timerPickerEnd, dateAndTime.get(Calendar.HOUR_OF_DAY), dateAndTime.get(Calendar.MINUTE), true); this.activity = activity; //If we have redefine the time picker dialog title //timePickerDialog.setTitle(R.string.endtimedialog_message_label); } /** * Update the endTimeLabel located in the activity ScheduleTab, with the * selected by user endTime. */ private void updateEndTimeLabel () { try { if (endTimeLabel != null) endTimeLabel.setText(timeFormat.format(dateAndTime.getTime())); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Update the Schedule object from the database with the end time objects * that have been used in the dialog and specified by the user. * * @throws Exception */ private void updateSchedule () { try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); /* If the Schedule object is null, then never have been created before * so, we have to create here. */ if (schedule == null) schedule = new Schedule(); schedule.setAllEndTime( dateAndTime.getTime(), timeFormat.format(dateAndTime.getTime())); clientDDBB.getUpdates().insertSchedule(schedule); clientDDBB.commit(); clientDDBB.close(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Schedule saved with the end time!!"); if (QSToast.RELEASE) QSToast.r( activity, activity.getString( R.string.schedule_toast_endTime), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(e.toString()); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import android.app.ProgressDialog; import android.content.Context; import es.cesar.quitesleep.R; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class AddAllDialog { private String CLASS_NAME = getClass().getName(); private ProgressDialog progressDialog; //-------- Getters & Setters --------------------------------------// public ProgressDialog getProgressDialog() { return progressDialog; } public void setProgressDialog(ProgressDialog progressDialog) { this.progressDialog = progressDialog; } //--------------------------------------------------------------------// /** * Constructor without parameters. */ public AddAllDialog () { } /** * Show the synchronization message */ public void showDialog (Context context) { progressDialog = ProgressDialog.show( context, "", context.getString(R.string.addalldialog_dialog_label), true); } /** * Hide and dismiss the synchronization message * @param context */ public void stopDialog (Context context) { //progressDialog.cancel(); progressDialog.dismiss(); } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.dialogs; import java.text.DateFormat; import java.util.Calendar; import android.app.Activity; import android.app.TimePickerDialog; import android.util.Log; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Schedule; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * Custom alert dialog for setup the start time for control the contacts calls * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class StartTimeDialog { private String CLASS_NAME = getClass().getName(); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); Calendar dateAndTime = Calendar.getInstance(); private TimePickerDialog timePickerDialog; private TextView startTimeLabel; private Activity activity; //-------------- Getters & Setters ------------------------------// public TimePickerDialog getTimePickerDialog() { return timePickerDialog; } public void setTimePickerDialog(TimePickerDialog timePickerDialog) { this.timePickerDialog = timePickerDialog; } public TextView getStartTimeLabel() { return startTimeLabel; } public void setStartTimeLabel(TextView startTimeLabel) { this.startTimeLabel = startTimeLabel; } //----------------------------------------------------------------------// TimePickerDialog.OnTimeSetListener timerPickerStart = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { view.setIs24HourView(true); dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay); dateAndTime.set(Calendar.MINUTE, minute); //Update operations updateSchedule(); updateStartTimeLabel(); } }; /** * Constructor with one parameter * * @param activity */ public StartTimeDialog (Activity activity) { timePickerDialog = new TimePickerDialog( activity, timerPickerStart, dateAndTime.get(Calendar.HOUR_OF_DAY), dateAndTime.get(Calendar.MINUTE), true); this.activity = activity; //If we have redefine the time picker dialog title //timePickerDialog.setTitle(R.string.starttimedialog_message_label); } /** * Update the startTimeLabel located in the activity ScheduleTab, with the * selected by user startTime. */ private void updateStartTimeLabel () { try { if (startTimeLabel != null) startTimeLabel.setText(timeFormat.format(dateAndTime.getTime())); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Update the Schedule object from the database with the start time objects * that have been used in the dialog and specified by the user. * * @throws Exception */ private void updateSchedule () { try { ClientDDBB clientDDBB = new ClientDDBB(); Schedule schedule = clientDDBB.getSelects().selectSchedule(); /* If the Schedule object is null, then never have been created before * so, we have to create here. */ if (schedule == null) schedule = new Schedule(); schedule.setAllStartTime( dateAndTime.getTime(), timeFormat.format(dateAndTime.getTime())); clientDDBB.getUpdates().insertSchedule(schedule); clientDDBB.commit(); clientDDBB.close(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Schedule saved with the start time!!"); if (QSToast.RELEASE) QSToast.r( activity, activity.getString( R.string.schedule_toast_startTime), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Error(e.toString()); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.smsmessages; import java.util.ArrayList; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.telephony.SmsManager; import android.util.Log; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * Class that implements Android Service for send sms to the incoming caller * */ public class SendSMSService extends Service { private final String CLASS_NAME = getClass().getName(); private String smsText; private String incomingCallNumber; //-------------- Getters & Setters --------------------------// public String getSmsText() { return smsText; } public void setSmsText(String smsText) { this.smsText = smsText; } public String getIncomingCallNumber() { return incomingCallNumber; } public void setIncomingCallNumber(String incomingCallNumber) { this.incomingCallNumber = incomingCallNumber; } //------------------------------------------------------------------------// //------------ Inherited method re-implement ----------------------// @Override public void onCreate () { } @Override public IBinder onBind (Intent intent) { return null; } @Override public int onStartCommand (Intent intent, int flags, int startId) { String incomingCallNumber = intent.getExtras().getString(ConfigAppValues.INCOMING_CALL_NUMBER); SendSMSService sendSMS = new SendSMSService(incomingCallNumber); sendSMS.sendSms(); return Service.START_STICKY; } //------------------------------------------------------------------------// /** * Constructor without parameters */ public SendSMSService () { } /** * Constructor with the phonenumber of the receiver sms */ public SendSMSService (String incomingCallNumber) { init(incomingCallNumber); } /** * Function that is called for onStartCommand Service method start * @param incomingCallNumber */ public void init (String incomingCallNumber) { this.incomingCallNumber = incomingCallNumber; getAllData(); } /** * Get all data of SMS settings */ private void getAllData () { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) smsText = settings.getSmsText(); clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Check if the receiver phone number have permission to use for send SMS * message * * @return true or false if the phone number (receiver) can or not receive * messages */ private boolean checkSendPhoneNumber () { try { ClientDDBB clientDDBB = new ClientDDBB(); Phone phone = clientDDBB.getSelects().selectPhoneForPhoneNumber(incomingCallNumber); clientDDBB.close(); if (phone != null) return phone.isUsedToSend(); else return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Send one SMS message to the receiver * */ private void sendSms () { try { if (checkSendPhoneNumber()) { final String SENT_SMS_ACTION = "SENT_SMS_ACTION"; final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION"; //Create the setIntent parameter Intent sentIntent = new Intent(SENT_SMS_ACTION); PendingIntent sentPI = PendingIntent.getBroadcast( ConfigAppValues.getContext(), 0, sentIntent, 0); //Create the deliveryIntetn parameter Intent deliveryIntent = new Intent(DELIVERED_SMS_ACTION); PendingIntent deliverPI = PendingIntent.getBroadcast( ConfigAppValues.getContext(), 0, deliveryIntent, 0); SmsManager smsManager = SmsManager.getDefault(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SmsText: " + smsText); /* In Nexus One there is a bug (how in htc tatoo) that sent sms * using sendTextMessage not found, so i try to send sms by * cut into parts (if its necessary) and send using sendMultipartMessage */ ArrayList<String> multipartSmsText = smsManager.divideMessage(smsText); int smsSize = multipartSmsText.size(); //Create the arraylist PendingIntents for use it. ArrayList<PendingIntent> sentPiList = new ArrayList<PendingIntent>(smsSize); ArrayList<PendingIntent> deliverPiList = new ArrayList<PendingIntent>(smsSize); for (int i=0; i<smsSize; i++) { sentPiList.add(sentPI); deliverPiList.add(deliverPI); } //Try to send the sms message smsManager.sendMultipartTextMessage( incomingCallNumber, null, multipartSmsText, sentPiList, deliverPiList); } }catch (Exception e) { Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.smsmessages; import java.util.ArrayList; import android.app.PendingIntent; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.telephony.SmsManager; import es.cesar.quitesleep.ddbb.CallLog; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * Class that implements Java Thread for send sms to the incoming caller * */ public class SendSMSThread extends Thread { private final String CLASS_NAME = getClass().getName(); private String smsText; private String incomingCallNumber; private CallLog callLog; //-------------- Getters & Setters --------------------------// public String getSmsText() { return smsText; } public void setSmsText(String smsText) { this.smsText = smsText; } public String getIncomingCallNumber() { return incomingCallNumber; } public void setIncomingCallNumber(String incomingCallNumber) { this.incomingCallNumber = incomingCallNumber; } public CallLog getCallLog() { return callLog; } public void setCallLog(CallLog callLog) { this.callLog = callLog; } //------------------------------------------------------------------------// /** * Constructor with the phonenumber of the receiver sms */ public SendSMSThread (String incomingCallNumber, CallLog callLog) { init(incomingCallNumber, callLog); } /** * Function that is called for the constructor * @param incomingCallNumber */ public void init (String incomingCallNumber, CallLog callLog) { this.incomingCallNumber = incomingCallNumber; this.callLog = callLog; getAllData(); } /** * Get all data of SMS settings */ private void getAllData () { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) smsText = settings.getSmsText(); clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Check if the receiver phone number have permission to use for send SMS * message * * @return true or false if the phone number (receiver) can or not receive * messages */ private boolean checkSendPhoneNumber () { try { ClientDDBB clientDDBB = new ClientDDBB(); Phone phone = clientDDBB.getSelects().selectPhoneForPhoneNumber(incomingCallNumber); clientDDBB.close(); if (phone != null) return phone.isUsedToSend(); else return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } @Override public void run () { sendSms(); } /** * Send one SMS message to the receiver * */ public void sendSms () { try { if (checkSendPhoneNumber()) { final String SENT_SMS_ACTION = "SENT_SMS_ACTION"; final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION"; //Create the setIntent parameter Intent sentIntent = new Intent(SENT_SMS_ACTION); PendingIntent sentPI = PendingIntent.getBroadcast( ConfigAppValues.getContext(), 0, sentIntent, 0); //Create the deliveryIntetn parameter Intent deliveryIntent = new Intent(DELIVERED_SMS_ACTION); PendingIntent deliverPI = PendingIntent.getBroadcast( ConfigAppValues.getContext(), 0, deliveryIntent, 0); SmsManager smsManager = SmsManager.getDefault(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SmsText: " + smsText); /* In Nexus One there is a bug (how in htc tatoo) that sent sms * using sendTextMessage not found, so i try to send sms by * cut into parts (if its necessary) and send using sendMultipartMessage */ ArrayList<String> multipartSmsText = smsManager.divideMessage(smsText); int multipartSize = multipartSmsText.size(); //Create the arraylist PendingIntents for use it. ArrayList<PendingIntent> sentPiList = new ArrayList<PendingIntent>(multipartSize); ArrayList<PendingIntent> deliverPiList = new ArrayList<PendingIntent>(multipartSize); for (int i=0; i<multipartSize; i++) { sentPiList.add(sentPI); deliverPiList.add(deliverPI); } if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "MultipartSize: " + multipartSize); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "MultpartMessage: " + multipartSmsText); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Send sms to: " + incomingCallNumber); String operator = getOperator(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Operator: " + operator); smsManager.sendMultipartTextMessage( incomingCallNumber, operator, multipartSmsText, sentPiList, deliverPiList); /* In the smssettings.xml layout i specified only 160 character, * one message, so if the send have been done, setSendSms is true */ if (multipartSize > 0) { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "MEssage send!!!"); callLog.setSendSms(true); } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } private String getOperator () { try { final Uri SMS_CONTENT_URI = Uri.parse("content://sms"); final String REPLY_PATH_PRESENT = "reply_path_present"; final String SERVICE_CENTER = "service_center"; final int COLUMN_REPLY_PATH_PRESENT = 0; final int COLUMN_SERVICE_CENTER = 1; final String[] SERVICE_CENTER_PROJECTION = new String[] {REPLY_PATH_PRESENT, SERVICE_CENTER,}; Cursor cursor = ConfigAppValues.getContext().getContentResolver().query(SMS_CONTENT_URI, SERVICE_CENTER_PROJECTION, "thread_id = " + 0, null, "date DESC"); // cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(), // Sms.CONTENT_URI, SERVICE_CENTER_PROJECTION, // "thread_id = " + threadId, null, "date DESC"); if ((cursor == null) || !cursor.moveToFirst()) { return null; } boolean replyPathPresent = (1 == cursor.getInt(COLUMN_REPLY_PATH_PRESENT)); if (cursor != null) cursor.close(); return replyPathPresent ? cursor.getString(COLUMN_SERVICE_CENTER) : null; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return null; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import es.cesar.quitesleep.R; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class About extends Activity implements OnClickListener { private final String CLASS_NAME = getClass().getName(); private final int backButtonId = R.id.information_button_cancel; private Button backButton; public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); backButton = (Button)findViewById(backButtonId); backButton.setOnClickListener(this); } public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case backButtonId: setResult(Activity.RESULT_CANCELED); finish(); break; default: break; } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.widget.ToggleButton; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.dialogs.WarningDialog; import es.cesar.quitesleep.operations.DialogOperations; import es.cesar.quitesleep.operations.SmsOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class SmsSettings extends Activity implements OnClickListener { final private String CLASS_NAME = getClass().getName(); final private int WARNING_DIALOG = 0; //Ids for widgets final int smsEditTextId = R.id.smssettings_edittext_savesms; final int saveSmsButtonId = R.id.smssettings_button_savesms; final int smsServiceToggleButtonId = R.id.smssettings_togglebutton_smsservice; final int cancelButtonId = R.id.smssettings_button_cancel; //Widgets private EditText smsEditText; private Button saveSmsButton; private ToggleButton smsServiceToggleButton; private Button cancelButton; private WarningDialog warningDialog; public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.smssettings); smsEditText = (EditText)findViewById(smsEditTextId); saveSmsButton = (Button)findViewById(saveSmsButtonId); smsServiceToggleButton = (ToggleButton)findViewById(smsServiceToggleButtonId); cancelButton = (Button)findViewById(cancelButtonId); saveSmsButton.setOnClickListener(this); smsServiceToggleButton.setOnClickListener(this); cancelButton.setOnClickListener(this); warningDialog = new WarningDialog( this, ConfigAppValues.WARNING_SMS_ACTION); //Put in the widgets the prevoious data saved into ddbb. getDefaultValues(); } @Override public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case saveSmsButtonId: prepareSaveSmsOperation(); break; case smsServiceToggleButtonId: if (smsServiceToggleButton.isChecked()) showDialog(WARNING_DIALOG); else DialogOperations.checkSmsService( this, smsServiceToggleButton.isChecked()); break; case cancelButtonId: setResult(Activity.RESULT_CANCELED); finish(); break; default: break; } } /** * Create the activity dialogs used for it * * @param id * @return the dialog for the option specified * @see Dialog */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case WARNING_DIALOG: if (QSLog.DEBUG_E)QSLog.d(CLASS_NAME, "Create the WarningDialog for 1st time"); dialog = warningDialog.getAlertDialog(); break; default: dialog = null; } return dialog; } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case WARNING_DIALOG: warningDialog.setContext(this); warningDialog.setToggleButtonIsChecked(smsServiceToggleButton.isChecked()); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put the default values saved in the ddbb in the widgets */ private void getDefaultValues () { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { if (settings.getSmsText()!= null && !settings.getSmsText().equals("")) smsEditText.setText(settings.getSmsText()); smsServiceToggleButton.setChecked(settings.isSmsService()); }else { settings = new Settings(false); clientDDBB.getInserts().insertSettings(settings); /* Save the sms text in the settings if the Settings object haven't * been created, so the predefined text will be, for the moment, * the sms text in the settings object */ settings.setSmsText(smsEditText.getText().toString()); clientDDBB.commit(); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that prepare the data for save into ddbb and call to the function * that does the operation. */ private void prepareSaveSmsOperation () { try { String smsText = smsEditText.getText().toString(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SmsEditText: " + smsText); if (SmsOperations.saveSmsSettings(smsText)) if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.smssettings_toast_save), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.widget.ToggleButton; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Settings; import es.cesar.quitesleep.dialogs.WarningDialog; import es.cesar.quitesleep.operations.DialogOperations; import es.cesar.quitesleep.operations.MailOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class MailSettings extends Activity implements OnClickListener { private final String CLASS_NAME = getClass().getName(); final private int WARNING_DIALOG = 0; //Widgets id's private final int userEditTextId = R.id.mailsettings_edittext_user; private final int passwdEditTextId = R.id.mailsettings_edittext_passwd; private final int subjectEditTextId = R.id.mailsettings_edittext_subject; private final int bodyEditTextId = R.id.mailsettings_edittext_body; private final int saveMailButtonId = R.id.mailsettings_button_savemail; private final int mailServiceToggleButtonId = R.id.mailsettings_togglebutton_mailservice; private final int cancelButtonId = R.id.mailsettings_button_cancel; //Widgets private EditText userEditText; private EditText passwdEditText; private EditText subjectEditText; private EditText bodyEditText; private Button saveMailButton; private ToggleButton mailServiceToggleButton; private Button cancelButton; private WarningDialog warningDialog; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mailsettings); //Set the widgets elements userEditText = (EditText)findViewById(userEditTextId); passwdEditText = (EditText)findViewById(passwdEditTextId); subjectEditText = (EditText)findViewById(subjectEditTextId); bodyEditText = (EditText)findViewById(bodyEditTextId); saveMailButton = (Button)findViewById(saveMailButtonId); mailServiceToggleButton = (ToggleButton)findViewById(mailServiceToggleButtonId); cancelButton = (Button)findViewById(cancelButtonId); //Set OnClickListener events saveMailButton.setOnClickListener(this); mailServiceToggleButton.setOnClickListener(this); cancelButton.setOnClickListener(this); warningDialog = new WarningDialog( this, ConfigAppValues.WARNING_MAIL_ACTION); //Put in the widgets the prevoious data saved into ddbb. getDefaultValues(); } @Override public void onClick (View view) { int viewId = view.getId(); switch (viewId) { case saveMailButtonId: prepareSaveMailOperation(); break; case mailServiceToggleButtonId: if (mailServiceToggleButton.isChecked()) showDialog(WARNING_DIALOG); else DialogOperations.checkMailService( this, mailServiceToggleButton.isChecked()); break; case cancelButtonId: setResult(Activity.RESULT_CANCELED); finish(); break; default: break; } } /** * Create the activity dialogs used for it * * @param id * @return the dialog for the option specified * @see Dialog */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case WARNING_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the WarningDialog for 1st time"); dialog = warningDialog.getAlertDialog(); break; default: dialog = null; } return dialog; } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case WARNING_DIALOG: warningDialog.setContext(this); warningDialog.setToggleButtonIsChecked(mailServiceToggleButton.isChecked()); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Function that put in the widgets the data saved into ddbb. */ private void getDefaultValues () { try { ClientDDBB clientDDBB = new ClientDDBB(); Settings settings = clientDDBB.getSelects().selectSettings(); if (settings != null) { if (settings.getUser() != null && !settings.getUser().equals("")) userEditText.setText(settings.getUser()); if (settings.getPasswd() != null && !settings.getPasswd().equals("")) passwdEditText.setText(settings.getPasswd()); if (settings.getSubject() != null && !settings.getSubject().equals("")) subjectEditText.setText(settings.getSubject()); if (settings.getBody() != null && !settings.getBody().equals("")) bodyEditText.setText(settings.getBody()); mailServiceToggleButton.setChecked(settings.isMailService()); } //If Settings object haven't been created previously, here we create. else { settings = new Settings(false); /* Save the mail settings, only the subject and the body if the * Settings object haven't been created for have something for * default attributes, user and passwd not because is important * for the mail send, and the user soon or later will have set this. */ settings.setSubject(subjectEditText.getText().toString()); settings.setBody(bodyEditText.getText().toString()); clientDDBB.getInserts().insertSettings(settings); clientDDBB.commit(); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Prepare all data from widgets for call to the function that save data * into ddbb in Settings object * */ private void prepareSaveMailOperation () { try { String user = userEditText.getText().toString(); String passwd = passwdEditText.getText().toString(); String subject = subjectEditText.getText().toString(); String body = bodyEditText.getText().toString(); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "user: " + user); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "passwd: " + passwd); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "subject: " + subject); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "body: " + body); if (MailOperations.saveMailSettings(user, passwd, subject, body)) //All right, start the service was ok! if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.mailsettings_toast_save), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.dialogs.WarningDialog; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * * @version 0.1, 03-13-2010 * * Class for AddContacts to the banned user list * */ public class AddBanned extends ListActivity { //Constants final private String CLASS_NAME = this.getClass().getName(); final private int WARNING_DIALOG = 0; //Widgets Id's final private int addAllMenuId = R.id.menu_addall; //Widgets private WarningDialog warningDialog; private ArrayAdapter<String> arrayAdapter; //Auxiliar attributes private String selectContactName; /** * onCreate * * @param savedInstanceState */ @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); warningDialog = new WarningDialog( this, ConfigAppValues.WARNING_ADD_ALL_CONTACTS); getAllContactList(); } /** * Get all not banned contacts from the database and parse it for create * one contact list only with their contactNames */ private void getAllContactList () { try { ClientDDBB clientDDBB = new ClientDDBB(); List<Contact> contactList = clientDDBB.getSelects().selectAllNotBannedContacts(); List<String> contactListString = convertContactList(contactList); if (contactListString != null) { arrayAdapter = new ArrayAdapter<String>( this, R.layout.addbanned, R.id.addBanned_textview_name, contactListString); setListAdapter(arrayAdapter); } clientDDBB.close(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * * @param contactList * @return The contactList but only the list with the name contacts * @see List<String> */ private List<String> convertContactList (List<Contact> contactList) throws Exception { try { if (contactList != null && contactList.size()>0) { List<String> contactListString = new ArrayList<String>(); for (int i=0; i<contactList.size(); i++) { String contactName = contactList.get(i).getContactName(); if (contactName != null) contactListString.add(contactName); } return contactListString; } return null; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); throw new Exception(); } } @Override protected void onListItemClick ( ListView listView, View view, int position, long id){ try { if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "OnListItemClick"); super.onListItemClick(listView, view, position, id); selectContactName = (String) this.getListAdapter().getItem(position); if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Name: " + selectContactName); /* If we like to use one subactivity for show better contact details * and select what phone number and/or mail addresses are used for * send busy response. */ Intent intentContactDetails = new Intent(this,ContactDetails.class); intentContactDetails.putExtra(ConfigAppValues.CONTACT_NAME, selectContactName); startActivityForResult(intentContactDetails, ConfigAppValues.REQCODE_CONTACT_DETAILS); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public void onActivityResult (int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case ConfigAppValues.REQCODE_CONTACT_DETAILS: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Valor retornado: " + resultCode); if (resultCode == Activity.RESULT_OK) arrayAdapter.remove(selectContactName); break; default: break; } } /** * Create the activity dialogs used for it * * @param id * @return the dialog for the option specified * @see Dialog */ @Override protected Dialog onCreateDialog (int id) { Dialog dialog; switch (id) { case WARNING_DIALOG: if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the WarningDialog for 1st time"); dialog = warningDialog.getAlertDialog(); break; default: dialog = null; } return dialog; } /** * This function prepare the dalogs every time to call for some of this * * @param int * @param dialog */ @Override protected void onPrepareDialog (int idDialog, Dialog dialog) { try { switch (idDialog) { case WARNING_DIALOG: warningDialog.setContext(this); warningDialog.setArrayAdapter(arrayAdapter); warningDialog.setHandler(handler); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public boolean onCreateOptionsMenu (Menu menu) { try { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.addallmenu, menu); return true; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * @param item * @return boolean */ @Override public boolean onOptionsItemSelected (MenuItem item) { try { switch (item.getItemId()) { case addAllMenuId: showDialog(WARNING_DIALOG); break; default: break; } return false; }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); return false; } } /** * Handler for clear the listView and the array adapter once we have been * add all contacts to the banned list */ public final Handler handler = new Handler() { public void handleMessage(Message message) { final String NUM_BANNED = "NUM_BANNED"; if (arrayAdapter != null && arrayAdapter.getCount()>0) { //int count = arrayAdapter.getCount(); int numBanned = message.getData().getInt(NUM_BANNED); //clear the arrayAdapter arrayAdapter.clear(); //Show the toast message if (QSToast.RELEASE) QSToast.r( ConfigAppValues.getContext(), numBanned + " " + ConfigAppValues.getContext().getString( R.string.menu_addall_toast_insertscount), Toast.LENGTH_SHORT); } } }; }
Java
/* Copyright 2010 Cesar Valiente Gordo This file is part of QuiteSleep. QuiteSleep is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QuiteSleep is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>. */ package es.cesar.quitesleep.subactivities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import es.cesar.quitesleep.R; import es.cesar.quitesleep.ddbb.ClientDDBB; import es.cesar.quitesleep.ddbb.Contact; import es.cesar.quitesleep.ddbb.Mail; import es.cesar.quitesleep.ddbb.Phone; import es.cesar.quitesleep.operations.ContactOperations; import es.cesar.quitesleep.staticValues.ConfigAppValues; import es.cesar.quitesleep.utils.ExceptionUtils; import es.cesar.quitesleep.utils.QSLog; import es.cesar.quitesleep.utils.QSToast; /** * * @author Cesar Valiente Gordo * @mail cesar.valiente@gmail.com * */ public class ContactDetails extends Activity implements OnClickListener { final private String CLASS_NAME = getClass().getName(); //Global widgets private ScrollView scrollView; private LinearLayout linearLayout; //Phone and mail list for dynamic checkbox private List<CheckBox> phoneCheckboxList; private List<CheckBox> mailCheckboxList; /* The contact Name selected in parent and caller activity when the user * selectd clicking in it. */ private String selectContactName; //Ids for button widgets private final int addContactButtonId = 1; private final int cancelButtonId = 2; //Ids for colors private final int backgroundColor = R.color.black; private final int textColor = R.color.black; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); initDynamicLayout(); } /** * Create and initialize the dynamic layout and put some widgets on it */ private void initDynamicLayout () { try { /* Get the contactName passed from the parent activity to this, and * use for get a Contact object refferenced to this name. */ selectContactName = getIntent().getExtras().getString( ConfigAppValues.CONTACT_NAME); ClientDDBB clientDDBB = new ClientDDBB(); Contact contact = clientDDBB.getSelects().selectContactForName(selectContactName); if (contact != null && !contact.isBanned()) { if (QSLog.DEBUG_D)QSLog.d( CLASS_NAME, "selectContactName: " + selectContactName); createLayout(); createHeader(); createPhoneNumbersSection(clientDDBB, contact); createMailAddressesSection(clientDDBB, contact); addButtons(); setContentView(scrollView); clientDDBB.close(); }else { clientDDBB.close(); setResult(Activity.RESULT_CANCELED); finish(); } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /* * Create the scrollView and LinearLayput for put some widgets on it */ private void createLayout () { try { scrollView = new ScrollView(this); linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL); scrollView.setBackgroundColor(this.getResources().getColor(backgroundColor)); scrollView.addView(linearLayout); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put the contactName and a separator view how header for the layout */ private void createHeader () { try { TextView contactName = new TextView(this); contactName.setText(selectContactName); //contactName.setTextColor(textColor); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); contactName.setLayoutParams(params); contactName.setTypeface(Typeface.create("", Typeface.BOLD_ITALIC)); contactName.setTextSize(25); linearLayout.addView(contactName); addDividerBlack(); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Create the phone numbers section * * @param clientDDBB * @param contact */ private void createPhoneNumbersSection (ClientDDBB clientDDBB, Contact contact) { try { List<Phone> contactPhones = clientDDBB.getSelects().selectAllContactPhonesForName(selectContactName); if (contactPhones != null) { addDividerDetails(R.string.contactdetails_label_phonedetails); phoneCheckboxList = new ArrayList<CheckBox>(contactPhones.size()); for (int i=0; i<contactPhones.size(); i++) { Phone phone = contactPhones.get(i); CheckBox checkbox = new CheckBox(this); checkbox.setText(phone.getContactPhone()); checkbox.setChecked(phone.isUsedToSend()); //checkbox.setTextColor(textColor); linearLayout.addView(checkbox); phoneCheckboxList.add(checkbox); } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Create the mail addresses section * * @param clientDDBB * @param contact */ private void createMailAddressesSection (ClientDDBB clientDDBB, Contact contact) { try { List<Mail> contactMails = clientDDBB.getSelects().selectAllContactMailsForName(selectContactName); if (contactMails != null && contactMails.size() > 0) { addDividerDetails(R.string.contactdetails_label_maildetails); mailCheckboxList = new ArrayList<CheckBox>(contactMails.size()); for (int i=0; i<contactMails.size(); i++) { Mail mail = contactMails.get(i); CheckBox checkbox = new CheckBox(this); checkbox.setText(mail.getContactMail()); checkbox.setChecked(mail.isUsedToSend()); //checkbox.setTextColor(textColor); linearLayout.addView(checkbox); mailCheckboxList.add(checkbox); } } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Put one black dividerDetails view in the layout. * Pass the resId with the string that we like it. * @param resId */ private void addDividerDetails (int resId) { TextView details = new TextView(this); details.setBackgroundResource(R.drawable.solid_black); details.setTypeface(Typeface.create("", Typeface.BOLD)); details.setTextSize(15); details.setText(resId); details.setPadding(0, 10, 0, 0); linearLayout.addView(details); } /** * Put one black divider view in the layout as separator for other views */ private void addDividerBlack () { TextView dividerBlack = new TextView(this); dividerBlack.setBackgroundResource(R.drawable.gradient_black); dividerBlack.setTextSize(3); linearLayout.addView(dividerBlack); } /** * Put one blue divider view in the layout as separator for other views */ private void addDividerBlue () { TextView dividerBlue = new TextView(this); dividerBlue.setBackgroundResource(R.drawable.gradient_blue); dividerBlue.setTextSize(2); linearLayout.addView(dividerBlue); } /** * Put two buttons, one for addContact to the banned list and other for * cancel and go back to the parent activity. */ private void addButtons () { try { addDividerBlack(); Button addContactButton = new Button(this); addContactButton.setText(R.string.contactdetails_button_addcontact); addContactButton.setId(addContactButtonId); addContactButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.add, 0, 0, 0); addContactButton.setId(addContactButtonId); addContactButton.setOnClickListener(this); linearLayout.addView(addContactButton); addDividerBlue(); Button cancelButton = new Button(this); cancelButton.setText(R.string.contactdetails_button_cancel); cancelButton.setId(cancelButtonId); cancelButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.back, 0, 0, 0); cancelButton.setId(cancelButtonId); cancelButton.setOnClickListener(this); linearLayout.addView(cancelButton); }catch (Exception e) { if (QSLog.DEBUG_E)Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } @Override public void onClick (View view) { try { int viewId = view.getId(); switch (viewId) { case addContactButtonId: boolean result = ContactOperations.addContact( selectContactName, phoneCheckboxList, mailCheckboxList); showToast(result); setResult(Activity.RESULT_OK); finish(); break; case cancelButtonId: setResult(Activity.RESULT_CANCELED); finish(); break; default: break; } }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } /** * Show toast notification for information to user * * @param result */ private void showToast (boolean result) { try { if (result) if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.contactdetails_toast_added), Toast.LENGTH_SHORT); else if (QSToast.RELEASE) QSToast.r( this, this.getString( R.string.contactdetails_toast_fail), Toast.LENGTH_SHORT); }catch (Exception e) { if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString( e.toString(), e.getStackTrace())); } } }
Java