Example usage for java.lang NumberFormatException printStackTrace

List of usage examples for java.lang NumberFormatException printStackTrace

Introduction

In this page you can find the example usage for java.lang NumberFormatException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.maxl.java.aips2sqlite.RealExpertInfo.java

/**
 * Extracts package info from Swissmedic package Excel file
 *///from w  w w .j a v  a2  s. c om
private void extractPackageInfo() {
    try {
        long startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.print("- Processing packages xlsx... ");
        // Load Swissmedic xls file         
        FileInputStream packages_file = new FileInputStream(Constants.FILE_PACKAGES_XLSX);
        // Get workbook instance for XLSX file (XSSF = Horrible SpreadSheet Format)
        XSSFWorkbook packages_workbook = new XSSFWorkbook(packages_file);
        // Get first sheet from workbook
        XSSFSheet packages_sheet = packages_workbook.getSheetAt(0);

        /*
        if (SHOW_LOGS)
           System.out.print("- Processing packages xls... ");
        // Load Swissmedic xls file         
        FileInputStream packages_file = new FileInputStream(FILE_PACKAGES_XLS);
        // Get workbook instance for XLS file (HSSF = Horrible SpreadSheet Format)
        HSSFWorkbook packages_workbook = new HSSFWorkbook(packages_file);
        // Get first sheet from workbook
        HSSFSheet packages_sheet = packages_workbook.getSheetAt(0);
        */
        // Iterate through all rows of first sheet
        Iterator<Row> rowIterator = packages_sheet.iterator();

        int num_rows = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (num_rows > 5) {
                String swissmedic_no5 = ""; // SwissmedicNo5 registration number (5 digits)
                String sequence_name = "";
                String package_id = "";
                String swissmedic_no8 = ""; // SwissmedicNo8 = SwissmedicNo5 + Package id (8 digits)
                String heilmittel_code = "";
                String package_size = "";
                String package_unit = "";
                String swissmedic_cat = "";
                String application_area = "";
                String public_price = "";
                String exfactory_price = "";
                String therapeutic_index = "";
                String withdrawn_str = "";
                String speciality_str = "";
                String plimitation_str = "";
                String add_info_str = ""; // Contains additional information separated by ;
                String ean_code_str = "";
                String pharma_code_str = "";

                // 0: Zulassungsnummer, 1: Dosisstrkenummer, 2: Prparatebezeichnung, 3: Zulassunginhaberin, 4: Heilmittelcode, 5: IT-Nummer, 6: ATC-Code
                // 7: Erstzulassung Prparat, 8: Zulassungsdatum Sequenz, 9: Gltigkeitsdatum, 10: Packungscode, 11: Packungsgrsse
                // 12: Einheit, 13: Abgabekategorie Packung, 14: Abgabekategorie Dosisstrke, 15: Abgabekategorie Prparat, 
                // 16: Wirkstoff, 17: Zusammensetzung, 18: Anwendungsgebiet Prparat, 19: Anwendungsgebiet Dosisstrke, 20: Gentechnisch hergestellte Wirkstoffe
                // 21: Kategorie bei Insulinen, 22: Betubungsmittelhaltigen Prparaten

                // @cybermax: 15.10.2013 - work around for Excel cells of type "Special" (cell0 and cell10)
                if (row.getCell(0) != null)
                    swissmedic_no5 = String.format("%05d", (int) (row.getCell(0).getNumericCellValue())); // Swissmedic registration number (5 digits)
                if (row.getCell(2) != null)
                    sequence_name = ExcelOps.getCellValue(row.getCell(2)); // Sequence name
                if (row.getCell(4) != null)
                    heilmittel_code = ExcelOps.getCellValue(row.getCell(4)); // Heilmittelcode               
                if (row.getCell(11) != null)
                    package_size = ExcelOps.getCellValue(row.getCell(11)); // Packungsgrsse
                if (row.getCell(12) != null)
                    package_unit = ExcelOps.getCellValue(row.getCell(12)); // Einheit
                if (row.getCell(13) != null)
                    swissmedic_cat = ExcelOps.getCellValue(row.getCell(13)); // Abgabekategorie Packung   
                if (row.getCell(18) != null)
                    application_area = ExcelOps.getCellValue(row.getCell(18)); // Anwendungsgebiet Prparat            
                if (row.getCell(10) != null) {
                    package_id = String.format("%03d", (int) (row.getCell(10).getNumericCellValue())); // Verpackungs ID
                    swissmedic_no8 = swissmedic_no5 + package_id;
                    // Fill in row
                    ArrayList<String> pack = new ArrayList<String>();
                    pack.add(swissmedic_no5); // 0
                    pack.add(sequence_name); // 1
                    pack.add(heilmittel_code); // 2
                    pack.add(package_size); // 3
                    pack.add(package_unit); // 4
                    pack.add(swissmedic_cat); // 5
                    if (!application_area.isEmpty())
                        pack.add(application_area + " (Swissmedic);"); // 6 = swissmedic + bag
                    else
                        pack.add("");
                    pack.add(public_price); // 7
                    pack.add(exfactory_price); // 8
                    pack.add(therapeutic_index);// 9
                    // By default the meds are "ausser Handel"
                    if (CmlOptions.DB_LANGUAGE.equals("de"))
                        withdrawn_str = "a.H."; // ausser Handel
                    else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                        withdrawn_str = "p.c."; // 
                    pack.add(withdrawn_str); // 10
                    pack.add(speciality_str); // 11
                    pack.add(plimitation_str); // 12
                    pack.add(add_info_str); // 13
                    // 22.03.2014: EAN-13 barcodes - initialization - check digit is missing!
                    ean_code_str = "7680" + swissmedic_no8;
                    pack.add(ean_code_str); // 14
                    pack.add(pharma_code_str); // 15

                    m_package_info.put(swissmedic_no8, pack);
                }
            }
            num_rows++;
        }
        long stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS) {
            System.out.println(
                    (m_package_info.size() + 1) + " packages in " + (stopTime - startTime) / 1000.0f + " sec");
        }
        startTime = System.currentTimeMillis();

        if (CmlOptions.SHOW_LOGS)
            System.out.print("- Processing atc classes xls... ");
        if (CmlOptions.DB_LANGUAGE.equals("de")) {
            /*
            // Load ATC classes xls file
            FileInputStream atc_classes_file = new FileInputStream(Constants.FILE_ATC_CLASSES_XLS);
            // Get workbook instance for XLS file (HSSF = Horrible SpreadSheet Format)
            HSSFWorkbook atc_classes_workbook = new HSSFWorkbook(atc_classes_file);
            // Get first sheet from workbook
            // HSSFSheet atc_classes_sheet = atc_classes_workbook.getSheetAt(1);   // --> 2013 file
            HSSFSheet atc_classes_sheet = atc_classes_workbook.getSheetAt(0);      // --> 2014 file         
            // Iterate through all rows of first sheet
            rowIterator = atc_classes_sheet.iterator();
                    
            num_rows = 0;
            while (rowIterator.hasNext()) {
               Row row = rowIterator.next();
               if (num_rows>2) {
                  String atc_code = "";
                  String atc_class = "";
                  if (row.getCell(0)!=null) {
             atc_code = row.getCell(0).getStringCellValue().replaceAll("\\s", "");
                  }
                  if (row.getCell(2)!=null) {
             atc_class = row.getCell(2).getStringCellValue();
                  }
                  // Build a full map atc code to atc class
                  if (atc_code.length()>0) {
             m_atc_map.put(atc_code, atc_class);
                  }
               }
               num_rows++;
            }
            */
            CSVReader reader = new CSVReader(
                    new InputStreamReader(new FileInputStream(Constants.FILE_EPHA_ATC_CODES_CSV), "UTF-8"));
            List<String[]> myEntries = reader.readAll();
            num_rows = myEntries.size();
            for (String[] s : myEntries) {
                if (s.length > 2) {
                    String atc_code = s[0];
                    String atc_class = s[1];
                    m_atc_map.put(atc_code, atc_class);
                }
            }
            reader.close();
        } else if (CmlOptions.DB_LANGUAGE.equals("fr")) {
            // Load ATC classes xls file
            FileInputStream atc_classes_file = new FileInputStream(Constants.FILE_WHO_ATC_CLASSES_XLS);
            // Get workbook instance for XLS file (HSSF = Horrible SpreadSheet Format)
            HSSFWorkbook atc_classes_workbook = new HSSFWorkbook(atc_classes_file);
            // Get first sheet from workbook
            HSSFSheet atc_classes_sheet = atc_classes_workbook.getSheetAt(0); // --> 2014 file         
            // Iterate through all rows of first sheet
            rowIterator = atc_classes_sheet.iterator();

            num_rows = 0;
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (num_rows > 0) {
                    String atc_code = "";
                    String atc_class = "";
                    if (row.getCell(1) != null) {
                        atc_code = row.getCell(1).getStringCellValue();
                        if (atc_code.length() > 0) {
                            // Extract L5 and below
                            if (atc_code.length() < 6 && row.getCell(2) != null) {
                                atc_class = row.getCell(2).getStringCellValue();
                                // Build a full map atc code to atc class
                                m_atc_map.put(atc_code, atc_class);
                                // Extract L7
                            } else if (atc_code.length() == 7 && row.getCell(4) != null) {
                                atc_class = row.getCell(4).getStringCellValue();
                                m_atc_map.put(atc_code, atc_class);
                            }
                        }
                    }
                }
                num_rows++;
            }

            // Load multilingual ATC classes txt file, replace English with French
            String atc_classes_multi = FileOps.readFromFile(Constants.FILE_ATC_MULTI_LINGUAL_TXT);
            // Loop through all lines
            Scanner scanner = new Scanner(atc_classes_multi);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                List<String> atc_class = Arrays.asList(line.split(": "));
                String atc_code = atc_class.get(0);
                String[] atc_classes_str = atc_class.get(1).split(";");
                String atc_class_french = atc_classes_str[1].trim();
                // Replaces atc code...
                m_atc_map.put(atc_code, atc_class_french);
            }
            scanner.close();
        }
        stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(
                    (m_atc_map.size() + 1) + " classes in " + (stopTime - startTime) / 1000.0f + " sec");

        // Load Refdata xml file
        File refdata_xml_file = new File(Constants.FILE_REFDATA_PHARMA_XML);
        FileInputStream refdata_fis = new FileInputStream(refdata_xml_file);

        startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println("- Unmarshalling Refdatabase for " + CmlOptions.DB_LANGUAGE + "... ");

        JAXBContext context = JAXBContext.newInstance(Refdata.class);
        Unmarshaller um = context.createUnmarshaller();
        Refdata refdataPharma = (Refdata) um.unmarshal(refdata_fis);
        List<Refdata.ITEM> pharma_list = refdataPharma.getItem();

        String smno8;
        for (Refdata.ITEM pharma : pharma_list) {
            String ean_code = pharma.getGtin();
            String pharma_code = pharma.getPhar();
            if (ean_code.length() == 13) {
                smno8 = ean_code.substring(4, 12);
                // Extract pharma corresponding to swissmedicno8 (source: swissmedic package file)
                ArrayList<String> pi_row = m_package_info.get(smno8);
                // Replace sequence_name
                if (pi_row != null) {
                    // Prparatname + galenische Form
                    if (CmlOptions.DB_LANGUAGE.equals("de"))
                        pi_row.set(1, pharma.getNameDE());
                    else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                        pi_row.set(1, pharma.getNameFR());
                    // If med is in refdata file, then it is "in Handel!!" ;)
                    pi_row.set(10, ""); // By default this is set to a.H. or p.C.
                    // 22.03.2014: EAN-13 barcodes - replace with refdata if package exists
                    pi_row.set(14, ean_code);
                    // Pharma code
                    pi_row.set(15, pharma_code);
                } else {
                    if (CmlOptions.SHOW_ERRORS) {
                        if (pharma.getATYPE().equals("PHARMA"))
                            System.err.println(
                                    ">> Does not exist in BAG xls: " + smno8 + " (" + pharma.getNameDE() + ")");
                    }
                }
            } else if (ean_code.length() < 13) {
                if (CmlOptions.SHOW_ERRORS)
                    System.err.println(">> EAN code too short: " + ean_code + ": " + pharma.getNameDE());
            } else if (ean_code.length() > 13) {
                if (CmlOptions.SHOW_ERRORS)
                    System.err.println(">> EAN code too long: " + ean_code + ": " + pharma.getNameDE());
            }
        }

        stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(pharma_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec");

        // Load BAG xml file
        File bag_xml_file = new File(Constants.FILE_PREPARATIONS_XML);
        FileInputStream fis_bag = new FileInputStream(bag_xml_file);

        startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println("- Processing preparations xml... ");

        context = JAXBContext.newInstance(Preparations.class);
        um = context.createUnmarshaller();
        Preparations prepInfos = (Preparations) um.unmarshal(fis_bag);
        List<Preparations.Preparation> prep_list = prepInfos.getPreparations();

        int num_preparations = 0;
        for (Preparations.Preparation prep : prep_list) {
            String swissmedicno5_str = prep.getSwissmedicNo5();
            if (swissmedicno5_str != null) {
                String orggencode_str = ""; // "O", "G" or empty -> ""
                String flagSB20_str = ""; // "Y" -> 20% or "N" -> 10%
                if (prep.getOrgGenCode() != null)
                    orggencode_str = prep.getOrgGenCode();
                if (prep.getFlagSB20() != null) {
                    flagSB20_str = prep.getFlagSB20();
                    if (flagSB20_str.equals("Y")) {
                        if (CmlOptions.DB_LANGUAGE.equals("de"))
                            flagSB20_str = "SB 20%";
                        else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                            flagSB20_str = "QP 20%";
                    } else if (flagSB20_str.equals("N")) {
                        if (CmlOptions.DB_LANGUAGE.equals("de"))
                            flagSB20_str = "SB 10%";
                        else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                            flagSB20_str = "QP 10%";
                    } else
                        flagSB20_str = "";
                }
                m_add_info_map.put(swissmedicno5_str, orggencode_str + ";" + flagSB20_str);
            }

            List<Preparation.Packs> packs_list = prep.getPacks();
            for (Preparation.Packs packs : packs_list) {
                // Extract codes for therapeutic index / classification
                String bag_application = "";
                String therapeutic_code = "";
                List<Preparations.Preparation.ItCodes> itcode_list = prep.getItCodes();
                for (Preparations.Preparation.ItCodes itc : itcode_list) {
                    List<Preparations.Preparation.ItCodes.ItCode> code_list = itc.getItCode();
                    int index = 0;
                    for (Preparations.Preparation.ItCodes.ItCode code : code_list) {
                        if (index == 0) {
                            if (CmlOptions.DB_LANGUAGE.equals("de"))
                                therapeutic_code = code.getDescriptionDe();
                            else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                                therapeutic_code = code.getDescriptionFr();
                        } else {
                            if (CmlOptions.DB_LANGUAGE.equals("de"))
                                bag_application = code.getDescriptionDe();
                            else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                                bag_application = code.getDescriptionFr();
                        }
                        index++;
                    }
                }
                // Generate new package info
                List<Preparation.Packs.Pack> pack_list = packs.getPack();
                for (Preparation.Packs.Pack pack : pack_list) {
                    // Get SwissmedicNo8 and used it as a key to extract all the relevant package info
                    String swissMedicNo8 = pack.getSwissmedicNo8();
                    ArrayList<String> pi_row = null;
                    if (swissMedicNo8 != null)
                        pi_row = m_package_info.get(swissMedicNo8);
                    // Preparation also in BAG xml file (we have a price)
                    if (pi_row != null) {
                        // Update Swissmedic catory if necessary ("N->A", Y->"A+")
                        if (pack.getFlagNarcosis().equals("Y"))
                            pi_row.set(5, pi_row.get(5) + "+");
                        // Extract point limitations
                        List<Preparations.Preparation.Packs.Pack.PointLimitations> point_limits = pack
                                .getPointLimitations();
                        for (Preparations.Preparation.Packs.Pack.PointLimitations limits : point_limits) {
                            List<Preparations.Preparation.Packs.Pack.PointLimitations.PointLimitation> plimits_list = limits
                                    .getPointLimitation();
                            if (plimits_list.size() > 0)
                                if (plimits_list.get(0) != null)
                                    pi_row.set(12, ", LIM" + plimits_list.get(0).getPoints() + "");
                        }
                        // Extract exfactory and public prices
                        List<Preparations.Preparation.Packs.Pack.Prices> price_list = pack.getPrices();
                        for (Preparations.Preparation.Packs.Pack.Prices price : price_list) {
                            List<Preparations.Preparation.Packs.Pack.Prices.PublicPrice> public_price = price
                                    .getPublicPrice();
                            List<Preparations.Preparation.Packs.Pack.Prices.ExFactoryPrice> exfactory_price = price
                                    .getExFactoryPrice();
                            if (exfactory_price.size() > 0) {
                                try {
                                    float f = Float.valueOf(exfactory_price.get(0).getPrice());
                                    String ep = String.format("%.2f", f);
                                    pi_row.set(8, "CHF " + ep);
                                } catch (NumberFormatException e) {
                                    if (CmlOptions.SHOW_ERRORS)
                                        System.err.println("Number format exception (exfactory price): "
                                                + swissMedicNo8 + " (" + public_price.size() + ")");
                                }
                            }
                            if (public_price.size() > 0) {
                                try {
                                    float f = Float.valueOf(public_price.get(0).getPrice());
                                    String pp = String.format("%.2f", f);
                                    pi_row.set(7, "CHF " + pp);
                                    if (CmlOptions.DB_LANGUAGE.equals("de"))
                                        pi_row.set(11, ", SL");
                                    else if (CmlOptions.DB_LANGUAGE.equals("fr"))
                                        pi_row.set(11, ", LS");
                                } catch (NullPointerException e) {
                                    if (CmlOptions.SHOW_ERRORS)
                                        System.err.println("Null pointer exception (public price): "
                                                + swissMedicNo8 + " (" + public_price.size() + ")");
                                } catch (NumberFormatException e) {
                                    if (CmlOptions.SHOW_ERRORS)
                                        System.err.println("Number format exception (public price): "
                                                + swissMedicNo8 + " (" + public_price.size() + ")");
                                }
                            }
                            // Add application area and therapeutic code
                            if (!bag_application.isEmpty())
                                pi_row.set(6, pi_row.get(6) + bag_application + " (BAG)");
                            pi_row.set(9, therapeutic_code);
                        }
                    }
                }
            }
            num_preparations++;
        }

        stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(
                    num_preparations + " preparations in " + (stopTime - startTime) / 1000.0f + " sec");

        // Loop through all SwissmedicNo8 numbers
        /*
        for (Map.Entry<String, ArrayList<String>> entry : package_info.entrySet()) {
           String swissmedicno8 = entry.getKey();
           ArrayList<String> pi_row = entry.getValue();
        }
        */

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

From source file:com.irccloud.android.NetworkConnection.java

public Bitmap fetchImage(URL url, boolean cacheOnly) throws Exception {
    HttpURLConnection conn = null;

    Proxy proxy = null;/*  w  ww .  j ava 2 s .  co m*/
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
        if (url.getHost().equals(IRCCLOUD_HOST))
            https.setSSLSocketFactory(IRCCloudSocketFactory);
        conn = https;
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);
    conn.setRequestProperty("User-Agent", useragent);
    if (cacheOnly)
        conn.addRequestProperty("Cache-Control", "only-if-cached");
    Bitmap bitmap = null;

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi");
        } else {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (conn.getInputStream() != null) {
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        }
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();
    return bitmap;
}

