Vaadin7 jQuery UI integration - javascript

Vaadin 7 supports custom javascript. But my question is if we want to integrate jQuery-ui with vaadin7, how can we add jQuery-ui css files. At the moment #Javascript supports adding javascript only. If we wanna add css, we have add that as sass style.

To add jQuery (or any other javascript library) to a Vaadin 7 application, follow these easy steps:
First Create a Vaadin project either using your favorite IDE or the vaadin maven archetype (or both). Create a new class that extends from VaadinServlet, and override the servletInitialized method:
import javax.servlet.ServletException;
import com.vaadin.server.BootstrapFragmentResponse;
import com.vaadin.server.BootstrapListener;
import com.vaadin.server.BootstrapPageResponse;
import com.vaadin.server.ServiceException;
import com.vaadin.server.SessionInitEvent;
import com.vaadin.server.SessionInitListener;
import com.vaadin.server.VaadinServlet;
public class TestJqueryVaadinServlet extends VaadinServlet {
#Override
protected void servletInitialized() throws ServletException {
super.servletInitialized();
getService().addSessionInitListener(new SessionInitListener() {
#Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
event.getSession().addBootstrapListener(new BootstrapListener() {
#Override
public void modifyBootstrapPage(BootstrapPageResponse response) {
// With this code, Vaadin servlet will add the line:
//
// <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" />
//
// as the first line inside the document's head tag in the generated html document
response.getDocument().head().prependElement("script").attr("type", "text/javascript").attr("src", "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
}
#Override
public void modifyBootstrapFragment(BootstrapFragmentResponse response) {}
});
}
});
}
}
Then add the reference to the servlet in your web.xml or annotate the class with the #WebServlet annotation.
And then Create your jQuery snippet and invoke it using the JavaScript class, for example:
public class MyVaadinUI extends UI {
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Label label = new Label("This will fade-out once you click the button");
Button button = new Button("Hide Label");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
JavaScript.getCurrent().execute("$('.v-label').animate({opacity: 0.0}, 3000);");
}
});
layout.addComponent(label);
layout.addComponent(button);
}
}
Including style sheets or JavaScript files in your add-ons or as a part of your application can now be done by adding a #StyleSheet or #JavaScript annotation to a Component or Extension class. Each annotation takes a list of strings with URLs to the resources that should be loaded on the page before the framework initializes the client-side Component or Extension.
The URLs can either be complete absolute urls (e.g."https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js") or relative URLs (e.g. "redbutton.css"). A relative URL is converted to a special URL that will download the file from the Java package where the defining class is located. This means that e.g. #StyleSheet({"redbutton.css"}) on the class com.example.RedButton will cause the file com/example/redbutton.css on the classpath to be loaded in the browser. #JavaScript works in exactly the same way
#!java
#StyleSheet("redbutton.css")
public class RedButton extends NativeButton {
public RedButton(String caption) {
super(caption);
addStyleName("redButton");
}
}
In this simple example, the RedButton component just adds a
redButton
style name to a normal
NativeButton
. redbutton.css is located in the same folder as RedButton.java and has this content:
#!css
.redButton {
background-color: red;
}
This new mechanism makes it very easy to include style sheet or JavaScript files with add-ons and automatically load them in the browser when the add-on is used.
Second and my favorite way:
you can also use the #Stylesheet and #Javascript annotations. its much simpler.
#StyleSheet({
/*
* JQuery UI
*/
"vaadin://jquery/jquery-ui-1.9.2.custom/css/ui-darkness/jquery-ui-1.9.2.custom.min.css",
})
#JavaScript({
/*
* JQuery
*/
"vaadin://jquery/jquery-1.11.1.min.js",
/*
* JQuery UI
*/
"vaadin://jquery/jquery-ui-1.9.2.custom/js/jquery-ui-1.9.2.custom.min.js",
})
public class MyUI extends UI {
...
}

Related

Run some Javascript file like index.js in Flutter Webview

