Example usage for java.util Vector toArray

List of usage examples for java.util Vector toArray

Introduction

In this page you can find the example usage for java.util Vector toArray.

Prototype

@SuppressWarnings("unchecked")
public synchronized <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

Usage

From source file:com.flexoodb.common.FlexUtils.java

/**
* obtains an HTML Input Form prototype for the object.
*
* @param  title optional title in the XSL prorotype, can be null (ie none).
* @param  obj optional UI configuration.
* @param  obj the object containing the elements that will be used to populate the XSL.
* @return XSL string.//from   www.j  ava2 s.  c  om
* @see Hashtable
 *@see Element
*/
public String getHTMLFormPrototype(String title, Config config, Object obj, String parentclass)
        throws Exception {
    Class c = obj.getClass();
    //Method[] m = c.getMethods();
    Vector ve = retrieveMethods(c, null);
    Method[] m = new Method[ve.size()];
    ve.toArray(m);

    StringBuffer xml = new StringBuffer();
    //xml.append("<"+c.getSimpleName()+">");
    Hashtable fields = getFields(obj);

    Enumeration it = fields.keys();

    if (parentclass != null) {
        xml.append("\n<div>\n<span style=\"font-size:14px;font-weight:bold\">\n");
        xml.append("    <a onClick=\"javascript:linkchangecontent('<%var_context[" + parentclass.toLowerCase()
                + "parent]%>?id=<%var_context[" + parentclass.toLowerCase()
                + "parentid]%>','contentdyn')\" href=\"#\">\n");
        xml.append("    <%var_context[" + parentclass.toLowerCase() + "parentname]%>\n");
        xml.append("    </a>\n");
        xml.append("</span>\n</div>\n\n");
    }

    if (title != null) {
        xml.append("          <fieldset>\n            <legend>" + title
                + "</legend>\n            <div class=\"fieldsetwrap\">\n");
    } else {
        xml.append("          <fieldset>\n            <legend>New "
                + c.getSimpleName().substring(0, c.getSimpleName().length() - 4)
                + "</legend>\n            <div class=\"fieldsetwrap\">\n");
    }

    if (fields.contains("byte[]")) {
        xml.append("\n     <form class=\"webform\" id=\"" + c.getSimpleName().toLowerCase() + "\" name=\""
                + c.getSimpleName().toLowerCase()
                + "\" method=\"post\" enctype=\"multipart/form-data\" action=\"add" + c.getSimpleName()
                + ".igx\">\n");
    } else {
        xml.append("\n     <form class=\"webform\" id=\"" + c.getSimpleName().toLowerCase() + "\" name=\""
                + c.getSimpleName().toLowerCase() + "\" method=\"post\" action=\"add" + c.getSimpleName()
                + ".igx\">\n");
    }
    xml.append("     <input name=\"id\" type=\"hidden\" value=\"<%var_request[id]%>\"/>\n");

    xml.append("     <div class=\"datafieldwrap\">\n");
    xml.append("      <table class=\"datafield\">\n");

    ConfigElement ce = config.getElementConfig(c.getSimpleName());
    // if we found a config for this then we generate it in order.
    if (ce != null) {
        Map cef = ce.getFields();

        Iterator itr = cef.values().iterator();
        while (itr.hasNext()) {
            ConfigFieldInfo cfi = (ConfigFieldInfo) itr.next();

            if (cfi.visible && _types.indexOf(cfi.type) > -1) {
                if (cfi.type.equalsIgnoreCase("boolean")) {
                    if (cfi.addable) {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\">\n<SELECT id=\"select" + cfi.name
                                + "\" name=\"" + cfi.name.toLowerCase()
                                + "\">\n<OPTION SELECTED=\"\">true</OPTION>\n<OPTION>false</OPTION>\n</SELECT></td></tr>\n");
                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"></td></tr>\n");
                    }
                } else if (cfi.type.equalsIgnoreCase("byte[]") || cfi.type.equalsIgnoreCase("file")) {
                    if (cfi.addable) {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\">\n<input id=\"file" + cfi.name
                                + "\" type=\"file\" name=\"" + cfi.name.toLowerCase() + "\"/></td></tr>\n");
                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"></td></tr>\n");
                    }

                } else if (cfi.type.equalsIgnoreCase("date")) {
                    if (cfi.addable) {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\">\n<input class=\"txtdtt\" id=\"calendar"
                                + cfi.name + "\" type=\"text\" name=\"" + cfi.name.toLowerCase()
                                + "\"/><a href=\"javascript:NewCssCal('calendar" + cfi.name
                                + "','yyyymmdd','arrow',false,24,true)\"><img src=\"images/cal.gif\" width=\"16\" height=\"16\" alt=\"Pick a date\"/></a></td></tr>\n");
                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"></td></tr>\n");
                    }

                } else if (cfi.type.equalsIgnoreCase("dateTime")) {
                    if (cfi.addable) {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\">\n<input class=\"txtdtt\" id=\"calendar"
                                + cfi.name + "\" type=\"text\" name=\"" + cfi.name.toLowerCase()
                                + "\"/><a href=\"javascript:NewCssCal('calendar" + cfi.name
                                + "','yyyymmdd','arrow',true,24,false)\"><img src=\"images/cal.gif\" width=\"16\" height=\"16\" alt=\"Pick a date\"/></a></td></tr>\n");
                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"></td></tr>\n");
                    }
                } else if (cfi.type.equalsIgnoreCase("select")) {
                    if (cfi.addable) {

                        String options = null;

                        // first we check if the choices is a dynamic one
                        if (cfi.choices.indexOf("Type.") > -1) {
                            String optionname = null;
                            String idfield = null;
                            if (cfi.choices.split("=").length > 1) {
                                optionname = cfi.choices.split("=")[0] + cfi.choices.split("=")[1];
                                idfield = cfi.choices.split("=")[0];
                            } else {
                                optionname = cfi.choices;
                            }

                            options = "<%dyn_" + cfi.choices.substring(0, cfi.choices.indexOf("."))
                                    + cfi.choices.substring(cfi.choices.indexOf(".") + 1) + "Select.igx%>";

                        } else {
                            String[] choices = cfi.choices.split(",");
                            if (choices != null && choices.length > 0) {
                                for (int i = 0; i < choices.length; i++) {
                                    if (i == 0) {
                                        options = "<OPTION SELECTED=\"\" value=\"" + choices[i] + "\">"
                                                + choices[i] + "</OPTION>";
                                    } else {
                                        options = options + "<OPTION value=\"" + choices[i] + "\">" + choices[i]
                                                + "</OPTION>";
                                    }
                                }
                            } else {
                                options = "<OPTION SELECTED=\"\" value=\"Active\">Active</OPTION>\n<OPTION value=\"Suspended\">Suspended</OPTION>";
                            }
                        }

                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\">\n<SELECT id=\"select" + cfi.name
                                + "\" name=\"" + cfi.name.toLowerCase() + "\">\n" + options
                                + "\n</SELECT></td></tr>\n");

                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"></td></tr>\n");
                    }
                } else if (cfi.type.equalsIgnoreCase("textarea")) {
                    if (cfi.addable) {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"><textarea class=\"ta\" id=\"textarea"
                                + cfi.name + "\" name=\"" + cfi.name.toLowerCase() + "\" rows=\"" + cfi.rows
                                + "\" cols=\"" + cfi.columns + "\"></textarea></td></tr>\n");
                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                + ":</td><td class=\"data full\"></td></tr>\n");
                    }

                } else {
                    if (cfi.addable) {
                        if (cfi.maxlength > 0) {
                            xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                    + ":</td><td class=\"data full\"><input class=\"txt\" id=\"text" + cfi.name
                                    + "\" name=\"" + cfi.name.toLowerCase()
                                    + "\" type=\"text\" value=\"\" style=\"width: " + (cfi.maxlength * 10)
                                    + "px;\" maxlength=\"" + cfi.maxlength + "\"/></td></tr>\n");
                        } else {
                            xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                    + ":</td><td class=\"data full\"><input class=\"txt\" id=\"text" + cfi.name
                                    + "\" name=\"" + cfi.name.toLowerCase()
                                    + "\" type=\"text\" value=\"\"/></td></tr>\n");
                        }

                    } else {
                        if (cfi.maxlength > 0) {
                            xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                    + ":</td><td class=\"data full\"></td></tr>\n");
                        } else {
                            xml.append("          <tr><td class=\"lbl\">" + cfi.label
                                    + ":</td><td class=\"data full\"></td></tr>\n");
                        }
                    }
                }
            }
        }
    } else {
        while (it.hasMoreElements()) {
            String f = (String) it.nextElement();
            String t = (String) fields.get(f);

            if (t.equalsIgnoreCase("boolean")) {
                xml.append("          <tr><td class=\"lbl\">" + f
                        + ":</td><td class=\"data full\">\n<SELECT id=\"select" + f + "\" name=\""
                        + f.toLowerCase()
                        + "\">\n<OPTION SELECTED=\"\">true</OPTION>\n<OPTION>false</OPTION>\n</SELECT></td></tr>\n");
            } else if (t.equalsIgnoreCase("byte[]")) {
                xml.append("          <tr><td class=\"lbl\">" + f
                        + ":</td><td class=\"data full\">\n<input id=\"file" + f + "\" type=\"file\" name=\""
                        + f.toLowerCase() + "\"/></td></tr>\n");
            } else if (t.equalsIgnoreCase("XMLGregorianCalendar")) {
                xml.append("          <tr><td class=\"lbl\">" + f
                        + ":</td><td class=\"data full\">\n<input class=\"txtdtt\" id=\"calendar" + f
                        + "\" type=\"text\" name=\"" + f.toLowerCase()
                        + "\"/><a href=\"javascript:NewCssCal('calendar" + f
                        + "','yyyymmdd','arrow',false,24,true)\"><img src=\"images/cal.gif\" width=\"16\" height=\"16\" alt=\"Pick a date\"/></a></td></tr>\n");
            } else {
                // generate text area for common text field names
                if (_textfields.indexOf(f.toLowerCase()) > -1) {
                    xml.append("          <tr><td class=\"lbl\">" + f
                            + ":</td><td class=\"data full\"><textarea class=\"ta\" id=\"textarea" + f
                            + "\" name=\"" + f.toLowerCase()
                            + "\" rows=\"5\" cols=\"65\"></textarea></td></tr>\n");
                } else {
                    // hard coded convenience
                    if (f.equalsIgnoreCase("status")) {
                        xml.append("          <tr><td class=\"lbl\">" + f
                                + ":</td><td class=\"data full\">\n<SELECT id=\"select" + f + "\" name=\""
                                + f.toLowerCase()
                                + "\">\n<OPTION SELECTED=\"\">Active</OPTION>\n<OPTION>Suspended</OPTION>\n</SELECT></td></tr>\n");
                    } else {
                        xml.append("          <tr><td class=\"lbl\">" + f
                                + ":</td><td class=\"data full\"><input class=\"txt\" id=\"text" + f
                                + "\" name=\"" + f.toLowerCase() + "\" type=\"text\" value=\"\"/></td></tr>\n");
                    }
                }
            }
        }
    }

    xml.append("      </table>\n");
    xml.append("     </div>\n");

    xml.append("          <input type=\"button\" value=\"Save\"  onClick=\"javascript:buttonchangecontent('add"
            + c.getSimpleName() + ".igx','" + c.getSimpleName().toLowerCase() + "','contentdyn')\"/>\n");
    xml.append("     </form>\n     <div class=\"clear\"></div>\n   </div>\n    </fieldset>\n");
    xml.append("      <table><tr>\n");
    xml.append("     <td>\n");
    xml.append("     <form class=\"inlineform\" id=\"list" + c.getSimpleName().toLowerCase() + "\" name=\"list"
            + c.getSimpleName().toLowerCase() + "\" method=\"post\" action=\"list" + c.getSimpleName()
            + ".igx\">\n");
    if (parentclass != null) {
        xml.append("     <input type=\"button\" onClick=\"javascript:linkchangecontent('<%var_context["
                + parentclass.toLowerCase() + "parent]%>?id=<%var_context[" + parentclass.toLowerCase()
                + "parentid]%>','contentdyn')\" value=\"Cancel\"/>\n");
    } else {
        xml.append("     <input type=\"button\" onClick=\"javascript:linkchangecontent('list"
                + c.getSimpleName() + ".igx?from=0&amp;to=10','contentdyn')\" value=\"Cancel\"/>\n");

    }

    xml.append("     </form></td>\n");
    xml.append("      </tr></table>\n");

    //main.append("<"+c.getSimpleName()+" id=\""+id+"\" parentid=\""+parentid+"\">");
    return xml.toString();

}

From source file:uk.ac.babraham.FastQC.Modules.KmerContent.java

private synchronized void calculateEnrichment() {

    /*/*  ww w .  ja  v a  2  s . c  o  m*/
     * For each Kmer we work out whether there is a statistically
     * significant deviation in its coverage at any given position
     * compared to its average coverage over all positions.
     */

    // We'll be grouping together positions later so make up the groups now
    groups = BaseGroup.makeBaseGroups((longestSequence - MIN_KMER_SIZE) + 1);

    Vector<Kmer> unevenKmers = new Vector<Kmer>();

    Iterator<Kmer> rawKmers = kmers.values().iterator();

    while (rawKmers.hasNext()) {
        Kmer k = rawKmers.next();
        char[] chars = k.sequence().toCharArray();

        long totalKmerCount = 0;

        // This gets us the total number of Kmers of this type in the whole
        // dataset.
        for (int i = 0; i < totalKmerCounts.length; i++) {
            totalKmerCount += totalKmerCounts[i][k.sequence().length() - 1];
        }

        // This is the expected proportion of all Kmers which have this
        // specific Kmer sequence.  We no longer make any attempt to judge
        // overall enrichment or depletion of this sequence since once you
        // get to longer lengths the distribution isn't flat anyway

        float expectedProportion = k.count / (float) totalKmerCount;

        // We now want to go through each of the positions looking for whether
        // this Kmer was seen an unexpected number of times compared to what we
        // expected from the global values

        float[] obsExpPositions = new float[groups.length];
        float[] binomialPValues = new float[groups.length];

        long[] positionCounts = k.getPositions();

        for (int g = 0; g < groups.length; g++) {
            // This is a summation of the number of Kmers of this length which
            // fall into this base group
            long totalGroupCount = 0;

            // This is a summation of the number of hit Kmers which fall within
            // this base group.
            long totalGroupHits = 0;
            for (int p = groups[g].lowerCount() - 1; p < groups[g].upperCount()
                    && p < positionCounts.length; p++) {
                totalGroupCount += totalKmerCounts[p][chars.length - 1];
                totalGroupHits += positionCounts[p];
            }

            float predicted = expectedProportion * totalGroupCount;
            //            obsExpPositions[g] = (float)(Math.log(totalGroupHits/predicted)/Math.log(2));
            obsExpPositions[g] = (float) (totalGroupHits / predicted);

            // Now we can run a binomial test to see if there is a significant
            // deviation from what we expect given the number of observations we've
            // made

            BinomialDistribution bd = new BinomialDistribution((int) totalGroupCount, expectedProportion);
            if (totalGroupHits > predicted) {
                binomialPValues[g] = (float) ((1 - bd.cumulativeProbability((int) totalGroupHits))
                        * Math.pow(4, chars.length));
            } else {
                binomialPValues[g] = 1;
            }

        }

        k.setObsExpPositions(obsExpPositions);

        // To keep this we need a p-value below 0.01 and an obs/exp above 5 (actual values are log2 transformed)
        float lowestPValue = 1;
        for (int i = 0; i < binomialPValues.length; i++) {
            //            if (binomialPValues[i] < 0.01 && obsExpPositions[i] > (Math.log(5)/Math.log(2))) {
            if (binomialPValues[i] < 0.01 && obsExpPositions[i] > 5) {
                if (binomialPValues[i] < lowestPValue) {
                    lowestPValue = binomialPValues[i];
                }
            }
        }

        if (lowestPValue < 0.01) {
            k.setLowestPValue(lowestPValue);
            unevenKmers.add(k);
        }

    }

    Kmer[] finalKMers = unevenKmers.toArray(new Kmer[0]);

    // We sort by the highest degree of enrichment over the average      
    Arrays.sort(finalKMers);

    // So we don't end up with stupidly long lists of Kmers in the
    // report we'll only report the top 20
    if (finalKMers.length > 20) {
        Kmer[] shortenedKmers = new Kmer[20];
        for (int i = 0; i < shortenedKmers.length; i++) {
            shortenedKmers[i] = finalKMers[i];
        }

        finalKMers = shortenedKmers;
    }

    // Now we take the enrichment positions for the top 6 hits and
    // record these so we can plot them on a line graph
    enrichments = new double[Math.min(6, finalKMers.length)][];
    xLabels = new String[enrichments.length];

    xCategories = new String[groups.length];

    for (int i = 0; i < xCategories.length; i++) {
        xCategories[i] = groups[i].toString();
    }

    for (int k = 0; k < enrichments.length; k++) {
        enrichments[k] = new double[groups.length];

        float[] obsExpPos = finalKMers[k].getObsExpPositions();

        for (int g = 0; g < groups.length; g++) {
            enrichments[k][g] = obsExpPos[g];
            if (obsExpPos[g] > maxGraphValue)
                maxGraphValue = obsExpPos[g];
            if (obsExpPos[g] < minGraphValue)
                minGraphValue = obsExpPos[g];
        }

        xLabels[k] = finalKMers[k].sequence();

    }

    minGraphValue = 0;

    //      System.err.println("Max value="+maxGraphValue+" min value="+minGraphValue);

    this.enrichedKmers = finalKMers;

    // Delete the initial data structure so we don't suck up more memory
    // than we have to.
    kmers.clear();

    calculated = true;
}

From source file:com.example.krishnateja.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from  w  ww . j  ava2  s .com*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            mContext.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray);
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherContract.WeatherEntry
                .buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder);

        cVVector = new Vector<ContentValues>(cur.getCount());
        if (cur.moveToFirst()) {
            do {
                ContentValues cv = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cur, cv);
                cVVector.add(cv);
            } while (cur.moveToNext());
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:com.example.android.popularmovies.FetchMovieTask.java

private void getMovieDataFromJson(String movieJsonStr, String sortType) throws JSONException {

    //final String LOG_TAG = getMovieDataFromJson.class.getSimpleName();

    final String LOG_TAG = "getMovieDataFromJson";

    // These are the names of the JSON objects that need to be extracted.
    final String MDB_RESULTS = "results";
    final String MDB_POPULARITY = "popularity";
    final String MDB_ORIGINAL_TITLE = "original_title";
    final String MDB_POSTER_PATH_THUMBNAIL = "poster_path";
    final String MDB_PLOT_SYNOPSIS = "overview";
    final String MDB_USER_RATING = "vote_average";
    final String MDB_RELEASE_DATE = "release_date";
    final String MDB_ID = "id";

    try {//from  ww w . j a v a2s  . c  o  m
        JSONObject movieJson = new JSONObject(movieJsonStr);
        JSONArray movieArray = movieJson.getJSONArray(MDB_RESULTS);

        // Insert the new  movie information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(movieArray.length());

        for (int i = 0; i < movieArray.length(); i++) {
            // Get the JSON object representing the movie
            JSONObject singleMovie = movieArray.getJSONObject(i);

            ContentValues movieValues = new ContentValues();

            String yy = mContext.getString(R.string.pref_sort_favourite);

            if (sortType.equals(mContext.getString(R.string.pref_sort_popular))) {
                Log.v(LOG_TAG, "Sort: Order Popular");

                movieValues.put(MovieListEntry.COLUMN_MOVIE_ID, singleMovie.getString(MDB_ID));
                movieValues.put(MovieListEntry.COLUMN_POPULARITY, singleMovie.getInt(MDB_POPULARITY));
                movieValues.put(MovieListEntry.COLUMN_ORIGINAL_TITLE,
                        singleMovie.getString(MDB_ORIGINAL_TITLE));
                movieValues.put(MovieListEntry.COLUMN_PLOT_SYNOPSIS, singleMovie.getString(MDB_PLOT_SYNOPSIS));
                movieValues.put(MovieListEntry.COLUMN_USER_RATING, singleMovie.getDouble(MDB_USER_RATING));
                movieValues.put(MovieListEntry.COLUMN_RELEASE_DATE, singleMovie.getString(MDB_RELEASE_DATE));
                movieValues.put(MovieListEntry.COLUMN_POSTER_PATH_THUMBNAIL,
                        singleMovie.getString(MDB_POSTER_PATH_THUMBNAIL));

            } else if (sortType.equals(mContext.getString(R.string.pref_sort_highestrated))) {
                Log.v(LOG_TAG, "Sort: Order Highest Rated");
                movieValues.put(HighestRatedMovies.COLUMN_MOVIE_ID, singleMovie.getString(MDB_ID));
                movieValues.put(HighestRatedMovies.COLUMN_POPULARITY, singleMovie.getInt(MDB_POPULARITY));
                movieValues.put(HighestRatedMovies.COLUMN_ORIGINAL_TITLE,
                        singleMovie.getString(MDB_ORIGINAL_TITLE));
                movieValues.put(HighestRatedMovies.COLUMN_PLOT_SYNOPSIS,
                        singleMovie.getString(MDB_PLOT_SYNOPSIS));
                movieValues.put(HighestRatedMovies.COLUMN_USER_RATING, singleMovie.getDouble(MDB_USER_RATING));
                movieValues.put(HighestRatedMovies.COLUMN_RELEASE_DATE,
                        singleMovie.getString(MDB_RELEASE_DATE));
                movieValues.put(HighestRatedMovies.COLUMN_POSTER_PATH_THUMBNAIL,
                        singleMovie.getString(MDB_POSTER_PATH_THUMBNAIL));

            } else if (sortType.equals(mContext.getString(R.string.pref_sort_favourite))) {
                Log.v(LOG_TAG, "Sort: Order Favorite");
                movieValues.put(MovieListEntry.COLUMN_MOVIE_ID, singleMovie.getString(MDB_ID));
                movieValues.put(MovieListEntry.COLUMN_POPULARITY, singleMovie.getInt(MDB_POPULARITY));
                movieValues.put(MovieListEntry.COLUMN_ORIGINAL_TITLE,
                        singleMovie.getString(MDB_ORIGINAL_TITLE));
                movieValues.put(MovieListEntry.COLUMN_PLOT_SYNOPSIS, singleMovie.getString(MDB_PLOT_SYNOPSIS));
                movieValues.put(MovieListEntry.COLUMN_USER_RATING, singleMovie.getDouble(MDB_USER_RATING));
                movieValues.put(MovieListEntry.COLUMN_RELEASE_DATE, singleMovie.getString(MDB_RELEASE_DATE));
                movieValues.put(MovieListEntry.COLUMN_POSTER_PATH_THUMBNAIL,
                        singleMovie.getString(MDB_POSTER_PATH_THUMBNAIL));

                //Default oto Highest Rated Movie view if sort order preference is favorite and no movie is marked as favorite
                // Display Message to user

            } else {
                Log.d(LOG_TAG, "Sort Order Not Found:" + sortType);
            }

            cVVector.add(movieValues);
        }
        int inserted = 0;

        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            if (sortType.equals(mContext.getString(R.string.pref_sort_popular))) {
                inserted = mContext.getContentResolver().bulkInsert(MovieListEntry.CONTENT_URI, cvArray);
            } else if (sortType.equals(mContext.getString(R.string.pref_sort_highestrated))) {
                inserted = mContext.getContentResolver().bulkInsert(HighestRatedMovies.CONTENT_URI, cvArray);
            }
        }

        // Log.d(LOG_TAG, "FetchMovieTask Complete. " + cVVector.size() + " Inserted");
        Log.d(LOG_TAG, "FetchMovieTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }

}

From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p>/*  w ww.  j a  v  a  2 s.co m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        GregorianCalendar calendar = new GregorianCalendar();
        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            ContentResolver contentResolver = getContext().getContentResolver();
            inserted = contentResolver.bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
            contentResolver.delete(WeatherEntry.CONTENT_URI, WeatherEntry.COLUMN_DATE + "<= " + "?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianStartDay - 1)) });

            notifyWeather();
        }
        Log.d(TAG, "getWeatherDataFromJson: " + inserted + " inserted");
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/*from   w  ww  . java2  s  .c o m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            getContext().getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray);

            // delete old data so we don't build up an endless history
            getContext().getContentResolver().delete(WeatherContract.WeatherEntry.CONTENT_URI,
                    WeatherContract.WeatherEntry.COLUMN_DATE + " <= ?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianStartDay - 1)) });

            notifyWeather();
        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.example.rafa.sunshine.app.experiments.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//ww w. ja  va2  s. co  m
 */

//Agafa les dades en format JSON i les introdueix a la db.
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:focusedCrawler.util.parser.PaginaURL.java

protected void separadorTextoCodigo(String arquivo) { // arquivo equivale ao codigo HTML da pagina
    if (codes.size() == 0) {
        loadHashCodes();//  w  ww. ja va 2  s.co m
    }

    //       System.out.println(arquivo);   
    boolean obj_isRDF = false;
    boolean ignorar_espacos = true;
    boolean tag_tipo_fim = false;
    boolean tag_tipo_vazia = true;
    boolean em_script = false;
    boolean ehInicioALT = true;
    boolean em_titulo = false;
    boolean em_option = false;
    boolean em_comentario = false;
    int num_comentario = 0;
    int PONTUACAO_PALAVRAS_TEXTO = 2;
    int PONTUACAO_PALAVRAS_OPTION = 1;
    int PONTUACAO_PALAVRAS_URL = 3;
    int PONTUACAO_PALAVRAS_META = 1;
    int PONTUACAO_PALAVRAS_TITULO = 7;
    int PONTUACAO_PALAVRAS_DESCRIPTION = 5;
    int PONTUACAO_PALAVRAS_ALT = 1;
    int posicao_da_palavra = 1;
    int numOfHtmlTags = 0;

    // UTILIZANDO AS PALAVRAS DA URL COMO INFORMACAO TEXTUAL
    if (pagina != null && !filterURL) {

        StringTokenizer url_pontos = new StringTokenizer(pagina.getHost(), "./:");

        while (url_pontos.hasMoreTokens()) {
            String parte_host = url_pontos.nextToken();

            if (!parte_host.equals("www") && !parte_host.equals("org") && !parte_host.equals("gov")
                    && !parte_host.equals("com") && !parte_host.equals("br")) {

                boolean adicionou = adicionaAoVetorDeTexto(parte_host);

                if (adicionou) {
                    adicionaTermoPosicao(parte_host, posicao_da_palavra); // atualiza o centroide
                    adicionaPontuacaoTermo(parte_host, PONTUACAO_PALAVRAS_URL);
                    String parte_host_sem_acento = Acentos.retirarNotacaoHTMLAcentosANSI(parte_host);
                    if (!parte_host_sem_acento.equals(parte_host)) {
                        adicionou = adicionaAoVetorDeTexto(parte_host_sem_acento);
                        if (adicionou) {
                            adicionaTermoPosicao(parte_host_sem_acento, posicao_da_palavra); // atualiza o centroide
                            adicionaPontuacaoTermo(parte_host_sem_acento, PONTUACAO_PALAVRAS_URL);
                        }
                    }
                    posicao_da_palavra++;
                }
            }
        }

    }

    boolean em_body = false;
    boolean em_meta_robots = false;
    boolean tagScript = false;
    boolean tagTitulo = false;
    boolean tagBody = false;
    boolean tagOption = false;
    int pos_caracter_especial = -1;
    char quote_char = '\0';
    URL base = pagina; // pagina = URL da pagina atual...

    Vector frames = new Vector();
    char c = '\0';
    char ant1 = '\0';
    char ant2 = '\0';
    int n = 0;
    int n_anterior = 0;
    String str = "";
    String anchor = "";
    int numOfwordsAnchor = 0;

    LinkNeighborhood ln = null;
    String tagName = "";
    String lastTag = "";
    String atributo = "";

    boolean insideATag = false;

    boolean em_meta_description = false; // thiago
    String str_da_metatag_description = null; // thiago

    final int INICIO = 1;
    final int TAG_NAME = 2;
    final int TOKEN_PALAVRA = 3;
    final int PALAVRA = 4;
    final int ATRIBUTO = 5;
    final int FECHANDO = 6;
    final int IGUAL = 7;
    final int VALOR = 8;
    final int META_TAG = 10;
    final int ALT_TAG = 11;
    int estado = INICIO;

    try {

        //          FileOutputStream fout = null;
        //          DataOutputStream dout = null;
        //System.out.println("FORM!!! : " + form.getURL());
        //            try {
        //              fout = new FileOutputStream("/home/lbarbosa/test");
        //               dout = new DataOutputStream( fout );
        //              dout.writeBytes("begin");
        //
        //            }
        //            catch (FileNotFoundException ex) {
        //              ex.printStackTrace();
        //                 }
        //            catch (IOException ex) {
        //              ex.printStackTrace();
        //         }

        while (n < arquivo.length()) {
            if (n_anterior < n) { /* we advanced a character */
                ant1 = ant2;
                ant2 = c;
            }

            n_anterior = n;
            c = arquivo.charAt(n);
            //                System.out.print(c+"");
            //                int ascii = (int) c;
            //                System.out.print(ascii);
            //                System.out.println("");
            //                dout.writeBytes(c+"");
            //                dout.flush();
            //                if(c=='\u0000'){
            //                   organizaDados();
            //                   return;
            //                }
            if (em_comentario && num_comentario > 0) {
                if ((ant1 == '-') && (ant2 == '-') || (c == '>')) {
                    num_comentario--;
                    if (num_comentario == 0)
                        em_comentario = false;
                }

                n++;
            } else if (ignorar_espacos) {
                if (Character.isWhitespace(c)) {
                    n++;
                } else {
                    ignorar_espacos = false;
                }
            } else {
                boolean fimDeString = false;

                switch (estado) {

                case INICIO:

                    /* INICIO - Esperando texto ou caracter de abertura de tag '<' */

                    // System.out.println("Entrei no inicio e caractere=" + c);
                    if (c == '<') {
                        estado = TAG_NAME;
                        tagName = "";
                        tag_tipo_fim = false;
                        em_meta_robots = false;
                        n++;
                    } else {
                        estado = TOKEN_PALAVRA;
                        pos_caracter_especial = -1;
                    }

                    quote_char = '\0';

                    break;

                case TOKEN_PALAVRA:
                    //                       if(str.contains("1044")){
                    //                          System.out.println("TEST");
                    //                       }
                    /* faz o token da string */
                    if ((caracterFazParteDePalavra(c)) || (c == ';') || (c == '&')) {
                        str += converteChar(c);
                        n++;
                        int begin = str.indexOf("&#");
                        int end = str.indexOf(";");
                        if (begin != -1 && end != -1) {
                            String specialchar = str.substring(begin + 2, end);
                            try {
                                int hex = Integer.parseInt(specialchar);
                                char uni = (char) hex;
                                String unicode = uni + "";
                                str = str.substring(0, begin) + unicode;
                                //                             System.out.println(unicode);
                                pos_caracter_especial = -1;
                                continue;
                            } catch (Exception e) {
                                // TODO: handle exception
                            }
                        }
                        if (str.toLowerCase().contains("&ntilde;")) {
                            str = str.toLowerCase().replace("&ntilde;", "n");
                            pos_caracter_especial = -1;
                            continue;
                        }
                        if (str.contains("")) {
                            str = str.replace("", "n");
                            pos_caracter_especial = -1;
                            continue;
                        }
                        if (c == '&') {
                            pos_caracter_especial = n;
                        } else
                        //                               System.out.println(str + ":" + pos_caracter_especial);
                        if (pos_caracter_especial != -1) {
                            int posicao = str.length() - (n - pos_caracter_especial) - 1;
                            char ch = caracterEspecial(str, posicao);

                            if (ch != '\0') {
                                if (caracterFazParteDePalavra(ch)) {
                                    str = str.substring(0, posicao) + converteChar(ch);
                                } else {
                                    str = str.substring(0, posicao);
                                    estado = PALAVRA;

                                    if (em_titulo) {
                                        titulo += str + ch;
                                    }
                                }
                            }
                            if ((c == ';') || (n - pos_caracter_especial) > 9) {
                                pos_caracter_especial = -1;
                            }
                        }
                    } else {
                        estado = PALAVRA;

                        if (em_titulo) {
                            titulo += str;
                        }
                        if (!(c == '<')) {
                            if (em_titulo) {
                                //                                   if(!Character.isLetterOrDigit(c)){
                                //                                      c = ' ';
                                //                                   }
                                titulo += c;
                            }

                            n++;
                        }
                    }

                    break;

                case PALAVRA:
                    //                      System.out.println("PALAVRA:"+lastTag);
                    if (insideATag) {
                        anchor = anchor + " " + str.toLowerCase();

                        numOfwordsAnchor++;
                        //                                                  insideATag = false;

                        //                          System.out.println("ANCHOR:"+anchor);
                    }
                    //                      if(anchor.indexOf("school") != -1){
                    //                        System.out.println("TEST");
                    //                      }
                    /* PALAVRA - palavra pronta */
                    if (!em_script && (str.length() > 0)) {
                        if (em_body && paragrafo.length() + str.length() < MAX_PARAGRAPH_SIZE) {
                            if (Character.isWhitespace(c)) {
                                paragrafo += str + c; // atualiza variavel paragrafo
                            } else {
                                paragrafo += str + " ";
                            }
                        }

                        if (!em_titulo) {
                            boolean adicionou = adicionaAoVetorDeTexto(str);
                            if (adicionou) {
                                around.add(str);
                                adicionaTermoPosicao(str, posicao_da_palavra); // atualiza o centroide
                                if (em_option) {
                                    adicionaPontuacaoTermo(str, PONTUACAO_PALAVRAS_OPTION);
                                } else {
                                    adicionaPontuacaoTermo(str, PONTUACAO_PALAVRAS_TEXTO);
                                }
                                String str_sem_acento = Acentos.retirarNotacaoHTMLAcentosANSI(str);
                                if (!str_sem_acento.equals(str)) {
                                    adicionou = adicionaAoVetorDeTexto(str_sem_acento);
                                    if (adicionou) {
                                        adicionaTermoPosicao(str_sem_acento, posicao_da_palavra); // atualiza o centroide
                                        if (em_option) {
                                            adicionaPontuacaoTermo(str_sem_acento, PONTUACAO_PALAVRAS_OPTION);
                                        } else {
                                            adicionaPontuacaoTermo(str_sem_acento, PONTUACAO_PALAVRAS_TEXTO);
                                        }
                                    }
                                }
                                posicao_da_palavra++;
                            }
                        } else {
                            boolean adicionou = adicionaAoVetorDeTexto(str);
                            if (adicionou) {
                                adicionaTermoPosicao(str, posicao_da_palavra); // atualiza o centroide
                                adicionaPontuacaoTermo(str, PONTUACAO_PALAVRAS_TITULO);
                                String str_sem_acento = Acentos.retirarNotacaoHTMLAcentosANSI(str);
                                if (!str_sem_acento.equals(str)) {
                                    adicionou = adicionaAoVetorDeTexto(str_sem_acento);
                                    if (adicionou) {
                                        adicionaTermoPosicao(str_sem_acento, posicao_da_palavra); // atualiza o centroide
                                        adicionaPontuacaoTermo(str_sem_acento, PONTUACAO_PALAVRAS_TITULO);
                                    }
                                }
                                posicao_da_palavra++;
                            }
                        }
                    }

                    estado = INICIO;
                    ignorar_espacos = true;
                    str = "";

                    break;

                case TAG_NAME:

                    /* TAG_NAME - terminated by space, \r, \n, >, / */
                    if (em_script) {
                        if (c != '>') {
                            if ("/script".startsWith(str + c) || "/SCRIPT".startsWith(str + c)
                                    || "/style".startsWith(str + c) || "/STYLE".startsWith(str + c)) {
                                str += c;
                            } else {
                                str = "";
                                estado = INICIO;
                            }
                            n++;
                        } else if (c == '>') {
                            if (str.equalsIgnoreCase("/script") || str.equalsIgnoreCase("/style")) {
                                fimDeString = true;
                                tag_tipo_fim = true;
                                tagScript = true;
                                estado = FECHANDO;
                            } else {
                                n++;
                            }
                        }
                    } else {
                        if (str.equals("BASE")) {
                            //                                System.out.println("EM TAG_NAME, str="+str + ", c="+c+", tagTitulo="+tagTitulo);
                            if (c == '>') {
                                estado = FECHANDO;
                            } else {
                                n++;
                            }
                        } else {
                            //                                if ((c == '"') || (c == '\'')) {
                            //                                if ((c == '\'')) {
                            //                                    organizaDados(); //new
                            //                                    return;    /* error - these are not allowed in tagname */
                            //                                } else 
                            if (c == ' ') {

                                /*
                                 * Note: Both mozilla and XML don't allow any spaces between < and tagname.
                                 * Need to check for zero-length tagname.
                                 */
                                //                                    if (str.length() == 0) {
                                //                                        organizaDados(); //new
                                //                                        return;    /* str is the buffer we're working on */
                                //                                    }

                                fimDeString = true;
                                estado = ATRIBUTO;
                                ignorar_espacos = true;
                                n++;
                            } else if (c == '/') {
                                if (tagName.length() == 0) {
                                    tag_tipo_fim = true; /* indicates end tag if no tag name read yet */
                                } else if (obj_isRDF) { /* otherwise its an empty tag (RDF only) */
                                    fimDeString = true;
                                    tag_tipo_vazia = true;
                                    estado = FECHANDO;
                                }
                                //                                    else {
                                //                                        organizaDados(); //new
                                //                                        return;
                                //                                    }

                                n++;
                            } else if (c == '>') {
                                fimDeString = true;
                                //                                tag_tipo_fim = true;
                                estado = FECHANDO;
                            } else if ((c != '\r') && (c != '\n')) {

                                // System.out.println("Estou NO CAMINHO CERTO!!!!");
                                str += c;
                                n++;
                            } else {
                                fimDeString = true;
                                estado = ATRIBUTO; /* note - mozilla allows newline after tag name */
                                ignorar_espacos = true;
                                n++;
                            }

                            if (fimDeString) {
                                //if (str.equals("!--")) {    /* html comment */
                                if (str.startsWith("!--")) { /* html comment */
                                    em_comentario = true;
                                    num_comentario++;
                                    estado = INICIO;
                                } else {
                                    str = str.toLowerCase();
                                    tagName = str;
                                    tagBody = str.equals("body");
                                    tagTitulo = str.equals("title");
                                    tagOption = str.equals("option");
                                    if (tagName.equals("html")) {
                                        if (!tag_tipo_fim) {
                                            numOfHtmlTags++;
                                        } else {
                                            numOfHtmlTags--;
                                        }
                                        //                                           System.out.println(">>>>>>>>>>>>>" + numOfHtmlTags);
                                    }

                                    //if (tagTitulo) {
                                    //    System.out.println("achot tag titulo " + str);
                                    //}
                                    tagScript = str.equals("script") || str.equals("style");

                                    if (str.equals("form")) {
                                        this.forms++;
                                    }
                                }

                                str = "";
                                fimDeString = false;
                            }

                            // System.out.println("A STRING DO ATRIBUTO EH: " + str + " estado novo "+ estado);
                        }
                    }
                    break;

                case FECHANDO:
                    /* FECHANDO - expecting a close bracket, anything else is an error */
                    //                        System.out.println("END OF TAG:"+tagName);
                    //                        if(ln!=null){
                    //                          ln.setAnchor(anchor);
                    //                          System.out.println("URL---"+ln.getLink());
                    //                         System.out.println("ANC---"+ln.getAnchor());
                    //                      }

                    if ((tag_tipo_fim && tagName.equals("a")) || tagName.equals("area")) {

                        insideATag = false;
                        if (ln != null) {
                            Vector anchorTemp = new Vector();
                            //                          System.out.println("URL---"+ln.getLink());
                            //                          System.out.println("ANC---"+anchor);
                            StringTokenizer tokenizer = new StringTokenizer(anchor, " ");
                            while (tokenizer.hasMoreTokens()) {
                                anchorTemp.add(tokenizer.nextToken());
                            }
                            String[] anchorArray = new String[anchorTemp.size()];
                            anchorTemp.toArray(anchorArray);
                            ln.setAnchor(anchorArray);
                            ln.setAroundPosition(around.size());
                            ln.setNumberOfWordsAnchor(numOfwordsAnchor);
                            linkNeigh.add(ln.clone());
                            //                            anchor = "";
                            ln = null;
                        }
                        anchor = "";
                    }
                    // System.out.println("Entrei em fechando");
                    if (c == '>') {
                        if (tagScript) {

                            /* we're inside a script tag (not RDF) */
                            em_script = !tag_tipo_fim;
                        }

                        if (tagTitulo) {
                            em_titulo = !tag_tipo_fim;
                            //System.out.println("EM tag titulo " + str + ", em_titulo"+ em_titulo);
                            //System.out.println("EM tag titulo " + str + ", tag_tipo_fim"+ tag_tipo_fim);
                            //System.out.println("EM tag titulo " + str + ", tagTitulo"+ tagTitulo);
                        }

                        if (tagBody) {
                            em_body = !tag_tipo_fim;

                            // System.out.println("Entrei no estado inicial");
                        }
                        if (tagOption) {
                            em_option = !tag_tipo_fim;

                            // System.out.println("Entrei no estado inicial");
                        }
                        //                            if(tag_tipo_fim && tagName.equals("html") && numOfHtmlTags == 0){
                        //                                organizaDados();
                        //                                return;
                        //                            }

                        tagTitulo = false;
                        tagBody = false;
                        tagScript = false;
                        tagOption = false;
                        estado = INICIO;
                        str = "";
                        tagName = "";

                        numOfwordsAnchor = 0;
                        ignorar_espacos = true;
                        n++;
                    } else {

                        organizaDados(); //new
                        return; /* error */
                    }

                    break;

                case ATRIBUTO:

                    /* ATRIBUTO - expecting an attribute name, or / (RDF only) or > indicating no more attributes */

                    /*
                     * accept attributes without values, such as <tag attr1 attr2=val2>
                     * or <tag attr2=val2 attr1>
                     */
                    if (quote_char == c) {
                        quote_char = '\0'; /* close quote */
                    } else if (((c == '"') || (c == '\'')) && (quote_char == '\0')) {

                        /* start a quote if none is already in effect */
                        quote_char = c;
                    }

                    if (quote_char == '\0') {
                        if ((((c == '/') && obj_isRDF) || (c == '>')) && (str.length() == 0)) {
                            estado = FECHANDO;
                        } else if ((c == ' ') || (c == '=') || (c == '\n') || (c == '\r')
                                || ((c == '/') && obj_isRDF) || (c == '>')) {
                            atributo = str;
                            str = "";
                            estado = IGUAL;
                            //System.out.println("[ATRIBUTO c='"+c+"', estado=IGUAL], atributo="+atributo);
                            /* if non-null attribute name */
                        } else {
                            str += c;
                            n++;
                        }
                    } else {
                        str += c;
                        n++;
                    }

                    break;

                case IGUAL:
                    atributo = atributo.toLowerCase();
                    tagName = tagName.toLowerCase();

                    // System.out.println("------------------------------------");
                    // System.out.println(" A TAG NAME EH: " + tagName);
                    // if(atributo.equals("src") && tagName.equals("img") && (c == '='))
                    // {
                    // ignorar_espacos = true;
                    // estado = IMAGEM;
                    // n++;
                    // }
                    // else
                    // {
                    /****
                                            if (atributo.equals("content")
                        && tagName.equals("meta") && (c == '=')) {
                    ignorar_espacos = true;
                    estado = META_TAG;
                    n++;
                                            } else if (atributo.equals("alt")
                                && tagName.equals("img") && (c == '=')) {
                    ignorar_espacos = true;
                    estado = ALT_TAG;
                    n++;
                                            } else {
                    ***/
                    if ((c == ' ') || (c == '\n') || (c == '\r')) {
                        ignorar_espacos = true;
                        n++;
                    } else if (c == '=') {
                        ignorar_espacos = true;
                        estado = VALOR;
                        n++;
                    } else { /* no value for the attribute - error in RDF? */
                        str = "";
                        atributo = "";

                        // estado = ATRIBUTO;
                        if (c == '>') {
                            // System.out.println("Entrei aqui no MENOR QUE");
                            tagScript = false;
                            tagBody = false;
                            tagTitulo = false;
                            estado = FECHANDO;
                        } else {
                            ignorar_espacos = true;

                            // System.out.println("Entrei PARA ANDAR NA LINHA");
                            n++;
                        }
                    }
                    //                        }

                    // }
                    break;

                case ALT_TAG: // nao usa mais, foi mudado, ver no estado VALOR 
                    if (((c == ' ') || (c == '"')) && ehInicioALT) {
                        ignorar_espacos = false;

                        boolean adicionou = adicionaAoVetorDeTexto(str);
                        if (adicionou) {
                            adicionaTermoPosicao(str, posicao_da_palavra); // atualiza o centroide
                            adicionaPontuacaoTermo(str, PONTUACAO_PALAVRAS_ALT);
                            String str_sem_acento = Acentos.retirarNotacaoHTMLAcentosANSI(str);
                            if (!str_sem_acento.equals(str)) {
                                adicionou = adicionaAoVetorDeTexto(str_sem_acento);
                                if (adicionou) {
                                    adicionaTermoPosicao(str_sem_acento, posicao_da_palavra); // atualiza o centroide
                                    adicionaPontuacaoTermo(str_sem_acento, PONTUACAO_PALAVRAS_ALT);
                                }
                            }
                            posicao_da_palavra++;
                        }

                        str = "";
                        ehInicioALT = false;
                    } else {
                        if (c == '>') {
                            //                                estado = INICIO; //nao sei se esta' ok
                            estado = VALOR;
                            ehInicioALT = true;
                        } else {
                            if (c == '.' || c == ',') {
                            } else {
                                if ((c != '\0') && (c != '\r') && (c != '\n') && (c != '"')) {
                                    str += c;
                                } else {
                                    if (c == '"') {
                                        estado = ATRIBUTO;
                                        ehInicioALT = true;
                                    }
                                }
                            }
                        }
                    }

                    n++;

                    break;

                case META_TAG: // nao usa mais, foi mudado, ver no estado VALOR [ogm]
                    if ((c == ' ') || (c == '"') || (c == '\n') || (c == ',')) {
                        ignorar_espacos = false;

                        textoMeta.addElement(str); // adiciona a palavra na variavel texto

                        for (int contadorI = 0; contadorI < PONTUACAO_PALAVRAS_META; contadorI++) {
                            adicionaTermoMetaPosicao(str, textoMeta.size());
                        }

                        str = "";
                    } else {
                        if (c == '>') {
                            estado = INICIO;
                            //                                estado = VALOR;
                        } else {
                            if (c == '.' || c == ',') {
                            } else {
                                if ((c != '\0') && (c != '\r') && (c != '\n') && (c != '"')) {
                                    str += c;
                                }
                            }
                        }
                    }

                    n++;

                    break;

                case VALOR:

                    /* expecting a value, or space, / (RDF only), or > indicating end of value. */
                    /* whether the current character should be included in value */
                    boolean include = true;
                    //                        System.out.println("LENGTH:"+str.length());
                    //                        if(str.length() > 300){
                    //                          System.out.println("TEST");
                    //                        }
                    if (quote_char == c || str.length() > 10000) {
                        quote_char = '\0'; /* close quote */
                        include = false;
                    } else if (((c == '"') || (c == '\'')) && (quote_char == '\0')) {

                        /* start a quote if none is already in effect */
                        quote_char = c;
                        include = false;

                    }

                    if (quote_char == '\0') {
                        if ((c == '/') && obj_isRDF) {
                            fimDeString = true;
                            estado = FECHANDO;
                            n++;
                            //                            } else if (c == '>' || str.length() > 10000) {
                        } else if (c == '>' || str.length() > 100000) {
                            fimDeString = true;
                            estado = FECHANDO;
                        } else if ((c == ' ') || (c == '\r') || (c == '\n')) {
                            fimDeString = true;
                            ignorar_espacos = true;
                            estado = ATRIBUTO; /* if non-null value name */
                            n++;
                        } else if (include) {
                            str += c;
                            n++;
                        } else {
                            n++;
                        }
                    } else if (include) {
                        str += c;
                        n++;
                    } else {
                        n++;
                    }

                    if (fimDeString) {
                        tagName = tagName.toLowerCase();

                        //                            System.out.println("TAG:"+tagName);
                        atributo = atributo.toLowerCase();

                        //                            System.out.println("[VALOR, estado='"+estado+"', c="+c+"] "+tagName+"."+atributo+"="+str);

                        if (tagName.equals("a") && atributo.equals("href")) {
                            insideATag = true;
                            String urlTemp = adicionaLink(str, base);
                            //                                  System.out.println("----URL:"+urlTemp);
                            if (urlTemp != null && urlTemp.startsWith("http")) {
                                if (ln != null) {
                                    Vector anchorTemp = new Vector();
                                    StringTokenizer tokenizer = new StringTokenizer(anchor, " ");
                                    while (tokenizer.hasMoreTokens()) {
                                        anchorTemp.add(tokenizer.nextToken());
                                    }
                                    String[] anchorArray = new String[anchorTemp.size()];
                                    anchorTemp.toArray(anchorArray);
                                    ln.setAnchor(anchorArray);
                                    ln.setAroundPosition(around.size());
                                    ln.setNumberOfWordsAnchor(numOfwordsAnchor);
                                    linkNeigh.add(ln.clone());
                                    anchor = "";
                                    ln = null;
                                }
                                ln = new LinkNeighborhood(new URL(urlTemp));
                            }
                            //                                System.out.println("CREATE LINK:"  + urlTemp);
                        } else if (tagName.equals("link") && atributo.equals("href")) {
                            String urlTemp = adicionaLink(str, base);
                            if (urlTemp != null && urlTemp.startsWith("http")) {
                                ln = new LinkNeighborhood(new URL(urlTemp));
                            }
                            //                                System.out.println("CREATE LINK:"  + urlTemp);
                        } else if (tagName.equals("area") && atributo.equals("href")) {
                            adicionaLink(str, base);
                            String urlTemp = adicionaLink(str, base);
                            if (urlTemp != null && urlTemp.startsWith("http")) {
                                ln = new LinkNeighborhood(new URL(urlTemp));
                            }
                        } else if (tagName.equals("img") && atributo.equals("src")) {
                            if (ln != null) {
                                ln.setImgSource(str);
                            }
                            try {
                                imagens.addElement(parseLink(base, str).toString());
                            } catch (Exception e) {
                                // TODO: handle exception
                            }

                        }
                        //                            else if((tagName.equals("area") || tagName.equals("a"))&& atributo.equals("alt")){
                        //                               anchor = anchor + " " + str.toLowerCase();
                        //                            } 
                        else if (tagName.equals("frame") && atributo.equals("src")) {
                            frames.addElement(str);
                            adicionaLink(str, base);
                        } else if (tagName.equals("img") && (atributo.equals("alt") || atributo.equals("title")
                                || atributo.equals("id"))) {
                            //                                System.out.println("img.alt.str="+str);
                            Vector<String> altWords = new Vector<String>();
                            StringTokenizer st = new StringTokenizer(str);
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken();
                                if (token.contains("")) {
                                    token = token.replace("", "n");
                                }
                                token = token.toLowerCase();
                                if (token.contains("&#241;")) {
                                    token = token.replace("&#241;", "n");
                                }
                                if (token.contains("&ntilde;")) {
                                    token = token.replace("&ntilde;", "n");
                                }
                                if (token.contains("")) {
                                    token = token.replace("", "n");
                                }

                                altWords.add(token);
                                if (!caracterFazParteDePalavra(token.charAt(0))) {
                                    token = token.substring(1);
                                }
                                if (token.equals("")) {
                                    break;
                                }
                                if (!caracterFazParteDePalavra(token.charAt(token.length() - 1))) {
                                    token = token.substring(0, token.length() - 1);
                                }
                                if (token.equals("")) {
                                    break;
                                }
                                boolean adicionou = adicionaAoVetorDeTexto(token);
                                if (adicionou) {
                                    adicionaTermoPosicao(token, posicao_da_palavra); // atualbejiza o centroide
                                    adicionaPontuacaoTermo(token, PONTUACAO_PALAVRAS_ALT);
                                    String token_sem_acento = Acentos.retirarNotacaoHTMLAcentosANSI(token);
                                    if (!token_sem_acento.equals(token)) {
                                        adicionou = adicionaAoVetorDeTexto(token_sem_acento);
                                        if (adicionou) {
                                            adicionaTermoPosicao(token_sem_acento, posicao_da_palavra); // atualiza o centroide
                                            adicionaPontuacaoTermo(token_sem_acento, PONTUACAO_PALAVRAS_ALT);
                                        }
                                    }
                                    posicao_da_palavra++;
                                }
                            }
                            if (ln != null) {
                                String[] current = ln.getImgAlt();
                                if (current == null) {
                                    String[] terms = new String[altWords.size()];
                                    altWords.toArray(terms);
                                    ln.setImgAlt(terms);
                                } else {
                                    String[] terms = new String[altWords.size() + current.length];
                                    int indexTerms = 0;
                                    for (int i = 0; i < current.length; i++, indexTerms++) {
                                        terms[indexTerms] = current[i];
                                    }
                                    for (int i = 0; i < altWords.size(); i++, indexTerms++) {
                                        terms[indexTerms] = altWords.elementAt(i);
                                    }
                                    ln.setImgAlt(terms);
                                }
                            }
                        } else if (tagName.equals("meta") && atributo.equals("content")) {
                            if (em_meta_description) {
                                str_da_metatag_description = str;
                                em_meta_description = false;
                                if (USAR_DESCRIPTION) {
                                    StringTokenizer st = new StringTokenizer(str);
                                    while (st.hasMoreTokens()) {
                                        String token = st.nextToken();
                                        int posicao = texto.size();
                                        boolean adicionou = adicionaAoVetorDeTexto(token);
                                        if (adicionou) {
                                            adicionaTermoPosicao(token, posicao_da_palavra); // atualiza o centroide
                                            adicionaPontuacaoTermo(token, PONTUACAO_PALAVRAS_DESCRIPTION);
                                            String token_sem_acento = Acentos
                                                    .retirarNotacaoHTMLAcentosANSI(token);
                                            if (!token_sem_acento.equals(token)) {
                                                adicionou = adicionaAoVetorDeTexto(token_sem_acento);
                                                if (adicionou) {
                                                    adicionaTermoPosicao(token_sem_acento, posicao_da_palavra); // atualiza o centroide
                                                    adicionaPontuacaoTermo(token_sem_acento,
                                                            PONTUACAO_PALAVRAS_DESCRIPTION);
                                                }
                                            }
                                            posicao_da_palavra++;
                                        }
                                    }
                                }
                            }

                            //                                System.out.println("meta.content.str="+str);
                            StringTokenizer st = new StringTokenizer(str);
                            while (st.hasMoreTokens()) {
                                String token = st.nextToken();
                                textoMeta.addElement(token); // adiciona a palavra na variavel texto
                                for (int contadorI = 0; contadorI < PONTUACAO_PALAVRAS_META; contadorI++) {
                                    adicionaTermoMetaPosicao(token, textoMeta.size());
                                }
                            }
                        } else if (tagName.equals("meta") && atributo.equals("name")) {
                            if (str.toLowerCase().equals("robot")) {
                                em_meta_robots = true;
                            }
                            if (str.toLowerCase().equals("description")
                                    || str.toLowerCase().equals("descricao")) {
                                //System.out.println("meta.description.str="+str);
                                em_meta_description = true;
                            }
                        } else if (em_meta_robots && atributo.equals("content")) {
                            if (str.toLowerCase().indexOf("noindex") != -1) {
                                noindex = true;
                            }

                            if (str.toLowerCase().indexOf("nofollow") != -1) {
                                nofollow = true;
                            }
                        } else if (tagName.equals("base") && atributo.equals("href")) {
                            try {
                                base = parseLink(pagina, str);
                            } catch (Exception e) {
                            } // ignora
                        }

                        str = "";
                        atributo = "";
                        fimDeString = false;
                    }

                    break;
                default:
                    break;
                }
            }
        }
        if (USAR_DESCRIPTION) {
            if (str_da_metatag_description != null) {
                paragrafo = str_da_metatag_description;
            }
        }
        if (estado == PALAVRA && str != null && !"".equals(str)) {
            boolean adicionou = adicionaAoVetorDeTexto(str);
            if (adicionou) {
                adicionaTermoPosicao(str, posicao_da_palavra); // atualiza o centroide
                adicionaPontuacaoTermo(str, PONTUACAO_PALAVRAS_TEXTO);
                String str_sem_acento = Acentos.retirarNotacaoHTMLAcentosANSI(str);
                if (!str_sem_acento.equals(str)) {
                    adicionou = adicionaAoVetorDeTexto(str_sem_acento);
                    if (adicionou) {
                        adicionaTermoPosicao(str_sem_acento, posicao_da_palavra); // atualiza o centroide
                        adicionaPontuacaoTermo(str_sem_acento, PONTUACAO_PALAVRAS_TEXTO);
                    }
                }
                posicao_da_palavra++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.frames = frames.size();
    this.images = imagens.size();
    organizaDados();

}

From source file:com.hangulo.powercontact.MainActivity.java

private int makeDemoData(int max) {

    showLoadingCircle(true);/*w w  w.  ja v a2 s.  com*/
    //    ?  ~~~!!!!!

    deleteDemoData();

    // ?? .

    String[] dummyNames;
    dummyNames = getResources().getStringArray(R.array.dummy_names);
    int maxNames = dummyNames.length - 1;

    Vector<ContentValues> cVVector = new Vector<>(max + 10);

    // ArrayList<PowerContactAddress> retAddress = new ArrayList<>();
    LatLng currentLatLng = getCurrentLatLng();
    double lat, lng;
    for (int i = 1; i <= (max + 2); i++) {
        // South Korea
        // double latitude = Utils.getRandomNumber((double) 36.4922565f, (double) 38.4922565f);
        // double longitude = Utils.getRandomNumber((double) 125.92319053333333f, (double) 127.92319053333333f);

        ContentValues addrValues = new ContentValues(); // addr 

        String name = dummyNames[Utils.getRandomNumber(0, maxNames)] + " :" + i;

        if (i <= max) {
            lat = Utils.getRandomNumber((currentLatLng.latitude - 1), currentLatLng.latitude + 1);
            lng = Utils.getRandomNumber(currentLatLng.longitude - 1, currentLatLng.longitude + 1);
        } else {// to make same location data
            lat = currentLatLng.latitude;
            lng = currentLatLng.longitude;
            name = "duplicated" + i;
        }

        long contactId = 100000 + i;
        long dataId = 1000000 + i;
        String lookupKey = "";

        String address = "Address Phone " + i;
        int type = 1;
        String addrLabel = "";

        // double dist = Utils.getDistanceX(currentLatLng.latitude, currentLatLng.longitude, lat, lng); // 

        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_CONTACT_ID, contactId);
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_DATA_ID, dataId);
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_LOOKUP_KEY, lookupKey);
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_NAME, name);
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_ADDR, address);
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_TYPE, type);
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_LABEL, addrLabel);

        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_LAT, lat); // ?
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_LNG, lng); //?

        // constants for calculation distance query   * http://king24.tistory.com/4
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_SIN_LAT, Math.sin(Math.toRadians(lat)));
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_SIN_LNG, Math.sin(Math.toRadians(lng)));
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_COS_LAT, Math.cos(Math.toRadians(lat)));
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_COS_LNG, Math.cos(Math.toRadians(lng)));

        // this is demo
        addrValues.put(PowerContactContract.PowerContactEntry.COLUMN_CONTACT_DATA_TYPE,
                PowerContactContract.PowerContactEntry.CONTACT_DATA_TYPE_DEMO);

        cVVector.add(addrValues); // save this row -->   ??.
    }

    // wrote to database // bulk update
    int return_count = 0;
    if (cVVector.size() > 0) {
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        return_count = getContentResolver().bulkInsert(PowerContactContract.PowerContactEntry.CONTENT_URI,
                cvArray);
    }

    showDemoInfo(return_count);

    Log.v(LOG_TAG, "makeDemoData()/dummydata input : " + return_count);

    showLoadingCircle(false);
    return return_count;
}

From source file:barqsoft.footballscores.service.FetchScores.java

private void processJSONdata(String JSONdata, Context mContext, boolean isReal) {
    Log.d("FetchScores", JSONdata);
    //JSON data//from  ww  w.j av a 2s  . co  m
    // This set of league codes is for the 2015/2016 season. In fall of 2016, they will need to
    // be updated. Feel free to use the codes
    final String BUNDESLIGA1 = "394";
    final String BUNDESLIGA2 = "395";
    final String LIGUE1 = "396";
    final String LIGUE2 = "397";
    final String PREMIER_LEAGUE = "398";
    final String PRIMERA_DIVISION = "399";
    final String SEGUNDA_DIVISION = "400";
    final String SERIE_A = "401";
    final String PRIMERA_LIGA = "402";
    final String Bundesliga3 = "403";
    final String EREDIVISIE = "404";
    final String CHAMPIONS_LEAGUE = "405";

    final String SEASON_LINK = "http://api.football-data.org/alpha/soccerseasons/";
    final String MATCH_LINK = "http://api.football-data.org/alpha/fixtures/";
    final String TEAM_LINK = "http://api.football-data.org/alpha/teams/";
    final String FIXTURES = "fixtures";
    final String LINKS = "_links";
    final String SOCCER_SEASON = "soccerseason";
    final String SELF = "self";
    final String MATCH_DATE = "date";
    final String HOME_TEAM = "homeTeamName";
    final String AWAY_TEAM = "awayTeamName";
    final String RESULT = "result";
    final String HOME_GOALS = "goalsHomeTeam";
    final String AWAY_GOALS = "goalsAwayTeam";
    final String MATCH_DAY = "matchday";
    final String HOME_ID = "homeTeam";
    final String AWAY_ID = "awayTeam";
    final String CREST_URL = "crestUrl";

    //Match data
    String League = null;
    String mDate = null;
    String mTime = null;
    String Home = null;
    String Away = null;
    String Home_goals = null;
    String Away_goals = null;
    String match_id = null;
    String match_day = null;
    String home_id = null;
    String away_id = null;
    String home_crest_url = null;
    String away_crest_url = null;

    try {
        JSONArray matches = new JSONObject(JSONdata).getJSONArray(FIXTURES);
        Log.d("FetchScores", "matches.length():" + matches.length());

        //ContentValues to be inserted
        Vector<ContentValues> values = new Vector<>(matches.length());
        for (int i = 0; i < matches.length(); i++) {

            JSONObject match_data = matches.getJSONObject(i);
            League = match_data.getJSONObject(LINKS).getJSONObject(SOCCER_SEASON).getString("href");
            League = League.replace(SEASON_LINK, "");

            home_id = match_data.getJSONObject(LINKS).getJSONObject(HOME_ID).getString("href");
            home_id = home_id.replace(TEAM_LINK, "");

            away_id = match_data.getJSONObject(LINKS).getJSONObject(AWAY_ID).getString("href");
            away_id = away_id.replace(TEAM_LINK, "");

            //This if statement controls which leagues we're interested in the data from.
            //add leagues here in order to have them be added to the DB.
            // If you are finding no data in the app, check that this contains all the leagues.
            // If it doesn't, that can cause an empty DB, bypassing the dummy data routine.

            match_id = match_data.getJSONObject(LINKS).getJSONObject(SELF).getString("href");
            match_id = match_id.replace(MATCH_LINK, "");
            if (!isReal) {
                //This if statement changes the match ID of the dummy data so that it all goes into the database
                match_id = match_id + Integer.toString(i);
            }

            mDate = match_data.getString(MATCH_DATE);
            mTime = mDate.substring(mDate.indexOf("T") + 1, mDate.indexOf("Z"));
            mDate = mDate.substring(0, mDate.indexOf("T"));
            SimpleDateFormat match_date = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
            match_date.setTimeZone(TimeZone.getTimeZone("UTC"));

            try {
                Date parseddate = match_date.parse(mDate + mTime);
                SimpleDateFormat new_date = new SimpleDateFormat("yyyy-MM-dd:HH:mm");
                new_date.setTimeZone(TimeZone.getDefault());
                mDate = new_date.format(parseddate);
                mTime = mDate.substring(mDate.indexOf(":") + 1);
                mDate = mDate.substring(0, mDate.indexOf(":"));

                if (!isReal) {
                    //This if statement changes the dummy data's date to match our current date range.
                    Date fragmentdate = new Date(System.currentTimeMillis() + ((i - 2) * 86400000));
                    SimpleDateFormat mformat = new SimpleDateFormat("yyyy-MM-dd");
                    mDate = mformat.format(fragmentdate);
                }
            } catch (Exception e) {
                Log.d(LOG_TAG, "error here!");
                Log.e(LOG_TAG, e.getMessage());
            }
            Home = match_data.getString(HOME_TEAM);
            Away = match_data.getString(AWAY_TEAM);
            Home_goals = match_data.getJSONObject(RESULT).getString(HOME_GOALS);
            Away_goals = match_data.getJSONObject(RESULT).getString(AWAY_GOALS);
            match_day = match_data.getString(MATCH_DAY);
            ContentValues match_values = new ContentValues();
            match_values.put(DatabaseContract.scores_table.MATCH_ID, match_id);
            match_values.put(DatabaseContract.scores_table.DATE_COL, mDate);
            match_values.put(DatabaseContract.scores_table.TIME_COL, mTime);
            match_values.put(DatabaseContract.scores_table.HOME_COL, Home);
            match_values.put(DatabaseContract.scores_table.AWAY_COL, Away);
            match_values.put(DatabaseContract.scores_table.HOME_GOALS_COL, Home_goals);
            match_values.put(DatabaseContract.scores_table.AWAY_GOALS_COL, Away_goals);
            match_values.put(DatabaseContract.scores_table.LEAGUE_COL, League);
            match_values.put(DatabaseContract.scores_table.HOME_ID, home_id);
            match_values.put(DatabaseContract.scores_table.AWAY_ID, away_id);
            match_values.put(DatabaseContract.scores_table.MATCH_DAY, match_day);

            values.add(match_values);
        }

        int inserted_data = 0;
        ContentValues[] insert_data = new ContentValues[values.size()];
        values.toArray(insert_data);
        inserted_data = mContext.getContentResolver().bulkInsert(DatabaseContract.BASE_CONTENT_URI,
                insert_data);
        Log.d("FetchScores", "inserted_data:" + inserted_data);
        // Update widgets data
        updateWidgets();

        // Schedule a notification to the user
        notifyUser(Integer.toString(inserted_data));

        //Log.v(LOG_TAG,"Succesfully Inserted : " + String.valueOf(inserted_data));
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage());
    }

}