Reusable code at checking status respose with Javascript - javascript

I'm using Angular in Javascript to connect to the server, What I want to do is make reusable code.
The problem if that for each service that have to obtain data from server I have to know status response and if was 200 I have to know if the success was 1 or 0.
So... This is my code at today (using promise):
function obtenerUltimasOperacionesComplejo() {
return $http
.get(ultimasOperacionesUrl,
{params: {idComplejo: 11}})
.then(obtenerDatosUltimasOperaciones)
.catch(generarError);
}
function obtenerDatosUltimasOperaciones(data) {
var mensaje = '';
var status = data.status;
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
}
}
function generarError(e){
var newMessage = 'XHR error! :';
if (e.data && e.data.description) {
newMessage = newMessage + '\n' + e.data.description;
}
e.data.description = newMessage;
logger.error(newMessage);
return $q.reject('Ups! Hubo un problema al conectarse al servidor. Intente nuevamente');
}
This part of code:
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
...
I have to use it for each service that I have...
The problem that I have is that I can't put in a function the code above, because I don't know how to set the variable with the corresponding service, I mean:
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
This part of code changes for each service because "ultimasOperaciones" var is for this service in particular, for another service I have to use another variable and so on...
So... There is a way to disjoin this two part of code so I can reuse and don't have to copy and paste the most of the code?
Thanks!

please create a interceptor for checking every time the status of your response
http://thecodebarbarian.com/2015/01/24/angularjs-interceptors

Related

Ajax call falls into error before running the controller

I have an ajax call that is falling into error block before even running the controller.
The strange thing is that sometimes(after multiple requests) it does run succesfully but it does not save the cookies in the controller.
I think it could be the ajax call or some permission error.
AJAX CALL:
$('#loginAWGPE').on('click', function () {
var cpfLogin = $('#cpfValidacao').val().replace(/[^\d]+/g, '');
console.log(cpfLogin);
console.log(urlOrigem + appPath + "Login/validaCPF");
$.ajax({
type: 'POST',
url: urlOrigem + appPath + "Login/validaCPF",
datatype: String,
data: {
cpf: cpfLogin
},
success: function (teste) {
console.log('dataS: ' + teste);
if (teste = true) {
window.location = urlOrigem + appPath + "ProjetoEletrico/Index";
} else {
alert('CPF não cadastrado na Agência Virtual!');
}
},
error: function (teste2) {
console.log('dataE: ' + teste2);
alert('Erro na execusão');
}
});
});
-------CONTROLLER:
public JsonResult validaCPF(String cpf)
{
if (String.IsNullOrEmpty(cpf))
{
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json(false);
}
WebAPIPArameter id = new WebAPIPArameter();
id.ParameterName = "id";
id.ParameterValue = cpf;
List<WebAPIPArameter> list = new List<WebAPIPArameter>();
list.Add(id);
Usuario userInfo = (Usuario)apiClientSistema.GetItem<Usuario>(serviceNameUserInfo, list);
if (userInfo == null)
{
return Json(false);
}
else
{
CultureInfo cult = new CultureInfo("pt-BR");
String dataStr = userInfo.DTH_ULTIMO_ACESSO.ToString("dd/MM/yyyy HH:mm:ss", cult);
HttpCookie cook = new HttpCookie("UserInfo");
cook["cpfCnpj"] = userInfo.NUM_CPF_CNPJ_CLIENTE.ToString();
cook["nomeCompleto"] = userInfo.NOM_CLIENTE;
cook["dataAcesso"] = dataStr;
cook["email"] = userInfo.END_EMAIL;
cook.Expires = DateTime.Now.AddHours(4);
Response.Cookies.Add(cook);
//cookie de autenticacao
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
cpf, // Id do usuário é muito importante
DateTime.Now,
DateTime.Now.AddHours(4),
true, // Se você deixar true, o cookie ficará no PC do usuário
"");
HttpCookie cookieAuth = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookieAuth);
}
Response.Redirect("~/ProjetoEletrico/Index");
return Json(true);
}
I figure it out. It was a stupid mistake....
I forgot the "submit" in my form button and I also the ajax call.

Sending the current page HTML source to Spring MVC controller