how I can run Javascript file in the flutter_webview_plugin. I try it with this.
flutterWebViewPlugin.evalJavascript("require('./index.js');");
But nothing happens.
when I try to run flutter code it's shows nothing
my index.Js file contains a simple alert statement
alert('hello world');
First, You used "require" function. this function is not implemented in javascript itself. it's a part of NodeJs. so that function will not work.
In order to load a js file into flutter, you should consider it as a text file and load it properly. So, you need to add the file to assets folder, add into pubspec file, then load it. read the full answer here
Second, you used evalJavascript. this function can be used in many different situations. but it will work only if you have a view panel.
Check below example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
main() async {
String jsCode = await rootBundle.loadString('assets/javascript.js');
runApp(new MaterialApp(
home: LunchWebView(jsCode),
));
}
class LunchWebView extends StatelessWidget {
final String text;
LunchWebView(this.text);
#override
Widget build(BuildContext context) {
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
flutterWebviewPlugin.launch('https://www.google.com');
flutterWebviewPlugin.evalJavascript(text);
return Container();
}
}
NOTE: : I didn't handle reloading and other exceptions. you should check if there is any webview object open and then call Lunch method.

React Native Android Webview Video

I'm using React Native to create an Android/iOS app and trying to get a video to play in the WebView component. The video plays fine on iOS, but I'm having trouble getting it to play in the android WebView.
I've come across a few threads like this one (Enabling HTML5 video playback in android WebView?) that claim this is a fairly common problem on Android and can be solved by importing WebChromeClient and setting that option on the webview like so:
mainWebView.setWebChromeClient(new WebChromeClient());
But almost all these threads are strictly about building a native Android app and not using React Native.
Does anyone know how to get this to work in React Native?
I refer to an article by Yevgen Safronov
In it, he writes
Obviously the most challenging part of the application is handling
live video stream, because it requires switching stream’s video
quality based on available Internet bandwidth. But first things
first — I needed a RN native component to show any video stream. There
is a popular video component for RN but it has support for iOS only. I
decided to write my own RN component wrapper around Vitamio player. It
is well known open-source project and has support of RTMP protocol we
use for mobile app.
I had no prior experience with writing native RN components so I went
directly to RN documentation on how to create one. A guide I refer to
is called Native UI Components, there is similar one for iOS. There
are several essential parts to declare:
Implement custom ViewManager (Android part)
Register the ViewManager (Android part)
Implement the JavaScript module
Register the module (Android part)
Implement custom ViewManager Referring to the example of declaring
VideoView for Vitamio this is how the essence of VideoView declaration
looks like:
public class VideoViewDemo extends Activity {
#Override public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (!LibsChecker.checkVitamioLibs(this))
return;
setContentView(R.layout.videoview);
mEditText = (EditText) findViewById(R.id.url);
mVideoView = (VideoView) findViewById(R.id.surface_view);
if (path == "") { return; }
mVideoView.setVideoPath(path);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
}
...
}
The code looks quite straightforward. Apart from passing a reference
to Activity into LibsChecker, VideoView requires a path to a video
stream and instance of MediaController.
public class VitamioViewManager extends SimpleViewManager<VideoView>{
public static final String REACT_CLASS = “RCTVitamioView”;
#Override
public String getName() {
return REACT_CLASS;
}
expose setStreamUrl setter using ReactProp:
#ReactProp(name = "streamUrl")
public void setStreamUrl(VideoView view, #Nullable String streamUrl) {
if (!LibsChecker.checkVitamioLibs(mActivity))
return;
view.setVideoPath(streamUrl);
view.setMediaController(new MediaController(mContext));
view.requestFocus();
}
add createViewInstance implementation:
private ThemedReactContext mContext = null;
private Activity mActivity = null;
#Override
public VideoView createViewInstance(ThemedReactContext context){
mContext = context;
return new VideoView(context);
}
One note about the code. Because LibsChecker requires an instance of Activity we will receive it via constructor, it will reference root activity used for RN application;
public VitamioViewManager(Activity activity) {
mActivity = activity;
}
Register the ViewManager
The final Java step is to register the ViewManager to the application, this happens via the applications package member function createViewManagers:
...
public class VitamioViewPackage implements ReactPackage {
private Activity mActivity = null;
public VitamioViewPackage(Activity activity) {
mActivity = activity;
}
#Override
public List<NativeModule>
createNativeModules(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
#Override
public List<ViewManager>
createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new VitamioViewManager(mActivity)
);
}
}
Implement the JavaScript module In order to expose custom UI component
in JavaScript it is necessary to call special requireNativeComponent
function:
var { requireNativeComponent, PropTypes } = require('react-native');
var iface = {
name: 'VideoView',
propTypes: {
streamUrl: PropTypes.string
}
};
module.exports = requireNativeComponent('RCTVitamioView', iface);
Register the module Although it’s not mentioned as required step in
official documentation we need it because of reference to the root
activity: package com.vitamio_demo;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
import com.sejoker.VitamView.VitamioViewPackage; // <--- import
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "vitamio_demo";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
#Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new VitamioViewPackage(this) // <------ add here
);
}
}
Example of usage
Install the package in a project:
npm i react-native-android-vitamio --save
DeclareVideoView:
var VitamioView = require('react-native-android-vitamio');
class VideoScreen extends React.Component {
render() {
return (
<View>
<VitamioView style={styles.video} streamUrl="rtmp://fms.12E5.edgecastcdn.net/0012E5/mp4:videos/8Juv1MVa-485.mp4"/>
</View>
);
}
}
var styles = StyleSheet.create({
video: {
flex: 1,
flexDirection: 'row',
height: 400,
}
})
module.exports = VideoScreen;
Hope this is of help, A list of his own references is given in the article.

