Cold Fusion Close File cfscript - cfml

This should be simple, but how do I close and release the file opened with this
<cfscript>
FileName="C:\category1.txt";
FileIOClass=createObject("java","java.io.FileReader");
FileIO=FileIOClass.init(FileName);
LineIOClass=createObject("java","java.io.BufferedReader" );
LineIO=LineIOClass.init(FileIO);
</cfscript>
<cffile action = "delete" file = "C:\category1.txt">
ColdFusion could not delete the file C:\category1.txt for an unknown reason

Related

Python3/Redis: redis.exceptions.ResponseError: unknown command 'JSON.SET'

I'm trying to run the sample program from this RedisLabs page.
I chose Option A - which was to set up the free Redis cloud server.
(Seems like if you install manually, then you have to add the JSON as a plugin.)
I'm able to connect and use other "set" commands, but getting error on JSON:
File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\client.py", line 901, in execute_command
return self.parse_response(conn, command_name, **options)
File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\client.py", line 915, in parse_response
response = connection.read_response()
File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\connection.py", line 756, in read_response
raise response
redis.exceptions.ResponseError: unknown command 'JSON.SET'
My Python test program (except put in the sample endpoint before posting):
import redis
import json
import pprint
host_info = "redis.us-east-1-1.ec2.cloud.redislabs.com"
redisObj = redis.Redis(host=host_info, port=18274, password='xxx')
print ("Normal call to Redis")
redisObj.set('foo', 'bar')
value = redisObj.get('foo')
print(value)
capitals = {
"Lebanon": "Beirut",
"Norway": "Oslo",
"France": "Paris"
}
print ("capitals - before call to Redis")
pprint.pprint(capitals)
print("JSON call to Redis")
redisObj.execute_command('JSON.SET', 'doc', '.', json.dumps(capitals))
print("Data Saved, now fetch data back from redis")
reply = json.loads(redisObj.execute_command('JSON.GET', 'doc'))
print("reply from Redis get")
pprint.pprint(reply)
This is the screen shot from their website where I created the database. I didn't see any option to enable JSON or add any modules.
Not sure this was available when I created the REDIS database, but it is now. When you create it on redislabs.com, you can turn on the modules, and pick one from the list.
Then use this library: "rejson" from https://pypi.org/project/rejson/ to get the method "jsonset" method, using such code such as this:
rj = Client(host=config_dict['REDIS_CONFIG_HOST'], port=config_dict['REDIS_CONFIG_PORT'], password=config_dict['REDIS_CONFIG_PASSWORD'], decode_responses=True)
out_doc = {}
out_doc['firstname'] = "John"
out_doc['lastname'] = "Doe"
rj.jsonset('config', Path.rootPath(), out_doc)
get_doc = rj.jsonget('config', Path.rootPath())
pprint.pprint(get_doc)
I'm not used the cloud redis, in my local the Python don't load the JSON.SET
I just so make done, in this sample https://onelinerhub.com/python-redis/save-json-to-redis

How do you modify this script to run TinyPNG on opened files instead of having to use the open dialog to select a file?

