Spring Boot + Swagger + custom swagger-ui.html - java

I've got problems migrating a war application to a spring boot jar application.
I'm using spring boot 1.4.1 and swagger 2.6.0.
To customize swagger ui in a war you have to put a custom swagger-ui.html to /webapp directory. In spring boot it is not recommend to use the webapp directory because it does not work in a bundled jar. But putting a custom swagger-ui.html to /resources/static will be ignored by swagger.
Is there any simple solution (instead of adding the whole swagger distribution to my application)?
My custom swagger-ui.html looks like
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>API</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-2.0.0.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/underscore-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.7.3.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
<style>
.swagger-section #header {
background-color: #ff5722;
}
</style>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://www.my-app.com">my-app.com API</a>
<form id='api_selector'>
<div class='input' style="display: none">
<select id="select_baseUrl" name="select_baseUrl"/>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl"
type="text"/>
</div>
<!--
<div class='input'><input placeholder="Enter authorization token" id="input_apiKey" name="apiKey" type="text"/></div>
<div class='input' style="display: none"><a id="explore" href="#" data-sw-translate>Explore</a></div>
-->
</form>
</div>
</div>
<script type="text/javascript">
function addApiKeyAuthorization() {
var key = $('#input_apiKey')[0].value;
console.log("key: " + key);
if (key && key.trim() != "") {
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header");
window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth);
//window.authorizations.add("Authorization", new ApiKeyAuthorization("Authorization", key, "query"));
console.log("Set authorization token: " + key);
}
}
$('#input_apiKey').change(function () {
addApiKeyAuthorization();
});
</script>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