Can Selenium IDE/Builder run same test case on many pages?

Is there a way to run the same Selenium test case on many pages without specifically defining a list of pages?
Say, for example, I have a UIMap pageset defined like this:
var map = new UIMap();
map.addPageset({
name: 'pages',
description: 'all pages',
pathRegexp: '^thisistheroot/$'
});
In the pageset, I have all the elements defined for a test script that I want to test on each page in the pageset.
All of this is added to my core extensions.
Am I able to run a test case on the entire pageset? How can I do that?
I've looked into the issue a little more. Is there a way this is possible with Jenkins? https://jenkins-ci.org/
Edit:
I was trying to avoid using selenium webdriver, but if it is possible to obtain links as you would in a UIMap, that would probably point me in the right direction as well. I would try to iterate over the links with a single test case, which can easily be done in java. I'm using java for webdriver by the way.
Thanks.
The simple answer is "no" but Selenium WebDriver is one of the best choices for sure to find the links of a page and iterate over them. There is a very similar concept of your UIMapping called PageFactory where you map all the page elements in separate classes to keep the responsibility separate which makes debugging and refactoring much easier. I have used the PageFactory concept here.
Now coming back to your question, you can easily find the list of the links present in a page. In that case you just need to write the selector little carefully. You can then easily iterate over the links and come back and forth and so on.
Proof of concept on Google
BasePage
package google;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.NoSuchElementException;
/**
* Defines the generic methods/functions for PageObjects.
*/
public class BaseClass {
protected WebDriver driver;
/**
* #param _driver
* #param byKnownElement
*/
public BaseClass(WebDriver _driver, By byKnownElement) {
//assigning driver instance globally.
driver = _driver;
this.correctPageLoadedCheck(byKnownElement);
/* Instantiating all elements since this is super class
and inherited by each and every page object */
PageFactory.initElements(driver, this);
}
/**
* Verifies correct page was returned.
*
* #param by
*/
private void correctPageLoadedCheck(By by) {
try {
driver.findElement(by).isDisplayed();
} catch (NoSuchElementException ex) {
throw ex;
}
}
}
PageObject inherited BasePage
package google;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import java.util.List;
/**
* Created by Saifur on 5/30/2015.
*/
public class GoogleLandingPage extends BaseClass {
private static final By byKnownElement = By.xpath("//a[text()='Sign in']");
/**
* #param _driver
*/
public GoogleLandingPage(WebDriver _driver) {
super(_driver, byKnownElement);
}
//This should find all the links of the page
//You need to write the selector such a way
// so that it will grab all intended links.
#FindBy(how = How.CSS,using = ".gb_e.gb_0c.gb_r.gb_Zc.gb_3c.gb_oa>div:first-child a")
public List<WebElement> ListOfLinks;
}
BaseTest
package tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
public class BaseTest {
public WebDriver driver;
String url = "https://www.google.com/";
#BeforeClass
public void SetUpTests() {
driver = new FirefoxDriver();
//Navigate to url
driver.navigate().to(url);
//Maximize the browser window
driver.manage().window().maximize();
}
#AfterClass
public void CleanUpDriver() throws Exception {
try {
driver.quit();
}catch (Exception ex){
throw ex;
}
}
}
Link Iterator test inheriting BaseTest
package tests;
import google.GoogleLandingPage;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import java.util.List;
/**
* Created by Saifur on 5/30/2015.
*/
public class LinksIteratorTests extends BaseTest {
#Test
public void IterateOverLinks(){
GoogleLandingPage google = new GoogleLandingPage(driver);
List<WebElement> elementList = google.ListOfLinks;
for (int i=0;i<elementList.size(); i++){
elementList.get(i).click();
//possibly do something else to go back to the previous page
driver.navigate().back();
}
}
}
Note: I am using TestNG to maintain the tests and please note for lazy loading page you may need to add some explicit wait if necessary
Actually it's simple to run an IDE test against 1 specific page (base url actually): java -jar selenium-server.jar -htmlSuite "*firefox" "http://baseURL.com" "mytestsuite.html" "results.html"
So what you need to do is use jenkins (or any bash/batch script) to run that command multiple times with the base url set as "http://baseURL.com/page1", "http://baseURL.com/page2", etc.
This will only get you as far as static list of pages to test against. If you want a dynamic list you'd have to also "crawl" the pages and you could do that in the similar batch/bash script to obtain the list of pages to test against.
In this case you'd best be investing beyond selenium IDE and switch to webdriver where you'll have more power to loop and flow control.

