YouTube iFrame API Not Working Properly In JavaFX WebView? - api

So recently I've been working on making an audioplayer that can play playlists made by the user (mp3 files, wav files etc.) but that can also play YouTube playlists. In order to play YouTube videos I use JavaFX's WebView in combination with Google's YouTube iFrame API.
In order to do so, I use the following code;
#Override
public void loadList(String list)
{
html = "<!DOCTYPE html>\n" +
"<html>\n" +
" <body>\n" +
"<iframe id=\"player\" width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/videoseries?list=PL7aXwAD1wk5kdkuQOFBHY63R9Bhki7rCg&enablejsapi=1\" frameborder=\"0\" gesture=\"media\" allowfullscreen></iframe>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" var tag = document.createElement('script');\n" +
" tag.id = 'iframe-demo';\n" +
" tag.src = 'https://www.youtube.com/iframe_api';\n" +
" var firstScriptTag = document.getElementsByTagName('script')[0];\n" +
" var volume = 100;\n" +
" firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n" +
"\n" +
" var player;\n" +
" function onYouTubeIframeAPIReady() {\n" +
" player = new YT.Player('player', {\n" +
" events: {\n" +
" 'onReady': onPlayerReady,\n" +
" 'onError' : handleError,\n" +
" 'onStateChange' : stateChange,\n" +
" 'onApiChange' : stateChange\n" +
" }\n" +
" });\n" +
" }\n" +
" function onPlayerReady(event) {\n" +
" event.target.playVideo();\n" +
" //event.target.nextVideo();\n" +
" }\n" +
" \n" +
" function handleError(event)\n" +
" {\n" +
" console.log(event);\n" +
" player.nextVideo();\n" +
" }\n" +
" \n" +
" function setVolume(vol)\n" +
" {\n" +
" volume = vol;\n" +
" player.setVolume(vol);\n" +
" }\n" +
" \n" +
" function stateChange(event)\n" +
" {\n" +
" // player.setVolume(volume + 1);\n" +
" // player.setVolume(volume - 1);\n" +
" // player.setVolume(volume);\n" +
" }\n" +
"</script>\n" +
" </body>\n" +
"</html>";
jfxPanel = new JFXPanel();
Platform.runLater ( new Runnable () {
#Override
public void run () {
player = new WebView();
player.getEngine().setJavaScriptEnabled(true);
player.getEngine().loadContent(html);
jfxPanel.setScene(new Scene(player));
JFrame f = new JFrame();
f.add(jfxPanel);
f.setSize(1280,720);
f.setVisible(true);
}
} );
GraphicalInterface.uptodate = false;
}
The issue I am having is this:
Once I use the API's 'player.setVolume(vol)' functionality, it correctly changes the volume for the video it is currently playing. When a new video loads, the videoplayer still shows the volume is the same as it had previously been set to, but it outputs too high of a volume;
first video, lowered volume;
second video, volumeslider is lowered, volume itself isn't;
I only have this issue when using JavaFX's WebView. When I paste the HTML code in a .html file and run it that way, the audio is correctly lowered (and not just the audio slider).
Does anyone know why this could be happening and how I can fix this? Does it have to do with the WebView's settings?
Note:
In the JavaScript I have commented out a small piece of code. This code is a small temporary workaround that "re-setd" the audio to where it should be when a new video is loaded. This solution is not ideal though.

Related

Visual Basic / SQL Server: identity_insert is set to off error

