First steps obtaining user location
authorgumartinm <gu.martinm@gmail.com>
Tue, 20 Dec 2011 23:11:11 +0000 (00:11 +0100)
committergumartinm <gu.martinm@gmail.com>
Tue, 20 Dec 2011 23:11:11 +0000 (00:11 +0100)
The next one will be to use a Service

Allgemeines/PrinterHelper/src/printer/helper/PrinterHelper.java [new file with mode: 0644]
Allgemeines/src/printer/helper/PrinterHelper.java [deleted file]
Android/Testing/Test2/AndroidManifest.xml
Android/Testing/Test2/res/values/strings.xml
Android/Testing/Test2/src/de/android/test2/MobieAdHttpClient.java [new file with mode: 0644]
Android/Testing/Test2/src/de/android/test2/NextActivity.java
Android/Testing/Test2/src/de/android/test2/Test2Activity.java
Android/Testing/Test2/src/de/android/test2/TestService.java [new file with mode: 0644]

diff --git a/Allgemeines/PrinterHelper/src/printer/helper/PrinterHelper.java b/Allgemeines/PrinterHelper/src/printer/helper/PrinterHelper.java
new file mode 100644 (file)
index 0000000..6e085ca
--- /dev/null
@@ -0,0 +1,349 @@
+/**
+ * 
+ */
+package printer.helper;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+
+
+/**
+ * <p>
+ *  First of all some thoughts:
+ * </p>
+ * <p>
+ *  The device wrapper classes lack methods to change themselves the device configuration. 
+ * These methods can be found in the Logical layer, so this layer is device-dependent
+ * (it just will work with JavaPOS devices)
+ * Actually we have two options in order to write specific methods related to the device
+ * configuration. We can add these methods to the Logical layer or create a new Helper Class 
+ * for them but... What about if we need to add device specific methods? The Logical layer is right
+ * now JavaPOS dependent (although it was intended to be a device abstraction...) if we add 
+ * device specific methods such as methods related to a specific kind of Printer, the Logical
+ * layer will be useless and the code will be a mess (if some day a device is changed we will 
+ * have to search the whole code to find out what code is related with that device and 
+ * we will have to create new classes in the Logical layer for every device ) 
+ * </p>
+ * <p>
+ *      So this Helper is intended to store methods which do not fit into the Logical layer because
+ * they make this layer not just JPOS dependent but completely device-dependent. All of this because
+ * of the wrapper classes lack the required methods for these kinds of operations.
+ * </p>
+ * <p>
+ *  To sum up, before adding in this class new methods you should ask yourself two questions:
+ * <ul>
+ * <li>1. Is your method device independent? If the answer is yes, without doubt write your method in
+ * the Logical layer. If the answer is no you have to ask yourself a second question.</li>
+ * <br>
+ * <li>2. Is this method device or JavaPOS dependent? If the answer is JavaPOS-dependent write 
+ * your new method in the Logical layer and if it is device-dependent use this class for them.</li>
+ * </ul>
+ * </p>
+ * <p>
+ * Instances of this class are mutable. To use them concurrently, clients must surround each
+ * method invocation (or invocation sequence) with external synchronization of the clients' choosing.
+ * </p>
+ */
+public final class PrinterHelper {
+       private static final Logger logger = Logger.getLogger(PrinterHelper.class);
+       private static final String HOME_ENV_KEY = "HOME";
+       private static final String FORM_PROPERTIES_FILE_RELATIVE_PATH = "etc/"+ FormConfiguration.PROPERTIES_FILE;
+       private static final String TEMPLATE_FILE_EXTENSION = ".frm";
+       private static final String PRINTER_PROPERTY = "MethodToPrintImage";
+       private static final String PRINTER_PROPERTY_VALUE = "ESC/POS";
+       
+        // Prevents instantiation from other classes. Why do you want to extend this class?
+    private PrinterHelper() { }
+
+       
+    /**
+        * This method must try and fetch the model of the currently connected form printer (physically)
+        * on the given port
+        * 
+        * @param      formPrinterPort the printer port.
+        * @return     the model printer as a {@code FormPrinterModel enum} class
+     *             The first <code>char</code> value is at index <code>0</code>.
+        */
+       public static FormPrinterModel autoDetetectFormPrinterModel(final Port formPrinterPort) 
+       {
+               FormPrinterModel formPrinterModelDetected = null;
+               
+               final File scriptAutoDetect = new File(System.getProperty(HOME_ENV_KEY),"tools/detectatm88.sh");
+               if (scriptAutoDetect.exists() && scriptAutoDetect.canExecute()){
+
+
+                       final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                       final PrintStream output = new PrintStream(baos);
+
+                       final String command = "sh " + scriptAutoDetect.getAbsolutePath() +     " "  + formPrinterPort.getPhysicalPath();
+                       try {
+                               int result;
+
+                               //result field stores exit status of the executed command
+                               result = LauncherProcesses.exec(command,output);
+
+                               if(result==0)
+                               {
+                                       logger.debug("detectatm88 raw output: "+baos.toString());
+                                       //From detectatm88.sh script we receive a string like this one: "RESULT: 2"
+                                       //we must split the String and retrieve the integer value
+                                       final String[] parameters = baos.toString().split(" ");
+                                       final int model = Integer.parseInt(parameters[1].trim());
+                                       switch(model){
+                                       case 0:
+                                               logger.warn("TM88 not physically detected: run again detectatm88.sh script");
+                                               formPrinterModelDetected = null;
+                                               break;
+                                       case 2:
+                                               logger.info("TM-T88II detected");
+                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_II_III;
+                                               PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
+                                               break;
+                                       case 3:
+                                               logger.info("TM-T88III detected");
+                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_II_III;
+                                               PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
+                                               break;
+                                       case 4:
+                                               logger.info("TM-T88IV detected");
+                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_IV;
+                                               PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
+                                               break;
+                                       case 5:
+                                               logger.info("TM-T88V detected");
+                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_V;
+                                               PrinterHelper.removeFormPrinterProperty(PRINTER_PROPERTY);
+                                               break;
+                                       default:
+                                               logger.warn("Code retrieved from detectatm88.sh script does not match.");
+                                               formPrinterModelDetected = null;
+                                               break;
+                                       }               
+                               }
+                               //model not detected
+                               else{
+                                       logger.warn("TM88 not physically detected. Not conected printer or it is not a TM-T88");
+                               }
+                       } catch (Exception e) {
+                               logger.error(e);
+                       } 
+               }
+               else {
+                       logger.warn("Script for tm88 detection not found or not exectuable");
+               }
+
+               return formPrinterModelDetected;
+       }
+
+       /**
+        * This method is intended to add new properties in DtgFormToPrint.properties file used by TM88 printers.
+        * 
+        * @param  property  the property to be added
+        * @param  value     value of property param. Possible values:
+        *                                       <br>
+        *                                       <ul>
+        *                                       <li>printBitmap</li>
+        *                                       <li>printMemoryBitmap</li>
+        *                                       <li>setBitmap</li>
+        *                                       <li>ESC/POS</li>
+        *                                       </ul>
+        * @throws FileNotFoundException 
+        *                 If the file called DtgFormToPrint.properties
+        *         is not found.
+        */
+       public static void addFormPrinterProperty(final String property, final String value) throws FileNotFoundException
+       {
+               //If the property does not exist we do not have to remove it
+               if (FormConfiguration.getConfiguration().getSection().get(property) == null)
+               {
+                       FormConfiguration.getConfiguration().getSection().add(property,value);
+                       OutputStream formConfigurationFile;
+                       formConfigurationFile = new FileOutputStream
+                                       (new File(System.getProperty(HOME_ENV_KEY),FORM_PROPERTIES_FILE_RELATIVE_PATH));
+                       FormConfiguration.getConfiguration().save(formConfigurationFile);
+               }
+       }
+       
+       /**
+        * This method is intended to remove properties in DtgFormToPrint.properties file used by TM88 printers.
+        * 
+        * @param  property property to be removed
+        * @throws FileNotFoundException 
+        *                 If the file called DtgFormToPrint.properties
+        *         is not found.
+        */
+       public static void removeFormPrinterProperty(final String property) throws FileNotFoundException
+       {
+               FormConfiguration.getConfiguration().getSection().remove(property);
+               OutputStream formConfigurationFile;
+               formConfigurationFile = new FileOutputStream
+                               (new File(System.getProperty(HOME_ENV_KEY),FORM_PROPERTIES_FILE_RELATIVE_PATH));
+               FormConfiguration.getConfiguration().save(formConfigurationFile);
+
+       }
+       
+       /**
+        * This method returns a {@code List<File>} with the found files.
+        * 
+        * @param  extension the file extension name
+        * @return the found files
+        */
+       public static List<File> findFilebyExtension(final String extension)
+       {
+               final File dir = ConfigurationHelper.getInstance().getFormsFolder();
+               
+               final FilenameFilter filter = new FilenameFilter() {
+                   public boolean accept(final File dir, final String name) {
+                       return name.endsWith(extension);
+                   }
+               };
+               List<File> filesList = new ArrayList<File>();
+
+               for (File file : dir.listFiles(filter))
+               {
+                   filesList.add(file);
+               }
+               
+               return filesList;
+       }
+       
+       /**
+        * Read file line by line and stores the lines in a {@code List<String>}
+        * 
+        * @param file
+        * @param charset the file charset
+        * @return the file lines in a list
+        * @throws IOException
+        *                 If an I/O error occurs while reading or trying to open the file
+        */
+       public static List<String> readFile (final File file, final String charset) throws IOException
+       {
+               final BufferedReader bufferReader = new BufferedReader(new InputStreamReader
+                               (new FileInputStream(file), charset));
+               
+               List<String> contents = new ArrayList<String>();
+               String currentLine = null;
+               
+               try {
+                       currentLine = bufferReader.readLine();
+                       while (currentLine != null)
+                       {
+                               contents.add(currentLine);
+                               currentLine = bufferReader.readLine();
+                       }
+               } finally {
+                       bufferReader.close();
+               }
+
+               return contents;
+               
+       }
+       
+       /**
+        * Write lines to a file.
+        * 
+        * @param contents the lines to be written in a {@code List<String>}
+        * @param charset the file charset
+        * @param fileName the file name. Absolute or abstract pathname, it is your choice
+        * @throws IOException
+        *                 If an I/O error occurs while writing or trying to open the file
+        */
+       public static void writeFile (final List<String> contents, final String fileName, final String charset) throws IOException
+       {
+               final OutputStream outputStream = new FileOutputStream(fileName);
+               final PrintStream output = new PrintStream(outputStream, true, charset);
+               
+               try {
+                       for (String line : contents )
+                       {
+                               output.println(line);
+                       }
+               }
+               finally {
+                    output.close();
+               }
+       }
+       
+       /**
+        * Replace every line (file lines stored in a {@code List<String>})  
+        * with the lineReplacement if the line contains the pattern
+        * 
+        * @param contents the lines to be searched in a {@code List<String>}
+        * @param pattern the pattern to match in a line
+        * @param lineReplacement the whole line to replace in case of some match
+        * @return <b>true</b> if there is a match, otherwise <b>false</b>
+        */
+       public static boolean replaceLine (final List<String> contents, final String pattern, final String lineReplacement)
+       {
+               final ListIterator<String> itr = contents.listIterator();
+               boolean change = false;
+               
+               while (itr.hasNext())
+               {
+                       if (itr.next().trim().contains(pattern)) {
+                   itr.set(lineReplacement);
+                   change = true;
+                       }
+               }
+               
+               return change;
+       }
+       
+       /**
+        * Method intended to be used by the Logical layer. Search the template files
+        * of the form printer, replace the lines in case of match and write on the hard disk the 
+        * new files.
+        * 
+        * @param pattern the pattern to match
+        * @param lineReplacement the whole line to replace in case of some match
+        * @throws IOException
+        *                 If an I/O error occurs while writing or trying to open a file
+        */
+       public static void searchandReplace (final String pattern, final String lineReplacement) throws IOException
+       {
+               final List<File> fileList = PrinterHelper.findFilebyExtension(TEMPLATE_FILE_EXTENSION);
+               for (File file : fileList)
+               {
+                       final List<String> contents = PrinterHelper.readFile(file, FormConfiguration.getCharset());
+                       if (PrinterHelper.replaceLine(contents, pattern, lineReplacement))
+                       {
+                               PrinterHelper.writeFile(contents, file.getAbsolutePath(), FormConfiguration.getCharset());
+                       }
+               }
+       }
+       
+       /**
+        *  Method intended to be used by the Logical layer. It is smart enough to find out
+        *  it there is a new form printer model
+        * 
+        * @param oldModel The previous form printer model
+        * @param newModel The new form printer model
+        * @throws IOException
+        *                 If an I/O error occurs while writing or trying to open a file
+        */
+       public static void changedPrinter (final HardwareModel oldModel, final HardwareModel newModel) throws IOException
+       {
+               if(FormPrinterModel.EPSON_TM_88_V.getXmlDescriptor().equals(newModel.getXmlDescriptor()))
+               {
+                       PrinterHelper.searchandReplace("methodToPrintImage(ESC/POS)", "         COMMENT      \"usePageMode(false)\"");
+                       PrinterHelper.removeFormPrinterProperty(PRINTER_PROPERTY);
+               }
+               else if (FormPrinterModel.EPSON_TM_88_V.getXmlDescriptor().equals(oldModel.getXmlDescriptor()))
+               {       
+                       PrinterHelper.searchandReplace("usePageMode(false)", "         COMMENT      \"usePageMode(false) methodToPrintImage(ESC/POS)\"");
+                       PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
+               }
+       }
+}
\ No newline at end of file
diff --git a/Allgemeines/src/printer/helper/PrinterHelper.java b/Allgemeines/src/printer/helper/PrinterHelper.java
deleted file mode 100644 (file)
index 6e085ca..0000000
+++ /dev/null
@@ -1,349 +0,0 @@
-/**
- * 
- */
-package printer.helper;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-
-
-/**
- * <p>
- *  First of all some thoughts:
- * </p>
- * <p>
- *  The device wrapper classes lack methods to change themselves the device configuration. 
- * These methods can be found in the Logical layer, so this layer is device-dependent
- * (it just will work with JavaPOS devices)
- * Actually we have two options in order to write specific methods related to the device
- * configuration. We can add these methods to the Logical layer or create a new Helper Class 
- * for them but... What about if we need to add device specific methods? The Logical layer is right
- * now JavaPOS dependent (although it was intended to be a device abstraction...) if we add 
- * device specific methods such as methods related to a specific kind of Printer, the Logical
- * layer will be useless and the code will be a mess (if some day a device is changed we will 
- * have to search the whole code to find out what code is related with that device and 
- * we will have to create new classes in the Logical layer for every device ) 
- * </p>
- * <p>
- *      So this Helper is intended to store methods which do not fit into the Logical layer because
- * they make this layer not just JPOS dependent but completely device-dependent. All of this because
- * of the wrapper classes lack the required methods for these kinds of operations.
- * </p>
- * <p>
- *  To sum up, before adding in this class new methods you should ask yourself two questions:
- * <ul>
- * <li>1. Is your method device independent? If the answer is yes, without doubt write your method in
- * the Logical layer. If the answer is no you have to ask yourself a second question.</li>
- * <br>
- * <li>2. Is this method device or JavaPOS dependent? If the answer is JavaPOS-dependent write 
- * your new method in the Logical layer and if it is device-dependent use this class for them.</li>
- * </ul>
- * </p>
- * <p>
- * Instances of this class are mutable. To use them concurrently, clients must surround each
- * method invocation (or invocation sequence) with external synchronization of the clients' choosing.
- * </p>
- */
-public final class PrinterHelper {
-       private static final Logger logger = Logger.getLogger(PrinterHelper.class);
-       private static final String HOME_ENV_KEY = "HOME";
-       private static final String FORM_PROPERTIES_FILE_RELATIVE_PATH = "etc/"+ FormConfiguration.PROPERTIES_FILE;
-       private static final String TEMPLATE_FILE_EXTENSION = ".frm";
-       private static final String PRINTER_PROPERTY = "MethodToPrintImage";
-       private static final String PRINTER_PROPERTY_VALUE = "ESC/POS";
-       
-        // Prevents instantiation from other classes. Why do you want to extend this class?
-    private PrinterHelper() { }
-
-       
-    /**
-        * This method must try and fetch the model of the currently connected form printer (physically)
-        * on the given port
-        * 
-        * @param      formPrinterPort the printer port.
-        * @return     the model printer as a {@code FormPrinterModel enum} class
-     *             The first <code>char</code> value is at index <code>0</code>.
-        */
-       public static FormPrinterModel autoDetetectFormPrinterModel(final Port formPrinterPort) 
-       {
-               FormPrinterModel formPrinterModelDetected = null;
-               
-               final File scriptAutoDetect = new File(System.getProperty(HOME_ENV_KEY),"tools/detectatm88.sh");
-               if (scriptAutoDetect.exists() && scriptAutoDetect.canExecute()){
-
-
-                       final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                       final PrintStream output = new PrintStream(baos);
-
-                       final String command = "sh " + scriptAutoDetect.getAbsolutePath() +     " "  + formPrinterPort.getPhysicalPath();
-                       try {
-                               int result;
-
-                               //result field stores exit status of the executed command
-                               result = LauncherProcesses.exec(command,output);
-
-                               if(result==0)
-                               {
-                                       logger.debug("detectatm88 raw output: "+baos.toString());
-                                       //From detectatm88.sh script we receive a string like this one: "RESULT: 2"
-                                       //we must split the String and retrieve the integer value
-                                       final String[] parameters = baos.toString().split(" ");
-                                       final int model = Integer.parseInt(parameters[1].trim());
-                                       switch(model){
-                                       case 0:
-                                               logger.warn("TM88 not physically detected: run again detectatm88.sh script");
-                                               formPrinterModelDetected = null;
-                                               break;
-                                       case 2:
-                                               logger.info("TM-T88II detected");
-                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_II_III;
-                                               PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
-                                               break;
-                                       case 3:
-                                               logger.info("TM-T88III detected");
-                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_II_III;
-                                               PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
-                                               break;
-                                       case 4:
-                                               logger.info("TM-T88IV detected");
-                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_IV;
-                                               PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
-                                               break;
-                                       case 5:
-                                               logger.info("TM-T88V detected");
-                                               formPrinterModelDetected = FormPrinterModel.EPSON_TM_88_V;
-                                               PrinterHelper.removeFormPrinterProperty(PRINTER_PROPERTY);
-                                               break;
-                                       default:
-                                               logger.warn("Code retrieved from detectatm88.sh script does not match.");
-                                               formPrinterModelDetected = null;
-                                               break;
-                                       }               
-                               }
-                               //model not detected
-                               else{
-                                       logger.warn("TM88 not physically detected. Not conected printer or it is not a TM-T88");
-                               }
-                       } catch (Exception e) {
-                               logger.error(e);
-                       } 
-               }
-               else {
-                       logger.warn("Script for tm88 detection not found or not exectuable");
-               }
-
-               return formPrinterModelDetected;
-       }
-
-       /**
-        * This method is intended to add new properties in DtgFormToPrint.properties file used by TM88 printers.
-        * 
-        * @param  property  the property to be added
-        * @param  value     value of property param. Possible values:
-        *                                       <br>
-        *                                       <ul>
-        *                                       <li>printBitmap</li>
-        *                                       <li>printMemoryBitmap</li>
-        *                                       <li>setBitmap</li>
-        *                                       <li>ESC/POS</li>
-        *                                       </ul>
-        * @throws FileNotFoundException 
-        *                 If the file called DtgFormToPrint.properties
-        *         is not found.
-        */
-       public static void addFormPrinterProperty(final String property, final String value) throws FileNotFoundException
-       {
-               //If the property does not exist we do not have to remove it
-               if (FormConfiguration.getConfiguration().getSection().get(property) == null)
-               {
-                       FormConfiguration.getConfiguration().getSection().add(property,value);
-                       OutputStream formConfigurationFile;
-                       formConfigurationFile = new FileOutputStream
-                                       (new File(System.getProperty(HOME_ENV_KEY),FORM_PROPERTIES_FILE_RELATIVE_PATH));
-                       FormConfiguration.getConfiguration().save(formConfigurationFile);
-               }
-       }
-       
-       /**
-        * This method is intended to remove properties in DtgFormToPrint.properties file used by TM88 printers.
-        * 
-        * @param  property property to be removed
-        * @throws FileNotFoundException 
-        *                 If the file called DtgFormToPrint.properties
-        *         is not found.
-        */
-       public static void removeFormPrinterProperty(final String property) throws FileNotFoundException
-       {
-               FormConfiguration.getConfiguration().getSection().remove(property);
-               OutputStream formConfigurationFile;
-               formConfigurationFile = new FileOutputStream
-                               (new File(System.getProperty(HOME_ENV_KEY),FORM_PROPERTIES_FILE_RELATIVE_PATH));
-               FormConfiguration.getConfiguration().save(formConfigurationFile);
-
-       }
-       
-       /**
-        * This method returns a {@code List<File>} with the found files.
-        * 
-        * @param  extension the file extension name
-        * @return the found files
-        */
-       public static List<File> findFilebyExtension(final String extension)
-       {
-               final File dir = ConfigurationHelper.getInstance().getFormsFolder();
-               
-               final FilenameFilter filter = new FilenameFilter() {
-                   public boolean accept(final File dir, final String name) {
-                       return name.endsWith(extension);
-                   }
-               };
-               List<File> filesList = new ArrayList<File>();
-
-               for (File file : dir.listFiles(filter))
-               {
-                   filesList.add(file);
-               }
-               
-               return filesList;
-       }
-       
-       /**
-        * Read file line by line and stores the lines in a {@code List<String>}
-        * 
-        * @param file
-        * @param charset the file charset
-        * @return the file lines in a list
-        * @throws IOException
-        *                 If an I/O error occurs while reading or trying to open the file
-        */
-       public static List<String> readFile (final File file, final String charset) throws IOException
-       {
-               final BufferedReader bufferReader = new BufferedReader(new InputStreamReader
-                               (new FileInputStream(file), charset));
-               
-               List<String> contents = new ArrayList<String>();
-               String currentLine = null;
-               
-               try {
-                       currentLine = bufferReader.readLine();
-                       while (currentLine != null)
-                       {
-                               contents.add(currentLine);
-                               currentLine = bufferReader.readLine();
-                       }
-               } finally {
-                       bufferReader.close();
-               }
-
-               return contents;
-               
-       }
-       
-       /**
-        * Write lines to a file.
-        * 
-        * @param contents the lines to be written in a {@code List<String>}
-        * @param charset the file charset
-        * @param fileName the file name. Absolute or abstract pathname, it is your choice
-        * @throws IOException
-        *                 If an I/O error occurs while writing or trying to open the file
-        */
-       public static void writeFile (final List<String> contents, final String fileName, final String charset) throws IOException
-       {
-               final OutputStream outputStream = new FileOutputStream(fileName);
-               final PrintStream output = new PrintStream(outputStream, true, charset);
-               
-               try {
-                       for (String line : contents )
-                       {
-                               output.println(line);
-                       }
-               }
-               finally {
-                    output.close();
-               }
-       }
-       
-       /**
-        * Replace every line (file lines stored in a {@code List<String>})  
-        * with the lineReplacement if the line contains the pattern
-        * 
-        * @param contents the lines to be searched in a {@code List<String>}
-        * @param pattern the pattern to match in a line
-        * @param lineReplacement the whole line to replace in case of some match
-        * @return <b>true</b> if there is a match, otherwise <b>false</b>
-        */
-       public static boolean replaceLine (final List<String> contents, final String pattern, final String lineReplacement)
-       {
-               final ListIterator<String> itr = contents.listIterator();
-               boolean change = false;
-               
-               while (itr.hasNext())
-               {
-                       if (itr.next().trim().contains(pattern)) {
-                   itr.set(lineReplacement);
-                   change = true;
-                       }
-               }
-               
-               return change;
-       }
-       
-       /**
-        * Method intended to be used by the Logical layer. Search the template files
-        * of the form printer, replace the lines in case of match and write on the hard disk the 
-        * new files.
-        * 
-        * @param pattern the pattern to match
-        * @param lineReplacement the whole line to replace in case of some match
-        * @throws IOException
-        *                 If an I/O error occurs while writing or trying to open a file
-        */
-       public static void searchandReplace (final String pattern, final String lineReplacement) throws IOException
-       {
-               final List<File> fileList = PrinterHelper.findFilebyExtension(TEMPLATE_FILE_EXTENSION);
-               for (File file : fileList)
-               {
-                       final List<String> contents = PrinterHelper.readFile(file, FormConfiguration.getCharset());
-                       if (PrinterHelper.replaceLine(contents, pattern, lineReplacement))
-                       {
-                               PrinterHelper.writeFile(contents, file.getAbsolutePath(), FormConfiguration.getCharset());
-                       }
-               }
-       }
-       
-       /**
-        *  Method intended to be used by the Logical layer. It is smart enough to find out
-        *  it there is a new form printer model
-        * 
-        * @param oldModel The previous form printer model
-        * @param newModel The new form printer model
-        * @throws IOException
-        *                 If an I/O error occurs while writing or trying to open a file
-        */
-       public static void changedPrinter (final HardwareModel oldModel, final HardwareModel newModel) throws IOException
-       {
-               if(FormPrinterModel.EPSON_TM_88_V.getXmlDescriptor().equals(newModel.getXmlDescriptor()))
-               {
-                       PrinterHelper.searchandReplace("methodToPrintImage(ESC/POS)", "         COMMENT      \"usePageMode(false)\"");
-                       PrinterHelper.removeFormPrinterProperty(PRINTER_PROPERTY);
-               }
-               else if (FormPrinterModel.EPSON_TM_88_V.getXmlDescriptor().equals(oldModel.getXmlDescriptor()))
-               {       
-                       PrinterHelper.searchandReplace("usePageMode(false)", "         COMMENT      \"usePageMode(false) methodToPrintImage(ESC/POS)\"");
-                       PrinterHelper.addFormPrinterProperty(PRINTER_PROPERTY, PRINTER_PROPERTY_VALUE);
-               }
-       }
-}
\ No newline at end of file
index 14973c0..2fe6ac6 100644 (file)
@@ -6,6 +6,7 @@
 
     <uses-sdk android:minSdkVersion="14" />
     <uses-permission android:name="android.permission.INTERNET"/>
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 
     <application
         android:icon="@drawable/ic_launcher"