Is it possible to use JavaScript code in Android?

in this code Android app opens a web page with WebView and extracts a text from HTML which is between tags "body" and "/body".
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
public class MainAc extends Activity {
/** Called when the activity is first created. */
#SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.web);
TextView text2 = (TextView) findViewById(R.id.text);
Button infoButton = (Button) findViewById(R.id.b1);
infoButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// here is your button click logic, for example running another activity (page)
startActivity(new Intent(MainAc.this, JavaInterface.class));
}
});
class Javasc {
private TextView t2;
public Javasc (TextView i)
{
t2 = i;
}
#SuppressWarnings("unused")
public void processContent(String ii)
{
final String content = ii;
t2.post(new Runnable()
{
public void run()
{
t2.setText(content);
}
});
}
}
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Javasc(text2), "INTERFACE");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
view.loadUrl("javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText);");
}
});
webView.loadUrl("http://www.nytimes.com/2014/08/03/sports/basketball/pacers-paul-george-has-surgery-after-badly-injuring-leg.html?ref=sports");
}
}
Is it possible to use JavaScript functions for extracted text in android's TextView ?
for example this JavaScript function (or it could be any other JS function where need to work with text)
function myFunction() {
var text = document.body.innerText;
var titles =text.match(/^\n(.+?)\n\n/mg);
for (var i = 0; i < titles.length; i++) {
document.write(titles[i] + "<br />" + "<br />");
}
}
Thanks for answers :)
According to this article, the Dalvik VM supports Java's scripting features (javax.script). One of the premier languages supported by the javax.script stuff is, unsurprisingly, JavaScript.
So in theory, you can use the javax.script stuff to execute JavaScript code and get back results. I think (also based on that article), that you have to include the relevant jar(s) (javax.script isn't in the Android SDK). Fortunately, though, javax.script is largely a set of interfaces, which are implemented by jars for specific scripting languages.
Some resources about using javax.script to run script code:
The Java Scripting API (Oracle)
Java Scripting Programmer's Guide (Oracle)
You can use Rhino to achieve this. See specifically Context.jsToJava.
https://vec.io/posts/embed-javascript-in-android-java-code-with-rhino
You want to do a regex on a text and resorting to javascript for it, which is unnecessary when you have a better faster API in java with no overhead.
The equivalent to your example is:
http://developer.android.com/reference/java/util/regex/Pattern.html
Pattern p = Pattern.compile("/^\n(.+?)\n\n/mg");
Matcher m = p.matcher(myTextView.getText());
while (m.find()) {
String titles = m.group(1);
Log.V("TAG", titles);
}
There are plenty of other text analysis solutions included in the core framework or external libraries that have been proved for both mobile and server. You just have to look it up and not resort to a worse API you're comfortable with.

How to extend javascript editor in JSDT in Eclipse with adding new functions

I am using RCP to create special javascripts editor with special functions and want to extends js editor from JSDT by adding new functions in context menu and in content assistant. But how can I start. Here is my thinking:
1) rewrite a jscript editor which extends CompilationUnitEditor by import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor; But it seems not working, it only has part of functions from JSDT, no colored squiggly marks in the text.
import org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor;
public class Jscript extends CompilationUnitEditor {
public static final String ID="com.test.scripteditor.editor3";
public Jscript(){
super();
}
}
2) Any possibles ways to add exentsions directly from plugin.xml to make this process quick?
Thanks for any suggestions. I do really do not know how to do it.

Categories

Resources