I have found this simple way to customize Swagger into a Spring Boot application with just two files copied from original springfox-swagger-ui
First of all i have disabled #Configuration from SwaggerConfig.java:
//#Configuration <-- Attention, disable Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(Pageable.class)
.select().apis(RequestHandlerSelectors.any())
.paths(regex("/v1/.*"))
.build();
}
}
Then I have extended a WebMvcConfigurerAdapter:
#Configuration
#Import(SwaggerConfig.class)
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/doc/v1/**").addResourceLocations("classpath:/doc/v1/");
registry.addResourceHandler("/doc/v1/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Then I have just copied original file swagger-ui.html into src/main/resources/doc/v1/api.html with just a simple modification.
I have substituted this line:
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
with this line:
<script src='js/swagger.js' type='text/javascript'></script>
This is my api.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='js/springfox.js' type='text/javascript'></script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
<form id='api_selector'>
<div class='input'>
<select id="select_baseUrl" name="select_baseUrl"/>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
After that i have copied original springfox.js into src/main/resources/doc/v1/js/springfox.js where i have changed these lines:
"baseUrl": function() {
var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href);
return urlMatches[1];
},
with these lines:
"baseUrl": function() {
return window.location.origin;
},
This is my complete springfox.js
$(function() {
var springfox = {
"baseUrl": function() {
return window.location.origin;
},
"securityConfig": function(cb) {
$.getJSON(this.baseUrl() + "/swagger-resources/configuration/security", function(data) {
cb(data);
});
},
"uiConfig": function(cb) {
$.getJSON(this.baseUrl() + "/swagger-resources/configuration/ui", function(data) {
cb(data);
});
}
};
window.springfox = springfox;
window.oAuthRedirectUrl = springfox.baseUrl() + '/webjars/springfox-swagger-ui/o2c.html';
window.springfox.uiConfig(function(data) {
window.swaggerUi = new SwaggerUi({
dom_id: "swagger-ui-container",
validatorUrl: data.validatorUrl,
supportedSubmitMethods: data.supportedSubmitMethods || ['get', 'post', 'put', 'delete', 'patch'],
docExpansion: data.docExpansion || 'none',
jsonEditor: JSON.parse(data.jsonEditor) || false,
apisSorter: data.apisSorter || 'alpha',
defaultModelRendering: data.defaultModelRendering || 'schema',
showRequestHeaders: data.showRequestHeaders || true,
timeout: data.requestTimeout,
onComplete: function(swaggerApi, swaggerUi) {
initializeSpringfox();
if (window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
});
initializeBaseUrl();
function addApiKeyAuthorization(security) {
var apiKeyVehicle = security.apiKeyVehicle || 'query';
var apiKeyName = security.apiKeyName || 'api_key';
var apiKey = security.apiKey || '';
if (apiKey && apiKey.trim() != "") {
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(apiKeyName, apiKey, apiKeyVehicle);
window.swaggerUi.api.clientAuthorizations.add(apiKeyName, apiKeyAuth);
log("added key " + apiKey);
}
}
function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
function oAuthIsDefined(security) {
return security.clientId
&& security.clientSecret
&& security.appName
&& security.realm;
}
function initializeSpringfox() {
var security = {};
window.springfox.securityConfig(function(data) {
security = data;
addApiKeyAuthorization(security);
if (typeof initOAuth == "function" && oAuthIsDefined(security)) {
initOAuth(security);
}
});
}
});
$('#select_baseUrl').change(function() {
window.swaggerUi.headerView.trigger('update-swagger-ui', {
url: $('#select_baseUrl').val()
});
});
function maybePrefix(location, withRelativePath) {
var pat = /^https?:\/\//i;
if (pat.test(location)) {
return location;
}
return withRelativePath + location;
}
function initializeBaseUrl() {
var relativeLocation = springfox.baseUrl();
$('#input_baseUrl').hide();
$.getJSON(relativeLocation + "/swagger-resources", function(data) {
var $urlDropdown = $('#select_baseUrl');
$urlDropdown.empty();
$.each(data, function(i, resource) {
var option = $('<option></option>')
.attr("value", maybePrefix(resource.location, relativeLocation))
.text(resource.name + " (" + resource.location + ")");
$urlDropdown.append(option);
});
$urlDropdown.change();
});
}
});
This is my folder structure
Now you have just to run application and go to http://localhost:8080/doc/v1/api.html

Solution if you are using maven:
You should copy swagger-ui.html into src/main/webapp
Make your editions or replace screen.css by your theme.css
Than add these code into your pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>${basedir}/src/main/webapp</directory>
<filtering>true</filtering>
<includes>
<include>*.css</include>
<include>*.html</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>

Related

i have angular.min.js:129 TypeError: Cannot read properties of undefined (reading '0') error in my spring boot aplication

I'm trying to desingn login page by angular in my java Spring Boot Aplication. My problem is when I try login to panel page,username and password is ok and send to application by api controller and set user token correctly,but token don't set by cookeis in page, therefor panel page don't open and i have this error in inspect console :
my login page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Online Shop App | login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<script src="libs/angular.min.js"></script>
<script src="libs/jquery.min.js"></script>
<script src="libs/angular-cookies.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/loginController.js"></script>
<script src="scripts/services/ApiHandler.js"></script>
<link href="libs/bootstrap-5.1.3-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="libs/bootstrap-5.1.3-dist/js/bootstrap.min.js"></script>
<link href="styles/login.css" rel="stylesheet">
</head>
<body ng-app="onlineShopApp">
<div class="container-fluid" ng-controller="loginCtrl">
<div class="row">
<div class="col-3"></div>
<div class="col login-box-holder">
<form>
<h3>Login To Panel</h3>
<div class="form-group">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" ng-model="user.userName">
</div>
<div class="form-group">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" autocomplete="false"
ng-model="user.password">
<div id="emailHelp" class="form-text">Do not share your username and password</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="doLogin()">Login</button>
</form>
</div>
<div class="col-3"></div>
</div>
</div>
</body>
</html>
my login controller:
app.controller("loginCtrl", function ($scope, apiHandler, $cookies) {
$scope.user = {};
$scope.doLogin = () => {
apiHandler.callPost(
'user/login',
$scope.user,
(response) => {
var token=response.datalist[0].token;
$cookies.put("userToken",token);
if(token==null || token=="")
{
alert("invalid token");
return;
}
$cookies.put("uerToken",token);
alert("token is:");
location.href="/panel";
}, (error) => {
});
}
});
my panel page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Online Shop App | panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<script src="libs/angular.min.js"></script>
<script src="libs/jquery.min.js"></script>
<script src="libs/angular-cookies.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/panelController.js"></script>
<script src="scripts/services/ApiHandler.js"></script>
<link href="libs/bootstrap-5.1.3-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="libs/bootstrap-5.1.3-dist/js/bootstrap.min.js"></script>
</head>
<body ng-app="onlineShopApp">
<div class="container-fluid" ng-controller="panelCtrl">
<div class="row">
<h3>Panel</h3>
</div>
</div>
</body>
</html>
my panel controller:
app.controller("panelCtrl", function ($scope, apiHandler, $cookies) {
$scope.checkAccess = () => {
var token=$cookies.get("userToken");
if(token==undefined || token==null || token==""){
location.href="/login";
}
}
$scope.checkAccess();
});
i type wrong dataList in loginController file: (i change response.datalist[0] to=> response.dataList[0] )

Why page is not loaded in Java Spring boot Angularjs

I have a problem with load a simple page where will be display all messages. I using algular for front-end and spring boot app in back-end. When i try to load page (localhost:8080/messages), page is blank and give me to download JSON with messages. Any idea? Ps. in ViewAllMessages.html i write constant text to check when page is running.
MessageController:
#RestController
#RequestMapping("/api/message")
public class MessageController {
private final Logger LOG = LoggerFactory.getLogger(MessageController.class);
#Autowired
private MessageService messageService;
#RequestMapping(value = "/all", method = GET)
public List<MessageDTO> findAll() {
LOG.info("Received request to all messages.");
return messageService.findAll();
}
}
main.js
var chatApp = angular.module('chat', ['ngRoute']);
chatApp.config(function ($routeProvider) {
$routeProvider
.when('/messages',
{
controller: 'AllMessagesController',
templateURL: '/partials/ViewAllMessages.html'
})
.otherwise( {redirectTo: '/'});
});
chatApp.service('messageService', function(){
var message = {};
var addMessage = function (v) {
message = v;
};
var getMessage = function(){
return message;
};
return {
addMessage: addMessage,
getMessage: getMessage
};
});
chatApp.controller('AllMessagesController', function($scope, $window, $http){
$scope.transfer = {};
$scope.error = false;
$http
.get('/api/message/all')
.then(function(response) {
$scope.messages = response.data;
log.console(response.data);
});
});
index.html
<!doctype html>
<html>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/simple-sidebar.css" rel="stylesheet">
<link href="css/bootstrap-datetimepicker.css" rel="stylesheet">
<link href="css/office.css" rel="stylesheet">
<style type="text/css"> </style>
<body>
<script src="js/angular-route.min.js" type="text/javascript"></script>
<script src="js/angular-resource.min.js" type="text/javascript"></script>
<script src="js/main.js"></script>
<script src="js/angular.min.js" type="text/javascript"></script>
</body>
</html>
ViewAllMessages.html
<div class="container">
<div class="col-md-6">
<div class="row">
<div class="col-md-2">
<h2>Wiadomosci</h2>
</div>
</div>
</div>>
<div class="section">
<h3>{{headingTitle}}</h3>
<div>
<ul type="square">
<li>Luke</li>
<li>Darth</li>
<li>Anakin</li>
<li>Leia</li>
</ul>
</div>
</div>
<div class="panel panel-default" ng-repeat="message in messages">
<div class="row">
<div class="col-md-2">
<div class="panel-default"> {{message.id}}</div>
</div>
<div class="col-md-2">
<div class="panel-default"> {{message.message}}</div>
</div>
</div>>
</div>
</div>
page didn't show because you didn't import $routeParams dependency into your controller in index.js. After setting it, page shows up.

xlsx file becomes corrupt/ empty(0 bytes) sending across in a http request

I am sending an xlsx file over http request but the file becomes corrupt.
I just dont understand why the file becomes corrupt just sending across.
Please help, I am new at this.
Here is the jsp file :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="myApplication">
<head>
<!-- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> -->
<title>Preptune</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
angular.module('myApplication',["ngRoute"]).
directive('fileInput',['$parse',function($parse){
return {
restrict:'A',
link: function(scope,elm,attrs) {
elm.bind('change',function() {
$parse(attrs.fileInput)
.assign(scope,elm[0].files)
scope.$apply()
})
}
}
}])
.controller('myController',['$scope','$http',
function($scope,$http) {
$scope.message = "Test message";
$scope.filesChanged = function(elm) {
$scope.files=elm.files;
$scope.$apply();
};
$scope.upload = function() {
var fd = new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
})
$http.post('http://localhost:80/simple-web-services/uploadQuestions', fd,{
transformRequest : angular.identity,
headers:{'Content-Type':undefined}
})
.success(function(d){
console.log(d);
})
};
}
])
.config(function($routeProvider) {
$routeProvider
.when("/preptune", {
templateUrl : "/webPortal/homePage/welcome"
})
.when("/upload", {
templateUrl : "/webPortal/resources/html/uploadQuestion.html"
})
.when("/download", {
templateUrl : "/webPortal/resources/html/downloadTemplate.html"
})
.otherwise({redirectTo:'/'});
});
</script>
</head>
<body ng-controller="myController">
<nav class="navbar navbar-default">
<div class="container-fluid bg-info">
<div class="navbar-header">
<a class="navbar-brand" href="#prep">Prep</a>
</div>
<ul class="nav navbar-nav">
<li>Upload Question Paper</li>
<li>Download Question Template</li>
</ul>
</div>
</nav>
<div ng-view></div>
</body>
</html>
Here is the form : (uploadQuestion.html)
<form method="post">
<input type="file"
file-input="files"
multiple></input>
<button ng-click="upload()"> Upload </button>
<li ng-repeat="file in files" >{{file.name}} </li>
</form>
The exception says
java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: Your InputStream was neither an OLE2 stream, nor an OOXML stream

How to call a JavaScript function from java code android native

I need to load a HTML file which internally has some AJAX service calls.
I need to call a function in that HTML file from Java code.
I can see the data loading in web but not in Emulator.
My HTML file is below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=yes">
<link class="include" rel="stylesheet" type="text/css"
href="./jquery.jqplot.min.css" />
<link type="text/css" rel="stylesheet"
href="syntaxhighlighter/styles/shCoreDefault.min.css" />
<link type="text/css" rel="stylesheet"
href="syntaxhighlighter/styles/shThemejqPlot.min.css" />
<script class="include" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script class="include" type="text/javascript"
src="./jquery.jqplot.min.js"></script>
<script type="text/javascript"
src="syntaxhighlighter/scripts/shCore.min.js"></script>
<script type="text/javascript"
src="syntaxhighlighter/scripts/shBrushJScript.min.js"></script>
<script type="text/javascript"
src="syntaxhighlighter/scripts/shBrushXml.min.js"></script>
<!-- End Don't touch this! -->
<!-- Additional plugins go here -->
<script class="include" language="javascript" type="text/javascript"
src="./plugins/jqplot.dateAxisRenderer.min.js"></script>
<script class="include" language="javascript" type="text/javascript"
src="./plugins/jqplot.ohlcRenderer.min.js"></script>
<script class="include" language="javascript" type="text/javascript"
src="./plugins/jqplot.highlighter.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.dateAxisRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.canvasTextRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="./plugins/jqplot.cursor.min.js"></script>
<script class="code" language="javascript" type="text/javascript">
var arr = [];
var arr1 = [];
var jsonstr;
$(document).ready(function() {
$.jqplot.config.enablePlugins = true;
$("#status").html("Loading...");
$("#status").animate({opacity: 1,top: "200px"},200);
});
function getData(symbolId,timeLine,type){
//$("#mydiv").html(symbolId +" "+timeLine+" "+type);
$.ajax({
url: 'http://83.101.141.1:8020/mTadawul/TadawulService.svc/GetOHLCData?Symbol='+symbolId+'&Char='+timeLine,
dataType: 'json',
async: false,
success: function(data) {
jsonstr = jsontoarray(eval (data));
/*Custom Code to check the data*/
if(data != "")
{$("#status").animate({opacity: 0,top: "-50px"},200);createChart(type, timeLine);}else{$("#status").html("No Data");$("#status").animate({opacity: 1,top: "200px"},200);}
}
});
//$.getJSON('http://183.82.0.37:8080/TadawulWCFService/TadawulService.svc/GetOHLCData?Symbol=1010&Char='+timeLine, function(data) {
//});
return 1;
}
function jsontoarray(jsonstr){
var arrayl = [];
for (var i = 0; i < jsonstr.length; i++) {
var values = new Array();
values[0] = jsonstr[i].TimeStamp.replace("T"," ").replace("nm","");
values[1] = jsonstr[i].Open;
values[2] = jsonstr[i].High;
values[3] = jsonstr[i].Low;
values[4] = jsonstr[i].Close;
arrayl.push(values);
}
return arrayl;
}
function createChart(type, timeLine) {
timeLine = typeof timeLine !== 'undefined' ? timeLine : 'M';
console.log(jsonstr);
var charts = [{
name: "chart2",
seriesDefaults: {
yaxis: 'y2axis'
},
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
numberTicks:36,
tickOptions: {
formatString: '%b %e %Y ',
angle:-90
},
tickRenderer:$.jqplot.CanvasAxisTickRenderer,
labelOptions:{
fontFamily:'Arial',
fontSize: '14pt'
},
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
},
series: [{
renderer: $.jqplot.OHLCRenderer,
rendererOptions: {
candleStick: true
}
}],
highlighter: {
show: true,
showMarker: true,
tooltipAxes: 'xy',
yvalues: 4,
formatString: '<table class="jqplot-highlighter"> \<tr><td>date:</td><td>%s</td></tr> \<tr><td>open:</td><td>%s</td></tr> \<tr><td>high:</td><td>%s</td></tr> \<tr><td>low:</td><td>%s</td></tr> \<tr><td>close:</td><td>%s</td></tr></table>'
},
data: [jsonstr]
}];
if(type == "line"){
charts[0].series[0]={};
}
else if(type == "bar"){
charts[0].series[0].rendererOptions = {smooth : true};
}else
{
charts[0].series[0].rendererOptions = {candleStick : true};
}
if(timeLine == 'H'){
charts[0].axes.xaxis.tickOptions = { formatString: '%b %e %#I %p',
angle:-90};
//charts[0].axes.xaxis['tickInterval'] = "1 hour";
}
$('#chart2').jqplot(charts[0]);
}
</script>
<div id="mydiv"></div>
<label id="lbl"></label>
<div class="test" style="position:absolute; top:-50px; left:40%; color:#333333; opacity:0;z-index:9999;" id="status">No Data</div>
<div id="chart2" style="height: 400px; width: 720px;">
</div>
In that code I need to call getData() passing 3 parameters from Java code.
My Java code is below:
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
String loc = "file:///android_asset/candlechart/candlebar.html";
webView.getSettings().setJavaScriptEnabled(true);
webView.clearView();
// myWebView.measure(100, 100);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.loadUrl(loc);
webView.loadUrl("javascript:getData('1020','M','bar')");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String loc) {
}
});
You are calling your second loadUrl() way too soon. loadUrl() is asynchronous. You need to wait until your page is loaded. Call webView.loadUrl("javascript:getData('1020','M','bar')"); in the OnPageFinished method.