index 55e32e0..5eac31e 100644 (file)
@@ -4,7 +4,7 @@
         Do you really want to close the application?
     </string>
     <string name="error_dialog_connection_error">
-        Connection error. Check your network interface.
+        Connection error with MobAd server.
     </string>
     <string name="error_dialog_userpwd_error">
         The username or password you entered is incorrect.
diff --git a/Android/Testing/Test2/src/de/android/test2/MobieAdHttpClient.java b/Android/Testing/Test2/src/de/android/test2/MobieAdHttpClient.java
new file mode 100644 (file)
index 0000000..1aa0c98
--- /dev/null
@@ -0,0 +1,76 @@
+package de.android.test2;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.HttpGet;
+import android.net.http.AndroidHttpClient;
+import android.os.AsyncTask;
+import android.util.Log;
+
+public class MobieAdHttpClient extends AsyncTask<URL, Integer, HttpResponse> {
+       private static final String TAG = "MobieAdHttpClient";
+       private AndroidHttpClient httpClient;
+       private final String cookie;
+
+       public MobieAdHttpClient(final String cookie)
+       {
+               this.cookie = cookie;
+       }
+       
+       @Override
+       protected HttpResponse doInBackground(final URL... urls) {
+               final String USERAGENT ="MobieAds/1.0";
+               final HttpGet httpGet = new HttpGet();
+               HttpResponse httpResponse = null;
+
+               httpGet.setHeader("Cookie", this.cookie);
+               for(URL url : urls)
+        {    
+                       try {
+                               httpGet.setURI(url.toURI());
+                       } catch (URISyntaxException e) {
+                               Log.e(TAG, "Error while creating URI from URL.");
+                       }
+               this.httpClient = AndroidHttpClient.newInstance(USERAGENT);
+               try {
+                       httpResponse = httpClient.execute(httpGet);
+               } catch (ClientProtocolException e1) {
+                       Log.e(TAG, "Error while executing HTTP client connection.");
+               } catch (IOException e1) {
+                       Log.e(TAG, "Error while executing HTTP client connection.");
+               }
+         }
+               
+               return httpResponse;
+       }
+
+       
+       @Override
+       protected void onPostExecute(final HttpResponse result)
+       {
+               this.httpClient.close();
+               //It should not be null anyway this check is not harmful
+               if (result != null)
+               {
+                       switch (result.getStatusLine().getStatusCode()) {
+                               case HttpStatus.SC_OK:
+                                       //OK
+
+                                       break;
+                               case HttpStatus.SC_UNAUTHORIZED:
+                                       //ERROR IN USERNAME OR PASSWORD
+                                       break;
+                               case HttpStatus.SC_BAD_REQUEST:
+                                       //WHAT THE HECK ARE YOU DOING?
+                                       break;
+                               default:
+                                       Log.e(TAG, "Error while retrieving the HTTP status line.");
+                                       break;
+                       }
+               }       
+       }
+}
index 140d54c..1546a22 100644 (file)
 package de.android.test2;
 
