Martin Wood
ServiceNow Employee
ServiceNow Employee

There is an app on Share that runs a MID server job to post a CSV file to the instance.   Unfortunately, it uses the Apache HttpClient class, which appears to have issues with larger files.   This is noted in the relevant wiki article.   I rewrote it to use URLConnection, which seems more reliable.   This should be a drop-in replacement for the CSMIDServerRemoteFileImport MID Server Script Include.

6 Oct 2014: The script has updated to remove two lines that was used for testing.   Thanks for the spot Shawn!

var CSMIDServerRemoteFileImport = Class.create();

CSMIDServerRemoteFileImport.prototype = {
         initialize: function() {
                   /*
                   // Originally created by Marcus Fly (marcus.fly@cloudsherpas.com) and Valor Poland (valor.poland@cloudsherpas.com)
                   // Refactored by Martin Wood (martin.wood@servicenow.com).
                     */
                   this.debug = probe.getParameter("debug");
                   this.debug = true;
                   this.logMsg("Starting MID Server File Transfer");
                   this.charset = "UTF-8";
                   this.LINE_FEED = "\r\n";
                   
                   
                   this.boundary = "===" + new Date().getTime() + "===";
                   this.probeParameters = this._getProbeParameters();
         },
         
         getRemoteFileAndUploadToInstance: function() {
                   var url = this._getInstanceConnectionURL();
                   var conn = this._getURLConnection(url);
                   var file = this._getFile();
                   var response = this._writeFile(conn, file);
                   if (response != 200)
                             throw "HTTP response " + response;
                   this.logMsg("HTTP response " + response, "debug");
                   
                   ms.log("Completed MID Server File Transfer");
                   return response;
         },
         
         _getProbeParameters: function() {
                   var probeObj = {};
                   probeObj.instance = probe.getParameter("instance");
                   probeObj.instanceUser = ms.getConfigParameter("mid.instance.username");
                   
                   
                   probeObj.instancePassword = ms.getConfigParameter("mid.instance.password");
                   
                   
                   probeObj.filePath = probe.getParameter("filePath");
                   probeObj.targetImportSet = probe.getParameter("targetImportSet");
                   return probeObj;
         },
         
         _getInstanceConnectionURL: function() {
                   return this._joinParams(this.probeParameters.instance + "sys_import.do", [
                   this._encodeParam('sysparm_import_set_tablename', this.probeParameters.targetImportSet),
                   this._encodeParam('sysparm_transform_after_load', 'true')
                   ]);
         },
         
         _encodeParam: function (k, v) {
                   return k + "=" + Packages.java.net.URLEncoder.encode(v);
         },
         
         _joinParams: function (base, arr) {
                   return base + '?' + arr.join('&');
         },
         _getURLConnection: function(url) {
                   if (ms.getConfigParameter("mid.proxy.use_proxy") == 'true') {
                             Packages.java.lang.System.setProperty("https.proxyHost", ms.getConfigParameter("mid.proxy.host"));
                             Packages.java.lang.System.setProperty("http.proxyHost", ms.getConfigParameter("mid.proxy.host"));
                             Packages.java.lang.System.setProperty("https.proxyPort", ms.getConfigParameter("mid.proxy.port"));
                             Packages.java.lang.System.setProperty("http.proxyPort", ms.getConfigParameter("mid.proxy.port"));
                   }
                   var conn = new Packages.java.net.URL(url).openConnection();
                   this.logMsg("Sending to : " + url, "debug");
                   
                   var userpass = new java.lang.String(this.probeParameters.instanceUser + ":" + this.probeParameters.instancePassword);
                   var basicAuth = "Basic " + (new Packages.javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()) + '');
                   conn.setRequestProperty("Authorization", basicAuth);
                   conn.setDoOutput(true);
                   conn.setRequestMethod("POST");
                   conn.setUseCaches(false);
                   
                   conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + this.boundary);
                   conn.setRequestProperty("User-Agent", "MID Server POST");
                   
                   return conn;
                   
         },
         
         _getFile: function() {
                   return new Packages.java.io.File(this.probeParameters.filePath);
         },
         
         _writeFile: function(conn, uploadFile) {
                   
                   var outputStream = conn.getOutputStream();
                   var writer = new Packages.java.io.PrintWriter(new Packages.java.io.OutputStreamWriter(outputStream, this.charset), true);
                   var fieldName = 'file';
                   var fileName = uploadFile.getName();
                   
                   this.logMsg("Sending file : " + fileName, "debug");
                   
                   writer.append("--" + this.boundary).append(this.LINE_FEED);
                   writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(this.LINE_FEED);
                   writer.append("Content-Type: " + Packages.java.net.URLConnection.guessContentTypeFromName(fileName)).append(this.LINE_FEED);
                   writer.append("Content-Transfer-Encoding: binary").append(this.LINE_FEED);
                   writer.append(this.LINE_FEED).flush();
                   
                   this._writeFileData(uploadFile, outputStream);
                   
                   writer.append(this.LINE_FEED).flush();
                   writer.append(this.LINE_FEED).flush();
                   writer.append("--" + this.boundary + "--").append(this.LINE_FEED);
                   writer.close();
                   return conn.getResponseCode();
         },
         
         
         _writeFileData: function(uploadFile, outputStream) {
                   var inputStream = new Packages.java.io.FileInputStream(uploadFile);
                   
                   var data = new Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 4096);
                   var bytesRead = 0;
                   while ((bytesRead = inputStream.read(data)) != -1) {
                             outputStream.write(data, 0, bytesRead);
                             outputStream.flush();
                   }
                   inputStream.close();
         },
         
         
         logMsg: function(message, logType) {
                   logType = logType || 'info';
                   var prefixStr = "*** MID Server Remote File";
                   if (logType == 'info' || logType == 'error') {
                             ms.log(prefixStr + " " + logType.toUpperCase() + "*** " + message);
                   }
                   if (this.debug && logType == 'debug') {
                             ms.log(" DEBUG *** " + message);
                   }
         },
         
         type: 'CSMIDServerRemoteFileImport'
};
Comments
Shawn Dowler
Tera Guru