I just recently started toying with all of this programming stuff, so I'm not quite sure on how to fix a minor problem I seem to have with the communication between the server and the client.
when I start up the server, players are able to connect and log out when they are done playing without any problems, but the server throws an error and doesn't save the item in the table items.
It's almost as if the server/client can't communicate properly with the dbo.items table :/
Any help would be appreciated! Thank you.
And sorry for the bad English
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Goose
{
/**
* Item, holds the actual item data
*
* Each item in game is separate
* Holds the original template and modified/added stats
*
*/
public class Item : IItem
{
public int ItemID { get; set; }
public int TemplateID { get; set; }
public ItemTemplate Template { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int GraphicEquipped { get; set; }
public int GraphicTile { get; set; }
public int GraphicR { get; set; }
public int GraphicG { get; set; }
public int GraphicB { get; set; }
public int GraphicA { get; set; }
int weapondamage = 0;
public int WeaponDamage
{
get
{
return this.weapondamage + (int)Math.Ceiling(this.Template.WeaponDamage * this.StatMultiplier);
}
set
{
this.weapondamage = value;
}
}
/**
* Body pose/state 1 for normal, 3 for staff, 4 for sword
*/
public int BodyState { get; set; }
public AttributeSet BaseStats { get; set; }
public AttributeSet TotalStats { get; set; }
public decimal StatMultiplier { get; set; }
/**
* Dirty, has data changed since loading
*
*/
public bool Dirty { get; set; }
/**
* Delete, item is no longer in game so delete it
*/
public bool Delete { get; set; }
public long Value { get; set; }
bool bound = false;
public bool IsBound
{
get { return this.bound; }
set { this.bound = value; }
}
/**
* These properties are read only and just pass along from the templates properties
*
*/
public int WeaponDelay { get { return this.Template.WeaponDelay; } }
public int StackSize { get { return this.Template.StackSize; } }
public bool IsLore { get { return this.Template.IsLore; } }
public bool IsBindOnPickup { get { return this.Template.IsBindOnPickup; } }
public bool IsBindOnEquip { get { return this.Template.IsBindOnEquip; } }
public bool IsEvent { get { return this.Template.IsEvent; } }
public ItemTemplate.ItemSlots Slot { get { return this.Template.Slot; } }
public ItemTemplate.ItemTypes Type { get { return this.Template.Type; } }
public ItemTemplate.UseTypes UseType { get { return this.Template.UseType; } }
public int MinLevel { get { return this.Template.MinLevel; } }
public int MaxLevel { get { return this.Template.MaxLevel; } }
public long MinExperience { get { return this.Template.MinExperience; } }
public long MaxExperience { get { return this.Template.MaxExperience; } }
/**
* This is a bitmask
* Therefore only limited to about 64 classes, which should be enough.
* If the bit is set then that class id CAN'T use the item.
*
*/
public long ClassRestrictions { get { return this.Template.ClassRestrictions; } }
public SpellEffect SpellEffect { get { return this.Template.SpellEffect; } }
public decimal SpellEffectChance { get { return this.Template.SpellEffectChance; } }
public int LearnSpellID { get { return this.Template.LearnSpellID; } }
public bool Unsaved { get; set; }
public Item()
{
this.Unsaved = true;
this.ItemID = 0;
this.TotalStats = new AttributeSet();
this.BaseStats = new AttributeSet();
this.StatMultiplier = 1;
this.Dirty = true;
this.Delete = false;
}
/**
* LoadFromTemplate, loads item from a template
*
* This is when we want an item the same as the template.
*
*/
public void LoadFromTemplate(ItemTemplate template)
{
this.Template = template;
this.TemplateID = this.Template.ID;
this.TotalStats += this.Template.BaseStats;
this.Name = this.Template.Name;
this.Description = this.Template.Description;
this.GraphicEquipped = this.Template.GraphicEquipped;
this.GraphicTile = this.Template.GraphicTile;
this.GraphicR = this.Template.GraphicR;
this.GraphicG = this.Template.GraphicG;
this.GraphicB = this.Template.GraphicB;
this.GraphicA = this.Template.GraphicA;
this.Value = this.Template.Value;
this.BodyState = this.Template.BodyState;
}
/**
* LoadTemplate, adds template to item
*
* This is when we want to just add the templates stats to our item
* ie when loading the items database, eg for surname/titled items
*
* Note: Doesn't load the value from the template as we want to keep the value as 0
* if the item is custom for example
*
*/
public void LoadTemplate(ItemTemplate template)
{
this.TotalStats += template.BaseStats;
this.TotalStats *= this.StatMultiplier;
this.TotalStats += this.BaseStats;
}
/**
* AddItem, adds item to database
*
*/
public void AddItem(GameWorld world)
{
SqlParameter nameParam = new SqlParameter("#itemName", SqlDbType.VarChar, 64);
nameParam.Value = this.Name;
SqlParameter descriptionParam = new SqlParameter("#itemDescription", SqlDbType.VarChar, 64);
descriptionParam.Value = this.Description;
string query = "INSERT INTO items (item_id, item_template_id, item_name, item_description, " +
"player_hp, player_mp, player_sp, stat_ac, stat_str, stat_sta, stat_dex, stat_int, " +
"res_fire, res_water, res_spirit, res_air, res_earth, weapon_damage, item_value, " +
"graphic_tile, graphic_equip, graphic_r, graphic_g, graphic_b, graphic_a, stat_multiplier, " +
"bound, body_state) VALUES (" +
this.ItemID + "," +
this.TemplateID + ", " +
"#itemName, " +
"#itemDescription, " +
this.BaseStats.HP + ", " +
this.BaseStats.MP + ", " +
this.BaseStats.SP + ", " +
this.BaseStats.AC + ", " +
this.BaseStats.Strength + ", " +
this.BaseStats.Stamina + ", " +
this.BaseStats.Dexterity + ", " +
this.BaseStats.Intelligence + ", " +
this.BaseStats.FireResist + ", " +
this.BaseStats.WaterResist + ", " +
this.BaseStats.SpiritResist + ", " +
this.BaseStats.AirResist + ", " +
this.BaseStats.EarthResist + ", " +
this.weapondamage + ", " +
this.Value + ", " +
this.GraphicTile + ", " +
this.GraphicEquipped + ", " +
this.GraphicR + ", " +
this.GraphicG + ", " +
this.GraphicB + ", " +
this.GraphicA + ", " +
this.StatMultiplier + ", " +
(this.bound ? "'1'" : "'0'") + ", " +
this.BodyState + ")";
this.Dirty = false;
this.Unsaved = false;
SqlCommand command = new SqlCommand(query, world.SqlConnection);
command.Parameters.Add(nameParam);
command.Parameters.Add(descriptionParam);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
}
/**
* SaveItem, updates item info in database
*
*/
public void SaveItem(GameWorld world)
{
SqlParameter nameParam = new SqlParameter("#itemName", SqlDbType.VarChar, 64);
nameParam.Value = this.Name;
SqlParameter descriptionParam = new SqlParameter("#itemDescription", SqlDbType.VarChar, 64);
descriptionParam.Value = this.Description;
string query = "UPDATE items SET " +
"item_template_id=" + this.TemplateID + ", " +
"item_name=" + "#itemName, " +
"item_description=" + "#itemDescription, " +
"player_hp=" + this.BaseStats.HP + ", " +
"player_mp=" + this.BaseStats.MP + ", " +
"player_sp=" + this.BaseStats.SP + ", " +
"stat_ac=" + this.BaseStats.AC + ", " +
"stat_str=" + this.BaseStats.Strength + ", " +
"stat_sta=" + this.BaseStats.Stamina + ", " +
"stat_dex=" + this.BaseStats.Dexterity + ", " +
"stat_int=" + this.BaseStats.Intelligence + ", " +
"res_fire=" + this.BaseStats.FireResist + ", " +
"res_water=" + this.BaseStats.WaterResist + ", " +
"res_spirit=" + this.BaseStats.SpiritResist + ", " +
"res_air=" + this.BaseStats.AirResist + ", " +
"res_earth=" + this.BaseStats.EarthResist + ", " +
"weapon_damage=" + this.weapondamage + ", " +
"item_value=" + this.Value + ", " +
"graphic_tile=" + this.GraphicTile + ", " +
"graphic_equip=" + this.GraphicEquipped + ", " +
"graphic_r=" + this.GraphicR + ", " +
"graphic_g=" + this.GraphicG + ", " +
"graphic_b=" + this.GraphicB + ", " +
"graphic_a=" + this.GraphicA + ", " +
"stat_multiplier=" + this.StatMultiplier + ", " +
"bound=" + (this.bound ? "'1'" : "'0'") + ", " +
"body_state=" + this.BodyState +
" WHERE item_id=" + this.ItemID;
SqlCommand command = new SqlCommand(query, world.SqlConnection);
command.Parameters.Add(nameParam);
command.Parameters.Add(descriptionParam);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
this.Dirty = false;
}
/**
* DeleteItem, deletes item from database
*
*/
public void DeleteItem(GameWorld world)
{
SqlCommand command = new SqlCommand(
"DELETE FROM items WHERE item_id=" + this.ItemID,
world.SqlConnection);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
}
}
}
public void AddItem(GameWorld world)
{
SqlParameter nameParam = new SqlParameter("#itemName", SqlDbType.VarChar, 64);
nameParam.Value = this.Name;
SqlParameter descriptionParam = new SqlParameter("#itemDescription", SqlDbType.VarChar, 64);
descriptionParam.Value = this.Description;
string query = "INSERT INTO items (item_template_id, item_name, item_description, " +
"player_hp, player_mp, player_sp, stat_ac, stat_str, stat_sta, stat_dex, stat_int, " +
"res_fire, res_water, res_spirit, res_air, res_earth, weapon_damage, item_value, " +
"graphic_tile, graphic_equip, graphic_r, graphic_g, graphic_b, graphic_a, stat_multiplier, " +
"bound, body_state) VALUES (" +
this.TemplateID + ", " +
"#itemName, " +
"#itemDescription, " +
this.BaseStats.HP + ", " +
this.BaseStats.MP + ", " +
this.BaseStats.SP + ", " +
this.BaseStats.AC + ", " +
this.BaseStats.Strength + ", " +
this.BaseStats.Stamina + ", " +
this.BaseStats.Dexterity + ", " +
this.BaseStats.Intelligence + ", " +
this.BaseStats.FireResist + ", " +
this.BaseStats.WaterResist + ", " +
this.BaseStats.SpiritResist + ", " +
this.BaseStats.AirResist + ", " +
this.BaseStats.EarthResist + ", " +
this.weapondamage + ", " +
this.Value + ", " +
this.GraphicTile + ", " +
this.GraphicEquipped + ", " +
this.GraphicR + ", " +
this.GraphicG + ", " +
this.GraphicB + ", " +
this.GraphicA + ", " +
this.StatMultiplier + ", " +
(this.bound ? "'1'" : "'0'") + ", " +
this.BodyState + ")";
this.Dirty = false;
this.Unsaved = false;
SqlCommand command = new SqlCommand(query, world.SqlConnection);
command.Parameters.Add(nameParam);
command.Parameters.Add(descriptionParam);
command.BeginExecuteNonQuery(new AsyncCallback(GameWorld.DefaultEndExecuteNonQueryAsyncCallback), command);
}
dont insert column item_id because it is identity and it will be inserted automatically

selenium webdriver: upload file by drag and drop

On a web page I'm trying to test, we implemented drag and drop file upload. I've looked at the drag and drop API for selenium action chain API. It looks like it supports only dragging and dropping between 2 elements on a page. How to emulate dragging from a file manager?
To perform an HTML5 file drop with Selenium:
static final String JS_DROP_FILE =
"var tgt=arguments[0],e=document.createElement('input');e.type='" +
"file';e.addEventListener('change',function(event){var dataTrans" +
"fer={dropEffect:'',effectAllowed:'all',files:e.files,items:{},t" +
"ypes:[],setData:function(format,data){},getData:function(format" +
"){}};var emit=function(event,target){var evt=document.createEve" +
"nt('Event');evt.initEvent(event,true,false);evt.dataTransfer=da" +
"taTransfer;target.dispatchEvent(evt);};emit('dragenter',tgt);em" +
"it('dragover',tgt);emit('drop',tgt);document.body.removeChild(e" +
");},false);document.body.appendChild(e);return e;";
WebDriver driver = new FirefoxDriver();
driver.get("http://html5demos.com/file-api");
WebElement drop_area = driver.findElement(By.id("holder"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(JS_DROP_FILE, new Object[] {
drop_area
}).sendKeys("C:\\image.png");
AutoIt has the DLL wrapper. I use it directly from C#/Selenium code.
Drop file using jsExecutor
public void dropFile(File filePath, WebElement target) {
if (!filePath.exists())
throw new WebDriverException("File not found: " + filePath.toString());
JavascriptExecutor jse = (JavascriptExecutor) getDriver();
String JS_DROP_FILE =
"var target = arguments[0]," +
" offsetX = arguments[1]," +
" offsetY = arguments[2]," +
" document = target.ownerDocument || document," +
" window = document.defaultView || window;" +
"" +
"var input = document.createElement('INPUT');" +
"input.type = 'file';" +
"input.style.display = 'none';" +
"input.onchange = function () {" +
" var rect = target.getBoundingClientRect()," +
" x = rect.left + (offsetX || (rect.width >> 1))," +
" y = rect.top + (offsetY || (rect.height >> 1))," +
" dataTransfer = { files: this.files };" +
"" +
" ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
" var evt = document.createEvent('MouseEvent');" +
" evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
" evt.dataTransfer = dataTransfer;" +
" target.dispatchEvent(evt);" +
" });" +
"" +
" setTimeout(function () { document.body.removeChild(input); }, 25);" +
"};" +
"document.body.appendChild(input);" +
"return input;";
WebElement input = (WebElement) jse.executeScript(JS_DROP_FILE, target, 0, 0);
input.sendKeys(filePath.getAbsoluteFile().toString());
waitFor(ExpectedConditions.stalenessOf(input));
}
Use AWT Robot class for performing drag and drop:
Robot robot=new Robot();
// drag
robot.mouseMove(x1, y1);
robot.mousePress(InputEvent.BUTTON1_MASK);
// drop
robot.mouseMove(x2, y2);
robot.mouseRelease(InputEvent.BUTTON1_MASK);

Restar Loader can't update gridview

I've got two SQL tables inner join with content provider query builder. My loader shows the first in a gridview like a charm. The second table has been created to show a favorite list and so it has primary key, foreign key and another column. By the way when I try to retrieve value from this one I get null. Some suggestions, please!
I have this in content provider:
static {
sMovieByFavoriteQueryBuilder = new SQLiteQueryBuilder();
sMovieByFavoriteQueryBuilder.setTables(
MoviesContract.FavoriteEntry.TABLE_NAME + " INNER JOIN " +
MoviesContract.MovieEntry.TABLE_NAME +
" ON " + MoviesContract.FavoriteEntry.TABLE_NAME +
"." + MoviesContract.FavoriteEntry.COLUMN_FAVORITE_KEY +
" = " + MoviesContract.MovieEntry.TABLE_NAME +
"." + MoviesContract.MovieEntry._ID);
}
private static final String sFavoriteSelection =
MoviesContract.FavoriteEntry.TABLE_NAME +
"." + MoviesContract.FavoriteEntry.COLUMN_MOVIE_ID + " = ? AND " +
MoviesContract.FavoriteEntry.COLUMN_MOVIE_POSTER + " = ? AND " +
MoviesContract.MovieEntry.COLUMN_RELEASE_DATE + " = ? AND " +
MoviesContract.MovieEntry.COLUMN_MOVIE_POSTER + " = ? AND " +
MoviesContract.MovieEntry.COLUMN_ORIGINAL_TITLE + " = ? AND " +
MoviesContract.MovieEntry.COLUMN_SYNOSIS + " = ? AND " +
MoviesContract.MovieEntry.COLUMN_USER_RATING + " = ? ";
I call this method by uri from fragment:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(MOVIES_LOADER, null, this);
getLoaderManager().initLoader(FAVORITE_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
void onSortChanged() {
System.out.println("onSortChanged: true");
updateMovies();
getLoaderManager().restartLoader(MOVIES_LOADER, null, this);
System.out.println("LoaderManager: " + getLoaderManager().restartLoader(MOVIES_LOADER, null, this));
}
void onFavorite() {
getLoaderManager().restartLoader(FAVORITE_LOADER, null, this);
mMoviesAdapter.setSelectedIndex(mPosition);
mMoviesAdapter.notifyDataSetChanged();
}
private void updateMovies() {
PopularMoviesSyncAdapter.syncImmediately(getActivity());
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (MainActivity.mFavorite == true) {
String sortOrder = MoviesContract.FavoriteEntry.COLUMN_FAVORITE_KEY;
String sortSetting = Utility.getPreferredSort(getActivity());
Uri movieFavoriteUri = MoviesContract.MovieEntry.buildMovieWithSortDate(sortSetting, System.currentTimeMillis());
System.out.println("movieFavoriteUri: " + movieFavoriteUri);
cursorFav = new CursorLoader(getActivity(),
movieFavoriteUri,
FAVORITE_COLUMNS,
null,
null,
sortOrder);
return cursorFav;
} else {
String sortOrder = MoviesContract.MovieEntry.COLUMN_DATE;
String sortSetting = Utility.getPreferredSort(getActivity());
System.out.println("sortSetting: " + sortSetting);
Uri movieForSortUri = MoviesContract.MovieEntry.buildMovieSort(sortSetting);
System.out.println("movieForSortUri: " + movieForSortUri);
cursorMov = new CursorLoader(getActivity(),
movieForSortUri,
MOVIES_COLUMNS,
null,
null,
sortOrder);
return cursorMov;
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mMoviesAdapter.swapCursor(data);
if (mPosition != GridView.INVALID_POSITION) {
// If we don't need to restart the loader, and there's a desired position to restore
// to, do so now.
mGridView.smoothScrollToPosition(mPosition);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mMoviesAdapter.swapCursor(null);
}
Instead of:
sMovieByFavoriteQueryBuilder.setTables(
MoviesContract.FavoriteEntry.TABLE_NAME + " INNER JOIN " +
MoviesContract.MovieEntry.TABLE_NAME +
" ON " + MoviesContract.FavoriteEntry.TABLE_NAME +
"." + MoviesContract.FavoriteEntry.COLUMN_FAVORITE_KEY +
" = " + MoviesContract.MovieEntry.TABLE_NAME +
"." + MoviesContract.MovieEntry._ID);
Create a string so you can debug it easy.
strTables = MoviesContract.FavoriteEntry.TABLE_NAME + " INNER JOIN " +
MoviesContract.MovieEntry.TABLE_NAME +
" ON " + MoviesContract.FavoriteEntry.TABLE_NAME +
"." + MoviesContract.FavoriteEntry.COLUMN_FAVORITE_KEY +
" = " + MoviesContract.MovieEntry.TABLE_NAME +
"." + MoviesContract.MovieEntry._ID);
sMovieByFavoriteQueryBuilder.setTables(strTables);
Then try to run that join direct on db. My guess is the query have some issues.
I checked and the query works good. But my method can't return anything
private Cursor getMovieByFavorite(Uri uri, String[] projection, String movieId) {
String sortSetting = MoviesContract.MovieEntry.getFavoriteFromUri(uri);
long date = MoviesContract.MovieEntry.getDateFromUri(uri);
String[] selectionArgs;
String selection;
selection = sFavoriteSelection;
selectionArgs = new String[]{sortSetting};
return sMovieByFavoriteQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
null,
null,
null,
movieId
);
}

Execute Javascript using Selenium or HtmlUnit

I need small help.
I want to open some page using Java and Selenium or HtmlUnit, and after opening this page execute url like Ajax and get to String the response.
Let say, a want to open http://www.somepage.com , when driver is still on this page, execute GET http://www.somepage.com/myAjax/xyz , which should return JSON.
Then i want to get the JSON response and do something with it.
Could you help me, how to do it ?
Best regards
To inject your own javascript, you can do something like:
new WebConnectionWrapper(webClient) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if (request.getUrl().toExternalForm().contains("my_url")) {
String content = response.getContentAsString("UTF-8");
// inject the below to the 'content'
String tobeInjected = ""
+ "<script>\n"
+ "var myOwnVariable;\n"
+ "var xmlhttp;\n"
+ "if (window.XMLHttpRequest) {\n"
+ " xmlhttp=new XMLHttpRequest();\n"
+ "}\n"
+ "else {\n"
+ " xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');\n"
+ "}\n"
+ "\n"
+ "xmlhttp.onreadystatechange=function() {\n"
+ " if (xmlhttp.readyState==4 && xmlhttp.status==200) {\n"
+ " myOwnVariable = xmlhttp.responseText;\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "xmlhttp.open('GET', 'http://www.somepage.com/myAjax/xyz', true);\n"
+ "xmlhttp.send();\n"
+ "</script>";
WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
response = new WebResponse(data, request, response.getLoadTime());
}
return response;
}
};
To retrieve the value of the javascript variable:
webClient.waitForBackgroundJavaScript(5_000);
String value = htmlPage.executeJavaScript("myOwnVariable").toString();

google places api for unity3d

Wish you a Very Happy New Year!!
Has anyone used Google Places API for Unity3D? I am trying to make an augmented reality app using Places API in Unity3D. I followed all the steps mentioned here
I have first fetched the device coordinates and fed those lat-lon to the places api url for a JSON response (creating an API key for Android). Following is my Unity3D C# code,
#define ANDROID
using UnityEngine;
using System.Collections;
using System.Timers;
using SimpleJSON;
public class Places : MonoBehaviour
{
static int Neversleep;
LocationInfo currentGPSPosition;
string gpsString;
public GUIStyle locStyle;
int wait;
float radarRadius;
string radarType, APIkey, radarSensor;
string googleRespStr;
void Start ()
{
Screen.sleepTimeout = SleepTimeout.NeverSleep;
radarRadius = 1000f;
radarType = "restaurant";
APIkey = "MyAPIkey";
radarSensor = "false";
}
void RetrieveGPSData()
{
currentGPSPosition = Input.location.lastData;
gpsString = "Lat: " + currentGPSPosition.latitude + " Lon: " + currentGPSPosition.longitude + " Alt: " + currentGPSPosition.altitude +
" HorAcc: " + Input.location.lastData.horizontalAccuracy + " VerAcc: " + Input.location.lastData.verticalAccuracy + " TS: " + Input.location.lastData.timestamp;
}
void OnGUI ()
{
GUI.Box (ScaleRect.scaledRect(25,25,700,100), "");
GUI.Label (ScaleRect.scaledRect(35,25,700,100), gpsString, locStyle);
GUI.Box (ScaleRect.scaledRect(25,130,700,800), "");
GUI.Label (ScaleRect.scaledRect(35,135,700,800), "" +googleRespStr, locStyle);
#if PC
Debug.Log("On PC / Don't have GPS");
#elif !PC
Input.location.Start(10f,1f);
int wait = 1000;
if(Input.location.isEnabledByUser)
{
while(Input.location.status == LocationServiceStatus.Initializing && wait>0)
{
wait--;
}
if (Input.location.status == LocationServiceStatus.Failed)
{}
else
{
RetrieveGPSData();
StartCoroutine(Radar());
}
}
else
{
GameObject.Find("gps_debug_text").guiText.text = "GPS not available";
}
#endif
}
IEnumerator Radar ()
{
string radarURL = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=" + currentGPSPosition.latitude + "," + currentGPSPosition.longitude + "&radius=" + radarRadius + "&types=" + radarType + "&sensor=false" + radarSensor + "&key=" + APIkey;
WWW googleResp = new WWW(radarURL);
yield return googleResp;
googleRespStr = googleResp.text;
print (googleRespStr);
}
}
I am getting correct latitude and longitude coordinates but for place, all I get is this,
{
"debug_info" : [],
"html_attributions" : [],
"results" : [],
"status" : "REQUEST_DENIED"
}
It would be great if someone could help me out with this...
Thanks in advance!
Edit:
Download the JSON files from here and extract and put the folder in Assets folder of your Unity3d project. Refer the above code.
got it working. turns out, if you leave the SHA-1 fingerprint field empty, then also google create API key which can be used in the app.