I am using Spring MVC, Following is a method which will take either String or Input Stream from the Request and convert into PDF and write the PDF to the respose.
public void generatePDF(RequestDTO requestUIDTO, Map<String, Object> responseMap,
HttpServletRequest request, HttpSession session, HttpServletResponse response) {
Document document = new Document();
PdfWriter writer;
try {
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
//Here I need to get the HTML file as String or InputStream from the request.
//For now i am getting InputStream, It may be string
InputStream in = request.getInputStream();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Now the problem is, I don't know how to send the current rendered page as HTML to the server, I tried the following Java script but it is not working, the request itself is not going to the server May be because i am sending a huge file as request parameter.
function downloadLoanForm(){
var params = {};
params = {
htmlContent : "htmlContent"
}
handleRequest(this, params, 'generatePDF.htm', '');
}
$(document).ready(function(){
var htmlContent = $('#mainFormId').html();
$('#htmlContent').val(htmlContent);
});
My Question is this, Please let me know a way to send the current rendered HTML code to the Server as either a String (or) Stream.
Here is the Java script code for handleRequest() function,
function handleRequest(obj, params, request_url, replacement_element_id,
error_redirection, function_call_after_response) {
//check if there is any value present for the request url
if(!request_url)
{
alert('<spring:message code="JS_MSG_PROVIDE_URL_FOR_REQUEST" text=""/>');
return false;
}
//check if the url is an external url
if(isExternal(request_url) === true)
{
alert('<spring:message code="JS_MSG_REQUEST_CANNOT_SENT_TO_EXTERNAL_LINK" text=""/>');
return false;
}
//global variable for making the decision on the page redirect after the error from the server - default value is false
error_redirection = error_redirection || false;
//variable containing the replacement element id which will be used to place the content after the response from the server
replacement_element_id = replacement_element_id || false;
//variable to decide whether some manipulation has to be done on the response data from the server
// the response data is being sent to this function along with the replacement element id
function_call_after_response = function_call_after_response || '';
//alert(function_call_after_response+'-here');
//set the replacement element's html values to to be empty before the request is being made so as to ensure that user does not go forward without getting the correct result
if(replacement_element_id)
{
$('#'+replacement_element_id).html("");
}
//var serializedData = Array();
var counter = 0;
//SETTING THE REQUIRED ELEMENTS VALUES TO AN JSON OBJECT FOR SENDING TO THE SERVER - the elements required for the post is passed as an array in the arguments
var serializedData = {};
$.each(params, function(key, field) {
if($("#"+key).length > 0) {
//field = escapeHtml(field);
var value = $("#"+key).val();
/*if($('input[name="'+field+'"]').length > 0)
{
value = $('input[name="'+field+'"]').val();
}
else if($('select[name="'+field+'"]').length > 0)
{
value = $('select[name="'+field+'"]').val();
}
else if($('textarea[name="'+field+'"]').length > 0)
{
value = $('textarea[name="'+field+'"]').val();
}*/
value = escapeHtml(value);
if(value != "")
{
counter++;
}
//serializedData.field = value;
serializedData[field] = value;
/*
if(counter == 0)
{
serializedData = field+'='+value;
}
else
{
serializedData += '&'+field+'='+value;
}
counter++;
*/
}
});
if(counter == 0)
{
return false;
}
serializedData.csrfToken = $('form > input[name=csrfToken]').val();
//alert($('form > input[name=csrfToken]').val());
if(isExternal(request_url) === false)
{
$('input[name="'+$(obj).attr('name')+'"]').css('float', 'left');
$.blockUI({ message: "<h3><img src='images/processing.gif' id='processing_plz_wait' alt='Processing...' title='Processing...' border='0' class='processing_img' /><br/><spring:message code="JS_MSG_PLEASE_WAIT" text=""/></h3>" });
$(".blockOverlay").show();
$(".blockOverlay").css("opacity", "0.6");
$(".blockMsg").show();
$(".blockMsg").css("opacity", "1");
//setTimeout(function() {
$.ajax({
type: "POST",
url: request_url,
data: serializedData,
success: function(data, status, xhr) {
if(data) {
//check for some strings to validate session time out - TODO need proper validation check
if(data.contains("<html>") && data.contains("<head>")){
document.location.href = 'logout.htm';
} else {
if(replacement_element_id === false) {
alert('<spring:message code="JS_MSG_OPERATION_PERFORMED_SUCCESSFULLY" text=""/>');
return false;
}
else {
//set the response from the server to the form display element
$('#'+replacement_element_id).html(data);
setTokenValFrmAjaxResp();
$('#'+replacement_element_id).find("form ").append('<input type="hidden" value="'+$('#csrfToken').val()+'" name="csrfToken">');
$('form > input[name=csrfToken]').val($('#csrfToken').val());
if(function_call_after_response != "")
{
eval(function_call_after_response);
}
return false;
}
}
}
},
//ERROR HANDLING AS PER THE RESPONSE FROM THE SERVER - TO DO (some extra layer of error handling to be done)
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('<spring:message code="JS_MSG_NOT_ABLE_TO_CONNECT_VERIFY_NETWORK" text=""/>');
} else if (jqXHR.status == 404) {
alert('<spring:message code="JS_MSG_REQUEST_PAGE_NOT_FOUND" text=""/>');
} else if (jqXHR.status == 500) {
alert('<spring:message code="JS_MSG_INTERNAL_SERVER_ERROR" text=""/>');
} else if (exception === 'parsererror') {
alert('<spring:message code="JS_MSG_REQUESTED_DATA_PARSE_FAILED" text=""/>');
} else if (exception === 'timeout') {
alert('<spring:message code="JS_MSG_TOME_OUT_ERROR" text=""/>');
} else if (exception === 'abort') {
alert('<spring:message code="JS_MSG_AJAX_REQUEST_ABORTED" text=""/>');
} else {
alert('<spring:message code="JS_MSG_UNCAUGHT_ERROR" text=""/>' + jqXHR.responseText);
if(error_redirection === true)
{
//redirect to the corresponding error page
document.location.href = '';
}
}
setTokenValFrmAjaxResp();
return false;
}
});
//}, 100);
}
}