We had to comment out lines 37 and 40 for this to work, but it worked great after that. Here is the entire file after commenting out those lines. Thanks to JohnG and his colleagues at Cloud Sherpas for figuring that out. I don't know if it's a fix that applies just to me, but if it's not working with those lines, try the following instead:



var CSMIDServerRemoteFileImport = Class.create();



CSMIDServerRemoteFileImport.prototype = {


        initialize: function() {


                  /*


                  // Originally created by Marcus Fly (marcus.fly@cloudsherpas.com) and Valor Poland (valor.poland@cloudsherpas.com)


                  // Refactored by Martin Wood (martin.wood@servicenow.com).


                    */


                  this.debug = probe.getParameter("debug");


                  this.debug = true;


                  this.logMsg("Starting MID Server File Transfer");


                  this.charset = "UTF-8";


                  this.LINE_FEED = "\r\n";




                  this.boundary = "===" + new Date().getTime() + "===";


                  this.probeParameters = this._getProbeParameters();


        },



        getRemoteFileAndUploadToInstance: function() {


                  var url = this._getInstanceConnectionURL();


                  var conn = this._getURLConnection(url);


                  var file = this._getFile();


                  var response = this._writeFile(conn, file);


                  if (response != 200)


                            throw "HTTP response " + response;


                  this.logMsg("HTTP response " + response, "debug");



                  ms.log("Completed MID Server File Transfer");


                  return response;


        },



        _getProbeParameters: function() {


                  var probeObj = {};


                  probeObj.instance = probe.getParameter("instance");


                  probeObj.instanceUser = ms.getConfigParameter("mid.instance.username");


                  //probeObj.instanceUser = 'temp.mid';



                  probeObj.instancePassword = ms.getConfigParameter("mid.instance.password");


                  //probeObj.instancePassword = 'temp.mid';



                  probeObj.filePath = probe.getParameter("filePath");


                  probeObj.targetImportSet = probe.getParameter("targetImportSet");


                  return probeObj;


        },



        _getInstanceConnectionURL: function() {


                  return this._joinParams(this.probeParameters.instance + "sys_import.do", [


                  this._encodeParam('sysparm_import_set_tablename', this.probeParameters.targetImportSet),


                  this._encodeParam('sysparm_transform_after_load', 'true')


                  ]);


        },



        _encodeParam: function (k, v) {


                  return k + "=" + Packages.java.net.URLEncoder.encode(v);


        },



        _joinParams: function (base, arr) {


                  return base + '?' + arr.join('&');


        },


        _getURLConnection: function(url) {


                  if (ms.getConfigParameter("mid.proxy.use_proxy") == 'true') {


                            Packages.java.lang.System.setProperty("https.proxyHost", ms.getConfigParameter("mid.proxy.host"));


                            Packages.java.lang.System.setProperty("http.proxyHost", ms.getConfigParameter("mid.proxy.host"));


                            Packages.java.lang.System.setProperty("https.proxyPort", ms.getConfigParameter("mid.proxy.port"));


                            Packages.java.lang.System.setProperty("http.proxyPort", ms.getConfigParameter("mid.proxy.port"));


                  }


                  var conn = new Packages.java.net.URL(url).openConnection();


                  this.logMsg("Sending to : " + url, "debug");



                  var userpass = new java.lang.String(this.probeParameters.instanceUser + ":" + this.probeParameters.instancePassword);


                  var basicAuth = "Basic " + (new Packages.javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()) + '');


                  conn.setRequestProperty("Authorization", basicAuth);


                  conn.setDoOutput(true);


                  conn.setRequestMethod("POST");


                  conn.setUseCaches(false);



                  conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + this.boundary);


                  conn.setRequestProperty("User-Agent", "MID Server POST");



                  return conn;



        },



        _getFile: function() {


                  return new Packages.java.io.File(this.probeParameters.filePath);


        },



        _writeFile: function(conn, uploadFile) {



                  var outputStream = conn.getOutputStream();


                  var writer = new Packages.java.io.PrintWriter(new Packages.java.io.OutputStreamWriter(outputStream, this.charset), true);


                  var fieldName = 'file';


                  var fileName = uploadFile.getName();



                  this.logMsg("Sending file : " + fileName, "debug");



                  writer.append("--" + this.boundary).append(this.LINE_FEED);


                  writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(this.LINE_FEED);


                  writer.append("Content-Type: " + Packages.java.net.URLConnection.guessContentTypeFromName(fileName)).append(this.LINE_FEED);


                  writer.append("Content-Transfer-Encoding: binary").append(this.LINE_FEED);


                  writer.append(this.LINE_FEED).flush();



                  this._writeFileData(uploadFile, outputStream);



                  writer.append(this.LINE_FEED).flush();


                  writer.append(this.LINE_FEED).flush();


                  writer.append("--" + this.boundary + "--").append(this.LINE_FEED);


                  writer.close();


                  return conn.getResponseCode();


        },




        _writeFileData: function(uploadFile, outputStream) {


                  var inputStream = new Packages.java.io.FileInputStream(uploadFile);



                  var data = new Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 4096);


                  var bytesRead = 0;


                  while ((bytesRead = inputStream.read(data)) != -1) {


                            outputStream.write(data, 0, bytesRead);


                            outputStream.flush();


                  }


                  inputStream.close();


        },




        logMsg: function(message, logType) {


                  logType = logType || 'info';


                  var prefixStr = "*** MID Server Remote File";


                  if (logType == 'info' || logType == 'error') {


                            ms.log(prefixStr + " " + logType.toUpperCase() + "*** " + message);


                  }


                  if (this.debug && logType == 'debug') {


                            ms.log(" DEBUG *** " + message);


                  }


        },



        type: 'CSMIDServerRemoteFileImport'


};


