/** * Retrieve similar pages of a page. * * @param wikipedia Wikipedia. * @param page Page. * @throws APIException */ public void retrieveSimilarPages( EnumWikipedia wikipedia, Page page) throws APIException { if (page == null) { return; } final API api = APIFactory.getAPI(); api.retrieveSimilarPages(wikipedia, page, true); }
@Override protected Exception doInBackground(Object... params) { DatabaseConnection dbConn = new DatabaseConnection(context); try { // String authKey = AuthenticationManager.getGoogleAuthKey(username, password); // SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); // int maxItemsInDatabase = // Integer.parseInt(mPrefs.getString(SettingsActivity.SP_MAX_ITEMS_SYNC, "200")); long lastModified = dbConn.getLastModified(); // dbConn.clearDatabaseOverSize(); // List<RssFile> files; long offset = dbConn.getLowestItemId(false); int requestCount; int maxSyncSize = Integer.parseInt(OwnCloudReaderMethods.maxSizePerSync); highestItemIdBeforeSync = dbConn.getHighestItemId(); SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); if (lastModified == 0) // Only on first sync { int maxItemsInDatabase = Constants.maxItemsCount; int totalCount = 0; do { requestCount = api.GetItems(TAGS.ALL, context, String.valueOf(offset), false, "0", "3", api); if (requestCount > 0) offset = dbConn.getLowestItemId(false); totalCount += requestCount; } while (requestCount == maxSyncSize); mPrefs.edit().putInt(Constants.LAST_UPDATE_NEW_ITEMS_COUNT_STRING, totalCount).commit(); do { offset = dbConn.getLowestItemId(true); requestCount = api.GetItems(TAGS.ALL_STARRED, context, String.valueOf(offset), true, "0", "2", api); // if(requestCount > 0) // offset = dbConn.getLowestItemId(true); totalCount += requestCount; } while (requestCount == maxSyncSize && totalCount < maxItemsInDatabase); } else { int[] result = api.GetUpdatedItems(TAGS.ALL, context, lastModified + 1, api); mPrefs.edit().putInt(Constants.LAST_UPDATE_NEW_ITEMS_COUNT_STRING, result[1]).commit(); // OwnCloudReaderMethods.GetUpdatedItems(TAGS.ALL, context, lastModified, api); } } catch (Exception ex) { return ex; } finally { dbConn.closeDatabase(); } return null; }
private Filter newInstance(API api) throws Exception { for (Constructor c : api.filter().getDeclaredConstructors()) { c.setAccessible(true); Class[] ps = c.getParameterTypes(); if (ps.length == 1 && RequestArguments.class.isAssignableFrom(ps[0])) return (Filter) c.newInstance(this); } for (Constructor c : api.filter().getDeclaredConstructors()) { Class[] ps = c.getParameterTypes(); if (ps.length == 0) return (Filter) c.newInstance(); } throw new Exception("Class " + api.filter().getName() + " must have an empty constructor"); }
/** * Retrieve disambiguation information for a list of pages. * * @param wikipedia Wikipedia. * @param pageList List of page. * @param knownPages Already known pages. * @param disambiguations Flag indicating if possible disambiguations should be retrieved. * @param forceApiCall True if API call should be forced even if the list of disambiguation pages is loaded. * @param block Flag indicating if the call should block until completed. * @throws APIException */ public void retrieveDisambiguationInformation( EnumWikipedia wikipedia, List<Page> pageList, List<Page> knownPages, boolean disambiguations, boolean forceApiCall, boolean block) throws APIException { if ((pageList == null) || (pageList.isEmpty())) { return; } final API api = APIFactory.getAPI(); // Retrieving disambiguation status final int maxPages = api.getMaxPagesPerQuery(); List<Page> filteredList = pageList; if (knownPages != null) { filteredList = new ArrayList<Page>(pageList); filteredList.removeAll(knownPages); } if (filteredList.size() <= maxPages) { addTask(new DisambiguationStatusCallable(wikipedia, this, api, filteredList, forceApiCall)); } else { int index = 0; while (index < filteredList.size()) { List<Page> tmpList = new ArrayList<Page>(api.getMaxPagesPerQuery()); for (int i = 0; (i < maxPages) && (index < filteredList.size()); i++, index++) { tmpList.add(filteredList.get(index)); } addTask(new DisambiguationStatusCallable(wikipedia, this, api, tmpList, forceApiCall)); } } block(true); // Retrieving possible disambiguations if (disambiguations) { for (Page p : pageList) { Iterator<Page> iter = p.getRedirectIteratorWithPage(); while (iter.hasNext()) { p = iter.next(); if ((Boolean.TRUE.equals(p.isDisambiguationPage())) && (!p.isRedirect())) { List<Page> links = p.getLinks(); if ((links == null) || (links.size() == 0)) { addTask(new LinksWRCallable(wikipedia, this, api, p, null, null, false)); } } } } } block(block); }
// 加载更多 private void getMoreData() { page += 1; API.getTradeRecordList( getActivity(), mTradeType, tradeClientName, tradeStartDate, tradeEndDate, page, Config.ROWS, new HttpCallback<Page<TradeRecord>>(getActivity()) { @Override public void onSuccess(Page<TradeRecord> data) { mRecordList.stopLoadMore(); mRecords.addAll(data.getList()); mAdapter.notifyDataSetChanged(); total = data.getTotal(); } @Override public TypeToken<Page<TradeRecord>> getTypeToken() { return new TypeToken<Page<TradeRecord>>() {}; } }); }
@Override protected Void doInBackground(Void... params) { /* Get all items from each machine */ Reader reader = API.getData("machines/stock/"); Machine machine = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC) .create() .fromJson(reader, Machine.class); MachineData machines = machine.getMachineData(); /* Store all items in the DB */ ActiveAndroid.beginTransaction(); try { List<ItemInfo> itemsList = new Select().from(ItemInfo.class).execute(); for (ItemInfo item : itemsList) { item.delete(); } for (ItemInfo item : machines.getBigItemInfo()) { item.save(); } for (ItemInfo item : machines.getLittleItemInfo()) { item.save(); } for (ItemInfo item : machines.getSnacktemInfo()) { item.save(); } ActiveAndroid.setTransactionSuccessful(); } finally { ActiveAndroid.endTransaction(); } return null; }
public ArrayList<ParticleDevice> getDevices() { ArrayList<ParticleDevice> response = api.getDevices(); for (ParticleDevice device : response) { device.setApi(api); } return response; }
/** * Add at least the first sentence from a doc block to the API. This is used by the report * generator if no comment is provided. Need to make sure that HTML tags are not confused with XML * tags. This could be done by stuffing the < character to another string or by handling HTML * in the parser. This second option seems neater. Note that XML expects all element tags to have * either a closing "/>" or a matching end element tag. Due to the difficulties of converting * incorrect HTML to XHTML, the first option is used. */ public void addDocumentation(ProgramElementDoc ped, int indent) { String rct = ((Doc) ped).getRawCommentText(); if (rct != null) { rct = stripNonPrintingChars(rct, (Doc) ped); rct = rct.trim(); if (rct.compareTo("") != 0 && rct.indexOf(Comments.placeHolderText) == -1 && rct.indexOf("InsertOtherCommentsHere") == -1) { int idx = endOfFirstSentence(rct); if (idx == 0) return; for (int i = 0; i < indent; i++) outputFile.print(" "); outputFile.println("<doc>"); for (int i = 0; i < indent; i++) outputFile.print(" "); String firstSentence = null; if (idx == -1) firstSentence = rct; else firstSentence = rct.substring(0, idx + 1); boolean checkForAts = false; if (checkForAts && firstSentence.indexOf("@") != -1 && firstSentence.indexOf("@link") == -1) { System.out.println("Warning: @ tag seen in comment: " + firstSentence); } String firstSentenceNoTags = API.stuffHTMLTags(firstSentence); outputFile.println(firstSentenceNoTags); for (int i = 0; i < indent; i++) outputFile.print(" "); outputFile.println("</doc>"); } } }
/** * Get a list of factories that match the given type. Only elements with a rank greater or equal * to minrank will be returned. The list of factories is returned by decreasing rank. * * @param type a {@link ElementFactoryListType} * @param minrank Minimum rank * @return a List of ElementFactory elements. */ public static List<ElementFactory> listGetElement(ElementFactoryListType type, Rank minrank) { GList glist = gst.gst_element_factory_list_get_elements(type.getValue(), minrank.getValue()); List<ElementFactory> list = new ArrayList<ElementFactory>(); GList next = glist; while (next != null) { if (next.data != null) { ElementFactory fact = new ElementFactory(initializer(next.data, true, true)); list.add(fact); } next = next.next(); } gst.gst_plugin_list_free(glist); return list; }
private Validator newValidator(API api) throws Exception { for (Constructor c : api.validator().getDeclaredConstructors()) { c.setAccessible(true); Class[] ps = c.getParameterTypes(); return (Validator) c.newInstance(); } return null; }
/** Update the app's API status. */ public void updateStatus(final Handler onwardsHandler) { getStatus(); mStatusRetries = 0; mStatusAuthErrors = 0; mOnwardsHandler = onwardsHandler; mAccount = null; mAPI.updateStatus(mStatusHandler); }
/** * Retrieve an instance of a factory that can produce {@link Element}s * * @param name The type of {@link Element} to produce. * @return An ElementFactory that will produce {@link Element}s of the desired type. */ public static ElementFactory find(String name) { logger.entering("ElementFactory", "find", name); ElementFactory factory = gst.gst_element_factory_find(name); if (factory == null) { throw new IllegalArgumentException("No such Gstreamer factory: " + name); } return factory; }
/** * Get a list of factories that match the given parameter. * * <p>It is a combination of listGetElement and listFilter passing all the results of the first * call to the second. * * <p>This method improves performance because there is no need to map to java list the elements * returned by the first call. * * @param type a {@link ElementFactoryListType} * @param minrank Minimum rank * @param caps a {@link Caps} * @param direction a {@link PadDirection} to filter on * @param subsetonly whether to filter on caps subsets or not. * @return a {@link List} of {@link ElementFactory} elements that match the given requisits. */ public static List<ElementFactory> listGetElementFilter( ElementFactoryListType type, Rank minrank, Caps caps, PadDirection direction, boolean subsetonly) { GList glist = gst.gst_element_factory_list_get_elements(type.getValue(), minrank.getValue()); return lister(glist, caps, direction, subsetonly); }
public static Pointer makeRawElement(String factoryName, String name) { logger.entering("ElementFactory", "makeRawElement", new Object[] {factoryName, name}); Pointer elem = gst.ptr_gst_element_factory_make(factoryName, name); logger.log(DEBUG, "Return from gst_element_factory_make=" + elem); if (elem == null) { throw new IllegalArgumentException("No such Gstreamer factory: " + factoryName); } return elem; }
/** * Creates a new element from the factory. * * @param name the name to assign to the created Element * @return A new {@link Element} */ public Element create(String name) { logger.entering("ElementFactory", "create", name); Pointer elem = gst.ptr_gst_element_factory_create(this, name); logger.log(DEBUG, "gst_element_factory_create returned: " + elem); if (elem == null) { throw new IllegalArgumentException("Cannot create GstElement"); } return elementFor(elem, getName()); }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.trade_client: Intent i = new Intent(getActivity(), TradeClientActivity.class); i.putExtra(CLIENT_NUMBER, tradeClientName); startActivityForResult(i, REQUEST_TRADE_CLIENT); break; case R.id.trade_start: showDatePicker(tradeStartDate, true); break; case R.id.trade_end: showDatePicker(tradeEndDate, false); break; case R.id.trade_search: hasSearched = true; mTradeSearchContent.setVisibility(View.VISIBLE); // 点击按钮重拉 page = 1; canLoadMore = true; API.getTradeRecordList( getActivity(), mTradeType, tradeClientName, tradeStartDate, tradeEndDate, page, Config.ROWS, new HttpCallback<Page<TradeRecord>>(getActivity()) { @Override public void onSuccess(Page<TradeRecord> data) { if (data.getList().size() < Config.ROWS) { canLoadMore = false; } mRecords.clear(); mRecords.addAll(data.getList()); mAdapter.notifyDataSetChanged(); total = data.getTotal(); } @Override public TypeToken<Page<TradeRecord>> getTypeToken() { return new TypeToken<Page<TradeRecord>>() {}; } }); break; case R.id.trade_statistic: Intent intent = new Intent(getActivity(), TradeStatisticActivity.class); intent.putExtra(TRADE_TYPE, mTradeType); intent.putExtra(CLIENT_NUMBER, tradeClientName); intent.putExtra(START_DATE, tradeStartDate); intent.putExtra(END_DATE, tradeEndDate); startActivity(intent); break; } }
private static List<ElementFactory> lister( GList glist, Caps caps, PadDirection direction, boolean subsetonly) { List<ElementFactory> filterList = new ArrayList<ElementFactory>(); GList gFilterList = gst.gst_element_factory_list_filter(glist, caps, direction, subsetonly); GList next = gFilterList; while (next != null) { if (next.data != null) { ElementFactory fact = new ElementFactory(initializer(next.data, true, true)); filterList.add(fact); } next = next.next(); } gst.gst_plugin_list_free(glist); gst.gst_plugin_list_free(gFilterList); return filterList; }
@Override protected Exception doInBackground(Object... params) { try { api.GetFeeds(context, api); } catch (Exception ex) { return ex; } return null; }
/** * Gets the list of {@link StaticPadTemplate} for this factory. * * @return The list of {@link StaticPadTemplate} */ public List<StaticPadTemplate> getStaticPadTemplates() { logger.entering("ElementFactory", "getStaticPadTemplates"); GList glist = gst.gst_element_factory_get_static_pad_templates(this); logger.log(DEBUG, "gst.gst_element_factory_get_static_pad_templates returned: " + glist); List<StaticPadTemplate> templates = new ArrayList<StaticPadTemplate>(); GList next = glist; while (next != null) { if (next.data != null) { GstStaticPadTemplate temp = new GstStaticPadTemplate(next.data); templates.add( new StaticPadTemplate( temp.name_template, temp.direction, temp.presence, gst.gst_static_caps_get(temp.static_caps))); } next = next.next(); } return templates; }
/** * Add qualifiers for the program element as attributes. * * @param ped The given program element. */ public void addCommonModifiers(ProgramElementDoc ped, int indent) { addSourcePosition(ped, indent); // Static and final and visibility on one line for (int i = 0; i < indent; i++) outputFile.print(" "); outputFile.print("static=\"" + ped.isStatic() + "\""); outputFile.print(" final=\"" + ped.isFinal() + "\""); // Visibility String visibility = null; if (ped.isPublic()) visibility = "public"; else if (ped.isProtected()) visibility = "protected"; else if (ped.isPackagePrivate()) visibility = "package"; else if (ped.isPrivate()) visibility = "private"; outputFile.println(" visibility=\"" + visibility + "\""); // Deprecation on its own line for (int i = 0; i < indent; i++) outputFile.print(" "); boolean isDeprecated = false; Tag[] ta = ((Doc) ped).tags("deprecated"); if (ta.length != 0) { isDeprecated = true; } if (ta.length > 1) { System.out.println( "JDiff: warning: multiple @deprecated tags found in comments for " + ped.name() + ". Using the first one only."); System.out.println("Text is: " + ((Doc) ped).getRawCommentText()); } if (isDeprecated) { String text = ta[0].text(); // Use only one @deprecated tag if (text != null && text.compareTo("") != 0) { int idx = endOfFirstSentence(text); if (idx == 0) { // No useful comment outputFile.print("deprecated=\"deprecated, no comment\""); } else { String fs = null; if (idx == -1) fs = text; else fs = text.substring(0, idx + 1); String st = API.hideHTMLTags(fs); outputFile.print("deprecated=\"" + st + "\""); } } else { outputFile.print("deprecated=\"deprecated, no comment\""); } } else { outputFile.print("deprecated=\"not deprecated\""); } } // addQualifiers()
private Theme getRenderingTheme(API api) { Optional<String> sessionThemeName = api.getSession().map(Session::getThemeName); if (!sessionThemeName.isPresent()) { return defaultTheme; } return sessionThemeName .map(themes::get) .orElseThrow( () -> new IllegalArgumentException( "Theme '" + sessionThemeName.get() + "' which is set as for the current session of app '" + name + "' does not exists.")); }
/** Clears stored credentials. */ public void clearCredentials() { Log.e(LTAG, "Clearing credentials."); // Automatically means our status needs to be cleared mAPI.resetCredentials(); mStatus = null; SharedPreferences prefs = getPrefs(); if (null == prefs) { return; } SharedPreferences.Editor edit = prefs.edit(); edit.remove(Globals.PREF_API_KEY); edit.remove(Globals.PREF_API_SECRET); edit.remove(Globals.PREF_RECORDING_TIME); edit.commit(); }
public static void main(String[] args) { // create API - on current thread API account = new API("MyAccessKey"); // create API that will use threadpool of 5 threads to send messages API threadedAccount = new API("MyAccessKey", 5); // create bucket Bucket bucket = new Bucket("myBucket", "Test bucket"); account.createBucket(bucket); // create data Data data = new Data("Tempreture", 37); account.createData(bucket, data); // create bulk data account.createBulkData(bucket, new Data[] {data, data}); // close account.terminate(); threadedAccount.terminate(); }
/** * Get the super class (aka the parent class) of the current meta API object. * * @return the super class meta API object (aka the parent class) */ public Component getSuper() { return API.getComponent(extendz); }
public static void load() { API.registerNEIGuiHandler(new NEICreativeGuiHandler()); API.registerNEIGuiHandler(new NEIChestGuiHandler()); API.registerNEIGuiHandler(new NEIDummySlotHandler()); }
/** * Replace text in a list of pages. * * @param pages List of pages. * @param replacements List of text replacements * Key: Additional comments used for the modification. * Value: Text replacements. * @param wiki Wiki. * @param comment Comment used for the modification. * @param description (Out) description of changes made. * @param automaticCW True if automatic Check Wiki fixing should be done also. * @param save True if modification should be saved. * @return Count of modified pages. * @throws APIException */ public int replaceText( Page[] pages, Map<String, List<AutomaticFixing>> replacements, EnumWikipedia wiki, String comment, StringBuilder description, boolean automaticCW, boolean save, boolean updateDabWarning) throws APIException { if ((pages == null) || (replacements == null) || (replacements.size() == 0)) { return 0; } UpdateDabWarningTools dabWarnings = new UpdateDabWarningTools(wiki, null, false, false); for (Page page : pages) { retrieveContents(wiki, page, false, true, false, true, false); // TODO: withRedirects=false ? } int count = 0; final API api = APIFactory.getAPI(); StringBuilder details = new StringBuilder(); Configuration config = Configuration.getConfiguration(); boolean secured = config.getBoolean(null, ConfigurationValueBoolean.SECURE_URL); while (hasRemainingTask() && !shouldStop()) { Object result = getNextResult(); if ((result != null) && (result instanceof Page)) { boolean changed = false; List<String> replacementsDone = new ArrayList<String>(); Page page = (Page) result; String oldContents = page.getContents(); if (oldContents != null) { String newContents = oldContents; details.setLength(0); for (Entry<String, List<AutomaticFixing>> replacement : replacements.entrySet()) { replacementsDone.clear(); String tmpContents = AutomaticFixing.apply(replacement.getValue(), newContents, replacementsDone); if (!newContents.equals(tmpContents)) { newContents = tmpContents; // Update description if (description != null) { if (!changed) { String title = "<a href=\"" + wiki.getSettings().getURL(page.getTitle(), false, secured) + "\">" + page.getTitle() + "</a>"; description.append(GT._("Page {0}:", title)); description.append("\n"); description.append("<ul>\n"); changed = true; } for (String replacementDone : replacementsDone) { description.append("<li>"); description.append(replacementDone); description.append("</li>\n"); } } // Memorize replacement if ((replacement.getKey() != null) && (replacement.getKey().length() > 0)) { if (details.length() > 0) { details.append(", "); } details.append(replacement.getKey()); } } } // Page contents has been modified if (!oldContents.equals(newContents)) { // Initialize comment StringBuilder fullComment = new StringBuilder(); fullComment.append(wiki.createUpdatePageComment(comment, details.toString())); // Apply automatic Check Wiki fixing if (automaticCW) { List<CheckErrorAlgorithm> algorithms = CheckErrorAlgorithms.getAlgorithms(wiki); List<CheckErrorAlgorithm> usedAlgorithms = new ArrayList<CheckErrorAlgorithm>(); newContents = AutomaticFormatter.tidyArticle( page, newContents, algorithms, false, usedAlgorithms); if (!usedAlgorithms.isEmpty()) { fullComment.append(" / "); fullComment.append(wiki.getCWConfiguration().getComment(usedAlgorithms)); if (description != null) { for (CheckErrorAlgorithm algorithm : usedAlgorithms) { description.append("<li>"); description.append(algorithm.getShortDescriptionReplaced()); description.append("</li>\n"); } } } } if ((description != null) && (changed)) { description.append("</ul>\n"); } // Save page setText(GT._("Updating page {0}", page.getTitle())); count++; if (save) { api.updatePage(wiki, page, newContents, fullComment.toString(), false, false); if (updateDabWarning) { dabWarnings.updateWarning( Collections.singletonList(page), null, null, null); } } } } } } block(true); return count; }
/** * Gets the duration answer for this duration query. * * @return The total duration. */ public long getDuration() { long[] duration = new long[1]; gst.gst_query_parse_duration(this, null, duration); return duration[0]; }
/** * Gets the format of this duration query. * * @return The {@link Format} of the duration value. */ public Format getFormat() { Format[] fmt = new Format[1]; gst.gst_query_parse_duration(this, fmt, null); return fmt[0]; }
/** * Answers a duration query by setting the requested value in the given format. * * @param format the {@link Format} for the duration * @param duration the duration of the stream */ public void setDuration(Format format, long duration) { gst.gst_query_set_duration(this, format, duration); }
/** * Constructs a new stream duration query object to query in the given format. A duration query * will give the total length of the stream. * * @param format the {@link Format} for this duration query. */ public DurationQuery(Format format) { super(initializer(gst.ptr_gst_query_new_duration(format))); }