Insert data in sql with ajax not working

I'm trying to insert data in a sql table using ajax and php, but it's not working. My ajax give me the result like it works, but when i look at the table, there's not in it. Doing it without ajax works fine, so i guess my php is working ok.
Here's the code:
HTML:
<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>
<input type="submit" value="Enviar"/>
</form>
PHP:
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
switch($passo){
case "cadUsr":
cadUsr();
break;
default:
getRetorno();
break;
}
function getRetorno(){
echo "Este texto foi escrito via PHP";
}
function cadUsr(){
require("dbCon.php");
require("mdl_usuario.php");
$usr = $_POST["txtNome"];
$idade = $_POST["txtIdade"];
$resultado = usuario_cadastrar($con,$usr,$idade);
if($resultado){
echo "Cadastro efetuado com sucesso";
} else {
echo "O cadastro falhou";
}
}
?>
OBS: I need to pass the action of the form with the url parameter as cadUsr, so it call the function in php.
AJAX:
window.onload = function(){
var xmlhttp;
var frm = document.querySelector("#frmCadUsr");
var url = frm.getAttribute("action");
var nm = document.querySelector("#txtNome").value;
var idade = document.querySelector("#txtIdade").value;
frm.addEventListener("submit",function(e){
e.preventDefault();
try{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("POST",url,true);
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//alert("Deu certo");
console.log(xmlhttp.responseText);
}
}
} catch(err){
alert("Ocorreu um erro.<br />"+ err);
}
});
}
The PHP function to insert the data:
function usuario_cadastrar($conexao,$nome,$idade){
if($nome == "" && $idade == ""){
return false;
}
$sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);
$resultado = mysqli_query($conexao,$sql);
return $resultado;
}
I think the problem is here servico.php?p=cadUsr. You copy the action-attribute from the form with a querystring. If you cut the querystring from it, I think it will work.
The main problem is being called by Hossein:
This :
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
Will not work. You're doing a post, you can't get GET variables.
You call value on value which will result in undefined and that will put no data in your database.
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
So remove value and add the cadUsr variable to the querystring in the send function. Update PHP to:
$passo = (isset($_POST['p'])) ? $_POST['p'] : "";
And it will work!
You can see your callback codes by adding console.log(xmlhttp.responseText); to your readystate success function.
Also you need to set the requestheader content-type to x-www-form-urlencoded when sending post.

User Register Sign up Error

I am making a website and I have a signup.php page where the users can register and enter their information into the mysqli database. When I do this, I am almost there, I just keep getting a problem at this one line:
ajax.send("&u="+u+"&e="+e+"&p="+p1+"&g="+g);
It is basically sending the variables in the ajax/javascript check to get ready for transport to server. But I am getting an internal server 500 error at that line. Any ideas? I will post more code if you want me to.
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
type:post;
ajax.send("&u="+u+"&e="+e+"&p="+p1+"&g="+g);
}
}
A 500 Internal Server Error code is an HTTP response code, indicating that you have reached out to the server and it has responded with an error. So it doesn't appear to be a problem with your JS code (at least as far as we can tell from what you've posted).
Try doing var_dump($_REQUEST); die(); as the first line in signup.php. Does that give you a 200 status code? If so, try moving that line down your code on the server until you get back to the 500 Internal Server Error, and you've found the line that's causing the problem.
You have the question tagged with jQuery, but I don't see any jQuery in your code sample. If you do have it, try this:
function signup() {
var status = $('#status');
var signupbtn = $('#signupbtn');
var data = {
u: $('#username').val(),
e: $('#email').val(),
p: $('#pass1').val(),
g: $('#gender').val()
};
if (data.u == '' || data.e == '' || data.p == '' || data.g == '') {
status.text('Fill out all of the form data');
return;
} else if (data.p != $('#pass2').val()) {
status.text('Your password fields do not match');
return;
}
signupbtn.hide();
status.text('please wait...');
$.ajax({
type: 'post',
url: 'signup.php',
data: data,
success: function(responseText) {
if (responseText != 'signup_success') {
status.text(responseText);
signupbtn.show();
return;
}
window.scrollTo(0, 0);
$('#signupform').html('OK '+ data.u +', check your email inbox and junk mail box at <u>'+ data.e +'</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.');
},
});
}