+import java.net.MalformedURLException;
+import java.net.URL;
 import android.app.Activity;
+import android.content.Context;
+import android.location.Criteria;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
 import android.os.Bundle;
 import android.webkit.CookieManager;
 import android.webkit.CookieSyncManager;
 
 public class NextActivity extends Activity {
+       private Location currentLocation;
+       private static final int TWO_MINUTES = 1000 * 60 * 2;
+       private String myCookie;
+       
         /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         CookieSyncManager.createInstance(this);
-        String myCookie = CookieManager.getInstance().getCookie("192.168.1.34/userfront.php");
+        myCookie = CookieManager.getInstance().getCookie("192.168.1.34/userfront.php");
         setContentView(R.layout.main2);
+        
+        Criteria criteria = new Criteria();
+        criteria.setAccuracy(Criteria.ACCURACY_FINE);
+        criteria.setAltitudeRequired(false);
+        criteria.setBearingAccuracy(Criteria.NO_REQUIREMENT);
+        criteria.setBearingRequired(false);
+        criteria.setCostAllowed(false);
+        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
+        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
+        criteria.setSpeedAccuracy(Criteria.ACCURACY_LOW);
+        criteria.setSpeedRequired(true);
+        criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
+        
+        
+     // Acquire a reference to the system Location Manager
+        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
+
+        // Define a listener that responds to location updates
+        LocationListener locationListener = new LocationListener() {
+            public void onLocationChanged(Location location) {
+              // Called when a new location is found by the network location provider.
+              makeUseOfNewLocation(location);
+            }
+
+            public void onStatusChanged(String provider, int status, Bundle extras) {
+               //1. Fin out the provider state. (see Copilot.java code GPSLocationListener)
+               //2. If it is TEMPORARILY_UNAVAILABLE:
+               //2.1. locationManager.removeUpdates(locationListener); <--- Stop wasting GPS or GSM connections
+               //2.2. Launch Timer with TimerTask 30 or 60 seconds before to enable the locationManager to find out if the provider status changed.
+               //3. If OUT_OF_SERVICE
+               //3.1. locationManager.removeUpdates(locationListener); <--- Stop wasting GPS or GSM connections
+               //3.2. Launch Timer with TimerTask 30 or 60 seconds before to enable the locationManager to find out if the provider status changed.
+               //4. If AVAILABLE 
+               //   Nothing to do here.
+               //Just when we are in the second or third point we have to stop draining battery because it is useless.
+               
+            }
+
+            public void onProviderEnabled(String provider) {}
+
+            public void onProviderDisabled(String provider) {}
+          };
+
+        // Register the listener with the Location Manager to receive location updates
+        locationManager.requestLocationUpdates(0, 10, criteria, locationListener, null);
+    }
+    
+    public void makeUseOfNewLocation(Location location) {
+       //if (isBetterLocation(location, currentLocation)) {
+               currentLocation = location;
+       //}
+       
+       String latitude = Double.toString(currentLocation.getLatitude());
+       String longitude = Double.toString(currentLocation.getLongitude());
+       String latitudeReplace = latitude.replace(".", ",");
+       String longitudeReplace = longitude.replace(".", ",");
+       final String URLAuth = "http://192.168.1.34/userfront.php/api/" + latitudeReplace + "/" + longitudeReplace + "/gpsads.json";
+       URL url = null;
+       
+               try {
+                       //RESTful WebService
+                       url = new URL(URLAuth);
+               } catch (MalformedURLException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+               new MobieAdHttpClient(this.myCookie).execute(url);      
     }
+    
+    
+    /** Determines whether one Location reading is better than the current Location fix
+     * @param location  The new Location that you want to evaluate
+     * @param currentBestLocation  The current Location fix, to which you want to compare the new one
+     */
+    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
+       if (currentBestLocation == null) {
+           // A new location is always better than no location
+           return true;
+       }
+
+       // Check whether the new location fix is newer or older
+       long timeDelta = location.getTime() - currentBestLocation.getTime();
+       boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
+       boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
+       boolean isNewer = timeDelta > 0;
+
+       // If it's been more than two minutes since the current location, use the new location
+       // because the user has likely moved
+       if (isSignificantlyNewer) {
+           return true;
+       // If the new location is more than two minutes older, it must be worse
+       } else if (isSignificantlyOlder) {
+           return false;
+       }
+
+       // Check whether the new location fix is more or less accurate
+       int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
+       boolean isLessAccurate = accuracyDelta > 0;
+       boolean isMoreAccurate = accuracyDelta < 0;
+       boolean isSignificantlyLessAccurate = accuracyDelta > 200;
+
+       // Check if the old and new location are from the same provider
+       boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
+
+       // Determine location quality using a combination of timeliness and accuracy
+       if (isMoreAccurate) {
+           return true;
+       } else if (isNewer && !isLessAccurate) {
+           return true;
+       } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
+           return true;
+       }
+       return false;
+   }
+
+   /** Checks whether two providers are the same */
+   private boolean isSameProvider(String provider1, String provider2) {
+       if (provider1 == null) {
+         return provider2 == null;
+       }
+       return provider1.equals(provider2);
+   }
 }
