Search code examples
javacoldfusionjsoupcoldfusion-2016

How do I load jsoup Java library from inside Coldfusion 2016?


TLDR: CreateObject function throws an exception (java.lang.ClassNotFoundException) because it cannot see the java class/JAR file.

Any ideas what am I doing wrong? Thanks


contents of Application.cfc

<cfcomponent output="true">

    <cfset path = "#Mid(CGI.CF_TEMPLATE_PATH, 1, FindNoCase("index.cfm", CGI.CF_TEMPLATE_PATH)-2)#/java/lib" />
    <cfoutput>path: #path#</cfoutput>

    <cftry>
        <cfset This.javaSettings = {LoadPaths = ["#path#/", "#path#/java/lib/jsoup-1.12.1.jar", "./java/lib/", "./java/lib/jsoup-1.12.1.jar"], loadColdFusionClassPath = true, reloadOnChange = true}>

        <cfset jsoup = CreateObject("java", "org.jsoup.Jsoup") />

        <cfcatch type="any">
            <cfdump var="#cfcatch#" />
        </cfcatch>
    </cftry>

    <cfabort>
</cfcomponent>

JAR file location

/Volumes/mydrive/work/myapp/java/lib/jsoup-1.12.1.jar

output of the cfoutput inside Application.cfc

path: /Volumes/mydrive/work/myapp/java/lib

Solution

  • @mrjayviper, I'm not sure why you have added the jsoup-1.12.1.jar in more times in loadPaths array ?

    As well as your PATH = > /Volumes/mydrive/work/myapp/java/lib, But you have passed the value in loadPaths array like #path#/java/lib/jsoup-1.12.1.jar. Then it's should consider it as /Volumes/mydrive/work/myapp/java/lib/java/lib/jsoup-1.12.1.jar So it's totally wrong. That's an causes of your problem.

    Here I wish to give some better solution for you with my sample application,

    My simple application files structure look like this,

    • Application.cfc : Just normal Application.cfc file which having this.javaSettings to load the JSOUP jar file
    • index.cfm : Having code to fetching web page content using jSoup & executes the parsing operation
    • jsoup-1.8.3.jar : The downloaded JSOUP jar file

    enter image description here

    Then you can set the javaSetting in application.cfc file like below

    component {
        this.name = "jSoupParser";
        //Loads the JAR File
        this.javaSettings = { loadPaths = [ "#expandPath('./jsoup-1.8.3.jar')#" ], 
                                reloadOnChange = false };
    }
    

    You could use the expandPath() and can point out your current application directory. Then you can create an object in your cfm file like below Index.cfm :

    <cfset getJsoup = createObject("java", "org.jsoup.Jsoup")> 
    

    I hope this help you more. If you want more explanation / clarification about this then please visit below link. Already my team gave the sample for this jSoup. https://www.mitrahsoft.com/index.cfm/blog/ColdFusion-Web-scraping-HTML-Parsing-using-JSOUP.