Alfresco : Non-Administrator users cannot turn a site into moderate mode

I've got an issue on the Share part of my Alfresco application.
Indeed, when I'm logged in under a normal account (not administrator) and I go to a created site that dont have his "Moderate" option checked, I've got an error message each time I want to modify the site's details and check the moderate option.
The error message is the following :
04110011 Wrapped Exception (with status template): 04110169 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110168 Access denied. You don't have the permission to perform this operation.
The problem never occurs when the site has already been created under the "moderate" option or when your logged in under the administrator account.
Here you have the console log :
ERROR [extensions.webscripts.AbstractRuntime] Exception from executeScript - redirecting to status template error: 04110001 Wrapped Exception (with status template): 04110097 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
org.springframework.extensions.webscripts.WebScriptException: 04110001 Wrapped Exception (with status template): 04110097 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
at org.springframework.extensions.webscripts.AbstractWebScript.createStatusException(AbstractWebScript.java:758)
at org.springframework.extensions.webscripts.DeclarativeWebScript.execute(DeclarativeWebScript.java:171)
at org.alfresco.repo.web.scripts.RepositoryContainer$2.execute(RepositoryContainer.java:383)
at org.alfresco.repo.transaction.RetryingTransactionHelper.doInTransaction(RetryingTransactionHelper.java:381)
at org.alfresco.repo.web.scripts.RepositoryContainer.transactionedExecute(RepositoryContainer.java:436)
at org.alfresco.repo.web.scripts.RepositoryContainer.transactionedExecuteAs(RepositoryContainer.java:466)
at org.alfresco.repo.web.scripts.RepositoryContainer.executeScript(RepositoryContainer.java:304)
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:333)
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:189)
at org.springframework.extensions.webscripts.servlet.WebScriptServlet.service(WebScriptServlet.java:118)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.alfresco.web.app.servlet.GlobalLocalizationFilter.doFilter(GlobalLocalizationFilter.java:58)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Caused by: org.alfresco.scripts.ScriptException: 04110097 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js': 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
at org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:194)
at org.alfresco.repo.processor.ScriptServiceImpl.executeScript(ScriptServiceImpl.java:282)
at org.alfresco.repo.web.scripts.RepositoryScriptProcessor.executeScript(RepositoryScriptProcessor.java:102)
at org.springframework.extensions.webscripts.AbstractWebScript.executeScript(AbstractWebScript.java:981)
at org.springframework.extensions.webscripts.DeclarativeWebScript.execute(DeclarativeWebScript.java:86)
... 24 more
Caused by: org.alfresco.repo.security.permissions.AccessDeniedException: 04110096 Access refusé. Vous n'avez pas la permission de réaliser cette opération.
at org.alfresco.repo.security.permissions.impl.ExceptionTranslatorMethodInterceptor.invoke(ExceptionTranslatorMethodInterceptor.java:48)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.alfresco.repo.audit.AuditMethodInterceptor.proceedWithAudit(AuditMethodInterceptor.java:217)
at org.alfresco.repo.audit.AuditMethodInterceptor.proceed(AuditMethodInterceptor.java:184)
at org.alfresco.repo.audit.AuditMethodInterceptor.invoke(AuditMethodInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy53.setPermission(Unknown Source)
at org.alfresco.repo.site.SiteServiceImpl.setModeratedPermissions(SiteServiceImpl.java:1680)
at org.alfresco.repo.site.SiteServiceImpl.updateSite(SiteServiceImpl.java:1068)
at org.alfresco.repo.site.script.Site.save(Site.java:279)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:155)
at org.mozilla.javascript.NativeJavaMethod.call(NativeJavaMethod.java:243)
at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:119)
at org.mozilla.javascript.gen.c44._c11(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js:337)
at org.mozilla.javascript.gen.c44.call(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.mozilla.javascript.optimizer.OptRuntime.callName0(OptRuntime.java:108)
at org.mozilla.javascript.gen.c44._c0(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js:366)
at org.mozilla.javascript.gen.c44.call(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:393)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:2834)
at org.mozilla.javascript.gen.c44.call(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.mozilla.javascript.gen.c44.exec(file:/C:/workspace_starter/Tomcat/home/tomcat/webapps/alfresco/WEB-INF/classes/alfresco/templates/webscripts/org/alfresco/repository/site/site.put.json.js)
at org.alfresco.repo.jscript.RhinoScriptProcessor.executeScriptImpl(RhinoScriptProcessor.java:472)
at org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:190)
... 28 more
Caused by: net.sf.acegisecurity.AccessDeniedException: Access is denied.
at net.sf.acegisecurity.vote.AffirmativeBased.decide(AffirmativeBased.java:86)
at net.sf.acegisecurity.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:394)
at net.sf.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:77)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.alfresco.repo.security.permissions.impl.ExceptionTranslatorMethodInterceptor.invoke(ExceptionTranslatorMethodInterceptor.java:44)
... 58 more
The error come from the "site.put.json.js" webscript, that contains the following source code :
<import resource="classpath:alfresco/module/customAlfrescoAMP/javascript/tsUtils.js">
<import resource="classpath:alfresco/module/customAlfrescoAMP/javascript/ts-constants.js">
function main()
{
// Get the site
var shortName = url.extension;
var site = siteService.getSite(shortName);
if (site != null)
{
// Updafte the sites details
if (json.has("title") == true)
{
site.title = json.get("title");
}
if (json.has("description") == true)
{
site.description = json.get("description");
}
// Use the visibility flag before the isPublic flag
if (json.has("visibility") == true)
{
site.visibility = json.get("visibility");
}
else if (json.has("isPublic") == true)
{
// Deal with deprecated isPublic flag accordingly
var isPublic = json.getBoolean("isPublic");
if (isPublic == true)
{
site.visibility = siteService.PUBLIC_SITE;
}
else
{
site.visibility = siteService.PRIVATE_SITE;
}
}
//début modif T&S
if (!site.node.hasAspect("st:siteType"))
{
site.node.addAspect("st:siteType");
}
var siteType = "";
if (json.has("type") == true)
{
siteType = json.get("type");
}
var assocs = site.node.assocs["st:siteTypeAssoc"];
if (assocs != null && assocs.length == 1) {
site.node.removeAssociation(assocs[0], "st:siteTypeAssoc");
assocs[0].remove();
}
var siteTypeNode = site.node.createNode(null, "cm:content");
siteTypeNode.content = siteType;
site.node.createAssociation(siteTypeNode, "st:siteTypeAssoc");
var siteiconNodeRef = null;
if (json.has("siteiconNodeRef"))
{
siteiconNodeRef = json.get("siteiconNodeRef");
}
if (siteiconNodeRef != null && siteiconNodeRef != "")
{
var image = search.findNode(siteiconNodeRef);
// ensure cm:person has 'cm:preferences' aspect applied - as we want to add the avatar as
// the child node of the 'cm:preferenceImage' association
if (!site.node.hasAspect("st:siteIcon"))
{
site.node.addAspect("st:siteIcon");
}
// remove old image child node if we already have one
var assocs = site.node.assocs["st:siteIconAssoc"];
if (assocs != null && assocs.length == 1)
{
site.node.removeAssociation(assocs[0], "st:siteIconAssoc");
//no need to remove the image ?
//assocs[0].remove();
}
//images are created in userhome, move them to the site
image.move(site.node);
site.node.createAssociation(image, "st:siteIconAssoc");
}
//fin modif T&S
// Save the site
site.save();
var members = site.listMembers(null, null, 0);
var templateNodeRef = search.luceneSearch( "#\\{http\\://www.alfresco.org/model/content/1.0\\}name:\"edit-site-mail.ftl\"")[0].nodeRef;
for (username in members)
{
/*var mail = actions.create("mail");
mail.parameters.to_many = users;
mail.parameters.subject = EDIT_SITE_MAIL_SUBJECT + site.title;
mail.parameters.template = templateNodeRef;
mail.execute(site.node);
*/
createAndSendHtmlMail(site.node, EDIT_SITE_MAIL_SUBJECT + site.title, people.getPerson(username).properties["cm:email"], "", templateNodeRef, null);
}
// Pass the model to the template
model.site = site;
}
else
{
// Return 404
status.setCode(status.STATUS_NOT_FOUND, "Site " + shortName + " does not exist");
return;
}
}
main();
So, if you have any suggestion...

Categories

Resources