From source file:com.irccloud.android.NetworkConnection.java

public String fetch(URL url, String postdata, String sk, String token, HashMap<String, String> headers)
        throws Exception {
    HttpURLConnection conn = null;

    Proxy proxy = null;/*from  ww  w .ja  v a 2s  .c o  m*/
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
        if (url.getHost().equals(IRCCLOUD_HOST))
            https.setSSLSocketFactory(IRCCloudSocketFactory);
        conn = https;
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setUseCaches(false);
    conn.setRequestProperty("User-Agent", useragent);
    conn.setRequestProperty("Accept", "application/json");
    if (headers != null) {
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key, headers.get(key));
        }
    }
    if (sk != null)
        conn.setRequestProperty("Cookie", "session=" + sk);
    if (token != null)
        conn.setRequestProperty("x-auth-formtoken", token);
    if (postdata != null) {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        OutputStream ostr = null;
        try {
            ostr = conn.getOutputStream();
            ostr.write(postdata.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ostr != null)
                ostr.close();
        }
    }
    BufferedReader reader = null;
    String response = "";

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi");
        } else {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile");
        }
    } catch (Exception e) {
    }

    try {
        if (conn.getInputStream() != null) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
        }
    } catch (IOException e) {
        if (conn.getErrorStream() != null) {
            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
        }
    }

    if (reader != null) {
        response = toString(reader);
        reader.close();
    }
    conn.disconnect();
    return response;
}