read jSON response

I am trying to read a json response from my python based backend. I am using this code for accessing the information.
URL for first call
public static final String JSON_RESPONSE_STRING="http://192.168.2.5:8000/mobile/";
URL forsecond call
public static final String PICKUP_DETAILS="http://192.168.2.5:8000/mobile/shippments/";
common method using
public static String GetJSONResponse(String stringUrl) throws IOException
{
StringBuilder response = new StringBuilder();
URL url = new URL(stringUrl);
HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
{
response.append(strLine);
}
input.close();
}
return response.toString();
}
django url patterns
urlpatterns = patterns('mobile_api.views',
url(r'^$','login_authenticate'),
url(r'^shippments/(?P<id>\w+)','pickup_details'),
url(r'^report/post/','pickup_report')
)
I am using this method twice in my code. For the first time this code is working absolutely fine and parsing the json response .
When I am using this method at other place I am call it
pick_up_id=getIntent().getStringExtra("pickup_id");
String stringUrl=Constants.PICKUP_DETAILS+"555";
String response = null;
try {
response = PickupList.GetJSONResponse(stringUrl);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String response=GetPickUpDetails(pick_up_id);
System.out.println("second call response"+response);
and getting this response
03-22 12:19:37.979: I/System.out(20703): second call response<!doctype html> <!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <title>ECOM</title> <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" > <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta property="og:image" content="http://www.domain.com/images/logo.png"/> <meta property="og:title" content="-- description here --"/> <meta property="og:url" content="http://www.domain.com"/> <link rel="shortcut icon" href="/static/assets/img/favicon.ico" /> <link rel="apple-touch-icon" href="/static/assets/img/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/assets/img/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/assets/img/apple-touch-icon-114x114.png"> <link rel="stylesheet" href="/static/assets/css/styles.css" /> <script src="/static/assets/js/libs/modernizr.custom.60077.js"></script> <link rel="stylesheet" href="/static/assets/css/popup.css" /> <script src="/static/assets/js/jquery-1.7.2.min.js"></script> <script src="/static/assets/authentication/js/popup.js"></script> </head><body><div id="backgroundPopup"></div> <div class="header" style="text-align:center; padding-top:10px;"> <img src="/static/assets/img/Ecomlogo.png"/> </div> <div class="container-fluid" roll="main" id="main"> <div class="span6">Track Shipment <div class="login"> <div class="title"> Login </div> <div class="content-login"> <form action="." method="POST"> <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='p0SPV6QzpX2nP2p588V5lDU9s9LLWZDO' /></div> <input type= "text" name ="username" placeholder="Username" class="user-name"/> <input type= "Password" name="password" placeholder="Password"/> <input type="submit" class="button-login"/> Forgot Your Password? </form> </div> </div> </div> <div class="span6"> <div class="login"> <div class="title"> Ecom Express News </div> <div class="content-login"> </div> </div> </div> </div> <!-- modal --> <div class="modal hide modal-add-revlet" id="add-revlet"> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3>Record</h3> </div> <div class="modal-body"> </div> </div><!--modal end--> <div id="popupContact"> <a id="popupContactClose">x</a> </div> <!-- uncomment pre-deloy --> <!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>--> <script>window.jQuery || document.write('<script src="assets/js/libs/jquery-1.7.1.min.js"><\/script>')</script> <!-- bootstrap --> <script src="/static/assets/js/bootstrap-transition.js"></script> <script src="/static/assets/js/bootstrap-alert.js"></script> <script src="/static/assets/js/bootstrap-modal.js"></script> <script src="/static/assets/js/bootstrap-dropdown.js"></script> <script src="/static/assets/js/bootstrap-scrollspy.js"></script> <script src="/static/assets/js/bootstrap-tab.js"></script> <script src="/static/assets/js/bootstrap-tooltip.js"></script> <script src="/static/assets/js/bootstrap-popover.js"></script> <script src="/static/assets/js/bootstrap-button.js"></script>
P.S Also, if there is any problem with the code then why is it working for first call.
NOTE 1 Both the response are json objects I have verified several times.my backend is dJango. On hitting the url on browser I am getting the correct response in .json format
check for csrf_exempt or proper permission for access to the url from app

Categories