Converting Java code to ColdFusion - java

I'm not skilled at Java at all so I could really use your help. I'm trying to read the duration and bit rate from an mp3 file. I'm using a java library called "mp3spi" from http://www.javazoom.net/mp3spi/documents.html.
So var I've been able to determine that these objects exist:
<cfset AudioFormat = createObject("java", "org.tritonus.share.sampled.TAudioFormat")>
<cfset AudioFileFormat = createObject("java", "org.tritonus.share.sampled.file.TAudioFileFormat")>
<cfset AudioFileReader = createObject("java", "javax.sound.sampled.spi.AudioFileReader")>
I'm having trouble with the following code and converting it to ColdFusion:
File file = new File("filename.mp3");
AudioFileFormat baseFileFormat = new MpegAudioFileReader().getAudioFileFormat(file);
Map properties = baseFileFormat.properties();
Long duration = (Long) properties.get("duration");
I've tried several ways of setting the above variables, but I keep getting an error that either MpegAudioFileReader or getAudioFileFormat doesn't exist. However when I dump the variables I used to create the Java objects, they do exist.
Here is what I have:
<cfscript>
mp3file = FileOpen(ExpandPath("./") & originalfile, "readBinary");
baseFileFormat = AudioFileReader.getAudioFileFormat(mp3file);
properties = baseFileFormat.properties();
duration = properties.get("duration");
</cfscript>