From source file:com.lgallardo.youtorrentcontroller.RefreshListener.java

protected void getSettings() {
    // Preferences stuff
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

    builderPrefs = new StringBuilder();

    builderPrefs.append("\n" + sharedPrefs.getString("language", "NULL"));

    // Get values from preferences
    currentServer = sharedPrefs.getString("currentServer", "1");
    hostname = sharedPrefs.getString("hostname", "");
    subfolder = sharedPrefs.getString("subfolder", "");

    protocol = sharedPrefs.getString("protocol", "NULL");

    // If user leave the field empty, set 8080 port
    try {//from   www  .  j av  a2  s  . c o  m
        port = Integer.parseInt(sharedPrefs.getString("port", "8080"));
    } catch (NumberFormatException e) {
        port = 8080;

    }
    username = sharedPrefs.getString("username", "NULL");
    password = sharedPrefs.getString("password", "NULL");
    https = sharedPrefs.getBoolean("https", false);

    // Check https
    if (https) {
        protocol = "https";
    } else {
        protocol = "http";
    }

    // Get refresh info
    auto_refresh = sharedPrefs.getBoolean("auto_refresh", true);

    try {
        refresh_period = Integer.parseInt(sharedPrefs.getString("refresh_period", "120000"));
    } catch (NumberFormatException e) {
        refresh_period = 120000;
    }

    // Get connection and data timeouts
    try {
        connection_timeout = Integer.parseInt(sharedPrefs.getString("connection_timeout", "10"));

        // New default value to make it work with qBittorrent 3.2.x
        if (connection_timeout < 10) {
            connection_timeout = 10;
        }
    } catch (NumberFormatException e) {
        connection_timeout = 10;
    }

    try {
        data_timeout = Integer.parseInt(sharedPrefs.getString("data_timeout", "20"));

        // New default value to make it work with qBittorrent 3.2.x
        if (data_timeout < 20) {
            data_timeout = 20;
        }

    } catch (NumberFormatException e) {
        data_timeout = 20;
    }

    sortby = sharedPrefs.getString("sortby", "NULL");
    reverse_order = sharedPrefs.getBoolean("reverse_order", false);

    dark_ui = sharedPrefs.getBoolean("dark_ui", false);

    MainActivity.token = sharedPrefs.getString("token", null);
    MainActivity.cookie = sharedPrefs.getString("cookie", null);

    // Get last state
    lastState = sharedPrefs.getString("lastState", "all");

    // Notification check
    try {
        notification_period = Long.parseLong(sharedPrefs.getString("notification_period", "120000L"));
    } catch (NumberFormatException e) {
        notification_period = 120000L;
    }

    header = sharedPrefs.getBoolean("header", true);

    // Get packge info
    PackageInfo pInfo = null;
    try {
        pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    // Get package name
    packageName = pInfo.packageName;

}

From source file:org.ecocean.servlet.EncounterForm.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    HashMap fv = new HashMap();

    //IMPORTANT - processingNotes can be used to add notes on data handling (e.g., poorly formatted dates) that can be reconciled later by the reviewer
    //Example usage: processingNotes.append("<p>Error encountered processing this date submitted by user: "+getVal(fv, "datepicker")+"</p>");
    StringBuffer processingNotes = new StringBuffer();

    HttpSession session = request.getSession(true);
    String context = "context0";
    context = ServletUtilities.getContext(request);
    Shepherd myShepherd = new Shepherd(context);
    myShepherd.setAction("EncounterForm.class");
    System.out.println("in context " + context);
    //request.getSession()getServlet().getServletContext().getRealPath("/"));
    String rootDir = getServletContext().getRealPath("/");
    System.out.println("rootDir=" + rootDir);

    /*/*w  w w .  j av  a 2  s . co  m*/
        Vector<String> fbImages = new Vector<String>();
        int fbi = 0;
        while (request.getParameter("socialphoto_" + fbi) != null) {
            fbImages.add(request.getParameter("socialphoto_" + fbi));
            fbi++;
        }
            
    System.out.println(fbImages);
        if (fbImages.size() > 0) {
            FacebookClient fbclient = null;
            try {
    fbclient = SocialAuth.getFacebookClient(context);
            } catch (Exception ex) {
    System.out.println("SocialAuth.getFacebookClient threw exception " + ex.toString());
            }
    WebContext ctx = new J2EContext(request, response);
    //String callbackUrl = "http://localhost.wildme.org/a/SocialConnect?type=facebook";
    String callbackUrl = "http://" + CommonConfiguration.getURLLocation(request) + "/XXXSocialConnect?type=facebook";
    if (request.getParameter("disconnect") != null) callbackUrl += "&disconnect=1";
    fbclient.setCallbackUrl(callbackUrl);
            
    OAuthCredentials credentials = null;
    try {
        credentials = fbclient.getCredentials(ctx);
    } catch (Exception ex) {
        System.out.println("caught exception on facebook credentials: " + ex.toString());
    }
            
    if (credentials != null) {
        FacebookProfile facebookProfile = fbclient.getUserProfile(credentials, ctx);
        User fbuser = myShepherd.getUserBySocialId("facebook", facebookProfile.getId());
        System.out.println("getId() = " + facebookProfile.getId() + " -> user = " + fbuser);
    if (fbuser != null) System.out.println("user = " + user.getUsername() + "; fbuser = " + fbuser.getUsername());
        if ((fbuser != null) && (fbuser.getUsername().equals(user.getUsername())) && (request.getParameter("disconnect") != null)) {
            fbuser.unsetSocial("facebook");
            //myShepherd.getPM().makePersistent(user);
            session.setAttribute("message", "disconnected from facebook");
            response.sendRedirect("myAccount.jsp");
            return;
            
        } else if (fbuser != null) {
            session.setAttribute("error", "looks like this account is already connected to an account");
            response.sendRedirect("myAccount.jsp");
            return;
            
        } else {  //lets do this
            user.setSocial("facebook", facebookProfile.getId());
            //myShepherd.getPM().makePersistent(user);
            session.setAttribute("message", "connected to facebook");
            response.sendRedirect("myAccount.jsp");
            return;
        }
    } else {
            
    System.out.println("*** trying redirect?");
        try {
            fbclient.redirect(ctx, false, false);
        } catch (Exception ex) {
            System.out.println("caught exception on facebook processing: " + ex.toString());
        }
        return;
    }
        }
            
    */
    //private Map<String, Object> measurements = new HashMap<String, Object>();
    //Map<String, Object> metalTags = new HashMap<String, Object>();

    /*
          private String acousticTagSerial = "";
          private String acousticTagId = "";
          private String satelliteTagSerial = "";
          private String satelliteTagArgosPttNumber = "";
          private String satelliteTagName = "";
    */

    //set up for response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean locked = false;

    String fileName = "None";
    String username = "None";
    String fullPathFilename = "";

    boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end)
    String doneMessage = "";
    List<String> filesOK = new ArrayList<String>();
    HashMap<String, String> filesBad = new HashMap<String, String>();

    List<FileItem> formFiles = new ArrayList<FileItem>();
    List<File> socialFiles = new ArrayList<File>();

    //Calendar date = Calendar.getInstance();

    long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context);
    long maxSizeBytes = maxSizeMB * 1048576;

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            upload.setHeaderEncoding("UTF-8");
            List<FileItem> multiparts = upload.parseRequest(request);
            //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (item.isFormField()) { //plain field
                    fv.put(item.getFieldName(),
                            ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon
                    //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")");
                } else if (item.getName().startsWith("socialphoto_")) {
                    System.out.println(item.getName() + ": " + item.getString("UTF-8"));
                } else { //file
                    //System.out.println("content type???? " + item.getContentType());   TODO note, the helpers only check extension
                    if (item.getSize() > maxSizeBytes) {
                        filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB");
                    } else if (myShepherd.isAcceptableImageFile(item.getName())
                            || myShepherd.isAcceptableVideoFile(item.getName())) {
                        formFiles.add(item);
                        filesOK.add(item.getName());
                    } else {
                        filesBad.put(item.getName(), "invalid type of file");
                    }
                }
            }

            doneMessage = "File Uploaded Successfully";
            fileSuccess = true;

        } catch (Exception ex) {
            doneMessage = "File Upload Failed due to " + ex;
        }

    } else {
        doneMessage = "Sorry this Servlet only handles file upload request";
    }

    if (fv.get("social_files_id") != null) {
        //TODO better checking of files (size, type etc)
        File socDir = new File(
                ServletUtilities.dataDir(context, rootDir) + "/social_files/" + fv.get("social_files_id"));
        for (File sf : socDir.listFiles()) {
            socialFiles.add(sf);
            filesOK.add(sf.getName());
        }
        filesBad = new HashMap<String, String>();
        fileSuccess = true;
    }

    session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray())));
    String badmsg = "";
    for (String key : filesBad.keySet()) {
        badmsg += key + " (" + getVal(filesBad, key) + ") ";
    }
    if (badmsg.equals("")) {
        badmsg = "none";
    }
    session.setAttribute("filesBadMessage", badmsg);

    if (fileSuccess) {

        //////////////////////////////////////////// START

        //{submitterID=tomcat, submitterProject=, photographerEmail=, metalTag(left)=, sex=unknown, measurement(weight)=34234, location=, acousticTagId=, behavior=yow behavior..., measurement(weightunits)=kilograms, acousticTagSerial=, photographerName=, lifeStage=sub-adult, submitterAddress=, satelliteTagSerial=, releaseDate=, photographerPhone=, measurement(lengthunits)=meters, measurement(weightsamplingProtocol)=samplingProtocol0, measurement(length)=, submitterOrganization=, photographerAddress=, longitude=, year=2014, lat=, measurement(lengthsamplingProtocol)=samplingProtocol0, submitterEmail=, minutes=00, elevation=, measurement(height)=, measurement(heightsamplingProtocol)=samplingProtocol0, scars=None, submitterPhone=, submitterName=tomcat, hour=-1, livingStatus=alive, depth=, country=, satelliteTagName=Wild Life Computers, metalTag(right)=, month=1, measurement(heightunits)=meters, Submit=Send encounter report, informothers=, day=0, satelliteTagArgosPttNumber=, comments=}

        //check for spamBots   TODO possibly move this to Util for general/global usage?
        boolean spamBot = false;
        String[] spamFieldsToCheck = new String[] { "submitterPhone", "submitterName", "photographerName",
                "photographerPhone", "location", "comments", "behavior" };
        StringBuffer spamFields = new StringBuffer();
        for (int i = 0; i < spamFieldsToCheck.length; i++) {
            spamFields.append(getVal(fv, spamFieldsToCheck[i]));
        }

        if (spamFields.toString().toLowerCase().indexOf("porn") != -1) {
            spamBot = true;
        }
        if (spamFields.toString().toLowerCase().indexOf("href") != -1) {
            spamBot = true;
        }
        //else if(spamFields.toString().toLowerCase().indexOf("[url]")!=-1){spamBot=true;}
        //else if(spamFields.toString().toLowerCase().indexOf("url=")!=-1){spamBot=true;}
        //else if(spamFields.toString().toLowerCase().trim().equals("")){spamBot=true;}
        //else if((theForm.getSubmitterID()!=null)&&(theForm.getSubmitterID().equals("N%2FA"))) {spamBot=true;}

        String locCode = "";
        System.out.println(" **** here is what i think locationID is: " + fv.get("locationID"));
        if ((fv.get("locationID") != null) && !fv.get("locationID").toString().equals("")) {
            locCode = fv.get("locationID").toString();

        }
        //see if the location code can be determined and set based on the location String reported
        else if (fv.get("location") != null) {
            String locTemp = getVal(fv, "location").toLowerCase();
            Properties props = new Properties();

            try {
                props = ShepherdProperties.getProperties("submitActionClass.properties", "", context);

                Enumeration m_enum = props.propertyNames();
                while (m_enum.hasMoreElements()) {
                    String aLocationSnippet = ((String) m_enum.nextElement()).trim();
                    if (locTemp.indexOf(aLocationSnippet) != -1) {
                        locCode = props.getProperty(aLocationSnippet);
                    }
                }
            } catch (Exception props_e) {
                props_e.printStackTrace();
            }

        } //end else
          //end location code setter
        fv.put("locCode", locCode);

        //TODO this should live somewhere else as constant? (e.g. to build in form as well)
        String[] scarType = new String[] { "None", "Tail (caudal) fin", "1st dorsal fin", "2nd dorsal fin",
                "Left pectoral fin", "Right pectoral fin", "Head", "Body" };
        int scarNum = -1;
        try {
            scarNum = Integer.parseInt(getVal(fv, "scars"));
        } catch (NumberFormatException e) {
            scarNum = -1;
        }
        if ((scarNum < 0) || (scarNum > 7)) {
            scarNum = -1;
        }
        if (scarNum >= 0) {
            fv.put("scars", scarType[scarNum]);
        }

        //System.out.println("about to do int stuff");

        //need some ints for day/month/year/hour (other stuff seems to be strings)
        int day = 0, month = -1, year = 0, hour = 0;
        String minutes = "";
        //try { day = Integer.parseInt(getVal(fv, "day")); } catch (NumberFormatException e) { day = 0; }
        //try { month = Integer.parseInt(getVal(fv, "month")); } catch (NumberFormatException e) { month = 0; }
        //try { year = Integer.parseInt(getVal(fv, "year")); } catch (NumberFormatException e) { year = 0; }

        //switch to datepicker

        LocalDateTime dt = new LocalDateTime();

        if ((getVal(fv, "datepicker") != null) && (!getVal(fv, "datepicker").trim().equals(""))) {
            //System.out.println("Trying to read date: "+getVal(fv, "datepicker").replaceAll(" ", "T"));
            //boolean badDate=false;
            try {
                DateTimeFormatter parser1 = ISODateTimeFormat.dateOptionalTimeParser();

                LocalDateTime reportedDateTime = new LocalDateTime(
                        parser1.parseMillis(getVal(fv, "datepicker").replaceAll(" ", "T")));
                StringTokenizer str = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"), "-");

                int numTokens = str.countTokens();

                if (numTokens >= 1) {
                    //try {
                    year = reportedDateTime.getYear();
                    if (year > (dt.getYear() + 1)) {
                        //badDate=true;
                        year = 0;
                        throw new Exception(
                                "    An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format: "
                                        + year + " > " + dt.getYear());
                    }

                    //} catch (Exception e) { year=-1;}
                }
                if (numTokens >= 2) {
                    try {
                        month = reportedDateTime.getMonthOfYear();
                    } catch (Exception e) {
                        month = -1;
                    }
                } else {
                    month = -1;
                }
                //see if we can get a day, because we do want to support only yyy-MM too
                if (str.countTokens() >= 3) {
                    try {
                        day = reportedDateTime.getDayOfMonth();
                    } catch (Exception e) {
                        day = 0;
                    }
                } else {
                    day = 0;
                }

                //see if we can get a time and hour, because we do want to support only yyy-MM too
                StringTokenizer strTime = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"),
                        "T");
                if (strTime.countTokens() > 1) {
                    try {
                        hour = reportedDateTime.getHourOfDay();
                    } catch (Exception e) {
                        hour = -1;
                    }
                    try {
                        minutes = (new Integer(reportedDateTime.getMinuteOfHour()).toString());
                    } catch (Exception e) {
                    }
                } else {
                    hour = -1;
                }

                //System.out.println("At the end of time processing I see: "+year+"-"+month+"-"+day+" "+hour+":"+minutes);

            } catch (Exception e) {
                System.out.println(
                        "    An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format.");
                e.printStackTrace();
                processingNotes.append("<p>Error encountered processing this date submitted by user: "
                        + getVal(fv, "datepicker") + "</p>");

            }
        }

        String guess = "no estimate provided";
        if ((fv.get("guess") != null) && !fv.get("guess").toString().equals("")) {
            guess = fv.get("guess").toString();
        }

        //let's handle genus and species for taxonomy
        String genus = null;
        String specificEpithet = null;

        try {

            //now we have to break apart genus species
            if (fv.get("genusSpecies") != null) {
                StringTokenizer tokenizer = new StringTokenizer(fv.get("genusSpecies").toString(), " ");
                if (tokenizer.countTokens() >= 2) {

                    genus = tokenizer.nextToken();
                    //enc.setGenus(tokenizer.nextToken());
                    specificEpithet = tokenizer.nextToken().replaceAll(",", "").replaceAll("_", " ");
                    //enc.setSpecificEpithet(tokenizer.nextToken().replaceAll(",","").replaceAll("_"," "));

                }
                //handle malformed Genus Species formats
                else {
                    throw new Exception(
                            "The format of the submitted genusSpecies parameter did not have two tokens delimited by a space (e.g., \"Rhincodon typus\"). The submitted value was: "
                                    + fv.get("genusSpecies"));
                }
            }

        } catch (Exception le) {

        }

        System.out.println("about to do enc()");

        Encounter enc = new Encounter(day, month, year, hour, minutes, guess, getVal(fv, "location"),
                getVal(fv, "submitterName"), getVal(fv, "submitterEmail"), null);
        boolean llSet = false;
        //Encounter enc = new Encounter();
        //System.out.println("Submission detected date: "+enc.getDate());
        String encID = enc.generateEncounterNumber();
        enc.setEncounterNumber(encID);
        System.out.println("hey, i think i may have made an encounter, encID=" + encID);
        System.out.println("enc ?= " + enc.toString());

        AssetStore astore = AssetStore.getDefault(myShepherd);
        ArrayList<Annotation> newAnnotations = new ArrayList<Annotation>();

        for (FileItem item : formFiles) {
            JSONObject sp = astore.createParameters(new File(enc.subdir() + File.separator + item.getName()));
            sp.put("key", Util.hashDirectories(encID) + "/" + item.getName());
            MediaAsset ma = new MediaAsset(astore, sp);
            File tmpFile = ma.localPath().toFile(); //conveniently(?) our local version to save ma.cacheLocal() from having to do anything?
            File tmpDir = tmpFile.getParentFile();
            if (!tmpDir.exists())
                tmpDir.mkdirs();
            //System.out.println("attempting to write uploaded file to " + tmpFile);
            try {
                item.write(tmpFile);
            } catch (Exception ex) {
                System.out.println("Could not write " + tmpFile + ": " + ex.toString());
            }
            if (tmpFile.exists()) {
                ma.addLabel("_original");
                ma.copyIn(tmpFile);
                ma.updateMetadata();
                newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma));
            } else {
                System.out.println("failed to write file " + tmpFile);
            }
        }

        ///////////////////TODO social files also!!!

        if (fv.get("mediaAssetSetId") != null) {
            MediaAssetSet maSet = ((MediaAssetSet) (myShepherd.getPM().getObjectById(
                    myShepherd.getPM().newObjectIdInstance(MediaAssetSet.class, fv.get("mediaAssetSetId")),
                    true)));
            if ((maSet != null) && (maSet.getMediaAssets() != null) && (maSet.getMediaAssets().size() > 0)) {
                int num = maSet.getMediaAssets().size();
                for (MediaAsset ma : maSet.getMediaAssets()) {
                    newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma));
                }
                session.setAttribute("filesOKMessage", num + " " + ((num == 1) ? "file" : "files"));
            }
        }

        enc.setAnnotations(newAnnotations);

        enc.setGenus(genus);
        enc.setSpecificEpithet(specificEpithet);

        /*
                    String baseDir = ServletUtilities.dataDir(context, rootDir);
                    ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>();
                    for (FileItem item : formFiles) {
        // this will actually write file to filesystem (or [FUTURE] wherever)
        //  TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc.
        try {
            //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir);
            SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir);
            //images.add(spv);
            enc.addSinglePhotoVideo(spv);
        } catch (Exception ex) {
            System.out.println("failed to save " + item.toString() + ": " + ex.toString());
        }
                    }
                
                    for (File sf : socialFiles) {
                File encDir = new File(enc.dir(baseDir));
                if (!encDir.exists()) encDir.mkdirs();
        File targetFile = new File(encDir, sf.getName());
        System.out.println("socialFile copy: " + sf.toString() + " ---> " + targetFile.toString());
        Files.copy(sf.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        SinglePhotoVideo spv = new SinglePhotoVideo(encID, targetFile);
        enc.addSinglePhotoVideo(spv);
                    }
        */

        //now let's add our encounter to the database

        enc.setComments(getVal(fv, "comments").replaceAll("\n", "<br>"));
        if (fv.get("releaseDate") != null && fv.get("releaseDate").toString().length() > 0) {
            String dateFormatPattern = CommonConfiguration.getProperty("releaseDateFormat", context);
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
                enc.setReleaseDate(simpleDateFormat.parse(fv.get("releaseDate").toString()).getTime());
            } catch (Exception e) {
                enc.addComments("<p>Reported release date was problematic: " + fv.get("releaseDate") + "</p>");
            }
        }
        if (fv.get("behavior") != null && fv.get("behavior").toString().length() > 0) {
            enc.setBehavior(fv.get("behavior").toString());
        }
        if (fv.get("alternateID") != null && fv.get("alternateID").toString().length() > 0) {
            enc.setAlternateID(fv.get("alternateID").toString());
        }
        if (fv.get("lifeStage") != null && fv.get("lifeStage").toString().length() > 0) {
            enc.setLifeStage(fv.get("lifeStage").toString());
        }

        List<MetalTag> metalTags = getMetalTags(fv);
        for (MetalTag metalTag : metalTags) {
            enc.addMetalTag(metalTag);
        }

        List<Measurement> measurements = getMeasurements(fv, encID, context);
        for (Measurement measurement : measurements) {
            enc.setMeasurement(measurement, myShepherd);
        }

        enc.setAcousticTag(getAcousticTag(fv));
        enc.setSatelliteTag(getSatelliteTag(fv));
        enc.setSex(getVal(fv, "sex"));
        enc.setLivingStatus(getVal(fv, "livingStatus"));

        if (fv.get("scars") != null) {
            enc.setDistinguishingScar(fv.get("scars").toString());
        }

        int sizePeriod = 0;
        if ((fv.get("measureUnits") != null) && fv.get("measureUnits").toString().equals("Feet")) {

            if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) {
                try {
                    double tempDouble = (new Double(fv.get("depth").toString())).doubleValue() / 3.3;
                    String truncDepth = (new Double(tempDouble)).toString();
                    sizePeriod = truncDepth.indexOf(".");
                    truncDepth = truncDepth.substring(0, sizePeriod + 2);
                    fv.put("depth", (new Double(truncDepth)).toString());
                } catch (java.lang.NumberFormatException nfe) {
                    enc.addComments(
                            "<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>");
                    fv.put("depth", "");
                } catch (NullPointerException npe) {
                    fv.put("depth", "");
                }
            }
            System.out.println("depth --> " + fv.get("depth").toString());

            if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) {
                try {
                    double tempDouble = (new Double(fv.get("elevation").toString())).doubleValue() / 3.3;
                    String truncElev = (new Double(tempDouble)).toString();
                    //String truncElev = ((new Double(elevation)) / 3.3).toString();
                    sizePeriod = truncElev.indexOf(".");
                    truncElev = truncElev.substring(0, sizePeriod + 2);
                    fv.put("elevation", (new Double(truncElev)).toString());
                } catch (java.lang.NumberFormatException nfe) {
                    enc.addComments("<p>Reported elevation was problematic: " + fv.get("elevation").toString()
                            + "</p>");
                    fv.put("elevation", "");
                } catch (NullPointerException npe) {
                    fv.put("elevation", "");
                }
            }

            if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) {

                try {
                    double tempDouble = (new Double(fv.get("size").toString())).doubleValue() / 3.3;
                    String truncSize = (new Double(tempDouble)).toString();
                    //String truncSize = ((new Double(size)) / 3.3).toString();
                    sizePeriod = truncSize.indexOf(".");
                    truncSize = truncSize.substring(0, sizePeriod + 2);
                    fv.put("size", (new Double(truncSize)).toString());
                } catch (java.lang.NumberFormatException nfe) {

                    enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>");
                    fv.put("size", "");
                } catch (NullPointerException npe) {
                    fv.put("size", "");
                }
            }
        } //measureUnits

        if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) {
            try {
                enc.setSize(new Double(fv.get("size").toString()));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>");
                fv.put("size", "");
            } catch (NullPointerException npe) {
                fv.put("size", "");
            }
        }

        if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) {
            try {
                enc.setMaximumElevationInMeters(new Double(fv.get("elevation").toString()));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments(
                        "<p>Reported elevation was problematic: " + fv.get("elevation").toString() + "</p>");
                fv.put("elevatoin", "");
            } catch (NullPointerException npe) {
                fv.put("elevation", "");
            }
        }

        if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) {
            try {
                enc.setDepth(new Double(fv.get("depth").toString()));
            } catch (java.lang.NumberFormatException nfe) {
                enc.addComments("<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>");
                fv.put("depth", "");
            } catch (NullPointerException npe) {
                fv.put("depth", "");
            }
        }

        //let's handle the GPS
        if ((fv.get("lat") != null) && (fv.get("longitude") != null) && !fv.get("lat").toString().equals("")
                && !fv.get("longitude").toString().equals("")) {
            //enc.setGPSLatitude(lat + "&deg; " + gpsLatitudeMinutes + "\' " + gpsLatitudeSeconds + "\" " + latDirection);

            try {
                double degrees = (new Double(fv.get("lat").toString())).doubleValue();
                double position = degrees;
                /*
                if (!gpsLatitudeMinutes.equals("")) {
                  double minutes2 = ((new Double(gpsLatitudeMinutes)).doubleValue()) / 60;
                  position += minutes2;
                }
                if (!gpsLatitudeSeconds.equals("")) {
                  double seconds2 = ((new Double(gpsLatitudeSeconds)).doubleValue()) / 3600;
                  position += seconds2;
                }
                if (latDirection.toLowerCase().equals("south")) {
                  position = position * -1;
                }*/
                enc.setDWCDecimalLatitude(position);

                double degrees2 = (new Double(fv.get("longitude").toString())).doubleValue();
                double position2 = degrees2;
                enc.setDWCDecimalLongitude(position2);
                llSet = true;

            } catch (Exception e) {
                System.out.println("EncounterSetGPS: problem!");
                e.printStackTrace();
            }

        }

        //enc.setMeasureUnits("Meters");
        enc.setSubmitterPhone(getVal(fv, "submitterPhone"));
        enc.setSubmitterAddress(getVal(fv, "submitterAddress"));
        enc.setSubmitterOrganization(getVal(fv, "submitterOrganization"));
        enc.setSubmitterProject(getVal(fv, "submitterProject"));

        enc.setPhotographerPhone(getVal(fv, "photographerPhone"));
        enc.setPhotographerAddress(getVal(fv, "photographerAddress"));
        enc.setPhotographerName(getVal(fv, "photographerName"));
        enc.setPhotographerEmail(getVal(fv, "photographerEmail"));
        enc.addComments("<p>Submitted on " + (new java.util.Date()).toString() + " from address: "
                + request.getRemoteHost() + "</p>");
        //enc.approved = false;

        enc.addComments(processingNotes.toString());

        if (CommonConfiguration.getProperty("encounterState0", context) != null) {
            enc.setState(CommonConfiguration.getProperty("encounterState0", context));
        }
        if (request.getRemoteUser() != null) {
            enc.setSubmitterID(request.getRemoteUser());
        } else {
            enc.setSubmitterID("N/A");
        }
        if (!getVal(fv, "locCode").equals("")) {
            enc.setLocationCode(locCode);
        }
        if (!getVal(fv, "country").equals("")) {
            enc.setCountry(getVal(fv, "country"));
        }
        if (!getVal(fv, "informothers").equals("")) {
            enc.setInformOthers(getVal(fv, "informothers"));
        }

        // xxxxxxx
        //add research team for GAq
        if (!getVal(fv, "researchTeam").equals("")) {
            enc.setDynamicProperty("Research Team", (getVal(fv, "researchTeam")));
        }
        if (!getVal(fv, "vessel").equals("")) {
            enc.setDynamicProperty("Vessel", (getVal(fv, "vessel")));
        }
        if (!getVal(fv, "conditions").equals("")) {
            enc.setDynamicProperty("Conditions", (getVal(fv, "conditions")));
        }

        if (!getVal(fv, "camera").equals("")) {
            enc.setDynamicProperty("Camera", (getVal(fv, "camera")));
        }
        if (!getVal(fv, "lens").equals("")) {
            enc.setDynamicProperty("Lens", (getVal(fv, "lens")));
        }
        if (!getVal(fv, "card").equals("")) {
            enc.setDynamicProperty("Card", (getVal(fv, "card")));
        }
        if (!getVal(fv, "folder").equals("")) {
            enc.setDynamicProperty("Folder", (getVal(fv, "folder")));
        }

        if (!getVal(fv, "numberOfBoats").equals("")) {
            enc.setDynamicProperty("Number of boats", (getVal(fv, "numberOfBoats")));
        }

        if (!getVal(fv, "startTime").equals("")) {
            enc.setDynamicProperty("Start Time", (getVal(fv, "startTime")));
        }

        if (!getVal(fv, "endTime").equals("")) {
            enc.setDynamicProperty("End Time", (getVal(fv, "endTime")));
        }

        if (!getVal(fv, "endLongitude").equals("")) {
            enc.setDynamicProperty("End Longitude", (getVal(fv, "endLongitude")));
        }
        if (!getVal(fv, "endLatitude").equals("")) {
            enc.setDynamicProperty("End Latitude", (getVal(fv, "endLatitude")));
        }

        if (!getVal(fv, "startLongitude").equals("")) {
            enc.setDynamicProperty("Start Longitude", (getVal(fv, "startLongitude")));
        }
        if (!getVal(fv, "startLatitude").equals("")) {
            enc.setDynamicProperty("Start Latitude", (getVal(fv, "startLatitude")));
        }

        if (!getVal(fv, "beginWaypoint").equals("")) {
            enc.setDynamicProperty("Begin Waypoint", (getVal(fv, "beginWaypoint")));
        }
        if (!getVal(fv, "endWaypoint").equals("")) {
            enc.setDynamicProperty("End Waypoint", (getVal(fv, "endWaypoint")));
        }

        //xxxxxxxx

        String guid = CommonConfiguration.getGlobalUniqueIdentifierPrefix(context) + encID;

        //new additions for DarwinCore
        enc.setDWCGlobalUniqueIdentifier(guid);
        enc.setDWCImageURL((request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                + "/encounters/encounter.jsp?number=" + encID));

        //populate DarwinCore dates

        DateTimeFormatter fmt = ISODateTimeFormat.date();
        String strOutputDateTime = fmt.print(dt);
        enc.setDWCDateAdded(strOutputDateTime);
        enc.setDWCDateAdded(new Long(dt.toDateTime().getMillis()));
        //System.out.println("I set the date as a LONG to: "+enc.getDWCDateAddedLong());
        enc.setDWCDateLastModified(strOutputDateTime);

        //this will try to set from MediaAssetMetadata -- ymmv
        if (!llSet)
            enc.setLatLonFromAssets();
        if (enc.getYear() < 1)
            enc.setDateFromAssets();

        String newnum = "";
        if (!spamBot) {
            newnum = myShepherd.storeNewEncounter(enc, encID);
            //enc.refreshAssetFormats(context, ServletUtilities.dataDir(context, rootDir));
            enc.refreshAssetFormats(myShepherd);

            Logger log = LoggerFactory.getLogger(EncounterForm.class);
            log.info("New encounter submission: <a href=\"" + request.getScheme() + "://"
                    + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + encID
                    + "\">" + encID + "</a>");
            System.out.println("ENCOUNTER SAVED???? newnum=" + newnum);
        }

        if (newnum.equals("fail")) {
            request.setAttribute("number", "fail");
            return;
        }

        //return a forward to display.jsp
        System.out.println("Ending data submission.");
        if (!spamBot) {
            response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
                    + "/confirmSubmit.jsp?number=" + encID);
        } else {
            response.sendRedirect(
                    request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/spambot.jsp");
        }

    } //end "if (fileSuccess)

    myShepherd.closeDBTransaction();
    //return null;
}