JohnG3
Mega Guru

Thanks also to Martin Wood   for the "port" to the URLConnection method.



Thanks Shawn for your patience with me and the CS team.



Cheers,



JohnG


Shawn Dowler
Tera Guru

Thanks Marcus Fly and valor for the original version of this that served me well until the Eureka upgrade and thanks to Martin Wood for this awesome upgrade to the MID Server Remote File Importer. Finally, thanks to JohnG and his colleagues at Cloud Sherpas for getting Martin's upgrade working in my company's ServiceNow instance.


nancyhz
Mega Contributor

Hi Shawn,



I downloaded "Remote File Importer" from Share SN and also replaced the CSMIDServerRemoteFileImport MID Server Script Include with your file.   I can manually transformed data file through data source, but when I used "Remote File Import, after I clicked "Execute Now" , nothing happened event Last run date/time: updated with current time.       Based on your experience, what would go wrong?   How can I check the error?


Shawn Dowler
Tera Guru

Without more information there are any number of things that could be going wrong. I suggest you ask the question in the support section and provide more details to get more visibility and a faster, better answer.



Is your MID Server set up and selected? Is the path to the file on the MID Server correct. Does the user that the MID Server runs as have access to the path you indicated? If the answers to all of these are yes, turn on debugging on the MID Server and watch the log file on the MID Server to see what errors if any it might be producing.