I'm not going to write your code for you, Simone, but there's a coupla general tips.
File file = new File("filename.mp3");
Well as you probably know, CFML is loosely-type, so you can dispense with the typing on the LHS, and then you need to use the createObject() function to create Java objects, which you already have a handle on. CF can't import Java libraries, so you'll need to give a fully-qualified path to the File class. You also need to explicitly call the constructor:
mp3File = createObject("java", "java.io.File").init("filename.mp3");
(as #Leigh points out below, file is a kinda reserved word in CFML, so best not to use it as a variable name! So I'm using mp3File here)
From there... you should be able to do the work for the other three statements easy enough. Basic method calls and assignments can pretty much be ported straight from the Java source, just lose the static-typing bits as per above, and the type-casting (long) etc.
If you cannot sort everything out from here, update your question with your experimentation, and we can improve this answer (or someone can post a different one). But you need to give us your specific problems, not just a general "write my code please". People won't do that, and you shouldn't be asking people to here (it's against the rules, and people are very big on rules on StackOverflow).

Adam's answer is solid. Since you'll need to invoke the constructor of a Java class in order to create an instance rather than being limited to using static methods, the "init()" method must be called. As follows...
mp3file = createObject("java", "java.io.File").init("filename.mp3");
baseFileFormat = createObject("java", "path.to.MpegAudioFileReader").init().getAudioFileFormat(mp3file);
properties = baseFileFormat.properties();
duration = properties.get("duration");
Adam's guidance is right on in that typing your variables when you initialize them won't fly. I don't have a ColdFusion environment set up to try this, but in the past we've used approaches like the one above to expand on ColdFusion's Hibernate integration by creating instances of the Java classes and invoking their methods. So long as the external libs that you're dependent on are in ColdFusion server's class path, you shouldn't have any trouble with this.

Related

Use option p of weka filter (RemoveType) in java code

I am using weka API in my java code and have a dataset with string ID to keep track of instances, weka mentioned in this page that there is an option p that can help printing the ID of each instance in the prediction result even if the attribute has removed. But how this can be approached in java code since none of the options listed in RemoveType filter is p?
Thank you
p option, on the weka page you mentioned, is the parameter which you can set through some of the the classes which are available in the package weka.classifiers.evaluation.output.prediction
With these classes you can set the things you want in output prediction file. E.g. OutputDistribution, AttributeIndices(P)- Attribute indices which you want to have in output file, Number of decimal places in prediction probabilities, etc.
You can use any of the below classes depending on the output file format you want.
PlainText
HTML
XML
CSV
Setting the parameters through code :
Evaluation eval = new Evaluation(data);
StringBuffer forPredictionsPrinting = new StringBuffer();
PlainText classifierOutput = new PlainText();
classifierOutput.setBuffer(forPredictionsPrinting);
Boolean outputDistribution = new Boolean(true);
classifierOutput.setOutputDistribution(true);
You can find detailed usage of this class at
https://www.programcreek.com/java-api-examples/?api=weka.classifiers.evaluation.output.prediction.PlainText

How to use Weka JSONLoader in Java IDE?

I want to use Weka in order to parse an existing json file in java eclipse. I believe this can be done using the JSONLoader class. After I read the classes' specifications (http://weka.sourceforge.net/doc.dev/weka/core/converters/JSONLoader.html#JSONLoader--) I thought that this could be easily done by doing this:
JSONLoader jsonLoader = new JSONLoader(jsonFile);
Then I thought by just doing jsonLoader.getFileDescription() or jsonLoader.getSource() would give me results. This is not how it's done though and I can't find anywhere how to use the JSONLoader class in my java code. So in order not to make this question too broad, how can I create a JSONLoader object that reads a source that is in JSON format?
First of all it has nothing to do with eclipse so you should edit your question.
A brief look at the documentation of JSONLoader(in the link you provided) can tell that you need to set the data source you want to parse using setSource (the constructor is empty):
JSONLoader jsonLoader = new JSONLoader();
File f = new File("PATH_TO_YOUR_JSON_FILE");
jsonLoader.setSource(f); //you can also use InputStream instead of a File
After doing that you can use other methods that parse your JSON:
Instances dataset = jsonLoader.getDataSet();
jsonLoader.getFileDescription();
...

Convert RTF string to HTML String using Java

I tried using the simple EditorKit option, but that doesn't seem to support all the RTF formats.
So I turned into using either Tika,JODConverter or POI.
As of now I managed to make it work with JODConverter and openOffice by using this
OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
.setPortNumbers(8100, 8101).buildOfficeManager();
officeManager.start();
OfficeDocumentConverter converter - new
OfficeDocumentConverter(officeManger);
try{
File tempFile = File.createTempFile("tempRtf", ".rtf");
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
bw.write(rtfString);
bw.close;
File outputTempFile = File.createTempFile("otuputTepFile", ".html");
converter.convert(tempFile, outputTempFile);
return FileUtils.readFileToString(outputTempFile);
This works.
My problem is that I actually set up a server and close it, which takes a lot of time.
I tried to see if I can bring up the process on the first run\report (I use it as a Handler in birt report) and then just to check if the process is running, if so use it to convert, and that's it, it'll save lots of time I see is wasted on initiating and closing process ( I don't care it will stay up)
My problem is that it seems like these classes as noted here are not present on my version of JODConverter.
After farther investigation, I found out that they are on the JODConverter 2.2 API and i use the 3.0 core-beta-4.
JODConverter seems to be kinda complex to a my simple need.
so if anyone knows how to start the office manger once and then just check if its up I'd love a code sample, and Of course if anyone got better solution than JODConverter to my need ill be glad to hear it.
EDIT: I need my Handler to do 2 things, 1. check if there is an instance of officemanager up, and connect to it (we skip the officeManager.start())
and 2. if the instance isn't up, then ill basically do what the code sample i wrote sent.
This code is written in a BIRT Handler, so i can't create the officeManager globally and just share it, cause the handler class runs everytime i call birt engine.
Maybe i can set up the officeManager in the Birt itself? then ill have the instance in the handler?

How to change the Properties.store() divider symbol from "=" to ":"?

I recently found out about java.util.Properties, which allows me to write and read from a config without writing my own function for it.
I was excited since it is so easy to use, but later noticed a flaw when I stored the modified config file.
Here is my code, quite simple for now:
FileWriter writer = null;
Properties configFile = new Properties();
configFile.load(ReadFileTest.class.getClassLoader().getResourceAsStream("config.txt"));
String screenwidth = configFile.getProperty("screenwidth");
String screenheight = configFile.getProperty("screenheight");
System.out.println(screenwidth);
System.out.println(screenheight);
configFile.setProperty("screenwidth", "1024");
configFile.setProperty("screenheight", "600");
try {
writer = new FileWriter("config.txt" );
configFile.store(writer, null);
} catch (IOException e) {
e.printStackTrace();
}
writer.flush();
writer.close();
The problem I noticed was that the config file I try to edit is stored like this:
foo: bar
bar: foo
foobar: barfoo
However, the output after properties.store(writer, null) is this:
foo=bar
bar=foo
foobar=barfoo
The config file I edit is not for my program, it is for an other application that needs the config file to be in the format shown above with : as divider or else it will reset the configuration to default.
Does anybody know how to easily change this?
I searched through the first 5 Google pages now but found noone with a similar problem.
I also checked the Javadoc and found no function that allows me to change it without writing a class for myself.
I would like to use Properties for now since it is there and quite easy to use.
I also got the idea of just replacing all = with : after I saved the file but maybe someone got a better suggestion?
Don't use a tool that isn't designed for the task - don't use Properties here. Instead, I'd just write your own - should be easy enough.
You can still use a Properties instance as your "store", but don't use it for serializing the properties to text. Instead, just use a FileWriter, iterate through the properties, and write the lines yourself - as key + ": " + value.
New idea here
Your comment about converting the = to : got me thinking: Properties.store() writes to a Stream. You could use an in-memory ByteArrayOutputStream, convert as appropriate in memory before you write to a file, then write the file. Likewise for Properties.load(). Or you could insert FilterXXXs instead. (I'd probably do it in memory).
I was looking into how hard it would be to subclass. It's nearly impossible. :-(
If you look at the source code for Properties, (I'm looking at Java 6) store() calls store0(). Now, unfortunately, store0 is private, not protected, and the "=" is given as a magic constant, not something read from a property. And it calls another private method called saveConvert() that also has a lot of magic constants.
Overall, I rate this code as D- quality. It breaks almost all the rules of good code and good style.
But, it's open source, so, theoretically, you could copy and paste (and improve!) a bunch of code into your own BetterProperties class.

Get real file extension -Java code

I would like to determine real file extension for security reason.
How can I do that?
Supposing you really mean to get the true content type of a file (ie it's MIME type) you should refer to this excellent answer.
You can get the true content type of a file in Java using the following code:
File file = new File("filename.asgdsag");
InputStream is = new BufferedInputStream(new FileInputStream(file));
String mimeType = URLConnection.guessContentTypeFromStream(is);
There are a number of ways that you can do this, some more complicated (and more reliable) than others. The page I linked to discusses quite a few of these approaches.
Not sure exactly what you mean, but however you do this it is only going to work for the specific set of file formats which are known to you
you could exclude executables (are you talking windows here?) - there's some file header information here http://support.microsoft.com/kb/65122 - you could scan and block files which look like they have an exe header - is this getting close to what you mean when you say 'real file extension'?

Categories

Resources