Scribe with QTIWorks - java

I'm using scribe to connect with QTIWorks
I found this question How to create a oAuth request using java?
I write this QTIWorks class
package testscribe;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;
import org.scribe.model.Verb;
public class QTIWorks extends DefaultApi10a {
#Override
public Verb getRequestTokenVerb()
{
return Verb.GET;
}
#Override
public String getRequestTokenEndpoint() {
return "https://webapps.ph.ed.ac.uk/qtiworks-dev2/lti/domainlaunch";
}
#Override
public String getAccessTokenEndpoint() {
return "none";
}
/*#Override
public String getAuthorizationUrl(Token requestToken) {
return "none";*/
#Override
public String getAuthorizationUrl(Token token) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and this is Main class
package testscribe;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
public class Main {
public static void main(String[] args){
OAuthService service = new ServiceBuilder().provider(QTIWorks.class).apiKey("gmail.com/zeina.helwani").apiSecret("v6wPuluQXPwX3vva71ZpR7i1fsbGPaT6")
.scope("API.Public").build();
Token requestToken = service.getRequestToken();
OAuthRequest request = new OAuthRequest(Verb.POST,"https://webapps.ph.ed.ac.uk/qtiworks-dev2/lti/domainlaunch");
service.signRequest(requestToken, request);
Response response = request.send();
System.out.println(response.getBody());
}
}
but it is give me this error
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: '
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QTIWorks - Method Not Allowed (HTTP Error 405)</title>
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:400,400italic,700,700italic|Ubuntu:500">
<link rel="stylesheet" href="/qtiworks-dev2/lib/960/reset.css">
<link rel="stylesheet" href="/qtiworks-dev2/lib/960/text.css">
<link rel="stylesheet" href="/qtiworks-dev2/lib/fluid960gs/grid.css">
<link rel="stylesheet" href="/qtiworks-dev2/includes/qtiworks.css?v=1.0-SNAPSHOT">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="/qtiworks-dev2/includes/qtiworks.js?v=1.0-SNAPSHOT"></script>
<!--[if lt IE 9]><script src="/qtiworks-dev2/lib/html5shiv.min.js"></script><![endif]-->
</head>
<body class="page">
<div class="container_12">
<header class="pageHeader">
<h1>QTIWorks</h1>
</header>
<h2>Method Not Allowed (HTTP Error 405)</h2>
<p>You used an HTTP method which is not allowed here.</p><h3>Further Details</h3>
<strong>Message:</strong> Request method 'GET' not supported<br>
<strong>Status Code:</strong> 405<br>
<strong>Request URI:</strong> /qtiworks-dev2/lti/domainlaunch<br>
<div class="clear"></div>
<footer>
<div class="logos">
<img src="/qtiworks-dev2/includes/images/jisc75.png" width="75" height="50" alt="JISC Logo" />
<img src="/qtiworks-dev2/includes/images/uoe.png" width="60" height="60" alt="University of Edinburgh Logo" />
</div>
<div class="copyright">
<p>
QTIWorks 1.0-SNAPSHOT ‒ Release notes
</p>
<p>
Copyright © Thu Apr 09 13:16:35 BST 2015
The School of Physics and Astronomy,
The University of Edinburgh.
</p>
<p>
Contact: David McKain
</p>
<p>
The University of Edinburgh is a charitable body, registered in Scotland,
with registration number SC005336.
</p>
</div>
</footer>
</div>
</body>
</html>
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at testscribe.Main.main(Main.java:24)
Java Result: 1
I think this url "https://webapps.ph.ed.ac.uk/qtiworks-dev2/lti/domainlaunch" is invalid, but I don't know what I should use.

Related

Thymeleaf can't view anything except one page

All I can is viewing index.html, but when I am trying to surf to adminLogin for example all i see is:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
here is PortfolioApplication:
#SpringBootApplication
public class PortfolioApplication {
public static void main(String[] args) {
SpringApplication.run(PortfolioApplication.class, args);
}
#GetMapping("/")
public String getMainPage() {
return "index.html";
}
#GetMapping("/adminLogin")
public String getAboutPage() {
return "adminLogin.html";
}
}
when i am trying to call another pages from index.html nothing happens:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hotel_Management_java_project</title>
<link rel="stylesheet" href="css/home.css">
</head>
<body>
<div class="home" id="home">
<nav>
<div class="logo">
<a href="#">
<h2>TourAgency</h2>
</a>
</div>
<div class="header_content">
<ul>
<li>Главная</li>
<div class="login">
<button class="loginbtn" id="loginbtn">Вход</button>
<div class="Login_content">
<a th:href="#{/adminLogin}">Вход для админа</a>
<a th:href="#{/employeelogin}">Вход для работника</a>
<a th:href="#{/userlogin}">Вход для пользователя</a>
</div>
</div>
</ul>
</div>
</nav>
</body>
</html>
UserController:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository urepo;
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/userlogin")
public String index1(Model model) {
model.addAttribute("user", new User());
return "userlogin";
}
I was trying change #Controller to #RestController, putting my main class to up and so on, but i've got no result

Java Rest app problem with printing results in HTML

I am a student and I have to develop a rest app using Java Spring, and the app is an online marks register. I have a StudentController class where I implemented a method in Java to show all the subjects which a student has and the grades related to each subject. I have an array list of hash maps that link a subject with the grades related to it. My problem is that I have to display the results from the Hash Maps from inside the list in the Html and even though I tried some things from the internet, it does not work. Can you please help me? Thank you in advance.
Here is the Java method:
#RequestMapping(value = "student")
public ModelAndView showGrades()
{
ModelAndView modelAndView = new ModelAndView();
List<Subject> subjects = subjectRepo.findAll();
Student student = new Student();
Person person = session.getUser();
ArrayList<HashMap<Subject, ArrayList<Integer> >> grades = new ArrayList<HashMap<Subject, ArrayList<Integer> >>();
student.setName(person.getName());
student.setAccount(person.getAccount());
for(int i=0; i<subjects.size(); i++){
HashMap<Subject, ArrayList<Integer> > mappingGrades = new HashMap<Subject, ArrayList<Integer>>();
Random rand = new Random();
ArrayList<Integer> studentGrades = new ArrayList<Integer>();
studentGrades.add(rand.nextInt(10));
studentGrades.add(rand.nextInt(10));
studentGrades.add(rand.nextInt(10));
mappingGrades.put(subjects.get(i), studentGrades);
student.setGrades(mappingGrades);
grades.add(mappingGrades);
}
modelAndView.addObject("grades", grades);
return modelAndView;
}
And here is the HTML code including my try for printing:
<!DOCTYPE html>
<html>
<head>
<!-- Site made with Mobirise Website Builder v4.11.4, https://mobirise.com -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Mobirise v4.11.4, mobirise.com">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<link rel="shortcut icon" href="assets/images/logo4.png" type="image/x-icon">
<meta name="description" content="">
<title>Student</title>
<link rel="stylesheet" href="assets/web/assets/mobirise-icons/mobirise-icons.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap-grid.min.css">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap-reboot.min.css">
<link rel="stylesheet" href="assets/tether/tether.min.css">
<link rel="stylesheet" href="assets/dropdown/css/style.css">
<link rel="stylesheet" href="assets/theme/css/style.css">
<link rel="preload" as="style" href="assets/mobirise/css/mbr-additional.css">
<link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">
</head>
<body>
<section class="header1 cid-rLBDn2JTwv" id="header16-9">
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-10 align-center">
<h1 class="mbr-section-title mbr-bold pb-3 mbr-fonts-style display-1">
GRADES
</h1>
<p class="mbr-text pb-3 mbr-fonts-style display-5">
Subjects and related grades.
</p>
</div>
</div>
</div>
</section>
<section class="engine">bootstrap theme</section>
<section class="services5 cid-rLBDGcNu8T" id="services5-b">
<!---->
<!---->
<!--Overlay-->
<!--Container-->
<div class="container">
<div class="row">
<!--Titles-->
<div class="title pb-5 col-12">
</div>
<!--Card-1-->
<div class="card px-3 col-12">
<div class="card-wrapper media-container-row media-container-row">
<div class="card-box">
<div class="top-line pb-3">
<h4 class="card-title mbr-fonts-style display-5">
<table>
<tbody>
<form action="student" method="showGrades">
<div th:each="map : ${grades}">
<div th:each="mapEntry : ${map}">
<span th:text="${mapEntry.key}"></span> =
<span th:text="${mapEntry.value}"></span>
</div>
</div>
</form>
</tbody>
</table>
</h4>
<p class="mbr-text cost mbr-fonts-style m-0 display-5">
$400
</p>
</div>
<div class="bottom-line">
</div>
</div>
</div>
</div>
<!--Card-2-->
<!--Card-3-->
<!--Card-4-->
<!--Card-5-->
<!--Card-6-->
<!--Card-7-->
<!--Card-8-->
<!--Card-9-->
<!--Card-10-->
<!--Card-11-->
<!--Card-12-->
</div>
</div>
</section>
<script src="assets/web/assets/jquery/jquery.min.js"></script>
<script src="assets/popper/popper.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/tether/tether.min.js"></script>
<script src="assets/smoothscroll/smooth-scroll.js"></script>
<script src="assets/dropdown/js/nav-dropdown.js"></script>
<script src="assets/dropdown/js/navbar-dropdown.js"></script>
<script src="assets/touchswipe/jquery.touch-swipe.min.js"></script>
<script src="assets/theme/js/script.js"></script>
</body>
</html>
In the code you supplied the value of mapEntry.key is a Subject object and the value of mapEntry.value is an ArrayList. You need to tell thymeleaf how to output those objects. If Subject has a proper toString method it will work as you expect but an ArrayList will not print properly. You need to use another nested each statement or you need to join it into a single string.

Thymeleaf TemplateInputException when loading html page

I have a html page where I use jQuery to load page content from a spring boot application
here is the project structure
I m using zuul as proxy I m confident about the Zuul Eureka configuration on my project
When I try to access my root project page (facturation.html) by calling in browser for localhost:9999/facturation I'm getting the following exception
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "root folder where all thymeleaf files/facturation.html")
Caused by: java.io.FileNotFoundException: ClassLoader resource "root folder where all thymeleaf files/facturation.html" could not be resolved
at org.thymeleaf.templateresource.ClassLoaderTemplateResource.reader(ClassLoaderTemplateResource.java:130) ~[thymeleaf-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:223) ~[thymeleaf-3.0.6.RELEASE.jar:3.0.6.RELEASE]
java.io.FileNotFoundException: ClassLoader resource "root folder where all thymeleaf files/facturation.html" could not be resolved
My spring controller is as below
#Controller
public class LandingController {
private static final Logger log = LoggerFactory.getLogger(LandingController.class);
#Autowired
private AppClientFeign appClientFeign;
#Autowired
private UserClientFeign userClientFeign;
#RequestMapping("/")
String home(Model model,Principal principal) {
List<Menu> appMenus = appClientFeign.getAppMenus("facturation");
model.addAttribute("applications", appClientFeign.getApps());
model.addAttribute("applicationsHistory", appClientFeign.getAppsHistory(principal.getName()));
model.addAttribute("currentUser", userClientFeign.getUserDetails(principal.getName()));
if(log.isDebugEnabled()) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(appMenus);
stringBuilder2.append("");
log.debug(stringBuilder2.toString());
}
model.addAttribute("menuV", appMenus);
model.addAttribute("addClientObject", AddClientDTO.builder().build());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" hello world ****************** ---------------------- ************************ \n \n \n");
stringBuilder.append(appClientFeign.getApps());
if(log.isDebugEnabled())log.debug(stringBuilder.toString());
return "facturation";
}
#RequestMapping("/html/{page}")
String resolveHTML(Model model,Principal principal,#PathVariable String page) {
List<Menu> appMenus = appClientFeign.getAppMenus("facturation");
model.addAttribute("applications", appClientFeign.getApps());
model.addAttribute("applicationsHistory", appClientFeign.getAppsHistory(principal.getName()));
model.addAttribute("currentUser", userClientFeign.getUserDetails(principal.getName()));
if(log.isDebugEnabled()) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(appMenus);
stringBuilder2.append("");
log.debug(stringBuilder2.toString());
}
model.addAttribute("menuV", appMenus);
model.addAttribute("addClientObject", AddClientDTO.builder().build());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" hello world ****************** ---------------------- ************************ \n \n \n");
stringBuilder.append(appClientFeign.getApps());
if(log.isDebugEnabled())log.debug(stringBuilder.toString());
return page;
}
#RequestMapping("/html/{folder}/{page}")
String resolveHTML(Model model,Principal principal,#PathVariable String page,#PathVariable String folder) {
List<Menu> appMenus = appClientFeign.getAppMenus("facturation");
model.addAttribute("applications", appClientFeign.getApps());
model.addAttribute("applicationsHistory", appClientFeign.getAppsHistory(principal.getName()));
model.addAttribute("currentUser", userClientFeign.getUserDetails(principal.getName()));
if(log.isDebugEnabled()) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append(appMenus);
stringBuilder2.append("");
log.debug(stringBuilder2.toString());
}
model.addAttribute("menuV", appMenus);
model.addAttribute("addClientObject", AddClientDTO.builder().build());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" hello world ****************** ---------------------- ************************ \n \n \n");
stringBuilder.append(appClientFeign.getApps());
if(log.isDebugEnabled())log.debug(stringBuilder.toString());
return folder+"/"+page;
}
}
My facturation.htl page is
<!DOCTYPE HTML>
<html lang="fr">
<head>
<meta charset="UTF-8"/>
<title>Facturation - MDS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/loader.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/main.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/facturation.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/chart.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/menus.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/grid.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/tab.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/notify.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/print.js"></script>
<script src="http://localhost:9999/MDS-WEB-RESSOURCE/js/check.js"></script>
<script onloadstart="loadAdditionalData()" src="http://localhost:9999/MDS-WEB-RESSOURCE/js/facturationLoader.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/main.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/facturation.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/chart.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/grid.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/tab.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/notify.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/menus.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/dropdown.css"/>
<link rel="stylesheet" type="text/css" href="http://localhost:9999/MDS-WEB-RESSOURCE/css/check.css"/>
</head>
<body>
<div id="overlay" class="overlay">
<div class="form-container">
</div>
</div>
<div style="height: 100%;">
<div id="header" class="header">
</div>
<div id="menu0" class="menu-V">
</div>
<div class="container">
<div id="menu0-func0-panel" class="main-panel" style="display: block;">
</div>
<div id="menu0-func1-panel" class="main-panel">
</div>
<div id="menu0-func2-panel" class="main-panel">
</div>
<div id="menu0-func3-panel" class="main-panel">
</div>
</div>
</div>
</body>
</html>
finally loader.js is as below
$(document).ready(function() {
$("#header").load("http://"+document.location.host+"/facturation/html/facturation-header");
$("#menu0").load("http://"+document.location.host+"/facturation/html/facturation-menu0");
$("#menu0-func0-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func0-panel", function() {
var option={
parent: "#stat-container",
type: "Pie",
labels: ['FACTURES EN ATTENTE', 'FACTURES EN RETARD (- DE 30 JOURS)', 'FACTURES EN RETARD (+ DE 30 JOURS)'],
data: [20, 15, 10],
colors: ["#0ae1ff", "#067180", "#dd4d40"],
canvasWidth: 250,
canvasHeight: 250,
legendType: "value",
legendPosition: "bottom",
legendUnit: "DZD",
overlay: false
};
chart(option);
});
$("#menu0-func1-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func1-panel");
$("#menu0-func2-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func2-panel");
$("#menu0-func3-panel").load("http://"+document.location.host+"/facturation/html/facturation-menu0-func3-panel");
});
to be honest, I don't have the slightest clue why I m getting this, nor an idea about what should I do or try.
NB: I m using zuul and eureka as mentioned, my service is named facturation that why I'm adding facturation after zuul address so he knows which service to contact
using this question I configured thymeleaf to get my pages from the classpath

Redirecting http request using custom Reverse Proxy controller in java

I want to fetch data from different servers according to client id.
PS: everything is running on https, stackoverflow does not allow me to put more then 2 links, thats why I removed https part.
Let say, My proxy controller server is running on - 192.168.2.0:8080
I have multiple servers, let say server A on 192.168.2.20:8080 and server B on 192.168.2.30:8080.
If, my user aaa is hitting on proxy controller it should get response from server A, if user bbb is hitting on proxy server it should get response from server B.
eg. 192.168.2.0:8080/api/aaa/ui/index.html should actually call 192.168.2.20:8080/ui/index.html and client should get response.
Same for bbb user, in that case response should come from 192.168.2.30:8080/ui/index.html.
This use case is working for static content, but not for dynamic contents. I am not able to get dynamic data from the server.
I guess internally my server is giving me
Code on my controller.
Controller
This handles the URL and invoke this function.
it will take a URL like, http://localhost:8080/userId/ui/index.html
and calls a server according to the userId, UserId can be aaa or bbb.
#RequestMapping(value = "/{userId}/**", method= RequestMethod.GET)
#ResponseBody
public String HTTPControllerEntry(#PathVariable("userId") String userId,HttpServletRequest request){
String urlEndSubstring = (String)request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
int index = urlEndSubstring.indexOf('/',1 + urlEndSubstring.indexOf('/'));
urlEndSubstring = urlEndSubstring.substring(index+1);
String URL = userId+urlEndSubstring;
String response=httpRedirectionService.RedirectHttpUrl(userId, urlEndSubstring);
return response;
}
This function will get the prefix of the URL on the bases of userId and genrate the full URL with the specific ipaddress of the user.
#Override
public String RedirectHttpUrl(String userId, String urlEndSubstring) {
UserConnectionProperties ucP = new UserConnectionProperties();
String urlPrefix= ucP.readUserConnectionProperty(userId);
String URL = urlPrefix+urlEndSubstring;
return callURL(URL);
}
This function just get the http request and return it back to the controller. Controller will be returning back to the client.
private String callURL(String httpURL) {
System.out.println("Requeted URL: " + httpURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(httpURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
System.out.println(("Exception while calling URL:"+ httpURL +" "+e+"\n"));
}
return sb.toString();
}
This will give the ipaddress of the internal server acccording to the userId
public String readUserConnectionProperty(String key){
Properties prop = loadPropertyfile();
return prop.getProperty(key);
}
To load the property file.
private Properties loadPropertyfile(){
Properties props = new Properties();
InputStream is = null;
try {
File f = new File("userConnection.properties");
is = new FileInputStream(f);
}
catch (Exception e){
is = null;
}
try {
if ( is == null ) {
is = getClass().getClassLoader().getResourceAsStream("userConnection.properties");
}
if(is!=null){
props.load( is );
}
else {
throw new FileNotFoundException("property file userConnection not found in class path");
}
}
catch ( Exception e ) { }
return props;
}
userConnection.properties
aaa=192.168.2.120:8080/
bbb=192.168.2.130:8080/
ccc=192.168.2.140:8380/
My Html file which I got from get request on my server with aaa as a user.
<html lang="en" ng-app="UI">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>UI</title>
<link type="text/css" href="css/bootstrap.min.css" rel="stylesheet">
<link type="text/css" href="css/angular-material.min.css" rel="stylesheet">
<!-- custom css files -->
<link type="text/css" href="css/components.css" rel="stylesheet">
<link type="text/css" href="css/layout.css" rel="stylesheet">
<link type="text/css" href="css/views.css" rel="stylesheet">
<link type="text/css" href="css/theme.css" rel="stylesheet">
<!-- Icons/Fonts -->
<link type="text/css" href="fonts/md-icons/md-icons.css" rel="stylesheet" media="all">
<link type="text/css" href="css/roboto-fontface.css" rel="stylesheet" media="all">
<meta name="apple-mobile-web-app-capable" content="yes" />
</head>
<body ng-controller="BodyController">
<div id="authentication" data-access-token="{{ACCESS_TOKEN}}"></div>
<div ng-include="'partials/include.extension.html'"></div>
<nav class="menu slide-menu-left" ng-controller="NavController">
<div class="top clickable" ng-click="navigateToRoot()">
<img id="logo" alt="Logo" src="img/logo.png" />
<h1 class="title">App</h1>
</div>
<ul>
<li ng-class="{active: isActive('control'), hidden: isHidden('control')}">
<a href="#control">
<span class="icon md-icon-dashboard"></span> Control</a>
</li>
<li ng-class="{active: isActive('inbox')}">
<a href="#inbox" class="clickable">
<span class="icon md-icon-add-circle-outline"></span> Inbox
<span ng-show="getNumberOfNewDiscoveryResults() > 0" class="badge">{{getNumberOfNewDiscoveryResults()}}</span>
</a>
</li>
<li ng-class="{active: isActive('configuration'), hidden: isHidden('configuration')}">
<a ng-click="open('configuration')" class="clickable">
<span class="icon md-icon-settings"></span> Configuration</a>
<ul ng-show="isActive('configuration')">
<li ng-class="{active: isSubActive('bindings')}">Bindings</li>
<li ng-class="{active: isSubActive('services')}">Services</li>
<li ng-class="{active: isSubActive('groups'), hidden: isHidden('groups')}">Groups</li>
<li ng-class="{active: isSubActive('things')}">Things</li>
</ul>
</li>
<li ng-class="{active: isActive('extensions'), hidden: isHidden('extensions')}">
<a href="#extensions">
<span class="icon md-icon-extension"></span>
Extensions</a>
</li>
<li ng-class="{active: isActive('rules'), hidden: isHidden('rules')}">
<a href="#rules">
<span class="icon md-icon-movie-creation"></span>
Rules</a>
</li>
<li ng-class="{active: isActive('preferences'), hidden: isHidden('preferences')}">
<a href="#preferences">
<span class="icon md-icon-brightness-medium"></span>
Preferences</a>
</li>
</ul>
<div class="bottom">
<span>UI</span>
</div>
</nav>
<div id="wrapper">
<header>
≡
<div class="title">
<h1>
{{title}}
<span ng-repeat="subtitle in subtitles" class="subtitle">
<span class="chevron md-icon-chevron-right"></span> {{subtitle}}</span>
</h1>
</div>
</header>
<ng-view autoscroll="true"></ng-view>
<footer> </footer>
</div>
<!-- lib js files -->
<script src="js/angular.min.js"></script>
<script src="js/angular-bundle.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- TODO: Create custom variant to save space -->
<script src="js/tinycolor.js"></script>
<script src="js/masonry.pkgd.min.js"></script>
<!-- TODO: Use angularized version? -->
<script src="js/sprintf.min.js"></script>
<!-- custom js files -->
<script src="js/app.js"></script>
<script src="js/constants.js"></script>
<script src="js/services.min.js"></script>
<script src="js/controllers.min.js"></script>
<script src="js/extensions.js"></script>
<script src="js/main.js"></script>
<script src="js/shared.properties.js"></script>
</body>
</html>

Phonegap Java call Javascript Function

I am currently making a hello world type Phonegap application for android, In which I call a javascript function from the native android code to set the text of one of the paragraphs in my app.
I have a javascript function that I define in my app's html, and I want to call it from my activity once the app loads up. The function just sets the text of a paragraph in my app. I cannot get this to work.
Here is my java activity code:
public class MyPhoneGapActivity extends DroidGap {
public DroidGap c;
public LoadInfo info;
#SuppressLint("SetJavaScriptEnabled")
#JavascriptInterface
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
c = this;
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
appView.loadUrl("file:///android_asset/www/index.html");
appView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
MyPhoneGapActivity.this.runOnUiThread(new Runnable() {
public void run() {
c.sendJavascript("javascript:getMassTimes()");
}
});
}
});
}
}
and here is my javascript and html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic Seed App</title>
<link href="lib/css/ionic.css" rel="stylesheet">
<link href="css/app.css" rel="stylesheet">
<link href="lib/css/mycss.css" rel="stylesheet">
<script src="lib/js/ionic.js"></script>
<script src="lib/js/angular/angular.js"></script>
<script src="lib/js/angular/angular-animate.js"></script>
<script src="lib/js/angular/angular-sanitize.js"></script>
<script src="lib/js/angular-ui/angular-ui-router.js"></script>
<script src="lib/js/ionic-angular.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.js"></script>
</head>
<body ng-app="myApp">
<script type="text/javascript">
function getMassTimes() {
document.getElementById("massTimes").textContent = "This is some text";
}
</script>
<div>
<header-bar title="Saint David the King"
class="bar bar-header bar-energized">
<h1 class="title">Saint David the King</h1>
</header-bar>
<br>
<content scroll="true" has-header="true" width="100%" height="100%"
id="content"> <img alt="Saint David the King"
src="file:///android_asset/www/img/saintdavidthekingbackground2.png"
width="100%" /> <br>
<p id="massTimes">
</p>
</content>
</div>
</body>
</html>
Is there something I am doing wrong?
I have seen these sites:
Resolved - Call javascript function from Java
How to call javascript function from java code
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/1o9PgfmyRd8
http://www.jumpbyte.com/2012/phonegap-native-to-javascript/
Javascript calls from Android using PhoneGap
how to call javascript function from android using phonegap plugin
And I have tried what they have on them, but I just can't get this to work.
Any help appreciated!
Replace c.sendJavascript("javascript:getMassTimes()"); with
myBrowser.loadUrl("javascript:getMassTimes()");. This worked for my problem.
If you want to pass a String from the activity to javascript use
String msgToSend = "Hello World!"; myBrowser.loadUrl("javascript:callFromActivity(\""+msgToSend+"\")");

Categories

Resources