nancyhz
Mega Contributor
I did ensure MID Server correctly selected and correct path (c:\load\mobile.csv).   I have admin access in ServiceNow instance, but I still got the following errors in ECC log:   Any suggestion?
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<results error="Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 115 112:
113:
114: _writeFileData: function(uploadFile, outputStream) {
==> 115: var inputStream = new Packages.java.io.FileInputStream(uploadFile);
116:
117: var data = new Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 4096);
118: var bytesRead = 0;
java.io.FileInputStream.open(Native Method) java.io.FileInputStream.<init>(Unknown Source) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) java.lang.reflect.Constructor.newInstance(Unknown Source) org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:235) org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:190) org.mozilla.javascript.ScriptRuntime.newObject(ScriptRuntime.java:1270) org.mozilla.javascript.gen.c116.call(script_include:CSMIDServerRemoteFileImport:115) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c115.call(script_include:CSMIDServerRemoteFileImport:104) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c108.call(script_include:CSMIDServerRemoteFileImport:24) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c11.call(probe:CSRemoteFileImport:2) org.mozilla.javascript.gen.c11.exec(probe:CSRemoteFileImport) com.service_now.mid.script.MIDScript.executeCompiledScript(MIDScript.java:190) com.service_now.mid.script.MIDScript.evaluate(MIDScript.java:106) com.service_now.mid.probe.JavascriptProbe.probe(JavascriptProbe.java:46) com.service_now.mid.probe.AProbe.process(AProbe.java:63) com.service_now.mid.queue_worker.AWorker.runWorker(AWorker.java:95) com.service_now.mid.queue_worker.AManagedThread.run(AManagedThread.java:36)
"
probe_time="719">
<result error="Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 115 112:
113:
114: _writeFileData: function(uploadFile, outputStream) {
==> 115: var inputStream = new Packages.java.io.FileInputStream(uploadFile);
116:
117: var data = new Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 4096);
118: var bytesRead = 0;
java.io.FileInputStream.open(Native Method) java.io.FileInputStream.<init>(Unknown Source) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) java.lang.reflect.Constructor.newInstance(Unknown Source) org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:235) org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:190) org.mozilla.javascript.ScriptRuntime.newObject(ScriptRuntime.java:1270) org.mozilla.javascript.gen.c116.call(script_include:CSMIDServerRemoteFileImport:115) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c115.call(script_include:CSMIDServerRemoteFileImport:104) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c108.call(script_include:CSMIDServerRemoteFileImport:24) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c11.call(probe:CSRemoteFileImport:2) org.mozilla.javascript.gen.c11.exec(probe:CSRemoteFileImport) com.service_now.mid.script.MIDScript.executeCompiledScript(MIDScript.java:190) com.service_now.mid.script.MIDScript.evaluate(MIDScript.java:106) com.service_now.mid.probe.JavascriptProbe.probe(JavascriptProbe.java:46) com.service_now.mid.probe.AProbe.process(AProbe.java:63) com.service_now.mid.queue_worker.AWorker.runWorker(AWorker.java:95) com.service_now.mid.queue_worker.AManagedThread.run(AManagedThread.java:36)
"
>
<output>
Evaluation error: Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 115 112:
113:
114: _writeFileData: function(uploadFile, outputStream) {
==> 115: var inputStream = new Packages.java.io.FileInputStream(uploadFile);
116:
117: var data = new Packages.java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 4096);
118: var bytesRead = 0;
java.io.FileInputStream.open(Native Method) java.io.FileInputStream.<init>(Unknown Source) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) java.lang.reflect.Constructor.newInstance(Unknown Source) org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:235) org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:190) org.mozilla.javascript.ScriptRuntime.newObject(ScriptRuntime.java:1270) org.mozilla.javascript.gen.c116.call(script_include:CSMIDServerRemoteFileImport:115) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c115.call(script_include:CSMIDServerRemoteFileImport:104) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c108.call(script_include:CSMIDServerRemoteFileImport:24) org.mozilla.javascript.ScriptRuntime.call(ScriptRuntime.java:1196) org.mozilla.javascript.gen.c11.call(probe:CSRemoteFileImport:2) org.mozilla.javascript.gen.c11.exec(probe:CSRemoteFileImport) com.service_now.mid.script.MIDScript.executeCompiledScript(MIDScript.java:190) com.service_now.mid.script.MIDScript.evaluate(MIDScript.java:106) com.service_now.mid.probe.JavascriptProbe.probe(JavascriptProbe.java:46) com.service_now.mid.probe.AProbe.process(AProbe.java:63) com.service_now.mid.queue_worker.AWorker.runWorker(AWorker.java:95) com.service_now.mid.queue_worker.AManagedThread.run(AManagedThread.java:36)
</output>
</result>
<parameters>
<parameter name="topic" value="JavascriptProbe"/>
<parameter name="queue" value="output"/>
<parameter name="error" value=""/>
<parameter name="from_sys_id" value=""/>
<parameter name="filePath" value="c:\load\mobile.csv"/>
<parameter name="sys_id" value="3eaf3d7e6fabe100d444247cbb3ee4da"/>
<parameter name="state" value="ready"/>
<parameter name="sys_created_on" value="2014-10-07 23:07:47"/>
<parameter name="from_host" value=""/>
<parameter name="script" value="var remoteFileImport = new CSMIDServerRemoteFileImport(); remoteFileImport.getRemoteFileAndUploadToInstance()"/>
<parameter name="agent" value="mid.server.ALTRIADEV_2"/>
<parameter name="processed" value=""/>
<parameter name="ecc_queue" value="3eaf3d7e6fabe100d444247cbb3ee4da"/>
<parameter name="response_to" value=""/>
<parameter name="source" value=""/>
<parameter name="sequence" value="148ecde56520000001"/>
<parameter name="name" value="CSRemoteFileImport"/>
<parameter name="table_name" value="ecc_queue"/>
<parameter name="agent_correlator" value=""/>
<parameter name="targetImportSet" value="u_commu_mobile"/>
<parameter name="instance" value="https://altriadev.service-now.com/"/>
</parameters>
</results>
lawrence_eng
Administrator
Administrator