I'm trying to modify this script to compress and then close all the opened files with the TinyPNG Photoshop plugin as opposed to having to choose one file at a time in an open dialog box. They do offer another script that allows you to compress a whole folder. However, I find myself needing to compress 10 out 50 images in a folder so I'd rather just be able to select those 10 or to open those 10 and run the script on all open files.
I've tried replacing
compressFile(File.openDialog("Choose a PNG or JPEG file to compress")
with
compressFile(app.activeDocument)
in an attempt to have the script just compress the current document.
Instead of using the active document it simply skips to the catch(error).
try {
// Compress Active File
compressFile(File.openDialog("Choose a PNG or JPEG file to compress"));
} catch(error) {
alert("No JPEG or PNG file selected or compression error.");
}
compressFile() requires a File object while activeDocument is a document object.
For opened documents you'll want a loop through the documents:
for (var i = documents.length - 1; i >= 0; i--) {
activeDocument = documents[i];
compressFile()
}
and in compressFile() you should get rid opener part (because all the documents are already opened) but you'll need to replace a file with actual document path:
// Compress the document
var tinify = new ActionDescriptor();
tinify.putPath(charIDToTypeID("In "), new File(activeDocument.path + "/" + activeDocument.name)); /* Overwrite original! */
tinify.putUnitDouble(charIDToTypeID("Scl "), charIDToTypeID("#Prc"), percentage);
For a files dialogue you can simply modify the last bit of Compress File.jsx:
//dialogue to select multiple files:
var startFolder = Folder.myDocuments,
myFiles = startFolder.openDlg(void(0), void(0), true);
if (myFiles != null) //if the dialogue wasn't cancelled
{
//launch compressFile for every selected file
for (var i = myFiles.length - 1; i >= 0; i--)
{
compressFile(myFiles[i])
}
}

Failing to write the query results to a csv file ColdFusion

I put my project on a new server where I am using ColdFusion 2016 but it is failing while running the following lines:
<cfset fastFileWriter = createObject("java", "FastResultsetToFile")>
<cfset fastFileWriter.exportResultsetToFile(myQuery, "#TempFile#", ',', "UTF-8")>
In ColdFusion 9, where my old server is, it is working just fine. Does anyone knows why this is happening and how to make this work for ColdFusion 2016?
Here is a bigger picture of the code:
<cfset yopath = "#application.masterpath#/platform_a/reports/pods/#pid#" />
<cfset acfile = "outbound_export_#session.callmeasurement_uid#.csv" />
<cfset TempFile = "#yopath#/#acfile#">
<cfif FileExists(TempFile)>
<cffile action="delete" file="#TempFile#" >
</cfif>
<cfset myQuery = QueryNew("Team_Member, Calls, Unique, Live_Connections, Rescued_Calls")>
<cfloop query = "pull_staff">
<cfset newrow = QueryAddRow(myQuery,1)>
<cfset temp = QuerySetCell(myQuery, 'Team_Member', #lename#)>
<cfset temp = QuerySetCell(myQuery, 'Calls', #all_calls#)>
<cfset temp = QuerySetCell(myQuery, 'Unique', #unique_calls#)>
<cfset temp = QuerySetCell(myQuery, 'Live_Connections', #live_convo#)>
<cfset temp = QuerySetCell(myQuery, 'Rescued_Calls', #rescued#)>
</cfloop>
<!--- The code is running just fine up to this point. I used a cfdump to check the query "pull_staff" and it is returning the right results with correct column names --->
<cfset fastFileWriter = createObject("java", "FastResultsetToFile")>
<cfset fastFileWriter.exportResultsetToFile(myQuery, "#TempFile#", ',', "UTF-8")>
I expect it has something to do with a missing Java dependency on the new server
<cfset fastFileWriter = createObject("java", "FastResultsetToFile")>
For this to work it requires that the FastResultsetToFile class (or related JAR) is in one of the directories that ColdFusion uses for its classpath, otherwise it will never run.

Coldfusion 11 - Global variables - Application.cfc or Application.cfm

I'm working on an application done in Coldfusion 9. I have to migrate it in CF11 and I would like to improve the code. The current application in CF9 is done like this:
Application.cfm:
<cfapplication name="MyApp"
clientManagement="yes"
clientStorage="registry"
setClientCookies="yes"
sessionManagement="yes"
sessionTimeout="#CreateTimeSpan(0,1,0,0)#"
applicationTimeout="#CreateTimeSpan(0,0,2,0)#"
/>
<cfset application.datasource = "MyApp"/>
<cfset application.name = "MyApp"/>
<cfset application.access = "App"/>
<cfset application.version = "1.1"/>
<cfset application.title = "My Application"/>
<cfset application.inc_path = "includes"/>
<cfset application.com_path = "components"/>
<cfset application.scripts_path = "scripts"/>
<cfset application.styles_path = "styles"/>
<cfset application.email = "firstname.lastnane#myapplication.com" />
<cfset application.YEAR = 2016/>
<cfif Not IsDefined("session.language_cd")>
<cfset session.language_cd = "ENG">
</cfif>
<cfset session.email_support_team = "support#myapplication.com" />
<cfinclude template="ui_lib.cfm">
Inside the file "ui_lib.cfm", there are a lot of variables defined and used in all other .cfm files:
<cfswitch expression="#session.ui_lng_cd#">
<cfcase value="FRA">
<cfset ui_lib_abbrev = "Abbréviation" />
<cfset ui_lib_acces = "Accès" />
<cfset ui_lib_active_sans_accent = "Actif" />
</cfcase>
<cfcase value="ENG">
<cfset ui_lib_abbrev = "Abbreviation" />
<cfset ui_lib_acces = "Access" />
<cfset ui_lib_active_sans_accent = "Active" />
</cfcase>
</cfswitch>
For example in menu.cfm:
<div id="menu">
<h5><cfoutput>#session.user#</cfoutput></h5>
<ul>
<li><cfoutput>#ui_lib_abbrev#</cfoutput></li>
<li><cfoutput>#ui_lib_acces#</cfoutput></li>
<li><cfoutput>#ui_lib_active_sans_accent#</cfoutput></li>
</ul>
</div>
I have tried to create an Application.cfc to replace application.cfm:
<cfcomponent displayname="MyApp">
<cfset This.name = "MyApp">
<cfset This.sessionManagement="yes">
<cfset This.clientManagement="no">
<cfset This.loginStorage="session">
<cfset This.sessionTimeout = CreateTimeSpan(0,0,0,1)>
<cfset This.applicationTimeout = CreateTimeSpan(0,0,2,0) >
<cfset This.setClientCookies="no">
<cfset This.domainCookies="yes">
<cfset This.scriptProtect = "All">
<cffunction name="onApplicationStart">
<cfscript>
Application.homePage = "/index.cfm";
Application.datasource = "MyApp";
Application.name = "MyApp";
Application.access = "App";
Application.version = "1.1";
Application.title = "My Application";
Application.inc_path = "includes";
Application.com_path = "components";
Application.scripts_path = "scripts";
Application.styles_path = "styles";
Application.email = "firstname.lastnane#myapplication.com"
Application.YEAR = 2016;
</cfscript>
<cfinclude template="ui_lib.cfm">
</cffunction>
<cffunction name="onSessionStart">
<cfif Not IsDefined("session.language_cd")>
<cfset session.language_cd = "ENG">
</cfif>
<cfif Not IsDefined("session.g_exercice")>
<cfset todayDate = Now()>
<cfset SESSION.g_exercice = #DateFormat(todayDate, "yyyy")#>
</cfif>
<cfif Not IsDefined("session.sec_first_pass")>
<cfset SESSION.sec_first_pass = 0>
</cfif>
<cfset session.email_support_team = "support#myapplication.com" />
</cffunction>
</cfcomponent>
I have created application.cfc and removed application.cfm and tried to run the application. It's ok, but I have Coldfusion errors with the variables defined in ui_lib.cfm. The server says that the variables are not defined. Could you please tell me why and how to solve the problem?
I would like to know if it's better to use a file Application.cfc with the same definitions or keep the current file Application.cfm ?
Thanks in advance for your help.
I've done some cfm to cfc conversions and the answer depends upon the usage. As has been mentioned, session based logic in the application scope won't work.
If there's a way to change the user's language which updates the session.ui_lng_cd value and therefore the language displayed to the user then the easiest answer is to set language variables in the OnRequestStart event. You'll have to change the scope of the variables to the request scope when set and used but hopefully that'll be easy enough with a global search and replace.
Additional notes:
It would also be possible to store those language variables in the session, by placing the code in the OnSessionStart event but generally it's a good idea to keep session storage minimal as if you start storing a lot in session on a busy site it can use up a lot of memory.
Another way to do this that would take more work but I think is more efficient if you have a lot of these would be to create a two level array in the application that stores the language strings and use the session language as the first level of key. This way very little memory is used on each request to old variables.
So in your application.cfc OnApplicationStart you'd have:
application.languageStrings = {};
application.languageStrings["ENG"] = {};
application.languageStrings["ENG"]["ui_lib_abbrev"] = "Abbreviation";
application.languageStrings["ENG"]["ui_lib_acces"] = "Access";
application.languageStrings["ENG"]["ui_lib_active_sans_accent"] = "Active";
application.languageStrings["FRA"] = {};
application.languageStrings["FRA"]["ui_lib_abbrev"] = "Abbréviatio";
application.languageStrings["FRA"]["ui_lib_acces"] = "Accès";
application.languageStrings["FRA"]["ui_lib_active_sans_accent"] = "Actif";
And to output the right string you'd use:
#application.languageStrings[session.language_cd]["ui_lib_active_sans_accent"]#
The variables defined in your UDF are places in the variables scope, but by placing the UDF inside onApplicationStart(), the include happens only the one time instead of every request. I think you've figured that out and have them defined again in the variables scope.
I feel the more appropriate solution would be to place them into the application scope so they're just defined the one time instead of them being redefined on every request.
application.ui = {
"ENG" = {
"abbrev" = "Abbreviation"
, "acces" = "Access"
, "active_sans_accent" = "Active"
}
, "FRA" = {
"abbrev" = "Abbréviation"
, "acces" = "Accès"
, "active_sans_accent" = "Actif"
}
};
Then just update any existing reference like so: #application.ui[session.ui_lng_cd].abbrev#.
If your need to manage translated context grows in the future, take a look at Resource Bundles.

How to pass uploaded file into amazon s3?

I have this in my code:
size=128,128
#app.route('/',methods=['GET','POST'])
def upload():
print request.method
if request.method == 'POST':
file = request.files['image']
im = Image.open(file)
im.resize(size)
im.save("test.png","PNG")
f=open("test.png",'r')
conn = tinys3.Connection('AKIAI2GPQ','fAQxDLbvZcqhXvjd',tls=True)
conn.upload(im,f,"snappie.watermarks")
print "got file"
return redirect("https://www.google.com")
return render_template('index.html')
hopefully you can see that I am trying to handle the file upload from request.files, resize it, and then upload that to amazon s3. However right now its getting hung up on the conn.upload(im,f,"snappie.watermarks") line.
This is the error:
File "/home/alex/snappie/web/server.py", line 25, in upload
conn.upload(im,f,"snappie.watermarks")
File "/usr/local/lib/python2.7/dist-packages/tinys3/connection.py", line 152, in upload
return self.run(r)
File "/usr/local/lib/python2.7/dist-packages/tinys3/connection.py", line 233, in run
return self._handle_request(request)
File "/usr/local/lib/python2.7/dist-packages/tinys3/connection.py", line 255, in _handle_request
return request.run()
File "/usr/local/lib/python2.7/dist-packages/tinys3/request_factory.py", line 147, in run
headers['Content-Type'] = self.content_type or mimetypes.guess_type(self.key)[0] or 'application/octet-stream'
File "/usr/lib/python2.7/mimetypes.py", line 298, in guess_type
return _db.guess_type(url, strict)
File "/usr/lib/python2.7/mimetypes.py", line 114, in guess_type
scheme, url = urllib.splittype(url)
File "/usr/lib/python2.7/urllib.py", line 1074, in splittype
match = _typeprog.match(url)
TypeError: expected string or buffer
Apparently its having issues with one of those 3 arguments but I am not sure which one? I am also not sure I am handling the file correctly. Do I need to save the image and then re-open it in order to upload it to amazon s3? I do this because all the tinys3 examples do so, but my file is already open so perhaps its redundant?
It looks like your image argument might be mixed up. Here's the signature we want:
conn.upload(key, local_file, bucket)
tinys3 expects a string value for the key and an open file-like object for local_file. Try the following:
conn.upload("test.png", f, "snappie.watermarks")