CA Service Management

 View Only

SPEL: How to upload attachment using SPEL 

Feb 02, 2017 02:19 PM

I would like to share method found while developing java app, not sure that someone will need it in real life, but...

 

Calling example

// Attaching txt from local disk to Issue
void run() {
     int newAttmntId;
     newAttmntId = newAttmnt("c:\\1234.txt", "doc_rep:1002")
     if (newAttmntId < 1) {
          switch (val) {
               case 0: printf("Unknown error"); break;
               case 1: printf("Failed to get file name"); break;
               case 2: printf("Failed to get file extension"); break;
               default: printf("I'm to lazy to fill this list"); break;
          }
     } else {
          send_wait(0, top_object(), "call_attr", "api", "insert_object", (uuid)NULL, "lrel_attachments_issues", NULL, 0,
                         "iss", "iss:12345678",
                         "attmnt", newAttmntId
                    );
     }
}

 

Entire code

i'm not using file attaching to make this code searcheable:

int newAttmnt(string filePath, string repPersid) {
     object boplog, rep, attmntObj, gl;
     string fileName, fileExt, escapedPath, attmntFileName, attmntRep, attmntRelFilePath, fileSlice[25], fileExtSlice[25];
     int i, j, uploadSession, fileSize, zipFlag;

     // Create new rep object
     rep = (object)format("@|rep_daemon:%s|top|0|0", getenv("NX_SERVER"));

     // Escape file path
     escapedPath = gsub(filePath, "\\\\", "/");
     printf("escaped path: %s\n", escapedPath);

     // Zipping
     zipFlag = 1;

     // Get file name
     split(fileSlice, escapedPath, "/");
     j = 24;
     while ( (j >= 0) && (strlen(fileSlice[j]) == 0) ) {
          j--;
     }
     if (j > -1)
          fileName = fileSlice[j];
     else
          return -1;
     printf("file : %s\n", fileName);

     // Get file extension
     split(fileExtSlice, fileName, "\\.");
     j = 24;
     while ( (j >= 0) && (strlen(fileExtSlice[j]) == 0) ) {
          j--;
     }
     if (j > -1)
          fileExt = fileExtSlice[j];
     else
          return -2;
     printf("file ext : %s\n", fileExt);

     // Get group leader
     send_wait(0, top_object(), "get_co_group");
     if (msg_error()) {
          for (i=0;i<msg_length();i++) {
               printf("\tERROR[%d]: %s\n", i, (string)msg[i]);
          }
          return -3;
     } else {
          gl = msg[0];
     }

     // Get new dob [attmnt]
     send_wait(0, top_object(), "call_attr", "attmnt", "get_new_dob", NULL, NULL, gl);
     if (msg_error()) {
          return -4;
     } else {
          attmntObj = msg[0];
     }

     // Open upload session, filename format > attmnt.id + "_" + file name
     send_wait(0, rep, "open_upload_session", format("%d_%s", attmntObj.id, fileName), repPersid, 0, 1, zipFlag);
     if (msg_error()) {
          for (i=0;i<msg_length();i++) {
               printf("\tERROR[%d]: %s\n", i, (string)msg[i]);
          }
          return -5;
     } else {
          uploadSession = msg[0];
          attmntFileName = msg[1];
          attmntRelFilePath = msg[2];
          attmntRep = msg[3];          
     }

     // Uploading file to local repository
     send_wait(0, rep, "upload_local_file", uploadSession, escapedPath);
     if (msg_error()) {
          for (i=0;i<msg_length();i++) {
               printf("\tERROR[%d]: %s\n", i, (string)msg[i]);
          }
          return -6;
     } else {
          // msg[0] contains rel_file_path folder
          fileSize = msg[1];
     }

     // Closing upload session
     send_wait(0, rep, "close_upload_session", uploadSession);
     if (msg_error()) {
          for (i=0;i<msg_length();i++) {
               printf("\tERROR[%d]: %s\n", i, (string)msg[i]);
          }
          return -7;
     }
     
     send_wait(0, attmntObj, "call_attr", "attmnt_name", "set_val", fileName);
     send_wait(0, attmntObj, "call_attr", "orig_file_name", "set_val", fileName);
     send_wait(0, attmntObj, "call_attr", "link_only", "set_val", 0);
     send_wait(0, attmntObj, "call_attr", "file_type", "set_val", fileExt);
     send_wait(0, attmntObj, "call_attr", "file_size", "set_val", fileSize);
     send_wait(0, attmntObj, "call_attr", "file_name", "set_val", attmntFileName);
     send_wait(0, attmntObj, "call_attr", "repository", "set_val", attmntRep);
     send_wait(0, attmntObj, "call_attr", "rel_file_path", "set_val", attmntRelFilePath);
     send_wait(0, attmntObj, "call_attr", "zip_flag", "set_val", zipFlag);
     send_wait(0, attmntObj, "call_attr", "status", "set_val", "INSTALLED");
     send_wait(0, gl, "checkin");
     if (msg_error()) {
          for (i=0;i<msg_length();i++) {
               printf("\tERROR[%d]: %s\n", i, (string)msg[i]);
          }
          return -8;
     } else {
          return attmntObj.id;
     }
}