From source file:org.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Initial the parameters class. Web.xml is in UTF-8 format. No need to do
 * encoding convertion./*  w ww.j a va  2s.co m*/
 * 
 * @param context
 *            Servlet Context
 */

public synchronized static void initParameters(ServletContext context) {
    if (isInitContext)
        return;

    if ("true".equalsIgnoreCase(System.getProperty(IBirtConstants.SYS_PROP_BIRT_ISDESIGNER))) //$NON-NLS-1$
        isDesigner = true;

    String workingPath = "${" + IBirtConstants.SYS_PROP_WORKING_PATH + "}/"; //$NON-NLS-1$//$NON-NLS-2$

    // Working folder setting
    workingFolder = processWorkingFolder(context, context.getInitParameter(INIT_PARAM_WORKING_DIR));

    // Document folder setting
    String initDocumentFolder = context.getInitParameter(INIT_PARAM_DOCUMENT_FOLDER);
    if (isDesigner && initDocumentFolder == null)
        initDocumentFolder = workingPath + IBirtConstants.DEFAULT_DOCUMENT_FOLDER;
    String documentFolder = processRealPath(context, initDocumentFolder, IBirtConstants.DEFAULT_DOCUMENT_FOLDER,
            true);

    // Image folder setting
    String initImageFolder = context.getInitParameter(ParameterAccessor.INIT_PARAM_IMAGE_DIR);
    if (isDesigner && initImageFolder == null)
        initImageFolder = workingPath + IBirtConstants.DEFAULT_IMAGE_FOLDER;
    String imageFolder = processRealPath(context, initImageFolder, IBirtConstants.DEFAULT_IMAGE_FOLDER, true);

    // Log folder setting
    String initLogFolder = context.getInitParameter(ParameterAccessor.INIT_PARAM_LOG_DIR);
    if (isDesigner && initLogFolder == null)
        initLogFolder = workingPath + IBirtConstants.DEFAULT_LOGS_FOLDER;
    logFolder = processRealPath(context, initLogFolder, IBirtConstants.DEFAULT_LOGS_FOLDER, true);

    // Log level setting
    logLevel = context.getInitParameter(ParameterAccessor.INIT_PARAM_LOG_LEVEL);
    if (logLevel == null)
        logLevel = IBirtConstants.DEFAULT_LOGS_LEVEL;

    String rootPath = "${" + IBirtConstants.SYS_PROP_ROOT_PATH + "}/"; //$NON-NLS-1$//$NON-NLS-2$      
    // Script lib folder setting
    String initScriptlibFolder = context.getInitParameter(ParameterAccessor.INIT_PARAM_SCRIPTLIB_DIR);
    if (isDesigner && initScriptlibFolder == null)
        initScriptlibFolder = rootPath + IBirtConstants.DEFAULT_SCRIPTLIB_FOLDER;
    scriptLibDir = processRealPath(context, initScriptlibFolder, IBirtConstants.DEFAULT_SCRIPTLIB_FOLDER,
            false);

    // WebApp Locale setting
    webAppLocale = getLocaleFromString(context.getInitParameter(INIT_PARAM_LOCALE));
    if (webAppLocale == null)
        webAppLocale = Locale.getDefault();

    webAppTimeZone = getTimeZoneFromString(context.getInitParameter(INIT_PARAM_TIMEZONE));

    isWorkingFolderAccessOnly = Boolean.valueOf(context.getInitParameter(INIT_PARAM_WORKING_FOLDER_ACCESS_ONLY))
            .booleanValue();

    urlReportPathPolicy = context.getInitParameter(INIT_PARAM_URL_REPORT_PATH_POLICY);

    // Get preview report max rows parameter from ServletContext
    String s_maxRows = context.getInitParameter(INIT_PARAM_VIEWER_MAXROWS);
    try {
        maxRows = Integer.valueOf(s_maxRows).intValue();
    } catch (NumberFormatException e) {
        maxRows = -1;
    }

    // Get preview report max cube fetch levels parameter from
    // ServletContext
    String s_maxRowLevels = context.getInitParameter(INIT_PARAM_VIEWER_MAXCUBE_ROWLEVELS);
    try {
        maxCubeRowLevels = Integer.valueOf(s_maxRowLevels).intValue();
    } catch (NumberFormatException e) {
        maxCubeRowLevels = -1;
    }

    String s_maxColumnLevels = context.getInitParameter(INIT_PARAM_VIEWER_MAXCUBE_COLUMNLEVELS);
    try {
        maxCubeColumnLevels = Integer.valueOf(s_maxColumnLevels).intValue();
    } catch (NumberFormatException e) {
        maxCubeColumnLevels = -1;
    }

    // Get cube memory size parameter from ServletContext
    String s_cubeMemSize = context.getInitParameter(INIT_PARAM_VIEWER_CUBEMEMSIZE);
    try {
        cubeMemorySize = Integer.valueOf(s_cubeMemSize).intValue();
    } catch (NumberFormatException e) {
        cubeMemorySize = 0;
    }

    // default resource path
    String initResourceFolder = context.getInitParameter(INIT_PARAM_BIRT_RESOURCE_PATH);
    if (isDesigner && initResourceFolder == null)
        initResourceFolder = "${" + IBirtConstants.SYS_PROP_RESOURCE_PATH + "}"; //$NON-NLS-1$ //$NON-NLS-2$
    birtResourceFolder = processRealPath(context, initResourceFolder, null, false);

    if (isDesigner) {
        // workaround for Bugzilla bug 231715
        // (must be removed once the web.xml is used for the designer)
        isOverWrite = true;
    } else {
        // get the overwrite flag
        String s_overwrite = DataUtil.trimString(context.getInitParameter(INIT_PARAM_OVERWRITE_DOCUMENT));
        if ("true".equalsIgnoreCase(s_overwrite)) //$NON-NLS-1$
        {
            isOverWrite = true;
        } else {
            isOverWrite = false;
        }
    }

    // initialize the application properties
    initProps = initViewerProps(context, initProps);

    if (loggers == null) {
        loggers = new HashMap();
    }

    // retrieve the logger names from the application properties
    for (Iterator i = initProps.keySet().iterator(); i.hasNext();) {
        String name = (String) i.next();
        if (name.startsWith("logger.")) //$NON-NLS-1$
        {
            String loggerName = name.replaceFirst("logger.", //$NON-NLS-1$
                    "" //$NON-NLS-1$
            );
            String levelName = (String) initProps.get(name);

            loggers.put(loggerName, levelName);

            i.remove();
        }
    }

    // print on the server side
    String flag = DataUtil.trimString(context.getInitParameter(INIT_PARAM_PRINT_SERVERSIDE));
    if (IBirtConstants.VAR_ON.equalsIgnoreCase(flag)) {
        isSupportedPrintOnServer = true;
    } else if (IBirtConstants.VAR_OFF.equalsIgnoreCase(flag)) {
        isSupportedPrintOnServer = false;
    }

    // get agent style flag
    String s_agentstyle = context.getInitParameter(INIT_PARAM_AGENTSTYLE_ENGINE);
    if ("false".equalsIgnoreCase(s_agentstyle)) //$NON-NLS-1$
        isAgentStyle = false;

    // try from servlet context
    String exportFilenameGeneratorClassName = context.getInitParameter(INIT_PARAM_FILENAME_GENERATOR_CLASS);
    if (exportFilenameGeneratorClassName != null) {
        Object generatorInstance = null;
        try {
            Class generatorClass = Class.forName(exportFilenameGeneratorClassName);
            generatorInstance = generatorClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (generatorInstance != null) {
            if (generatorInstance instanceof IFilenameGeneratorFactory) {
                exportFilenameGenerator = ((IFilenameGeneratorFactory) generatorInstance)
                        .createFilenameGenerator(context);
            } else if (generatorInstance instanceof IFilenameGenerator) {
                exportFilenameGenerator = (IFilenameGenerator) generatorInstance;
            }
        }
    }

    if (exportFilenameGenerator == null) {
        exportFilenameGenerator = new DefaultFilenameGenerator();
    }

    initViewingSessionConfig(documentFolder, imageFolder);

    // Finish init context
    isInitContext = true;
}

From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java

/**
 * Fixes the Schema for Database Version 1.2
 * @param conn/*from ww w .  j av  a 2  s  . c o m*/
 * @throws Exception
 */
private boolean doFixesForDBSchemaVersions(final Connection conn, final String databaseName) throws Exception {
    /////////////////////////////
    // PaleoContext
    /////////////////////////////
    getTableNameAndTitleForFrame(PaleoContext.getClassTableId());
    Integer len = getFieldLength(conn, databaseName, "paleocontext", "Text1");
    alterFieldLength(conn, databaseName, "paleocontext", "Text1", 32, 64);
    alterFieldLength(conn, databaseName, "paleocontext", "Text2", 32, 64);

    len = getFieldLength(conn, databaseName, "paleocontext", "Remarks");
    if (len == null) {
        int count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM paleocontext");
        int rv = update(conn, "ALTER TABLE paleocontext ADD Remarks VARCHAR(60)");
        if (rv != count) {
            errMsgList.add("Error updating PaleoContext.Remarks");
            return false;
        }
    }
    frame.incOverall();

    DBConnection dbc = DBConnection.getInstance();

    /////////////////////////////
    // FieldNotebookPage
    /////////////////////////////
    getTableNameAndTitleForFrame(FieldNotebookPage.getClassTableId());
    len = getFieldLength(conn, databaseName, "fieldnotebookpage", "PageNumber");
    if (len != null && len == 16) {
        alterFieldLength(conn, databaseName, "fieldnotebookpage", "PageNumber", 16, 32);
        update(conn, "ALTER TABLE fieldnotebookpage ALTER COLUMN ScanDate DROP DEFAULT");
    }
    frame.incOverall();

    /////////////////////////////
    // Project Table
    /////////////////////////////
    alterFieldLength(conn, databaseName, "project", "projectname", 50, 128);
    frame.incOverall();

    /////////////////////////////
    // AttachmentImageAttribute Table
    /////////////////////////////
    if (doesTableExist(databaseName, "attachmentimageattribute")) {
        alterFieldLength(conn, databaseName, "attachmentimageattribute", "CreativeCommons", 128, 500);
        frame.incOverall();
    }

    /////////////////////////////
    // LocalityDetail
    /////////////////////////////

    String tblName = getTableNameAndTitleForFrame(LocalityDetail.getClassTableId());

    boolean statusOK = true;
    String sql = String.format(
            "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'localitydetail' AND COLUMN_NAME = 'UtmScale' AND DATA_TYPE = 'varchar'",
            dbc.getDatabaseName());
    int count = BasicSQLUtils.getCountAsInt(sql);
    if (count > 0) {
        Vector<Object[]> values = query("SELECT ld.LocalityDetailID, ld.UtmScale, l.LocalityName "
                + "FROM localitydetail ld INNER JOIN locality l ON ld.LocalityID = l.LocalityID WHERE ld.UtmScale IS NOT NULL");

        update(conn, "ALTER TABLE localitydetail DROP COLUMN UtmScale");
        addColumn(conn, databaseName, tblName, "UtmScale", "FLOAT", "UtmOrigLongitude");
        addColumn(conn, databaseName, tblName, "MgrsZone", "VARCHAR(4)", "UtmScale");

        HashMap<String, String> badLocalitiesHash = new HashMap<String, String>();

        try {
            PreparedStatement pStmt = conn
                    .prepareStatement("UPDATE localitydetail SET UtmScale=? WHERE LocalityDetailID=?");

            for (Object[] row : values) {
                Integer locDetailId = (Integer) row[0];
                String scale = (String) row[1];
                String locName = (String) row[2];

                scale = StringUtils.contains(scale, ',') ? StringUtils.replace(scale, ",", "") : scale;
                if (!StringUtils.isNumeric(scale)) {
                    badLocalitiesHash.put(locName, scale);
                    continue;
                }

                float scaleFloat = 0.0f;
                try {
                    scaleFloat = Float.parseFloat(scale);

                } catch (NumberFormatException ex) {
                    badLocalitiesHash.put(locName, scale);
                    continue;
                }

                pStmt.setFloat(1, scaleFloat);
                pStmt.setInt(2, locDetailId);
                pStmt.execute();
            }
            pStmt.close();

        } catch (SQLException ex) {
            statusOK = false;
        }

        if (badLocalitiesHash.size() > 0) {
            try {
                File file = new File(
                        UIRegistry.getUserHomeDir() + File.separator + "localitydetailerrors.html");
                TableWriter tblWriter = new TableWriter(file.getAbsolutePath(), "Locality Detail Errors");
                tblWriter.startTable();
                tblWriter.logHdr(new String[] { "Locality Name", "Scale" });

                for (String key : badLocalitiesHash.keySet()) {
                    tblWriter.log(key, badLocalitiesHash.get(key));
                }
                tblWriter.endTable();
                tblWriter.flush();
                tblWriter.close();

                UIRegistry.showLocalizedError("LOC_DETAIL_ERRORS", badLocalitiesHash.size(),
                        file.getAbsoluteFile());

                badLocalitiesHash.clear();

                if (file.exists()) {
                    try {
                        AttachmentUtils.openURI(file.toURI());

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    } else {
        addColumn(conn, databaseName, tblName, "UtmScale", "FLOAT", "UtmOrigLongitude");
    }
    frame.incOverall();

    //////////////////////////////////////////////
    // collectingeventattribute Schema 1.3
    //////////////////////////////////////////////
    DBMSUserMgr dbmsMgr = DBMSUserMgr.getInstance();
    if (dbmsMgr.connectToDBMS(itUserNamePassword.first, itUserNamePassword.second, dbc.getServerName())) {
        boolean status = true;

        Connection connection = dbmsMgr.getConnection();
        try {
            // Add New Fields to Determination
            tblName = getTableNameAndTitleForFrame(Determination.getClassTableId());
            addColumn(conn, databaseName, tblName, "VarQualifier",
                    "ALTER TABLE %s ADD COLUMN %s VARCHAR(16) AFTER Qualifier");
            addColumn(conn, databaseName, tblName, "SubSpQualifier",
                    "ALTER TABLE %s ADD COLUMN %s VARCHAR(16) AFTER VarQualifier");
            frame.incOverall();

            // CollectingEventAttributes
            sql = String.format(
                    "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'collectingeventattribute' AND COLUMN_NAME = 'CollectionMemberID'",
                    dbc.getDatabaseName());
            count = BasicSQLUtils.getCountAsInt(sql);

            connection.setCatalog(dbc.getDatabaseName());

            //int numCEAttrs = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectingeventattribute");
            if (count > 0) {
                HashMap<Integer, Integer> collIdToDispIdHash = new HashMap<Integer, Integer>();
                sql = "SELECT UserGroupScopeId, DisciplineID FROM collection";
                for (Object[] cols : query(sql)) {
                    Integer colId = (Integer) cols[0];
                    Integer dspId = (Integer) cols[1];
                    collIdToDispIdHash.put(colId, dspId);
                }

                count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collectingeventattribute");

                IdMapperMgr.getInstance().setDBs(connection, connection);
                IdTableMapper mapper = new IdTableMapper("ceattrmapper", "id",
                        "SELECT CollectingEventAttributeID, CollectionMemberID FROM collectingeventattribute",
                        true, false);
                mapper.setFrame(frame);
                mapper.mapAllIdsNoIncrement(count > 0 ? count : null);

                Statement stmt = null;
                try {
                    getTableNameAndTitleForFrame(CollectingEventAttribute.getClassTableId());

                    stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_READ_ONLY);
                    update(conn, "DROP INDEX COLEVATSColMemIDX on collectingeventattribute");
                    update(conn, "ALTER TABLE collectingeventattribute DROP COLUMN CollectionMemberID");
                    update(conn, "ALTER TABLE collectingeventattribute ADD COLUMN DisciplineID int(11)");
                    update(conn, "CREATE INDEX COLEVATSDispIDX ON collectingeventattribute(DisciplineID)");

                    double inc = count > 0 ? (100.0 / (double) count) : 0;
                    double cnt = 0;
                    int percent = 0;
                    frame.setProcess(0, 100);
                    frame.setProcessPercent(true);

                    PreparedStatement pStmt = conn.prepareStatement(
                            "UPDATE collectingeventattribute SET DisciplineID=? WHERE CollectingEventAttributeID=?");
                    ResultSet rs = stmt
                            .executeQuery("SELECT CollectingEventAttributeID FROM collectingeventattribute");
                    while (rs.next()) {
                        Integer ceAttrId = rs.getInt(1);
                        Integer oldColId = mapper.get(ceAttrId);
                        if (oldColId != null) {
                            Integer dispId = collIdToDispIdHash.get(oldColId);
                            if (dispId != null) {
                                pStmt.setInt(1, dispId);
                                pStmt.setInt(2, ceAttrId);
                                pStmt.execute();

                            } else {
                                log.debug("Error getting hashed DisciplineID from Old Collection ID[" + oldColId
                                        + "]  ceAttrId[" + ceAttrId + "]");
                            }
                        } else {
                            log.debug("Error getting mapped  Collection ID[" + oldColId + "]  ceAttrId["
                                    + ceAttrId + "]");
                        }

                        cnt += inc;
                        if (((int) cnt) > percent) {
                            percent = (int) cnt;
                            frame.setProcess(percent);
                        }
                    }
                    rs.close();
                    pStmt.close();

                    frame.setProcess(100);

                } catch (SQLException ex) {
                    ex.printStackTrace();

                } finally {
                    if (stmt != null)
                        stmt.close();
                }
                mapper.cleanup();
            }
            frame.incOverall();

            //-----------------------------
            // Collectors
            //-----------------------------
            sql = String.format(
                    "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'collector' AND COLUMN_NAME = 'CollectionMemberID'",
                    dbc.getDatabaseName());
            count = BasicSQLUtils.getCountAsInt(sql);
            if (count > 0) {
                HashMap<Integer, Integer> collIdToDivIdHash = new HashMap<Integer, Integer>();
                sql = "SELECT c.UserGroupScopeId, d.DivisionID FROM collection c INNER JOIN discipline d ON c.DisciplineID = d.UserGroupScopeId";
                for (Object[] cols : query(sql)) {
                    Integer colId = (Integer) cols[0];
                    Integer divId = (Integer) cols[1];
                    collIdToDivIdHash.put(colId, divId);
                }

                count = BasicSQLUtils.getCountAsInt("SELECT COUNT(*) FROM collector");

                IdMapperMgr.getInstance().setDBs(connection, connection);
                IdTableMapper mapper = new IdTableMapper("collectormap", "id",
                        "SELECT CollectorID, CollectionMemberID FROM collector", true, false);
                mapper.setFrame(frame);
                mapper.mapAllIdsNoIncrement(count > 0 ? count : null);

                getTableNameAndTitleForFrame(Collector.getClassTableId());
                Statement stmt = null;
                try {
                    stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_READ_ONLY);
                    update(conn, "DROP INDEX COLTRColMemIDX on collector");
                    update(conn, "ALTER TABLE collector DROP COLUMN CollectionMemberID");
                    update(conn, "ALTER TABLE collector ADD COLUMN DivisionID INT(11)");
                    update(conn, "CREATE INDEX COLTRDivIDX ON collector(DivisionID)");

                    double inc = count > 0 ? (100.0 / (double) count) : 0;
                    double cnt = 0;
                    int percent = 0;
                    frame.setProcess(0, 100);
                    frame.setProcessPercent(true);

                    PreparedStatement pStmt = conn
                            .prepareStatement("UPDATE collector SET DivisionID=? WHERE CollectorID=?");
                    ResultSet rs = stmt.executeQuery("SELECT CollectorID FROM collector");
                    while (rs.next()) {
                        Integer coltrId = rs.getInt(1);
                        Integer oldColId = mapper.get(coltrId);
                        if (oldColId != null) {
                            Integer divId = collIdToDivIdHash.get(oldColId);
                            if (divId != null) {
                                pStmt.setInt(1, divId);
                                pStmt.setInt(2, coltrId);
                                pStmt.execute();

                            } else {
                                log.debug("Error getting hashed DisciplineID from Old Collection ID[" + oldColId
                                        + "]");
                            }
                        } else {
                            log.debug("Error getting mapped Collector ID[" + oldColId + "]");
                        }

                        cnt += inc;
                        if (((int) cnt) > percent) {
                            percent = (int) cnt;
                            frame.setProcess(percent);
                        }
                    }
                    rs.close();
                    pStmt.close();

                    frame.setProcess(100);

                } catch (SQLException ex) {
                    ex.printStackTrace();

                } finally {
                    if (stmt != null)
                        stmt.close();
                }
                mapper.cleanup();

                frame.incOverall();
            }

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {
            frame.getProcessProgress().setIndeterminate(true);
            frame.setDesc("Loading updated schema...");

            if (!status) {
                //UIRegistry.showLocalizedError("SCHEMA_UPDATE_ERROR", errMsgStr);
                JTextArea ta = UIHelper.createTextArea();
                ta.setText(errMsgStr);
                CellConstraints cc = new CellConstraints();
                PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g"));
                pb.add(new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), cc.xy(1, 1));
                pb.setDefaultDialogBorder();

                CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(),
                        getResourceString("SCHEMA_UPDATE_ERROR"), true, pb.getPanel());
                UIHelper.centerAndShow(dlg);
            }

            dbmsMgr.close();
        }
    }

    return statusOK;
}

From source file:net.tourbook.export.gpx.DialogExportTour.java

private void doExport() throws IOException {

    // disable button's
    getButton(IDialogConstants.OK_ID).setEnabled(false);
    getButton(IDialogConstants.CANCEL_ID).setEnabled(false);

    final String completeFilePath = _txtFilePath.getText();

    final boolean isOverwriteFiles = _chkOverwriteFiles.getSelection();
    final boolean isCamouflageSpeed = _chkCamouflageSpeed.getSelection();
    final float[] camouflageSpeed = new float[1];
    try {/*from   w ww  .j a v a  2s  .  com*/
        camouflageSpeed[0] = Float.parseFloat(_txtCamouflageSpeed.getText());
    } catch (final NumberFormatException e) {
        camouflageSpeed[0] = 0.1F;
    }
    camouflageSpeed[0] *= UI.UNIT_VALUE_DISTANCE / 3.6f;

    final ArrayList<GarminTrack> trackList = new ArrayList<GarminTrack>();
    final ArrayList<GarminWaypoint> wayPointList = new ArrayList<GarminWaypoint>();

    final FileCollisionBehavior fileCollisionBehaviour = new FileCollisionBehavior();

    if (_tourDataList.size() == 1) {

        // export one tour

        final TourData tourData = _tourDataList.get(0);

        final GarminLap tourLap = getLap(tourData, _chkExportNotes.getSelection());

        final GarminTrack track = getTrack(tourData, TourManager.getTourDateTime(tourData), isCamouflageSpeed,
                camouflageSpeed[0]);

        if (track != null) {
            trackList.add(track);
        }

        if (_chkExportMarkers.getSelection()) {
            // get markers when this option is checked
            getWaypoints(wayPointList, tourData);
        }

        doExportTour(tourLap, trackList, wayPointList, completeFilePath, fileCollisionBehaviour,
                isOverwriteFiles);

    } else {

        /*
         * export multiple tours
         */

        if (_chkMergeAllTours.getSelection()) {

            /*
             * merge all tours into one
             */

            _trackStartDateTime = TourManager.getTourDateTime(_tourDataList.get(0));
            DateTime trackDateTime;

            final GarminLap tourLap = new GarminLap();

            // create tracklist and lap
            for (final TourData tourData : _tourDataList) {

                mergeLap(tourLap, tourData, _chkExportNotes.getSelection());

                if (isCamouflageSpeed) {
                    trackDateTime = _trackStartDateTime;
                } else {
                    trackDateTime = TourManager.getTourDateTime(tourData);
                }

                final GarminTrack track = getTrack(tourData, trackDateTime, isCamouflageSpeed,
                        camouflageSpeed[0]);
                if (track != null) {
                    trackList.add(track);
                }
            }

            doExportTour(tourLap, trackList, wayPointList, completeFilePath, fileCollisionBehaviour,
                    isOverwriteFiles);

        } else {

            /*
             * export each tour separately
             */

            final String exportPathName = getExportPathName();
            final boolean addNotes = _chkExportNotes.getSelection();
            _progressIndicator.beginTask(_tourDataList.size());

            final Job exportJob = new Job("export files") { //$NON-NLS-1$
                @Override
                public IStatus run(final IProgressMonitor monitor) {

                    monitor.beginTask(UI.EMPTY_STRING, _tourDataList.size());
                    final IPath exportFilePath = new Path(exportPathName).addTrailingSeparator();

                    for (final TourData tourData : _tourDataList) {

                        // get filepath
                        final IPath filePath = exportFilePath.append(UI.format_yyyymmdd_hhmmss(tourData))
                                .addFileExtension(_exportExtensionPoint.getFileExtension());

                        final GarminLap tourLap = getLap(tourData, addNotes);

                        // create tracklist
                        trackList.clear();
                        final GarminTrack track = getTrack(tourData, TourManager.getTourDateTime(tourData),
                                isCamouflageSpeed, camouflageSpeed[0]);

                        if (track != null) {
                            trackList.add(track);

                            /*
                             * update dialog progress monitor
                             */
                            Display.getDefault().syncExec(new Runnable() {
                                public void run() {

                                    // display exported filepath
                                    _lblExportedFilePath.setText(NLS.bind(
                                            Messages.dialog_export_lbl_exportFilePath, filePath.toOSString()));

                                    // !!! force label update !!!
                                    _lblExportedFilePath.update();

                                    _progressIndicator.worked(1);
                                }
                            });

                            try {
                                doExportTour(tourLap, trackList, wayPointList, filePath.toOSString(),
                                        fileCollisionBehaviour, isOverwriteFiles);
                            } catch (final IOException e) {
                                e.printStackTrace();
                            }
                        }

                        // check if overwrite dialog was canceled
                        if (fileCollisionBehaviour.value == FileCollisionBehavior.DIALOG_IS_CANCELED) {
                            break;
                        }
                    }

                    return Status.OK_STATUS;
                }
            };

            exportJob.schedule();
            try {
                exportJob.join();
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}