I have a requirement where from my application I have to edit files using office 365. I have used WOPI and it was working fine before, but now I'm getting the following error.
When I contacted the support team, they said WOPI CheckFileInfo is not called, so I explicitly called still the issue persists.
Below is my code,
function submit(docId, type) {
var WOPISrc = "WOPISrc=https://" + host +"/wopi/files/" + docId;
if (type == 'word') {
$('#office_form_online').attr('action', 'https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?edit=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'excel') {
$('#office_form_online').attr('action', 'https://excel.officeapps.live.com/x/_layouts/xlviewerinternal.aspx?edit=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'powerpoint') {
$('#office_form_online').attr('action', 'https://powerpoint.officeapps.live.com/p/PowerPointFrame.aspx?PowerPointView=EditView&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else if (type == 'pdf') {
$('#office_form_online').attr('action', 'https://word-view.officeapps.live.com/wv/wordviewerframe.aspx?PdfMode=1&ui=en-US&rs=en-US&IsLicensedUser=1&hid=1234&sc=edit_form&' + WOPISrc);
} else {
return false;
}
var promise = createWOPIToken(docId);
promise.success(function (data) {
$.ajax({
url: "https://" + host + "/wopi/files/" + docId,
type: "GET",
data: {
access_token: data.token
},
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
return '';
},
success: function (data1) {
console.log(data1);
$.ajax({
url: "https://" + host + "/wopi/files/" + docId + "/content",
type: "GET",
data: {
access_token: data.token
},
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
return -1;
},
success: function (contents) {
$('#office_access_token_online').val(data.token);
$('#office_access_token_ttl_online').val(0);
var frameholder = document.getElementById('frameholder_online');
$(frameholder).show();
closeiFrame();
var office_frame = document.createElement('iframe');
office_frame.src = 'https://"+ host + "/wopi/files/" ' + docId + "?access_token="+data.token;
office_frame.name = 'office_frame_online';
office_frame.id = 'office_frame_online';
office_frame.title = 'Office Online Frame';
office_frame.setAttribute('allowfullscreen', 'true');
office_frame.setAttribute('sandbox',
'allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox');
frameholder.appendChild(office_frame);
document.getElementById('office_form_online').submit();
showCloseButton();
}
});
}
});
});
}
Java Code
#Override
#GET
#Path("/files/{fileId}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response checkFileInfo(
#NotNull #PathParam("fileId") Integer fileId,
#NotNull #QueryParam("access_token") String access_token) {
return Response.ok().entity(fileInfo).build();
}
}
#Override
#GET
#Path("/files/{fileId}/content")
#Produces(MediaType.APPLICATION_JSON)
public Response getFile(
#NotEmpty #PathParam("fileId") Integer fileId,
#QueryParam("access_token") String access_token) {
byte[] data = new byte[(int) content().length()];
DataInputStream dataIs = new DataInputStream(content.getBinaryStream());
dataIs.readFully(data);
return Response.ok(new ByteArrayInputStream(data)).build();
}
#Override
#POST
#Path("/files/{fileId}/contents")
#Transactional
public Response putFile(#PathParam("fileId") Integer fileId,
#QueryParam("access_token") String access_token, byte[] bytes) {
save(BlobProxy.generateProxy(SecurityWrapper.encrypt(bytes)));
return Response.ok().build();
}
The API calls are returning responses but it's not opening files.
EDIT
When I try hitting the below URL (which is used to open files online), without any source, still it shows as Service Unavailable.
https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?
Is it because of it, that my code isn't working? And in the test server, it's a different error, we ran into a problem.
And this is the console error
Any help is appreciated.
Thank you.
Related
I am new to using a RESTful API and I don't know why it is showing this error.
I am posting the values through jQuery. Do I need to do something else? This is my jQuery code:
Updated : Now it is showing 405 (Method Not Allowed)
$(document).ready(function(){
$("#patsubmit").click(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var mobileNumber = $("#mobileNumber").val();
var emailId = $("#emailId").val();
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '", "emailId":"' + emailId+'"}';
console.log(dataString);
if(firstName=='' )
{
alert("nothing in it");
}
else
{
$.ajax({
type: 'POST',
url : '/geniedoc/api/patient/register',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'}
success: function(){ // Uncaught SyntaxError: Unexpected identifier
console.log();
}
});}
return false;
});
});
This is my Java API. MAIN_PATIENT = api/patient and RestURIConstants.REGISTER = register
#RestController
#RequestMapping(value = RestURIConstants.MAIN_PATIENT)
public class PatientRestController extends AbstractController implements RestURIConstants, GenieDocConstants{
private static final Logger logger = Logger.getLogger(UserRestController.class);
#RequestMapping(value = RestURIConstants.REGISTER, method = RequestMethod.POST, consumes ="application/json")
public #ResponseBody ModelMap registerPatient(HttpServletRequest request, #RequestBody PatientVo patientVo){
logger.info("registerPatient : Start");
long startTime = System.currentTimeMillis();
ModelMap map = new ModelMap();
PatientVo patVo;
try {
if(patientVo.getFirstName() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_FIRST_NOT_EMPTY));
} else if(patientVo.getEmailId() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
} else if(patientVo.getEmailId() == "") {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_EMAIL_NOT_EMPTY));
} else if (patientVo.getMobileNumber() == null) {
map.addAttribute(STATUS_CODE, FAILURE);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(MESSAGE_MOBILE_NOT_EMPTY));
} else {
patVo = this.patientManagementService.provisionPatient(patientVo);
if (patVo != null) {
map.addAttribute("patientId", patVo.getEmailId());
map.addAttribute(STATUS_CODE, SUCCESS_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(SUCCESS_STATUS_CODE_REGPATIENT));
} else {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REG);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REG));
}
}
} catch (MongoDBDocumentNotFoundException e) {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE,this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
logger.error("Error : " + e.getMessage());
//e.printStackTrace();
} catch (UserAreadyExsistException e) {
map.addAttribute(STATUS_CODE, ERROR_STATUS_CODE_REGPATIENT);
map.addAttribute(STATUS_MESSAGE, this.env.getProperty(ERROR_STATUS_CODE_REGPATIENT));
logger.error("Error : " + e.getMessage());
//e.printStackTrace();
}
logger.debug("Exit: Total Time Taken: "+ (System.currentTimeMillis() - startTime));
return map;
}
You need to set the Content-Type Header to application/json
$.ajax({
type: 'POST',
url: '/geniedoc/api/patient/register',
data: dataString,
headers: {
'Content-Type':'application/json'
}
.....
}
In your spring controller you are defining, that only content of MIME Type application/json is accepted. Because standard content type text/plain the Spring controller does not accept your request and send back a status code 415 (Media type not supported)
Edit: As user6409738 mentioned, you need to send your data in json format. Otherwise the Spring Controller will cause an exception parsing the body.
For example the solution posted by Yagnesh Agola
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":' + emailId+'"}';
It depends what your PatientVo Class is looking like
Data you have send to server from client is not in JSON format.
var dataString = 'firstName='+ firstName + '&lastName=' + lastName + '&mobileNumber=' + mobileNumber + '&emailId=' + emailId;
Above line is used to send data string to server which is not in JSON format it is simple query string.
Either you can convert above string in JSON format
var dataString = '{"firstName":"'+ firstName + '","lastName":"' + lastName + '","mobileNumber":"' + mobileNumber + '","emailId":"' + emailId+'"}';
OR
You can directly submit form data in JSON using below code.
var formData = JSON.stringify($("#myForm").serializeArray());
add contentType parameter when use jQuery Ajax
$.ajax({
type : "POST",
contentType : 'application/json',
url : "/geniedoc/api/patient/register",
data : JSON.stringify({"param1" : "param1", "param2":2})
})
remove consumer = "application/json" in your request-mapping definition, (it's not necessary, SpringMVC will auto detect right converter)
because U use #RequestBody in springMVC controller, then SpringMVC will convert the argument with RequestResponseBodyMethodProcessor which use default converters to resolve the argument. default converters list is:
public RequestMappingHandlerAdapter() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
this.messageConverters = new ArrayList<HttpMessageConverter<?>>(4);
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(stringHttpMessageConverter);
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
For your situation, MappingJackson2HttpMessageConverter is expect to be used to resolve the argument. And here is the definition of MappingJackson2HttpMessageConverter, it need MediaType of application/json
public MappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
super(objectMapper, MediaType.APPLICATION_JSON_UTF8,
new MediaType("application", "*+json", DEFAULT_CHARSET));
}
$.ajax({
url: '/active/get-url',
type: 'get',
cache: false,
data: {
siteid: siteid,
sno: ids
},
success: function (data) {
console.log(data);
if (data.length > 0) {
rawdataIp = data[0].IP;
rawdataIp = rawdataIp.slice(7);
url = rawdataIp;
console.log("urlll" + url);
videourl = rawdataIp;
}
imageDisplay(url);
}
});
My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}
i have created a java webservice to return country list
#RequestMapping(value = "/getcountrylist", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
#ApiIgnore
Object getcountrylist(#RequestParam String pvtToken,
#RequestParam String lan) {
System.out.println(API_TAG + "Request recevied to get CountryList");
System.out.println("DB:"+dbName);
if (!this.pvtToken.equals(pvtToken)) {
CountryList countryList = new CountryList();
return new ResponseEntity<CountryList>(countryList,
HttpStatus.UNAUTHORIZED);
}
CountryList countryList = avlMobileAPIService.getCountryList(lan);
return new ResponseEntity<CountryList>(countryList, HttpStatus.OK);
}
i need to call the above webservice from javascript as JSONP, i wrote the following javascript code as below
function buttonClick(){
$.ajax({
type: "GET",
dataType: "jsonp",
crossDomain: true,
url: "http://localhost:8080/api/getcountrylist",
data: {pvtToken:"JXku56AE0067YtRUSAZEE",lan:"en"},
Accept: "application/jsonp",
jsonpCallback: function(data, status){
alert('callback');
alert(data);
},
success: function(data, status){
alert('sucess');
},
});
}
Above function call the webservice and returns the list, but shows "invalid label error" on client side.
{"countrylist":[{"countryId":"4","countryCodeAlpha2":"AF","countryCodeAlpha3":"AFG","countryName":"Afghanistan ","isdCode":"93"},{"countryId":"5","countryCodeAlpha2":"AL","countryCodeAlpha3":"ALB","countryName":"Albania ","isdCode":"355"},{"countryId":"6","countryCodeAlpha2":"DZ","countryCodeAlpha3":"DZA","countryName":"Algeria ","isdCode":"213"},{"countryId":"7","countryCodeAlpha2":"AS","countryCodeAlpha3":"ASM","countryName":"American Samoa ","isdCode":"684"}]}
i found in some article it says, the that ajax call expects JSONP , but return JSON data.
What is the solution?
reffer this link
http://www.iceycake.com/2012/06/xml-json-jsonp-web-service-endpoints-spring-3-1/
or try in this simple way
#RequestMapping(value = "/mobile_getcountrylist", method = RequestMethod.GET, produces = {"application/x-javascript"})
#ResponseBody
public Object mobile_getcountrylist( #RequestParam("callback") String jsonpCallback) {
System.out.println(API_TAG + "Request recevied to get CountryList");
CountryList countryList = avlMobileAPIService.getCountryList("en");
//countryList.setJsonCallback(jsonpCallback);
return convertToJsonP(countryList,jsonpCallback);
}
private String convertToJsonP(Object o,String jsonpCallback){
String outputmessage=null;
ObjectMapper mapper = new ObjectMapper();
try {
outputmessage=mapper.writeValueAsString(o);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(outputmessage!=null){
outputmessage=jsonpCallback + "(" + outputmessage + ")";
}
return outputmessage;
}
Javascript code
$.ajax({
type: 'GET',
url: 'http://localhost:8080/api/mobile_getcountrylist',
crossDomain: true,
async: false,
jsonpCallback: 'jsonpCallback',
dataType: 'jsonp',
contentType:'application/json',
success: function(data) {
alert('ok');
}
});
Environment: Eclipse running Tomcat v7.0, working with the Stripes framework for Java, and submitting to the service via a JQuery ajax call.
The Javascript:
jQuery( function(){
jQuery('#testForm').submit( function(e) {
e.preventDefault();
var dataString = jQuery('#testInput').val(); // Pulled from a textarea for testing purposes.
var urlString = jQuery('#urlDropdown').val(); // Pulled from a dropdown for testing purposes.
if( (jQuery('#urlId') != "" ) &&
(!isNaN(parseInt( jQuery('#urlId').val() )) ) ){ // Pulled from an input type=text for testing purposes.
urlString += '?id=' + parseInt( jQuery('#urlId').val() );
}
alert("urlString: " + urlString);
jQuery.ajax({
type: "POST",
url: urlString,
data: dataString,
dataType: 'json',
success: function( returnData ) {
jQuery('#content').html(JSON.stringify(returnData));
},
fail: function( returnData ) {
alert("FAIL");
}
});
});
});
The Stripes Interceptor:
#Before(stages=LifecycleStage.BindingAndValidation, on={"setClient"})
private Resolution intercept() {
String rbody = getRequestBody();
log.info("BODY: " + rbody);
this.setBody( rbody );
return null;
}
And the getRequestBody method being used:
protected String getRequestBody(){
StringBuffer body = new StringBuffer();
String line = null;
try {
BufferedReader reader = getContext().getRequest().getReader();
while ((line = reader.readLine()) != null)
body.append(line);
} catch (Exception e) {
log.error("Buffered Reader Failed", e);
e.printStackTrace();
}
log.info("BODY: " + body.toString());
return body.toString();
}
I am using Firebug to test the input, and the post body of the request is indeed filled with meaty json.
The log.info calls there output a completely empty string. If I call up the getContentLength() on the getRequest, it tells me that the content has the appropriate number of characters. But the content itself comes out as null.
I am 99.99% sure that nowhere else in the code is the Request body being consumed. At the moment, this is my only action file in the Stripes framework, as I've removed every single other file.
Somehow, the request body is completely empty. It should be full of meaty json. Help me, Stack Overflow, you're my only hope!
Thanks to the fine people on the Stripes IRC channel, I have an answer! I needed to add in contentType: "application/json", as so:
jQuery.ajax({
type: "POST",
url: urlString,
contentType: "application/json",
data: dataString,
dataType: 'json',
processData: false,
success: function( returnData ) {
jQuery('#content').html(JSON.stringify(returnData));
},
fail: function( returnData ) {
alert("FAIL");
}
});