Statistics
0 Favorited
32 Views
0 Files
0 Shares
0 Downloads

Tags and Keywords

Comments

Apr 23, 2018 07:56 AM

cdtj

I tried but no effect.

 

My function actually:

 

int z_upload_file(string zs_filepath, ...)
{
     ////////////////////////////////////////////////////////////////////////
     // Metodo:           z_upload_file
     // Autor:          Daniel Becker Bighelini
     // Criado em:          19/04/2018
     // Modificado por:     Daniel Becker Bighelini
     // Modificado em:     19/04/2018
     //
     // Parametros de entrada:
     // ARG #0 : (string) zs_filepath          Caminho completo do arquivo que sera carregado.
     // ARG #1 : (string) zs_rep_persid          [OPCIONAL] Persid do repositorio de anexos.
     // ARG #2 : (int) zi_depurar               [OPCIONAL] Nivel de depuracao da funcao 0-nenhum / 1-resumido / 2-detalhado / 3-SUPER detalhado
     // ARG #3 : (string) zs_metodo               [OPCIONAL] Nome do metodo que sera identificado no bloco
     //
     // Forma de funcionamento:
     //
     // Resultado:
     //          Arquivo carregado em um repositorio de anexos.
     //
     // Exemplo:
     //          z_upload_file('D:\PROGRA~1\CA\SERVIC~1\bin\relatorio_99999.tmp')
     //          z_upload_file('D:\PROGRA~1\CA\SERVIC~1\bin\relatorio_99999.tmp', 'doc_rep:400053')
     //          z_upload_file('D:\PROGRA~1\CA\SERVIC~1\bin\relatorio_99999.tmp', 'doc_rep:400053', 1, 'teste')
     ////////////////////////////////////////////////////////////////////////
     string zs_metodo, zs_msg;
     int zi_i, zi_j, zi_depurar;
     zs_metodo = 'z_upload_file';
     zs_msg = '';

     ///////////////////////////////////////////////////////////////////////////////////////
    // Inicio do codigo

     string zs_rep_persid;
     if (argc>1) {zs_rep_persid     = (string) argv[1];}
     if (argc>2) {zi_depurar     = (int) argv[2];}
     if (argc>3) {zs_metodo     = format("%s %s", (string) argv[3], zs_metodo);}

     // Entrada para debug mode
     if (zi_depurar > 0) {
          z_bloco_inicio(zi_depurar, zs_metodo);
          logf(SIGNIFICANT, "%s Quant. de argumentos : %d", zs_metodo, argc);
          for (zi_i=0; zi_i<argc; zi_i++) {
               logf(SIGNIFICANT, "%s ARG #%s : %s", zs_metodo, zi_i, argv[zi_i]);
          }
     } else {
          logf(SIGNIFICANT, "%s '%s'", zs_metodo, zs_filepath);
     }

     ////////////////////////////////////////////////////
     // Identificando USUARIO LOGADO
     ////////////////////////////////////////////////////
     uuid zu_who;
     zu_who = z_identifica_usuario_logado(zi_depurar, zs_metodo);

     ////////////////////////////////////////////////////
     // Definindo PERSID DO REPOSITORIO caso nao seja informado
     ////////////////////////////////////////////////////
     string zs_rep_sym, zs_prohibited_file_ext;
     if (is_empty(zs_rep_persid)) {
          string zs_wc, zs_factory;
          zs_factory = "doc_rep";
          zs_wc = format("repository_type=0 AND default_rep=1 AND delete_flag=0");
         
          if (zi_depurar > 0) logf(SIGNIFICANT, "%s Selecionando registros da factory '%s' com a clausula '%s'...", zs_metodo, zs_factory, zs_wc);
          send_wait(0, top_object(), "call_attr", zs_factory, "sync_fetch", "STATIC", zs_wc, -1, 0);
          if (msg_error()) {
               zs_msg = format("%s ERRO ao consultar a factory '%s' utilizando a clausula '%s': '%s'", zs_metodo, zs_factory, zs_wc, msg[0]);
               logf(ERROR, zs_msg);
               z_bloco_fim(zi_depurar, zs_metodo);
               return zs_msg;
          }
          object zo_rep_list;
          int zi_rep_count;
          zo_rep_list = msg[0];
          zi_rep_count = msg[1];
          if (zi_depurar > 0) logf(SIGNIFICANT, "%s Quantidade de registros encontrados: %d", zs_metodo, zi_rep_count);
         
          if (zi_rep_count > 0) {
               // Consultando atributos do primeiro registro de solucao
               if (zi_depurar > 1) logf(SIGNIFICANT, "%s Consultando os atributos dos repositorios encontrados...", zs_metodo);
               send_wait(0, top_object(), "call_attr", "api", "get_list_values", zu_who, zo_rep_list, 0, zi_rep_count, 0, "sym", "prohibited_file_ext");
               if (msg_error()) {
                    zs_msg = format("%s ERRO ao consultar atributos da lista: '%s'", zs_metodo, msg[0]);
                    logf(ERROR, zs_msg);
                    z_bloco_fim(zi_depurar, zs_metodo);
                    return -9;
               }
               zs_rep_persid = msg[0];
               zs_rep_sym = msg[2];
               zs_prohibited_file_ext = msg[4];
         
          } else {
               zs_msg = format("%s ERRO ao identificar persid do repositorio padrao de anexos: Nenhum foi encontrado.", zs_metodo);
               logf(ERROR, zs_msg);
               z_bloco_fim(zi_depurar, zs_metodo);
               return -9;
          }
    
     } else {
          zs_rep_sym = expand(format("&{%s = doc_rep.persistent_id->sym}", zs_rep_persid));
          if (is_empty(zs_rep_sym)) {
               zs_msg = format("%s ERRO ao localizar o persid '%s' informado: NAO foi encontrado.", zs_metodo, zs_rep_persid);
               logf(ERROR, zs_msg);
               z_bloco_fim(zi_depurar, zs_metodo);
               return -10;
          } else {
               zs_prohibited_file_ext = expand(format("&{%s = doc_rep.persistent_id->prohibited_file_ext}", zs_rep_persid));
          }
     }
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Repositorio '%s': '%s' ('%s')", zs_metodo, zs_rep_sym, zs_rep_persid, zs_prohibited_file_ext);
    
     // Escape file path
     string zs_escaped_path;
     zs_escaped_path = gsub(zs_filepath, "\\\\", "/");
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Escaped path: '%s'", zs_metodo, zs_escaped_path);

     /////////////////////////////////
     // VERIFICA se o arquivo pode ser acessado
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Tentando acessar o arquivo '%s'...", zs_metodo, zs_escaped_path);
     int zi_file_access;
     zi_file_access = access(zs_escaped_path, "r");
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Resultado da tentativa de acesso ao arquivo '%s': %d", zs_metodo, zs_escaped_path, zi_file_access);

     if (zi_file_access != 1) {
          zs_msg = format("%s ERRO ao acessar o arquivo '%s': %d", zs_metodo, zs_escaped_path, zi_file_access);
          logf(ERROR, zs_msg);
          z_bloco_fim(zi_depurar, zs_metodo);
          return -11;
     }
    
     /////////////////////////////////
     // Define ZIP FLAG
     /////////////////////////////////
     int zi_zipflag;
     zi_zipflag = 1;

     /////////////////////////////////
     // Get FILE NAME
     /////////////////////////////////
     string zs_file_slice[25];
     zi_j = split(zs_file_slice, zs_escaped_path, "/");
     string zs_filename;
     zs_filename = zs_file_slice[zi_j-1];
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Nome do arquivo: '%s'", zs_metodo, zs_filename);
    
     /////////////////////////////////
     // Get FILE EXTENSION
     /////////////////////////////////
     string zs_fileext_slice[25];
     zi_j = split(zs_fileext_slice, zs_filename, "\\.");
     string zs_fileext;
     if (sindex(zs_filename, '\\.') > -1) {
          zs_fileext = zs_fileext_slice[zi_j-1];
     } else {
          zs_fileext = '';
     }
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Extensao do arquivo: '%s'", zs_metodo, zs_fileext);
    
     /////////////////////////////////
     // VERIFICA se a extensao do arquivo eh permitida no repositorio
     /////////////////////////////////
     if (!is_empty(zs_prohibited_file_ext) && !is_empty(zs_fileext) && sindex(zs_prohibited_file_ext, zs_fileext) != -1) {
          zs_prohibited_file_ext = gsub(zs_prohibited_file_ext, "[!| ]", "");
          if (zi_depurar > 0) logf(SIGNIFICANT, "%s Lista de extensoes proibidas: '%s'", zs_metodo, zs_prohibited_file_ext);
         
          string zs_ext[25];
          int zi_ext;
          zi_ext = split(zs_ext, zs_prohibited_file_ext, ",");
          if (zi_depurar > 0) logf(SIGNIFICANT, "%s Quantidade de extensoes proibidas encontradas: %d", zs_metodo, zi_ext);
         
          for (zi_i=0; zi_i<zi_ext; zi_i++) {
               if (downcase(zs_fileext) == downcase(zs_ext[zi_i])) {
                    zs_msg = format("%s ERRO com a extensao do arquivo '%s': O repositorio '%s' nao permite a extensao '%s'.", zs_metodo, zs_filename, zs_rep_sym, zs_fileext);
                    logf(ERROR, zs_msg);
                    z_bloco_fim(zi_depurar, zs_metodo);
                    return -12;
               }
          }
     }
    
     /////////////////////////////////
     // Get GROUPLEADER
     /////////////////////////////////
     send_wait(0, top_object(), "get_co_group");
     if (msg_error()) {
          zs_msg = format("%s ERRO FATAL ao instanciar GL: '%s'", zs_metodo, msg[0]);
          logf(ERROR, "%s", zs_msg);
          return -3;
     }
     object zo_group_leader;
     zo_group_leader = msg[0];
     if (zi_depurar > 1) logf(SIGNIFICANT, "%s Group leader: '%s'", zs_metodo, (string) zo_group_leader);

     /////////////////////////////////
     // Get NEW DOB [attmnt]
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Criando novo registro...", zs_metodo);
     send_wait(0, top_object(), "call_attr", "attmnt", "get_new_dob", NULL, NULL, zo_group_leader);
     if (msg_error()) {
          zs_msg = format("%s ERRO ao criar novo registro na factory 'attmnt': '%s'", zs_metodo, msg[0]);
          logf(ERROR, "%s", zs_msg);
          return -4;
     }
     object zo_attmnt;
     zo_attmnt = msg[0];

     /////////////////////////////////
     // Define new rep object
     /////////////////////////////////
     object zo_rep;
     //zo_rep = (object) format("@|rep_daemon:%s|top|0|0", getenv("NX_SERVER"));
     zo_rep = (object) format("@|rep_daemon:%s|top|0|0", getenv("NX_PRIMARY_CMDB"));
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Object de repositorio: '%s'", zs_metodo, (string) zo_rep);

     /////////////////////////////////
     // OPEN UPLOAD SESSION
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Abrindo sessao de upload...", zs_metodo);
     send_wait(0, zo_rep, "open_upload_session", zs_filename, zs_rep_persid, 0, 1, zi_zipflag);
     if (msg_error()) {
          zs_msg = format("%s ERRO ao executar metodo 'open_upload_session': '%s'", zs_metodo, msg[0]);
          logf(ERROR, "%s", zs_msg);
          return -5;
     }
     int zi_upload_session;
     string zs_attmnt_filename, zs_attmnt_rep, zs_attmnt_rel_filepath;
     zi_upload_session = msg[0];
     zs_attmnt_filename = msg[1];
     zs_attmnt_rel_filepath = msg[2];
     zs_attmnt_rep = msg[3];
    
     if (zi_depurar > 0) {
          logf(SIGNIFICANT, "%s Upload session     : %d", zs_metodo, zi_upload_session);
          logf(SIGNIFICANT, "%s attmnt_filename    : '%s'", zs_metodo, zs_attmnt_filename);
          logf(SIGNIFICANT, "%s attmnt_rel_filepath: '%s'", zs_metodo, zs_attmnt_rel_filepath);
          logf(SIGNIFICANT, "%s attmnt_rep         : '%s'", zs_metodo, zs_attmnt_rep);
     }
    
     /////////////////////////////////
     // UPLOANDING FILE to local repository
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Carregando o arquivo '%s'...", zs_metodo, zs_escaped_path);
     send_wait(0, zo_rep, "upload_local_file", zi_upload_session, zs_escaped_path);
     if (msg_error()) {
          for (zi_i=0;zi_i<msg_length();zi_i++) {
               logf(ERROR, "%s msg[%d]: '%s'", zs_metodo, zi_i, (string) msg[zi_i]);
          }
          zs_msg = format("%s ERRO ao executar metodo 'upload_local_file': '%s'", zs_metodo, msg[0]);
          logf(ERROR, "%s", zs_msg);
          return -6;
     }
     // msg[0] contains rel_file_path folder
     int zi_filesize;
     zi_filesize = msg[1];
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Tamanho do arquivo carregado: %d", zs_metodo, zi_filesize);

     /////////////////////////////////
     // CLOSING UPLOAD SESSION
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Fechando sessao de upload...", zs_metodo);
     send_wait(0, zo_rep, "close_upload_session", zi_upload_session);
     if (msg_error()) {
          // for (zi_i=0;zi_i<msg_length();zi_i++) {
               // logf(ERROR, "%s msg[%d]: '%s'", zs_metodo, zi_i, (string) msg[zi_i]);
          // }
          zs_msg = format("%s ERRO ao executar metodo 'close_upload_session': '%s'", zs_metodo, msg[0]);
          logf(ERROR, "%s", zs_msg);
          return -7;
     }

     /////////////////////////////////
     // Alterando atributos do registro
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Alterando atributos do novo registro...", zs_metodo);
     send_wait(0, zo_attmnt, "call_attr", "attmnt_name", "set_val", zs_filename);
     send_wait(0, zo_attmnt, "call_attr", "orig_file_name", "set_val", zs_filename);
     send_wait(0, zo_attmnt, "call_attr", "link_only", "set_val", 0);
     send_wait(0, zo_attmnt, "call_attr", "file_type", "set_val", zs_fileext);
     send_wait(0, zo_attmnt, "call_attr", "file_size", "set_val", zi_filesize);
     send_wait(0, zo_attmnt, "call_attr", "file_name", "set_val", zs_attmnt_filename);
     send_wait(0, zo_attmnt, "call_attr", "repository", "set_val", zs_attmnt_rep);
     send_wait(0, zo_attmnt, "call_attr", "rel_file_path", "set_val", zs_attmnt_rel_filepath);
     send_wait(0, zo_attmnt, "call_attr", "zip_flag", "set_val", zi_zipflag);
     send_wait(0, zo_attmnt, "call_attr", "status", "set_val", "INSTALLED");
     send_wait(0, zo_attmnt, "call_attr", "description", "set_val", "Arquivo carregado automaticamente");
    
     /////////////////////////////////
     // CHECKIN
     /////////////////////////////////
     if (zi_depurar > 0) logf(SIGNIFICANT, "%s Persistindo alteracoes no registro '%s'...", zs_metodo, zo_attmnt.persistent_id);
     send_wait(0, zo_group_leader, "checkin");
     if (msg_error()) {
          zs_msg = format("%s ERRO ao fazer 'checkin' no objeto '%s': '%s'", zs_metodo, zo_attmnt.persistent_id, msg[0]);
          logf(ERROR, "%s", zs_msg);
          return -8;
     }

     z_bloco_fim(zi_depurar, zs_metodo);
     return zo_attmnt.id;
     // Fim do codigo
    ///////////////////////////////////    
}