index 3aa4d9f..8171039 100644 (file)
@@ -59,6 +59,7 @@ public class Test2Activity extends Activity {
                        httpEntity = new UrlEncodedFormEntity(nameValuePairs);
                } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, "Error while encoding POST parameters.", e);
+                       return;
                }
         httpPost.setEntity(httpEntity);
         httpPost.setHeader("User-Agent", "MobieAds/1.0");
@@ -68,34 +69,34 @@ public class Test2Activity extends Activity {
                } catch (ClientProtocolException e) {
                        Log.e(TAG, "Error while executing HTTP client connection.", e);
                        createErrorDialog(R.string.error_dialog_connection_error);
+                       return;
                } catch (IOException e) {
                        Log.e(TAG, "Error while executing HTTP client connection.", e);
                        createErrorDialog(R.string.error_dialog_connection_error);
+                       return;
                }
         
-        if (httpResponse != null)
-               {
-                       switch (httpResponse.getStatusLine().getStatusCode()) {
-                               case HttpStatus.SC_OK:
-                                       String cookie = httpResponse.getLastHeader("Set-Cookie").getValue();
-                                       CookieManager.getInstance().setCookie("192.168.1.34/userfront.php",cookie);
-                                       CookieSyncManager.getInstance().sync();
-                                       //Go to the main activity
-                               this.startActivity(new Intent(Intent.ACTION_RUN));
-                                       break;
-                               case HttpStatus.SC_UNAUTHORIZED:
-                                   //Username or password are incorrect
-                                       createErrorDialog(R.string.error_dialog_userpwd_error);
-                                       break;
-                               case HttpStatus.SC_BAD_REQUEST:
-                                       //What the heck are you doing?
-                                       createErrorDialog(R.string.error_dialog_userpwd_error);
-                                       break;
-                               default:
-                                       Log.e(TAG, "Error while retrieving the HTTP status line.");
-                                       createErrorDialog(R.string.error_dialog_userpwd_error);
-                                       break;
-                       }
+        switch (httpResponse.getStatusLine().getStatusCode()) {
+               case HttpStatus.SC_OK:
+                       String cookie = httpResponse.getLastHeader("Set-Cookie").getValue();
+                               CookieManager.getInstance().setCookie("192.168.1.34/userfront.php",cookie);
+                               CookieSyncManager.getInstance().sync();
+                               //Go to the main activity
+                               StrictMode.setThreadPolicy(currentPolicy);
+                           this.startActivity(new Intent(Intent.ACTION_RUN));
+                               break;
+                       case HttpStatus.SC_UNAUTHORIZED:
+                               //Username or password are incorrect
+                               createErrorDialog(R.string.error_dialog_userpwd_error);
+                               break;
+                       case HttpStatus.SC_BAD_REQUEST:
+                               //What the heck are you doing?
+                               createErrorDialog(R.string.error_dialog_userpwd_error);
+                               break;
+                       default:
+                               Log.e(TAG, "Error while retrieving the HTTP status line.");
+                               createErrorDialog(R.string.error_dialog_userpwd_error);
+                               break;
                }     
     }
     
diff --git a/Android/Testing/Test2/src/de/android/test2/TestService.java b/Android/Testing/Test2/src/de/android/test2/TestService.java
new file mode 100644 (file)
index 0000000..c4c94b5
--- /dev/null
@@ -0,0 +1,25 @@
+/**
+ * 
+ */
+package de.android.test2;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+
+/**
+ * @author gusarapo
+ *
+ */
+public class TestService extends Service {
+
+       /* (non-Javadoc)
+        * @see android.app.Service#onBind(android.content.Intent)
+        */
+       @Override
+       public IBinder onBind(Intent intent) {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+}