private void parseMethod(Api api, ExecutableElement executableElement) throws IOException { Element actionElement = generator .getProcessingEnvironment() .getElementUtils() .getTypeElement(ApiMethodDoc.class.getName()); TypeMirror apiMethodDocType = actionElement.asType(); for (AnnotationMirror am : executableElement.getAnnotationMirrors()) { if (am.getAnnotationType().equals(apiMethodDocType)) { api.apiMethodDoc = Maps.newHashMap(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> ee : am.getElementValues().entrySet()) { api.apiMethodDoc.put(ee.getKey().getSimpleName().toString(), ee.getValue()); } break; } } // generator.log("apiMethodDoc: " + api.apiMethodDoc); if (null == api.apiMethodDoc) { generator.log("Method miss @ApiMethodDoc. " + executableElement); return; } api.methodName = executableElement.getSimpleName().toString(); api.methodMapping = executableElement.getAnnotation(RequestMapping.class); api.parameters = Lists.newArrayList(); for (VariableElement var : executableElement.getParameters()) { api.parameters.add(var); } }
public static Video parse(JSONObject o) throws NumberFormatException, JSONException { Video v = new Video(); if (o.has("vid")) v.vid = o.getLong("vid"); if (o.has("id")) // video.getUserVideos v.vid = Long.parseLong(o.getString("id")); v.owner_id = o.getLong("owner_id"); v.title = Api.unescape(o.getString("title")); v.duration = o.getLong("duration"); v.description = Api.unescape(o.optString("description")); if (o.has("image")) v.image = o.optString("image"); v.image_big = o.optString("image_medium"); if (o.has("thumb")) // video.getUserVideos v.image = o.optString("thumb"); v.link = o.optString("link"); v.date = o.optLong("date"); v.player = o.optString("player"); if (o.has("views")) { v.views = o.getLong("views"); } JSONObject files = o.optJSONObject("files"); if (files != null) { v.external = files.optString("external"); v.mp4_240 = files.optString("mp4_240"); v.mp4_360 = files.optString("mp4_360"); v.mp4_480 = files.optString("mp4_480"); v.mp4_720 = files.optString("mp4_720"); v.flv_320 = files.optString("flv_320"); } return v; }
public void testRelease() { { try { st.release(new PSI(st, "g1", "i1", 823502L, 10)); } catch (EmptyStackException e) { } } { PSI psi0 = st.getStackItem("g2", "i0"); PSI psi1 = st.getStackItem("g2", "i1"); st.getStackItem("g2", "i2"); PSI psi3 = st.getStackItem("g2", "i3"); Mockery ctx = new Mockery(); final Log log = ctx.mock(Log.class); LogFactory lf = new ServerImplTest.TestLogFactory(log); Api api = new Api(); api.setIntfImplementor(LogFactory.class, lf); ApiStack.pushApi(api); try { psi3.close(); ctx.checking( new Expectations() { { one(log).error(with(any(String.class))); } }); psi1.close(); // must be error reported ctx.assertIsSatisfied(); psi0.close(); // no errors } finally { ApiStack.popApi(); } } }
private boolean authApi() { if (Api.authAPI(Api.getKey())) { getLogger().info("Using API Key: " + Api.getKey()); return true; } else { getLogger().warn("Invalid API Key! Use \"/MM APIKEY <APIKEY>\" to setup your APIKEY"); return false; } }
public void testLogout() throws Exception { api.logout(MockSubjectWorker.DEVICE_CODE); try { api.logout("wrong device code"); Assert.fail(); } catch (ClientResponseFailure e) { Assert.assertEquals(e.getMessage(), "Error status 400 Bad Request returned"); } }
public void testLogin() throws Exception { Assert.assertEquals( api.login(new Api.Login(LOGIN, MockUserWorker.PASSWORD)), MockSubjectWorker.DEVICE_CODE); try { api.login(new Api.Login("", "wrong pass")); Assert.fail(); } catch (ClientResponseFailure e) { Assert.assertEquals(e.getMessage(), "Error status 403 Forbidden returned"); } }
public static void applyRulesOnChange(Context context, final String reason) { final Context ctx = context.getApplicationContext(); if (!checkForNewCfg(ctx)) { Log.d(TAG, reason + ": interface state has not changed, ignoring"); return; } else if (!Api.isEnabled(ctx)) { Log.d(TAG, reason + ": firewall is disabled, ignoring"); return; } // update Api.PREFS_NAME so we pick up the right profile // REVISIT: this can be removed once we're confident that G is in sync with profile changes G.reloadPrefs(); boolean ret = Api.fastApply( ctx, new RootCommand() .setFailureToast(R.string.error_apply) .setCallback( new RootCommand.Callback() { @Override public void cbFunc(RootCommand state) { if (state.exitCode == 0) { Log.i(TAG, reason + ": applied rules"); } else { // error details are already in logcat // but lets try to run the full rules once Api.applySavedIptablesRules( ctx, false, new RootCommand() .setFailureToast(R.string.error_apply) .setCallback( new RootCommand.Callback() { @Override public void cbFunc(RootCommand state) { if (state.exitCode == 0) { Log.i(TAG, reason + ": applied rules"); } else { Api.setEnabled(ctx, false, false); errorNotification(ctx); } } })); } } })); if (!ret) { Log.e(TAG, reason + ": applySavedIptablesRules() returned an error"); errorNotification(ctx); } }
public Uri saveTheCutestCat(String query) { try { List<Cat> cats = api.queryCats(query); Cat cutest = findCutest(cats); Uri savedUri = api.store(cutest); return savedUri; } catch (Exception e) { e.printStackTrace(); return null; } }
/** * Retrieves a custom biome * * @param targetBiome The string name of the targertBiome. See {@link GetBiomeIDEvent#targetBiome} * for valid values. * @return The requested biome. If the biome does not exist, the <code>Optional</code> value will * not be present. */ public static Optional<BiomeGenBase> getBiome(String targetBiome) { final GetBiomeIDEvent event = new GetBiomeIDEvent(targetBiome); Api.getExtrabiomesXLEventBus().post(event); if (event.biomeID <= 0 || BiomeGenBase.getBiomeGenArray()[event.biomeID] == null) return Optional.absent(); return Optional.of(BiomeGenBase.getBiomeGenArray()[event.biomeID]); }
@Test public void test() throws ApiSenderException { L2NetworkInventory l2 = deployer.l2Networks.get("TestL2Network"); ClusterInventory cluster = deployer.clusters.get("Cluster1"); api.attachL2NetworkToCluster(l2.getUuid(), cluster.getUuid()); Assert.assertEquals(2, config.createBridgeCmds.size()); }
@Before public void setUp() throws Exception { DBUtil.reDeployDB(); WebBeanConstructor con = new WebBeanConstructor(); deployer = new Deployer("deployerXml/mevoco/TestMevoco.xml", con); deployer.addSpringConfig("mevocoRelated.xml"); deployer.load(); loader = deployer.getComponentLoader(); bus = loader.getComponent(CloudBus.class); dbf = loader.getComponent(DatabaseFacade.class); config = loader.getComponent(LocalStorageSimulatorConfig.class); fconfig = loader.getComponent(FlatNetworkServiceSimulatorConfig.class); Capacity c = new Capacity(); c.total = totalSize; c.avail = totalSize; config.capacityMap.put("host1", c); config.capacityMap.put("host2", c); deployer.build(); api = deployer.getApi(); session = api.loginAsAdmin(); }
@Test public void test() throws ApiSenderException, InterruptedException { final BackupStorageInventory sftp = deployer.backupStorages.get("sftp"); final ImageInventory img = new ImageInventory(); img.setName("image"); img.setPlatform(ImagePlatform.Linux.toString()); img.setMediaType(ImageMediaType.RootVolumeTemplate.toString()); img.setFormat("qcow2"); img.setUrl("http://test.img"); for (int i = 0; i < num; i++) { createVm(img, sftp.getUuid()); } latch.await(5, TimeUnit.MINUTES); Assert.assertEquals(num, vms.size()); fconfig.applyDhcpCmdList.clear(); HostInventory host = deployer.hosts.get("host1"); api.reconnectHost(host.getUuid()); Assert.assertFalse(fconfig.applyDhcpCmdList.isEmpty()); ApplyDhcpCmd cmd = fconfig.applyDhcpCmdList.get(0); Assert.assertEquals(num + 1, cmd.dhcp.size()); List<VmInstanceVO> vms = dbf.listAll(VmInstanceVO.class); for (VmInstanceVO vm : vms) { checkNic(vm, cmd.dhcp); } }
/** * Returns the fully configured {@link OAuthService} * * @return fully configured {@link OAuthService} */ public OAuthService build() { Preconditions.checkNotNull(api, "You must specify a valid api through the provider() method"); Preconditions.checkEmptyString(apiKey, "You must provide an api key"); Preconditions.checkEmptyString(apiSecret, "You must provide an api secret"); return api.createService( new OAuthConfig(apiKey, apiSecret, callback, signatureType, scope, grantType, debugStream)); }
public static WallMessage parse(JSONObject o) throws JSONException { WallMessage wm = new WallMessage(); wm.id = o.getLong("id"); wm.from_id = o.getLong("from_id"); wm.to_id = o.getLong("to_id"); wm.date = o.getLong("date"); wm.online = o.optString("online"); wm.text = Api.unescape(o.getString("text")); if (o.has("likes")) { JSONObject jlikes = o.getJSONObject(NewsJTags.LIKES); wm.like_count = jlikes.getInt("count"); wm.user_like = jlikes.getInt("user_likes") == 1; wm.can_like = jlikes.getInt("can_like") == 1; wm.like_can_publish = jlikes.getInt("can_publish") == 1; } wm.copy_owner_id = o.optLong("copy_owner_id"); JSONArray attachments = o.optJSONArray("attachments"); JSONObject geo_json = o.optJSONObject("geo"); // владельцем опроса является to_id. Даже если добавить опрос в группу от своего имени, то // from_id буду я, но опрос всё-равно будет принадлежать группе. wm.attachments = Attachment.parseAttachments(attachments, wm.to_id, wm.copy_owner_id, geo_json); if (o.has("comments")) { JSONObject jcomments = o.getJSONObject("comments"); wm.comment_count = jcomments.getInt("count"); wm.comment_can_post = jcomments.getInt("can_post") == 1; } return wm; }
@AsyncThread private void createVm(ImageInventory img, String bsUuid) throws ApiSenderException { img = api.addImage(img, bsUuid); InstanceOfferingInventory ioinv = deployer.instanceOfferings.get("small"); L3NetworkInventory l3 = deployer.l3Networks.get("TestL3Network1"); VmCreator creator = new VmCreator(api); creator.imageUuid = img.getUuid(); creator.session = api.getAdminSession(); creator.instanceOfferingUuid = ioinv.getUuid(); creator.name = "vm"; creator.addL3Network(l3.getUuid()); try { synchronized (vms) { vms.add(creator.create()); } } finally { latch.countDown(); } }
private void loadConfigOptions() throws IOException { Chat.get().SetupDefaultLanguage(); ConfigurationNode config = this.getConfig().load(); Api.setApi(ConfigHelper.getString(config, "ApiKey", "Apikey here")); this.interval = Math.max(ConfigHelper.getLong(config, "Interval", 90L), 10L); this.isGuiEnabled = ConfigHelper.getBoolean(config, "Enabled-GUI", false); // TODO forge this.shopCommand = ConfigHelper.getString(config, "Shop-Command", "shop"); this.isSignEnabled = ConfigHelper.getBoolean(config, "Enabled-signs", true); this.color = ConfigHelper.getString(config, "Color", "&0"); Log.setDebugging(ConfigHelper.getBoolean(config, "Debug", false)); }
public boolean cancelOrder(int id) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://app.bb-evacuator.ru/api/") .addConverterFactory(GsonConverterFactory.create()) .build(); Api api = retrofit.create(Api.class); Log.d("SD11", "OK"); Call<CancelResponse> call = api.cancelOrder(id); call.enqueue( new Callback<CancelResponse>() { @Override public void onResponse(Response<CancelResponse> response, Retrofit retrofit) { CancelResponse re = response.body(); Log.d("SD11", response.message()); if ((response.code() != 404 && response.code() != 401)) { isOk = re.getError() == 0; Log.d("SD11", String.valueOf(response.code())); Log.d("SD11", re.getErrorMessage()); Log.d("SD11", String.valueOf(re.getError())); re.getErrorMessage(); re.getError(); } else { isOk = false; } Log.d("SD11", String.valueOf(isOk)); } @Override public void onFailure(Throwable t) { Log.d("SD11", "eror" + t.toString()); } }); return isOk; }
public static Video parseForAttachments(JSONObject o) throws NumberFormatException, JSONException { Video v = new Video(); if (o.has("vid")) v.vid = o.getLong("vid"); if (o.has("id")) // video.getUserVideos v.vid = Long.parseLong(o.getString("id")); v.owner_id = o.getLong("owner_id"); v.title = Api.unescape(o.getString("title")); v.duration = o.getLong("duration"); v.description = Api.unescape(o.optString("description")); if (o.has("image")) v.image = o.optString("image"); v.image_big = o.optString("image_big"); if (o.has("thumb")) // video.getUserVideos v.image = o.optString("thumb"); v.link = o.optString("link"); v.date = o.optLong("date"); v.player = o.optString("player"); if (o.has("views")) { v.views = o.getLong("views"); } return v; }
/** @throws IOException */ public List<Api> parse(TypeElement typeElement) throws IOException { RequestMapping requestMapping = typeElement.getAnnotation(RequestMapping.class); if (requestMapping == null) { generator.log("Controller missing @RequestMapping, " + typeElement); return null; } ApiDoc apiDoc = typeElement.getAnnotation(ApiDoc.class); if (apiDoc == null) { generator.log("Controller missing @ApiDoc, " + typeElement); return null; } // printElement(typeElement); List<Api> apiList = Lists.newArrayList(); String controllerName = typeElement.getQualifiedName().toString(); for (Element ele : typeElement.getEnclosedElements()) { if (ele.getKind().equals(ElementKind.METHOD) && ele.getModifiers().contains(Modifier.PUBLIC)) { Api api = new Api(); api.apiDoc = apiDoc; api.packageMapping = requestMapping; api.controllerName = controllerName; ExecutableElement method = (ExecutableElement) ele; this.parseMethod(api, method); if (api.apiMethodDoc != null) { apiList.add(api); } } } return apiList; }
@Test public void test() throws ApiSenderException { VmInstanceInventory vm = deployer.vms.get("TestVm"); ClusterInventory cluster1 = deployer.clusters.get("Cluster1"); HostInventory host1 = deployer.hosts.get("host1"); ClusterInventory cluster2 = deployer.clusters.get("Cluster2"); HostInventory host2 = deployer.hosts.get("host2"); boolean s = false; try { // vm is running, failure api.getVmStartingCandidateHosts(vm.getUuid(), null); } catch (ApiSenderException e) { s = true; } Assert.assertTrue(s); api.stopVmInstance(vm.getUuid()); APIGetVmStartingCandidateClustersHostsReply reply = api.getVmStartingCandidateHosts(vm.getUuid(), null); Assert.assertEquals(2, reply.getClusterInventories().size()); Assert.assertEquals(2, reply.getHostInventories().size()); }
@Before public void setUp() throws Exception { DBUtil.reDeployDB(); WebBeanConstructor con = new WebBeanConstructor(); deployer = new Deployer("deployerXml/kvm/TestStartVmOnTargetHost.xml", con); deployer.addSpringConfig("KVMRelated.xml"); deployer.build(); api = deployer.getApi(); loader = deployer.getComponentLoader(); bus = loader.getComponent(CloudBus.class); dbf = loader.getComponent(DatabaseFacade.class); config = loader.getComponent(SftpBackupStorageSimulatorConfig.class); session = api.loginAsAdmin(); }
@BeforeClass public static void setUp() throws Exception { DBUtil.reDeployDB(); WebBeanConstructor con = new WebBeanConstructor(); deployer = new Deployer("deployerXml/kvm/TestKvmAttachL2Network.xml", con); deployer.addSpringConfig("Kvm.xml"); deployer.addSpringConfig("KVMSimulator.xml"); deployer.build(); api = deployer.getApi(); loader = deployer.getComponentLoader(); kvmFactory = loader.getComponent(KVMHostFactory.class); bus = loader.getComponent(CloudBus.class); dbf = loader.getComponent(DatabaseFacade.class); config = loader.getComponent(KVMSimulatorConfig.class); session = api.loginAsAdmin(); }
@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.friends, container, false); account.restore(getActivity()); if (account.access_token != null) { api = Api.get(); } else { Toast.makeText(getActivity(), "Access token == null", Toast.LENGTH_LONG).show(); } lvNews = (ListView) rootView.findViewById(R.id.ListView); getNotifications(account.user_id); return rootView; }
@Before public void setUp() throws Exception { DBUtil.reDeployDB(); WebBeanConstructor con = new WebBeanConstructor(); deployer = new Deployer("deployerXml/virtualRouter/startVirtualRouter.xml", con); deployer.addSpringConfig("VirtualRouter.xml"); deployer.addSpringConfig("VirtualRouterSimulator.xml"); deployer.addSpringConfig("KVMRelated.xml"); deployer.build(); api = deployer.getApi(); loader = deployer.getComponentLoader(); vconfig = loader.getComponent(VirtualRouterSimulatorConfig.class); kconfig = loader.getComponent(KVMSimulatorConfig.class); bus = loader.getComponent(CloudBus.class); dbf = loader.getComponent(DatabaseFacade.class); session = api.loginAsAdmin(); }
public static WallMessage parseForNotifications(JSONObject o) throws JSONException { WallMessage wm = new WallMessage(); wm.id = o.getLong("id"); wm.from_id = Long.parseLong(o.getString("owner_id")); wm.text = Api.unescape(o.getString("text")); // likes is there but I don't parse it because I don't need it // if (o.has("likes")){ // JSONObject jlikes = o.getJSONObject(NewsJTags.LIKES); // wm.like_count = jlikes.getInt("count"); // wm.user_like = jlikes.getInt("user_likes")==1; // wm.can_like = jlikes.getInt("can_like")==1; // wm.like_can_publish = jlikes.getInt("can_publish")==1; // } JSONArray attachments = o.optJSONArray("attachments"); JSONObject geo_json = o.optJSONObject("geo"); wm.attachments = Attachment.parseAttachments(attachments, wm.to_id, wm.copy_owner_id, geo_json); return wm; }
@Test public void test() throws ApiSenderException { ImageInventory iminv = deployer.images.get("TestImage"); InstanceOfferingInventory ioinv = deployer.instanceOfferings.get("TestInstanceOffering"); L3NetworkInventory l3inv = deployer.l3Networks.get("TestL3Network2"); APICreateVmInstanceMsg msg = new APICreateVmInstanceMsg(); msg.setImageUuid(iminv.getUuid()); msg.setInstanceOfferingUuid(ioinv.getUuid()); List<String> l3uuids = new ArrayList<String>(); l3uuids.add(l3inv.getUuid()); msg.setL3NetworkUuids(l3uuids); msg.setName("TestVm"); msg.setSession(session); msg.setServiceId(ApiMediatorConstant.SERVICE_ID); msg.setType(VmInstanceConstant.USER_VM_TYPE); ApiSender sender = api.getApiSender(); sender.send(msg, APICreateVmInstanceEvent.class); }
public static Note parse(JSONObject o) throws NumberFormatException, JSONException { Note note = new Note(); note.nid = o.optLong("id"); // в новости "добавил заметку" заметка приходит по-старому - баг в API if (!o.has("id") && o.has("nid")) note.nid = o.optLong("nid"); note.owner_id = o.getLong("owner_id"); note.title = Api.unescape(o.getString("title")); note.ncom = o.optLong("comments"); // в новости "добавил заметку" заметка приходит по-старому - баг в API if (!o.has("comments") && o.has("ncom")) note.ncom = o.optLong("ncom"); // note.read_ncom = o.optLong("read_comments"); note.text = o.optString("text"); note.date = o.optLong("date"); return note; }
@Bean protected ObserverFactory observerFactory() { return new DefaultObserverFactory( // userStore, // api.systemFluentApi(), // workflow.systemWorkflowLogicBuilder().build(), // email.emailAccountFacade(), // email.emailTemplateLogic(), // data.systemDataView(), // new Supplier<CMDataView>() { @Override public CMDataView get() { return user.userDataView(); } }, // emailTemplateSenderFactory() // ); }
@Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) { // Ignore application updates final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (!replacing) { // Update the Firewall if necessary final int uid = intent.getIntExtra(Intent.EXTRA_UID, -123); Api.applicationRemoved(context, uid); // Force app list reload next time Api.applications = null; } } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) { final boolean appExists = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (appExists) { // do nothing } else { // Force app list reload next time Api.applications = null; // check to see if Notifications are enabled SharedPreferences prefs = context.getSharedPreferences(Api.PREFS_NAME, 0); boolean NotifyEnabled = prefs.getBoolean(Api.PREF_NOTIFY, false); if (NotifyEnabled) { String new_app_installed = intent.getData().getSchemeSpecificPart(); if (PackageManager.PERMISSION_GRANTED == context .getPackageManager() .checkPermission(Manifest.permission.INTERNET, new_app_installed)) { // notify the User that a new app has been installed notifyUserOfAppInstall(context, new_app_installed); } } } } }
public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } String description; List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping controllerRM = controller.getAnnotation(RequestMapping.class); String[] controllerProduces = new String[0]; String[] controllerConsumes = new String[0]; if (controllerRM != null) { controllerConsumes = controllerRM.consumes(); controllerProduces = controllerRM.produces(); } if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); description = api.description(); } resourcePath = resource.getControllerMapping(); // collect api from method with @RequestMapping Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping == null) { continue; } ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); if (apiOperation == null || apiOperation.hidden()) { continue; } String httpMethod = null; Map<String, String> regexMap = new HashMap<String, String>(); String operationPath = parseOperationPath(path, regexMap); // http method for (RequestMethod requestMethod : requestMapping.method()) { httpMethod = requestMethod.toString().toLowerCase(); Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiProduces = requestMapping.produces(); String[] apiConsumes = requestMapping.consumes(); apiProduces = (apiProduces == null || apiProduces.length == 0) ? controllerProduces : apiProduces; apiConsumes = (apiConsumes == null || apiProduces.length == 0) ? controllerConsumes : apiConsumes; apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); apiProduces = updateOperationProduces(new String[0], apiProduces, operation); updateTagsForOperation(operation, apiOperation); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } } return swagger; }