Apr 21, 2018 03:47 AM

hi,

try to set zipFlag = 0.

regards.

Apr 20, 2018 10:40 AM

cdtj,

 

I am not getting this method to work correctly. In fact, the file is being loaded into the repository, then associated with the ticket, but when the user tries to download it, it is informed that the file can not be read.
I use version 14.1 AA in my environment with a UNC share directed to a fileserver.
Do you have any idea what might be happening?

Feb 10, 2017 05:52 AM

cdtj,

I'm glad I'm not the only one crazy here... I've also done this with the spelsrvr and webengine files. I even have to publish some of the findings ...

Feb 10, 2017 05:13 AM

Ok really interesting approach

Will definitively have a look into it.

Thanks for the sharing.

FYI: we did face also the limitations of maileater in the past and we did tackle it by creating a small java connector to read the mailbox. Where the call to that connector and all the business logic was handle in PAM

 

/J

Feb 10, 2017 05:03 AM

Thanks!

I have developed kind of Mail Eater/Sender service which is directly integrated with SDM platform: SDMMailProcessor Project (pdm_maileater_nxd alternative)

so i think there is no need to call external service when you can call it directly

 

Regards,

cdtj

Feb 10, 2017 04:53 AM

Nice Job cdtj!

Wondering for curiosity what is your use case to not use Web Service to attach those files from you java app?

/J

Feb 10, 2017 04:44 AM

Hi daniel-bighelini

mostly I'm using 2 ways:

- looking for method names and processes in executable ($NX_ROOT/bin/*.exe) and compiled spel files using Notepad++, for example WebEngine's methods from freeacess.spl looks like (entire file: freeaccess.spl > WebEngine methods preview):

 

- decomipe JAR libraries, a lot of them are located in: $NX_ROOT/java/lib and bopcfg subfolders.

 

And then I'm going deep in trail and error way

 

Regards,

cdtj

Feb 02, 2017 02:31 PM

Great method cdtj!

I learn more now. But i have a question...

Do you used pdm_trace to inspect slump conversation and discovery new SPEL methods?

Related Entries and Links

No Related Resource entered.