Saturday, 19 July 2014

Windchill and Scala: a quick dabble

Scala runs on the Java Virtual machine (JVM) and compiles to byte code the same as Java, this means that like jython it can also use Java libraries. One of the nice features of some modern languages is the REPL a console that allows the direct input of code to the interpreter along with instantaneous feedback.

 PTC's Windchill PLM/PDM Application is written in Java and also features an API to allow it to be customised to meet customer requirements. Running the Scala console inside a windchill shell allows access to windchill libraries and hence allows code be run on windchill's Method Servers using remote method server calls.

To give it a try download and install Scala from then open a windchill shell and type scala to access the Scala REPL.

Like Java, before you can make any calls using the Windchill API you need to import the classes, also to be able to run windchill methods we need a remote method server instance, so we can enter

import wc.method.remotemethodserver

 followed by

val remotemethodserver=RemoteMethodServer.getDefault()

 now that we have a method server  we can access it's methods, by entering


we can print out the start time of the method server as shown below.

Typing this in line by line would soon get repetitive and boring so we can create our code in a text file and then run it via the Scala console using scala filename.scala in this case scala WindchillExamples.scala

The below code shows some examples of using the windchill api to create a part and query the database, the syntax looks similar to how it would be written in Java with a few differences (specifying the class in the query spec and casting the returned part object from Persistable for instance). 

import wt.part.WTPart
import wt.method.RemoteMethodServer
import wt.fc.PersistenceHelper
import wt.query.QuerySpec
import wt.query.SearchCondition
object WindchillExamples {
def main(args: Array[String]) {
  println("Hello, Windchill!")
  // Get MethodServer
  val remotemethodserver=RemoteMethodServer.getDefault() 
  val name="examplePart" 
def countParts (name:String){
  //example query
  var qs=new QuerySpec(classOf[WTPart]) 
  qs.appendWhere(new SearchCondition(classOf[WTPart], WTPart.NAME,SearchCondition.LIKE, name))
  val qr = PersistenceHelper.manager.find(qs)
  println("Query results count: "+qr.size())
  val resultantPart=qr.nextElement()

def createPart(name:String){
  //example create part
  var part=WTPart.newWTPart()

No comments: