List of usage examples for java.util Vector toArray
@SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a)
From source file:com.rowland.hashtrace.sync.TweetHashTracerSyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/* w w w . ja v a 2 s.c o m*/ Log.d(LOG_TAG, "Starting sync"); // Getting the hashtag to send to the API String hashTagQuery = Utility.getPreferredHashTag(getContext()); long hashTagId = addHashTag(hashTagQuery, hashTagQuery); ArrayList<Tweet> tweetArrayList = new ArrayList<Tweet>(); List<Status> statuses = new ArrayList<Status>(); try { mTwitter = Utility.getTwitter(); statuses = mTwitter.search(new Query(hashTagQuery)).getTweets(); for (Status s : statuses) { Tweet tweet = Utility.createTweet(s); tweetArrayList.add(tweet); } } catch (TwitterException e) { e.printStackTrace(); } try { // Insert the new tweet information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(tweetArrayList.size()); for (int i = 0; i < tweetArrayList.size(); i++) { // These are the values that will be collected. Tweet tweet = tweetArrayList.get(i); long tweet_id = tweet.getTweetId(); String tweet_text = tweet.getTweetText(); Date tweet_text_date = tweet.getTweetTextDate(); int tweet_text_retweet_count = tweet.getTweetRetweetCount(); int tweet_text_favourite_count = tweet.getTweetFavouriteCount(); int tweet_text_mentions_count = tweet.getTweetMentionsCount(); String user_name = tweet.getUserName(); String user_image_url = tweet.getUserImageUrl(); String user_cover_url = tweet.getUserCoverUrl(); String user_location = tweet.getUserLocation(); String user_description = tweet.getUserDescription(); ContentValues tweetValues = new ContentValues(); tweetValues.put(TweetEntry.COLUMN_HASHTAG_KEY, hashTagId); tweetValues.put(TweetEntry.COLUMN_TWEET_TEXT_DATE, TweetHashTracerContract .getDbDateString(tweet_text_date, EDbDateLimit.DATE_FORMAT_NOW_LIMIT)); tweetValues.put(TweetEntry.COLUMN_TWEET_ID, tweet_id); tweetValues.put(TweetEntry.COLUMN_TWEET_TEXT, tweet_text); tweetValues.put(TweetEntry.COLUMN_TWEET_TEXT_RETWEET_COUNT, tweet_text_retweet_count); tweetValues.put(TweetEntry.COLUMN_TWEET_TEXT_FAVOURITE_COUNT, tweet_text_favourite_count); tweetValues.put(TweetEntry.COLUMN_TWEET_TEXT_MENTIONS_COUNT, tweet_text_mentions_count); tweetValues.put(TweetEntry.COLUMN_TWEET_USERNAME, user_name); tweetValues.put(TweetEntry.COLUMN_TWEET_USERNAME_IMAGE_URL, user_image_url); tweetValues.put(TweetEntry.COLUMN_TWEET_USERNAME_COVER_URL, user_cover_url); tweetValues.put(TweetEntry.COLUMN_TWEET_USERNAME_LOCATION, user_location); tweetValues.put(TweetEntry.COLUMN_TWEET_USERNAME_DESCRIPTION, user_description); cVVector.add(tweetValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int insertNo = getContext().getContentResolver().bulkInsert(TweetEntry.CONTENT_URI, cvArray); // Get's a calendar object with the current time. Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -3); // Signifies 3 days ago's date String previousDate = TweetHashTracerContract.getDbDateString(cal.getTime(), EDbDateLimit.DATE_FORMAT_NOW_LIMIT); getContext().getContentResolver().delete(TweetEntry.CONTENT_URI, TweetEntry.COLUMN_TWEET_TEXT_DATE + " <= ?", new String[] { previousDate }); notifyWeather(); } Log.d(LOG_TAG, "FetchTweetTask Complete. " + cVVector.size() + " Inserted"); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return; }
From source file:de.juwimm.cms.remote.ContentServiceSpringImpl.java
/** * @see de.juwimm.cms.remote.ContentServiceSpring#getAnchors(java.lang.Integer) *//*from w w w .j a v a2 s .c o m*/ @Override protected String[] handleGetAnchors(Integer contentId) throws Exception { try { String[] anchArr = new String[0]; ContentHbm content = super.getContentHbmDao().load(contentId); ContentVersionHbm cvl = content.getLastContentVersion(); String contentText = cvl.getText(); org.w3c.dom.Document doc = XercesHelper.string2Dom(contentText); Iterator nit = XercesHelper.findNodes(doc, "//anchor/a"); Vector<String> vec = new Vector<String>(); while (nit.hasNext()) { Element elm = (Element) nit.next(); try { String anchor = elm.getAttribute("name"); vec.add(anchor); } catch (Exception exe) { } } anchArr = vec.toArray(new String[0]); return anchArr; } catch (Exception e) { throw new UserException(e.getMessage()); } }
From source file:org.unitedinternet.cosmo.model.hibernate.EntityConverter.java
/** * Given a calendar with many different components, split into * separate calendars that contain only a single component type * and a single UID.// www . j a v a 2 s .c o m * @param calendar The calendar. * @return The split calendar. */ private CalendarContext[] splitCalendar(Calendar calendar) { Vector<CalendarContext> contexts = new Vector<CalendarContext>(); Set<String> allComponents = new HashSet<String>(); Map<String, ComponentList<CalendarComponent>> componentMap = new HashMap<>(); ComponentList<CalendarComponent> comps = calendar.getComponents(); for (CalendarComponent comp : comps) { // ignore vtimezones for now if (comp instanceof VTimeZone) { continue; } Uid uid = (Uid) comp.getProperty(Property.UID); RecurrenceId rid = (RecurrenceId) comp.getProperty(Property.RECURRENCE_ID); String key = uid.getValue(); if (rid != null) { key += rid.toString(); } // ignore duplicates if (allComponents.contains(key)) { continue; } allComponents.add(key); ComponentList<CalendarComponent> cl = componentMap.get(uid.getValue()); if (cl == null) { cl = new ComponentList<>(); componentMap.put(uid.getValue(), cl); } cl.add(comp); } for (Entry<String, ComponentList<CalendarComponent>> entry : componentMap.entrySet()) { Component firstComp = (Component) entry.getValue().get(0); Calendar cal = ICalendarUtils.createBaseCalendar(); cal.getComponents().addAll(entry.getValue()); addTimezones(cal); CalendarContext cc = new CalendarContext(); cc.calendar = cal; cc.type = firstComp.getName(); contexts.add(cc); } return contexts.toArray(new CalendarContext[contexts.size()]); }
From source file:org.kchine.r.server.manager.ServerManager.java
public static String[] getRInfo(String rbin) { File getInfoFile = new File(INSTALL_DIR + "getInfo.R"); File getInfoOutputFile = new File(INSTALL_DIR + "getInfo.Rout"); try {/*w w w .j ava2 s.com*/ getInfoOutputFile.delete(); } catch (Exception e) { e.printStackTrace(); } String rversion = null; String rlibraypath = null; String rjavapath = null; try { FileWriter fw = new FileWriter(getInfoFile); PrintWriter pw = new PrintWriter(fw); pw.println("paste('" + RHOMESTART + "',R.home(), '" + RHOMEEND + "',sep='%')"); pw.println("paste('" + RVERSTART + "', R.version.string , '" + RVEREND + "', sep='%')"); pw.println("library('rJava'); paste('" + RJAVAPATHSTART + "', .path.package('rJava') , '" + RJAVAPATHEND + "', sep='%')"); fw.close(); Vector<String> getInfoCommand = new Vector<String>(); String[] roptions = DirectJNI.getROptions(); if (rbin != null && !rbin.equals("")) { System.out.println("trying to execute :" + rbin); getInfoCommand.add(rbin); getInfoCommand.add("CMD"); getInfoCommand.add("BATCH"); for (int i = 0; i < roptions.length; ++i) getInfoCommand.add(roptions[i]); getInfoCommand.add(getInfoFile.getAbsolutePath()); getInfoCommand.add(getInfoOutputFile.getAbsolutePath()); } else { if (isWindowsOs()) { getInfoCommand.add(System.getenv().get("ComSpec")); getInfoCommand.add("/C"); getInfoCommand.add("R"); getInfoCommand.add("CMD"); getInfoCommand.add("BATCH"); for (int i = 0; i < roptions.length; ++i) getInfoCommand.add(roptions[i]); getInfoCommand.add(getInfoFile.getAbsolutePath()); getInfoCommand.add(getInfoOutputFile.getAbsolutePath()); } else { getInfoCommand.add(/* System.getenv().get("SHELL") */"/bin/sh"); getInfoCommand.add("-c"); StringBuffer roptions_str = new StringBuffer(); for (int i = 0; i < roptions.length; ++i) { roptions_str.append(roptions[i]); roptions_str.append(" "); } getInfoCommand.add("R CMD BATCH " + roptions_str + " " + getInfoFile.getAbsolutePath() + " " + getInfoOutputFile.getAbsolutePath()); } } Vector<String> systemEnvVector = new Vector<String>(); { Map<String, String> osenv = System.getenv(); Map<String, String> env = new HashMap<String, String>(osenv); for (String k : env.keySet()) { systemEnvVector.add(k + "=" + env.get(k)); } } System.out.println("exec->" + getInfoCommand); System.out.println(systemEnvVector); final Process getInfoProc = Runtime.getRuntime().exec(getInfoCommand.toArray(new String[0]), systemEnvVector.toArray(new String[0])); new Thread(new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(getInfoProc.getErrorStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(getInfoProc.getInputStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } }).start(); getInfoProc.waitFor(); if (getInfoOutputFile.exists()) { BufferedReader br = new BufferedReader(new FileReader(getInfoOutputFile)); String line = null; while ((line = br.readLine()) != null) { // System.out.println(line); if (line.contains(RHOMESTART + "%")) { rlibraypath = line.substring(line.indexOf(RHOMESTART + "%") + (RHOMESTART + "%").length(), (line.indexOf("%" + RHOMEEND) > 0 ? line.indexOf("%" + RHOMEEND) : line.length())); } if (line.contains(RVERSTART + "%")) { rversion = line.substring(line.indexOf(RVERSTART + "%") + (RVERSTART + "%").length(), line.indexOf("%" + RVEREND)); } if (line.contains(RJAVAPATHSTART + "%")) { rjavapath = line.substring( line.indexOf(RJAVAPATHSTART + "%") + (RJAVAPATHSTART + "%").length(), line.indexOf("%" + RJAVAPATHEND)); } } } else { System.out.println(getInfoOutputFile.toString() + " not found "); } } catch (Exception e) { e.printStackTrace(); } System.out.println("+rversion:" + rversion); System.out.println("+rlibraypath:" + rlibraypath); System.out.println("+rjavapath:" + rjavapath); if (rlibraypath != null) { return new String[] { rlibraypath, rversion, rjavapath }; } else { return null; } }
From source file:org.opencastproject.capture.impl.CaptureAgentImpl.java
/** * Compresses the files contained in the output directory * /*from w ww .j a va 2 s. c om*/ * @param recID * The ID for the recording whose files are going to be zipped * @return A File reference to the file zip created */ public File zipFiles(String recID) { logger.debug("Compressing files..."); AgentRecording recording = pendingRecordings.get(recID); if (recording == null) { logger.error("[zipFiles] Recording {} not found!", recID); setRecordingState(recID, RecordingState.COMPRESSING_ERROR); return null; } else { setRecordingState(recording.getID(), RecordingState.COMPRESSING); } Iterable<MediaPackageElement> mpElements = recording.getMediaPackage().elements(); Vector<File> filesToZip = new Vector<File>(); // Now adds the files from the MediaPackage for (MediaPackageElement item : mpElements) { File tmpFile = null; String elementPath = item.getURI().getPath(); // Relative and absolute paths are mixed if (elementPath.startsWith("file:") || elementPath.startsWith(File.separator)) { tmpFile = new File(elementPath); } else { tmpFile = new File(recording.getBaseDir(), elementPath); } if (!tmpFile.isFile()) { // TODO: Is this really a warning or should we fail completely and return an error? logger.warn("Required file {} doesn't exist!", tmpFile.getAbsolutePath()); } filesToZip.add(tmpFile); } filesToZip.add(new File(recording.getBaseDir(), CaptureParameters.MANIFEST_NAME)); logger.info("Zipping {} files:", filesToZip.size()); for (File f : filesToZip) { logger.debug("--> {}", f.getName()); } // Nuke any existing zipfile, we want to recreate it if it already exists. removeZipFile(recording); // Return a pointer to the zipped file File returnZip; try { File outputZip = new File(recording.getBaseDir(), CaptureParameters.ZIP_NAME); returnZip = ZipUtil.zip(filesToZip.toArray(new File[filesToZip.size()]), outputZip, ZipUtil.NO_COMPRESSION); } catch (IOException e) { logger.error("An IOException has occurred while zipping the files for recording {}: {}", recID, e); return null; } return returnZip; }
From source file:com.upenn.chriswang1990.sunshine.sync.SunshineSyncAdapter.java
/** * Take the retrofit weather response and the returned timezone ID and get the corresponding * weather data, save them in local SQL database *///from ww w . ja v a 2 s . c om private void saveToDatabase(Response<WeatherResponse> response, String timezoneID) { // Location information WeatherResponse weatherData = response.body(); String locationSetting = Utility.getPreferredLocation(context); String cityName = weatherData.getCity().getName(); double cityLatitude = weatherData.getCity().getCoord().getLat(); double cityLongitude = weatherData.getCity().getCoord().getLon(); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude, timezoneID); int listLength = weatherData.getList().toArray().length; // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<>(listLength); for (int i = 0; i < listLength; i++) { // These are the values that will be collected. WeatherResponse.ListBean dateWeather = weatherData.getList().get(i); long unixTimestamp = dateWeather.getDt(); // the unix time(in milliseconds); long dateTime = Utility.normalizeDate(unixTimestamp, timezoneID); double pressure = dateWeather.getPressure(); int humidity = dateWeather.getHumidity(); double windSpeed = dateWeather.getSpeed(); int windDirection = dateWeather.getDeg(); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. double high = dateWeather.getTemp().getMax(); double low = dateWeather.getTemp().getMin(); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. String description = dateWeather.getWeather().get(0).getMain(); int weatherId = dateWeather.getWeather().get(0).getId(); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE_UNIX_TIMESTAMP, unixTimestamp); 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 int rowsDeleted = 0; if (cVVector.size() > 0) { ContentValues[] values = new ContentValues[cVVector.size()]; cVVector.toArray(values); context.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, values); rowsDeleted = context.getContentResolver().delete(WeatherContract.WeatherEntry.CONTENT_URI, WeatherContract.WeatherEntry.COLUMN_DATE + " <= ?", new String[] { Long .toString(Utility.normalizeDate(System.currentTimeMillis() / 1000, timezoneID) - 1) }); notifyWeather(); } Utility.setLocationStatus(context, LOCATION_STATUS_OK); }
From source file:com.ricemap.spateDB.mapred.IndexedPrism.java
@SuppressWarnings("unchecked") @Override//from ww w. j a va 2s . c o m public InputSplit[] getSplits(final JobConf job, int numSplits) throws IOException { // Get a list of all input files. There should be exactly two files. final Path[] inputFiles = getInputPaths(job); GlobalIndex<Partition> gIndexes[] = new GlobalIndex[inputFiles.length]; BlockFilter blockFilter = null; try { Class<? extends BlockFilter> blockFilterClass = job.getClass(SpatialSite.FilterClass, null, BlockFilter.class); if (blockFilterClass != null) { // Get all blocks the user wants to process blockFilter = blockFilterClass.newInstance(); blockFilter.configure(job); } } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } if (blockFilter != null) { // Extract global indexes from input files for (int i_file = 0; i_file < inputFiles.length; i_file++) { FileSystem fs = inputFiles[i_file].getFileSystem(job); gIndexes[i_file] = SpatialSite.getGlobalIndex(fs, inputFiles[i_file]); } } final Vector<CombineFileSplit> matchedSplits = new Vector<CombineFileSplit>(); if (gIndexes[0] == null || gIndexes[1] == null) { // Join every possible pair (Cartesian product) BlockLocation[][] fileBlockLocations = new BlockLocation[inputFiles.length][]; for (int i_file = 0; i_file < inputFiles.length; i_file++) { FileSystem fs = inputFiles[i_file].getFileSystem(job); FileStatus fileStatus = fs.getFileStatus(inputFiles[i_file]); fileBlockLocations[i_file] = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen()); } LOG.info("Doing a Cartesian product of blocks: " + fileBlockLocations[0].length + "x" + fileBlockLocations[1].length); for (BlockLocation block1 : fileBlockLocations[0]) { for (BlockLocation block2 : fileBlockLocations[1]) { FileSplit fsplit1 = new FileSplit(inputFiles[0], block1.getOffset(), block1.getLength(), block1.getHosts()); FileSplit fsplit2 = new FileSplit(inputFiles[1], block2.getOffset(), block2.getLength(), block2.getHosts()); CombineFileSplit combinedSplit = (CombineFileSplit) FileSplitUtil.combineFileSplits(job, fsplit1, fsplit2); matchedSplits.add(combinedSplit); } } } else { // Filter block pairs by the BlockFilter blockFilter.selectCellPairs(gIndexes[0], gIndexes[1], new ResultCollector2<Partition, Partition>() { @Override public void collect(Partition p1, Partition p2) { try { List<FileSplit> splits1 = new ArrayList<FileSplit>(); Path path1 = new Path(inputFiles[0], p1.filename); splitFile(job, path1, splits1); List<FileSplit> splits2 = new ArrayList<FileSplit>(); Path path2 = new Path(inputFiles[1], p2.filename); splitFile(job, path2, splits2); for (FileSplit split1 : splits1) { for (FileSplit split2 : splits2) { matchedSplits.add( (CombineFileSplit) FileSplitUtil.combineFileSplits(job, split1, split2)); } } } catch (IOException e) { e.printStackTrace(); } } }); } LOG.info("Matched " + matchedSplits.size() + " combine splits"); // Return all matched splits return matchedSplits.toArray(new InputSplit[matchedSplits.size()]); }
From source file:ORG.oclc.os.SRW.ParallelSearching.SRWMergeDatabase.java
public TermList getTermList(CQLTermNode seedTerm, int position, int maxTerms, ScanRequestType request) { DiagnosticsType diagnostics, newDiagnostics = null; long startTime = System.currentTimeMillis(); // position-=1; // make it zero ordinal rb.setRequest(request, ++counter);/* w w w . j a v a2 s.com*/ rb.waitUntilDone(); int bestFit, comp = 1, vectorIndex; long count; String scanTerm = ""; try { CQLNode node = parser.parse(request.getScanClause()); if (node instanceof CQLTermNode) { scanTerm = ((CQLTermNode) node).getTerm(); if (log.isDebugEnabled()) log.debug("scanTerm=" + scanTerm); } } catch (org.z3950.zing.cql.CQLParseException e) { log.error(e, e); TermList tl = new TermList(); tl.addDiagnostic(SRWDiagnostic.newDiagnosticType(SRWDiagnostic.QuerySyntaxError, e.getMessage())); return tl; } catch (java.io.IOException e) { log.error(e, e); TermList tl = new TermList(); tl.addDiagnostic(SRWDiagnostic.newDiagnosticType(SRWDiagnostic.GeneralSystemError, e.getMessage())); return tl; } ScanResponseType scanResponse = null, newResponse = new ScanResponseType(); TermType term, termArray[], tterm; TermsType terms; Vector termsV = new Vector(); for (int i = 0; i < componentDBs.length; i++) { if (componentDBs[i].scanResponse == null) { log.error("mergeDB[" + i + "] (" + componentDBs[i].getName() + ") returned: " + componentDBs[i].scanResponse); continue; } scanResponse = (ScanResponseType) componentDBs[i].scanResponse; diagnostics = scanResponse.getDiagnostics(); if (diagnostics != null) { if (newDiagnostics == null) newDiagnostics = new DiagnosticsType(); newDiagnostics.setDiagnostic(diagnostics.getDiagnostic()); } terms = scanResponse.getTerms(); if (terms == null) // no terms returned; probably got a diagnostic continue; termArray = terms.getTerm(); vectorIndex = 0; for (int j = 0; j < termArray.length; j++) { term = termArray[j]; if (vectorIndex >= termsV.size()) { if (log.isDebugEnabled()) log.debug("adding to end: " + term.getValue()); termsV.add(term); vectorIndex++; } else { while (vectorIndex < termsV.size() && (comp = compare(termsV.get(vectorIndex), term)) < 0) vectorIndex++; if (vectorIndex >= termsV.size()) { if (log.isDebugEnabled()) log.debug("adding to end: " + term.getValue()); termsV.add(term); vectorIndex++; } else if (comp == 0) { tterm = (TermType) termsV.get(vectorIndex); if (log.isDebugEnabled()) log.debug("changing count: " + tterm.getValue()); count = tterm.getNumberOfRecords().longValue() + term.getNumberOfRecords().longValue(); tterm.setNumberOfRecords(new NonNegativeInteger(Long.toString(count))); } else { if (log.isDebugEnabled()) log.debug("inserting at " + vectorIndex + ": " + term.getValue()); termsV.add(vectorIndex++, term); } } } } if (maxTerms >= termsV.size()) { // just return what we have if (log.isDebugEnabled()) log.debug("number of terms returned: " + termsV.size()); termArray = new TermType[termsV.size()]; termArray = (TermType[]) termsV.toArray(termArray); } else { // pick the ones to return if (log.isDebugEnabled()) log.debug("number of terms returned: " + termsV.size()); for (bestFit = 0; bestFit < termsV.size(); bestFit++) if (compare(scanTerm, (TermType) termsV.get(bestFit)) <= 0) break; if (log.isDebugEnabled()) log.debug("bestFit=" + bestFit); int start = bestFit - position; if (start < 0) start = 0; if (start + maxTerms > termsV.size()) maxTerms = termsV.size() - start; termArray = new TermType[maxTerms]; for (int i = 0; i < maxTerms; i++) { termArray[i] = (TermType) termsV.get(start++); if (log.isDebugEnabled()) log.debug("returning term: " + termArray[i].getValue()); } } TermList tl = new TermList(); tl.setTerms(termArray); if (newDiagnostics != null) { if (log.isDebugEnabled()) log.debug(newDiagnostics.getDiagnostic(0).getUri()); tl.addDiagnostics(newDiagnostics); } if (log.isDebugEnabled()) log.debug("scan " + scanTerm + ": (" + (System.currentTimeMillis() - startTime) + "ms)"); return tl; }
From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java
private int processGuildMembers(String guildJsonStr) { int actualInsertCount = 0; // check to see if there is anything to do if (guildJsonStr == null) return 0; // These are the item keys that we want to extra from the JSON object // Guild data keys final String WOW_GUILD_LAST_MODIFIED = "lastModified"; final String WOW_GUILD_NAME = "name"; final String WOW_GUILD_REALM = "realm"; final String WOW_GUILD_BATTLEGROUP = "battlegroup"; final String WOW_GUILD_LEVEL = "level"; final String WOW_GUILD_SIDE = "side"; final String WOW_GUILD_POINTS = "achievementPoints"; final String WOW_GUILD_MEMBERS = "members"; // Member data keys final String WOW_MEMBER_CHARACTER = "character"; final String WOW_MEMBER_RANK = "rank"; // Member character data keys final String WOW_MEMBER_NAME = "name"; final String WOW_MEMBER_CLASS = "class"; final String WOW_MEMBER_RACE = "race"; final String WOW_MEMBER_GENDER = "gender"; final String WOW_MEMBER_LEVEL = "level"; final String WOW_MEMBER_POINTS = "achievementPoints"; final String WOW_MEMBER_THUMBNAIL = "thumbnail"; // store the last guild update and use it to keep the processing time to a minimum long mSavedTimestamp = Utility.getPreferenceForLastGuildMemberUpdate(mContext); // the region is not returned in the JSON data // so we use the same preference data that was used to get the JSON String region = Utility.getRegion(mContext); try {// w ww. j a va2s .c o m // create JSON object for the string JSONObject guildJson = new JSONObject(guildJsonStr); long modifiedTimestamp = guildJson.getLong(WOW_GUILD_LAST_MODIFIED); if (modifiedTimestamp <= mSavedTimestamp) { // we can stop processing now because nothing has changes since we // last checked. Save some processing power return actualInsertCount; } // create a guild object to hold the relevant data from the JSON object GuildViewerGuild currentGuild = new GuildViewerGuild(); // do a timestamp check to keep processing to minimum currentGuild.setLastModified(modifiedTimestamp); // save this time for the next round mSavedTimestamp = modifiedTimestamp; // default to WOW's modified date // setup the guild object currentGuild.setName(guildJson.getString(WOW_GUILD_NAME)); currentGuild.setRegion(region); currentGuild.setRealm(guildJson.getString(WOW_GUILD_REALM)); currentGuild.setBattlegroup(guildJson.getString(WOW_GUILD_BATTLEGROUP)); currentGuild.setLevel(guildJson.getInt(WOW_GUILD_LEVEL)); int side = guildJson.getInt(WOW_GUILD_SIDE); currentGuild.setSide(Utility.getGuildSide(mContext, side)); currentGuild.setAchievementPoints(guildJson.getInt(WOW_GUILD_POINTS)); //Add this to the database so that I know what to set the guild ID to in the members // But first delete the one that is in the database!! int deleted = mContext.getContentResolver().delete(GuildEntry.CONTENT_URI, null, null); //Log.v(LOG_TAG, "Deleted " + Integer.toString(deleted) + " Guilds from Database."); ContentValues currentGuildValues = createValuesObject(currentGuild); Uri guildUri = mContext.getContentResolver().insert(GuildEntry.CONTENT_URI, currentGuildValues); int guildId = GuildEntry.getGuildIdFromUri(guildUri); //Log.v(LOG_TAG, "New Guild Id is " + Integer.toString(guildId) ); // now process the array of guild members JSONArray membersArray = guildJson.getJSONArray(WOW_GUILD_MEMBERS); //Log.v(LOG_TAG, "Number of Guild Members Found in JSON:" + Integer.toString(membersArray.length())); // Insert the new members into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(membersArray.length()); for (int i = 0; i < membersArray.length(); i++) { GuildViewerMember currentMember = new GuildViewerMember(); // get the member object from the JSON object JSONObject jsonMember = membersArray.getJSONObject(i); // get the character object from the member object JSONObject characterJson = jsonMember.getJSONObject(WOW_MEMBER_CHARACTER); currentMember.setName(characterJson.getString(WOW_MEMBER_NAME)); currentMember.setGuildId(guildId); currentMember.setLevel(characterJson.getInt(WOW_MEMBER_LEVEL)); currentMember.setGender(Utility.getGender(mContext, characterJson.getInt(WOW_MEMBER_GENDER))); int raceId = characterJson.getInt(WOW_MEMBER_RACE); currentMember.setRace(Utility.getRace(mContext, raceId)); currentMember.setCharacterClass(Utility.getClass(mContext, characterJson.getInt(WOW_MEMBER_CLASS))); currentMember.setSide(Utility.getSide(mContext, raceId)); currentMember.setRank(jsonMember.getInt(WOW_MEMBER_RANK)); currentMember.setAchievementPoints(characterJson.getInt(WOW_MEMBER_POINTS)); currentMember.setThumbnail(characterJson.getString(WOW_MEMBER_THUMBNAIL)); // all the relevant data is extracted so create a ContentValues object // to store it and add it to the array of objects to process later ContentValues memberListValues = createValuesObject(currentMember); cVVector.add(memberListValues); //Log.v(LOG_TAG, currentMember.toString()); } // We are done processing the JSON object // store the new and unique news records that were found if (cVVector.size() > 0) { // convert to an array for the bulk insert to work with ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); // inserts into the storage actualInsertCount = mContext.getContentResolver().bulkInsert(MemberEntry.CONTENT_URI, cvArray); } // see if we need to update the latest timestamp information in the preference storage if (Utility.getPreferenceForLastGuildMemberUpdate(mContext) < mSavedTimestamp) { Utility.setPreferenceForLastGuildMemberUpdate(mContext, mSavedTimestamp); } } catch (JSONException e) { // if any JSON errors occurred log them and // for this app it is appropriate to just keep moving along... don't crash it! } return actualInsertCount; }
From source file:com.flexoodb.common.FlexUtils.java
static public Hashtable getFields(Object obj) { Hashtable<String, String> fields = new Hashtable<String, String>(); //Method[] m = obj.getClass().getMethods(); Vector ve = retrieveMethods(obj.getClass(), null); Method[] m = new Method[ve.size()]; ve.toArray(m); String name, retval;/* w w w.jav a 2 s .c o m*/ String id = null; String parentid = null; StringBuffer xml = new StringBuffer(); StringBuffer listheader = new StringBuffer(); //xml.append("<"+c.getSimpleName()+">"); for (int i = 0; i < m.length; i++) { name = m[i].getName(); retval = m[i].getReturnType().getName(); if (retval.equalsIgnoreCase("void") && name.startsWith("set")) { // we get the method name String field = name.substring(3); String getter = (((m[i].getParameterTypes()[0] + "").equals("boolean")) ? "is" : "get") + field; try { Method met = obj.getClass().getMethod(getter, (Class[]) null); Object o = null; try { o = met.invoke(obj, (Object[]) null); } catch (Exception g) { } if (o != null) { String t = met.getReturnType().getSimpleName(); if (indexable(t)) { if (field.equals("Id")) { id = o.toString(); } else if (field.equals("ParentId")) { parentid = o.toString(); } else { fields.put(field, t); } } else { fields.put(field, t); } } else { if (indexable(met.getReturnType().getSimpleName())) { fields.put(field, met.getReturnType().getSimpleName()); } else { //System.out.println(obj.getClass()+" field 3:"+field+" "+met.getReturnType().getSimpleName()+" "+indexable(met.getReturnType().getSimpleName())); } } } catch (Exception f) { //throw f; f.printStackTrace(); // attempt a get. } } } return fields; }