Moderator note: I moved this document out of Support and into CreateNow



thanks,


Lawrence


enojardi
ServiceNow Employee
ServiceNow Employee

Awesome stuff, Martin!


gbernie
Kilo Expert

Seriously great work Martin.


Exactly what we needed to get our imports back online.


enojardi
ServiceNow Employee
ServiceNow Employee

Is it a true CSV file you're trying to import?


nancyhz
Mega Contributor

Yes, it is CSV file. it did work if I create load folder under Mid Server folder (\load), but not for my local folder (c:\load\Mobile.csv)


mayankv
Kilo Contributor

Hey nancyhz



Were you able to fix this?



I am also getting the same error, my MID Server is up and running and the user I am using have admin credentials and MID Server role, not sure what I am missing - any ideas?



Thanks!


Probe: JavascriptProbe:CSRemoteFileImport WARNING *** WARNING *** java.io.IOException: Authentication failure


    Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 91



        88:          


        89:           _writeFile: function(conn, uploadFile) {


        90:                    


==>   91:                     var outputStream = conn.getOutputStream();


        92:                     var writer = new Packages.java.io.PrintWriter(new Packages.java.io.OutputStreamWriter(outputStream, this.charset), true);


        93:                     var fieldName = 'file';


        94:                     var fileName = uploadFile.getName();


Valor1
Giga Guru

Mayank Verma If you're getting "authentication error," it's rarely anything else.


Nickels
Tera Expert

So I seem to be missing something when importing this into my test instance.   I have downloaded the


Remote File Importer (Import Files from a MID Server) from the Share site, ServiceNow Share.   I then elevated my security privileges and when into Retrieved Update sets.   I clicked the link at the bottom for Import Update set from xml and uploaded the file. At this point, i am returned to retrieved update sets and I do not see this as an update set or do I see that it went ahead and installed it. My test instance is on Eureka.



Any suggestions would be greatly appreciated.


Thanks


-Chris


Valor1
Giga Guru

Chris Nick what SN version are you on?


brianscott
Kilo Explorer

I just got closure on this issue from ServiceNow support.   There is an open PRB on it, and the work around
is turning on Preemptive Authentication on your HTTP connection.



To do this update the CSMidServerRemoteFileImport MID Server Script Include to add this line



_getHttpClient : function() {


          var probeParms = this.probeParameters;      


          this.logMsg("_getHttpClient - instance: " + probeParms.instance + "\ninstanceUser: " + probeParms.instanceUser +


                                  "\ninstancePassword.length: " + probeParms.instancePassword, "debug");


         


          var jHttpClient     = new Packages.org.apache.commons.httpclient.HttpClient();


          var jInstanceCredentials = new Packages.org.apache.commons.httpclient.UsernamePasswordCredentials(probeParms.instanceUser, probeParms.instancePassword);


          jHttpClient.getState().setCredentials(new Packages.org.apache.commons.httpclient.auth.AuthScope(null, 443, null), jInstanceCredentials);


         


          if (ms.getConfigParameter("mid.proxy.use_proxy") == 'true') {


                this.logMsg("MID Server requires proxy. Setting HTTP Client proxy details", 'debug');


                jHttpClient = this._setProxyInfo(jHttpClient);


          }


      jHttpClient.getParams().setAuthenticationPreemptive(true);


          return jHttpClient;


    },  



After this you RemoteFileImport should handle files of any size.



Hope this helps!


johnnyjava
Kilo Guru

I hope it is not too shameful to comment here with a patch I wrote to optionally rename the file when it is uploaded.



Optionally Rename CSV on Remote File Import



My update set includes the patch listed in the original post by Martin Wood on this page.



EDIT: The document has now be re-posted.


Valor1
Giga Guru

I hope it's not too shameful to ask.. mind if we roll your change into the item on Share? 😉      


johnnyjava
Kilo Guru

That would be great. I'm not sure what happened, the link I posted above appears to no longer be valid.



Valor I will email you the update set directly.



EDIT: Community tells me that the document had been lost due to an issue. They pulled the record from a backup and encouraged me to re-post it. The new location is here - Optionally Rename CSV on Remote File Import


sgrison
Tera Guru

Hey Valor,


Will the transform map automatically run after the file is imported?


nk_dubey1
Kilo Contributor

Hi Valor,



I am getting similar error:



JavascriptProbe:CSRemoteFileImport Slow execution (203ms) of script: script_include:Class


09/22/15 10:01:18 (761) Probe: JavascriptProbe:CSRemoteFileImport Slow execution (359ms) of script: script_include:CSMIDServerRemoteFileImport


09/22/15 10:01:18 (761) Probe: JavascriptProbe:CSRemoteFileImport *** Script: *** MID Server Remote File INFO*** Starting MID Server File Transfer


09/22/15 10:01:39 (792) Probe: JavascriptProbe:CSRemoteFileImport WARNING *** WARNING *** java.net.ConnectException: Connection timed out: connect Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 87 84:



I am getting connection timeout error. I checked everything looks good from MID Server side. In what conditions we normally gets this error (I know it can be firewall issue, but I don't think this is issue here).



What all options you want me to try/check in order to resolve this issue.


burrowsr
Giga Contributor

Hi,



I also am getting a similar error to an earlier post:



JavascriptProbe:CSRemoteFileImport Slow execution (203ms) of script: script_include:Class


09/22/15 10:01:18 (761) Probe: JavascriptProbe:CSRemoteFileImport Slow execution (359ms) of script: script_include:CSMIDServerRemoteFileImport


09/22/15 10:01:18 (761) Probe: JavascriptProbe:CSRemoteFileImport *** Script: *** MID Server Remote File INFO*** Starting MID Server File Transfer


09/22/15 10:01:39 (792) Probe: JavascriptProbe:CSRemoteFileImport WARNING *** WARNING ***java.net.ConnectException: Connection timed out: connect Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 87 84:



I am getting connection timeout error.



Would appreciate any advise as to how to go about resolving this issue.



Cheers, Robin


praneeth24
Kilo Contributor

Will this update set work on helsinki patch 4 version?


telmo
Tera Expert

Hi,



I know this is an old thread.


I have Geneva patch 8 and this is not working for me.




I'm having:


10/25/16 12:18:08 (148) Worker-Standard:JavascriptProbe WARNING *** WARNING *** java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 authenticationrequired"


    Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 103



      100:     &#13;


      101:           _writeFile: function(conn, uploadFile) {   &#13;


      102:     &#13;


==&gt; 103:                     var outputStream = conn.getOutputStream();   &#13;


      104:                     var writer = new Packages.java.io.PrintWriter(new Packages.java.io.OutputStreamWriter(outputStream, this.charset), true);   &




I'm behind a Proxy server with authentication, and I have those configuration parameters set on the Mid server definition.


Looking at the code though I don't see anywhere to use the configuration parameters "mid.proxy.username" and "mid.proxy.password".



I've tried to change the code to use them but without any luck.




Does anyone has any idea how to overcome this?




Regards,


Telmo


Martin Wood
ServiceNow Employee
ServiceNow Employee

It's gonna be tricky. This thread from StackOverflow shows that you need to create a new Authenticator.



There are other options: this Update Set achieves pretty much the same thing, but in a different way. It's also written by the way cool enojardi!


telmo
Tera Expert

Hi Martin,



Thanks for the tip.


I already had looked at that update set in Share, but I think they should update the description, I didn't realize it was able to import files...



It's working with that one!




Telmo


enojardi
ServiceNow Employee
ServiceNow Employee

Thanks for that Telmo! Don't forget to leave your feedback in Share - the more it's used the more I can use it to persuade Product Management to include a similar feature OOB for future releases!


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Hi,



can anyone help please ?



I am trying to use this remote file importer and have updated my (istanbul) instance. I cannot find any example for the file path here, (file is located in a path (midserver ) for eg. /glide/files/abcd.csv


Also , the question i have is that there is no datasource on this remote file importer,   how would it locate the transform map ?



also , please provide me with an example/screen shot.



thanks


Karthik


johnnyjava
Kilo Guru

Karthik is that Unix or Windows (UNC) file path?



You must create a Data Source with Transform Maps and then link the Remote File Import to that Import Set Table.


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Hi Johnny



Thanks for the reply and the file path is unix



Regards


Karthik


johnnyjava
Kilo Guru

When the CS Remote File Importer posts the content of the file to the sys_import.do import processor for your instance, it sends 2 URL Parameters which are:



sysparm_import_set_tablename=your_import_set_table_name


sysparm_transform_after_load=true



Transform Maps have a Source Table field which is used to locate them for this process.


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Oh, thats brilliant! Thanks for the response once again. Is there any specific way of presenting the file path for unix ?



regards


Karthik


johnnyjava
Kilo Guru

Nah but for Windows UNC, you need to make it 4 leading slashes.


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Sure, thanks a lot



Regards


Karthik


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Hi all,



Need some help please !



i am not a java person and do not know how to import a csv file which is a semi colon delimited rather than comma delimited. I think the current solution works for comma delimited files. Can anyone please let me know the code which works for both semi colon or tab delimited file for this import to work without changing its functionality ?



Reason :



My Transform map doesn't work for this solution as i was initially using data source (where i can specify the delimiter)   to import the data using the same files. I understand this remote file import works with import table but not with the data source. I wanted to have a   working model for different delimited which works along with my transform map.



Please help!



Many thanks


Karthik


Martin Wood
ServiceNow Employee
ServiceNow Employee

You should just be able to change delimeter in the data source associated with the target table.   In otherwords, it should "just work".



Or, as I said in a previous comment, this app is an excellent alternative.


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Hi Martin,



Thanks a lot.



I am using this solution which does not have data source. As per your example you had given the details with actual java and that won't work for me.


I would like to have this WriteFile and WriteFileData to support delimiters such as semi colon or tab. I do not know how to modify this accordingly because i do not know Java. Please help


Thanks


Karthik


Martin Wood
ServiceNow Employee
ServiceNow Employee

You should have a data source, and a transform map. Make your import work by manually uploading the data, and once you are happy (with the proper delimeters in the data source, etc) automate it using this script.   When you set it up, use the same import set table in this app as the one that works manually.



You do not need to know Java or alter the code at all. All this code does is read in the file, and sends it unaltered to the instance.   This script does not care about delimeters: the instance which processes the data is what you need to work with. So do not attempt to alter the _writeData functions (or anything in this script) and concentrate on what the instance does.


karthikgopalan
ServiceNow Employee
ServiceNow Employee

Yes , i understand , i have got the data source , transform map and my import set table all are working manually and there is no problem at all. The issue starts only when i start using 'RemoteFileImporter' where it does not parse the records correctly because the data is delimited to 'semi-colon'. The RemoteFileImporter only uses the import set table and doesn't use Datasource. All i wanted to do is to parse the data correctly and load it to my staging table and the transform map does it work. my question is what do i need to do   for the 'RemoteFileImporter' to parse the data correctly (i.e As i mentioned earlier the CSV file is semi-colon delimited and when it loads the data to the staging table it stores the data in one field rather than 3 separate fields and thats where i need to do something). The solution you gave me earlier on 'JDBC file loader (via mid server) works fine because it uses data source. Is there anything like that here to for it use the data source so that i do not need to modify the script as you have specified.  


Thanks


denis hoffmann
Giga Guru

Hi,


When you upload a new file directly to import set table, it create a data source with default settings.



Could you check in your Data Sources table ( sys_data_source) sorted by "Created", if it isn't a new data source called "yourfile.csv (uploaded)" ?



If so, then open this new data source and set the semicolon (;) in "CSV delimiter" field.




Regards,


Denis.


JC Icaro1
Kilo Guru

Hi,
Is anyone able to get this to work if the MID Server is using a proxy that requires authentication (proxy username   and password)?


Thank you,


JC


Bruno De Graeve
ServiceNow Employee
ServiceNow Employee

When we downloaded the latest version from Share, we get these errors in the agent0.log of the MID server:



02/08/18 15:45:07 (488) Worker-Standard:JavascriptProbe WARNING *** WARNING *** org.mozilla.javascript.EcmaError: "java" is not defined.


    Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 67




        64:             var conn = new Packages.java.net.URL(url).openConnection();


        65:             this.logMsg("Sending to : " + url, "debug");


        66:            


==>   67:             var userpass = new java.lang.String(this.probeParameters.instanceUser + ":" + this.probeParameters.instancePassword);


        68:             var basicAuth = "Basic " + (new Packages.javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()) + '');


        69:             conn.setRequestProperty("Authorization", basicAuth);


        70:             conn.setDoOutput(true);




02/08/18 15:45:07 (488) Worker-Standard:JavascriptProbe WARNING *** WARNING *** org.mozilla.javascript.EcmaError: "java" is not defined.


    Caused by error in MID Server script include 'CSMIDServerRemoteFileImport' at line 21




        18:      


        19:       getRemoteFileAndUploadToInstance: function() {


        20:             var url = this._getInstanceConnectionURL();


==>   21:             var conn = this._getURLConnection(url);


        22:             var file = this._getFile();


        23:             var response = this._writeFile(conn, file);


        24:             if (response != 200)




02/08/18 15:45:07 (488) Worker-Standard:JavascriptProbe WARNING *** WARNING *** org.mozilla.javascript.EcmaError: "java" is not defined.


    Caused by error in JavaScript probe 'CSRemoteFileImport' at line 2




          1: var remoteFileImport = new CSMIDServerRemoteFileImport();


==>     2: remoteFileImport.getRemoteFileAndUploadToInstance()




Any ideas how this " "java" is not defined." should be solved ?



When I go to the Windows commandline and type "java -version", I get output that a JRE is installed.



thanks, Bruno


Bruno De Graeve
ServiceNow Employee
ServiceNow Employee

As I'm on Kingston, I had to update the Script Include:



here is the hint for correction, which can be found in the discussion at Share:


=================================


To make it work on Helsinki and Istanbul, edit the CSMIDServerRemoteFileImport MID Server Script Include and fix lines 67 and 113 by replacing:

java.lang.String with Packages.java.lang.String

and

java.lang.Byte.TYPE with Packages.java.lang.Byte.TYPE

Restarting the MID Server is required


=================================


ofaura
ServiceNow Employee
ServiceNow Employee

Hello,

We have started using this app, and we are facing one issue, in DEV everything works fine but on TST instance,we got following error:

<result error="Caused by error in JavaScript probe 'CSRemoteFileImport' at line 2&#10;&#10;      1: var remoteFileImport = new CSMIDServerRemoteFileImport(); &#10;==&gt;   2: remoteFileImport.getRemoteFileAndUploadToInstance()&#10;"><output>Evaluation error: Caused by error in JavaScript probe 'CSRemoteFileImport' at line 2

We are in Jakarta p6. Any idea, suggestion?

Thanks in advance,

 

Akash Rajput
Tera Contributor

This should be new Packages.java.

nateross1
Kilo Contributor

On Kingston found a working solution here so thanks to arthurm.gallagher:

 

 

https://community.servicenow.com/community?id=community_question&sys_id=2cdb07e1db9cdbc01dcaf3231f9619eb

 

basically it says to

change

userpass = java.lang.String

to

userpass = new Packages.java.lang.String

 

Also change

java.lang.Byte

to

Packages.java.lang.Byte.TYPE

John Vo1
Tera Guru

Does this work with Jarkata?

John Vo1
Tera Guru

Johnny,

 

Will it work on Jarkata?

 

Thanks,

John

iaind
Kilo Contributor

Quick question, has anyone used this in London release?  I'm currently testing it but can't get the file uploaded.

Chandan1
Tera Contributor

Hi,

This code works great for csv file having delimiter as comma (,);

How to enhance this code to process tilda (~) or other delimited csv files.

Thank you in advance for your help.

Version history
Last update:
‎09-30-2014 07:56 AM
Updated by: