|Language:||English, Spanish, Portuguese|
|Genre:||Fiction & Literature|
|Distribution:||Free* [*Register to download]|
Follow us on Twitter: Watch us on YouTube: These recipes exist because of the many contributions on the Lift mailing list, where Liftafarians , as they are known, generously give their time to ask questions, put together example projects, give answers, share alternatives, and chip in with comments.
Thank you. I am indebted to the contributors who have taken the trouble to write new recipes, and to those who have provided corrections and suggestions. These are fantastic communicators: This chapter covers questions regarding starting development with Lift: You want to install and run Lift on your computer. The only prerequisite for installing and running Lift is to have Java 1. Instructions for installing Java can be found at http: You can find out if you have Java from the shell or command prompt by asking for the version you have installed:.
Once you have Java, the following instructions will download, build, and start a basic Lift application. Visit http: Open your browser and go to http: Some versions of windows will display a warning that the SBT "publisher could not be verified". Click "Run" if this happens. Start your browser and go to http: In this recipe, we downloaded a ZIP file containing four fairly minimal Lift applications, and then started one of them via the build tool.
SBT will check the project definition and download any libraries required, which will include the Lift framework. This download happens once, and the downloaded files are stored on disk in. Your application build is configured by build.
The SBT command container: The word container refers to the software you deploy your application into. There are a variety of containers Jetty and Tomcat are probably the best known all of which conform to a standard for deployment. The upshot is you can build your application and deploy to whichever one you prefer.
The container: If you take a look at index. Instead, the view defines areas of the content that are replaced with functions, such as those functions defined in HelloWorld. The Simple Build Tool documentation is at http: You want to create a Lift web project from scratch without using the ZIP files provided on the official Lift website.
You will need to configure SBT and the Lift project yourself. Luckily, only five small files are needed. This file tells SBT that you will be using the xsbt-web-plugin. This plugin will allow you to start and stop your application. Feel free to change the various versions, though be aware that certain versions of Lift are only built for certain versions of Scala. Now that you have the basics of an SBT project, you can launch the sbt console. It should load all the necessary dependencies, including the proper Scala version, and bring you to a prompt.
The web. Next, create a sample index. For example:. Finally, set up the basic Lift boot settings by creating a Boot. The following contents will be sufficient:. You can verify that you have a working Lift project by launching the Jetty web container from the SBT console with the container: First, the Boot. You should be able to go to the address in your web browser and see the rendered index. As shown previously, creating a Lift project from scratch is a relatively simple process.
However, it can be a tricky one for newcomers, especially if you are not used to the Java Virtual Machine JVM ecosystem and its conventions for web containers. If you run into problems, make sure the files are in the correct locations and that their contents were not mistakenly modified. If all else fails, refer to the sample project next or ask for help on the Lift mailing list. Likewise, the web. Given these conventions, you should have a directory structure looking quite, if not exactly, like this:.
There is a sample project created using this method. You want to develop your Lift application using your favourite text editor, hitting reload in your browser to see changes. Run SBT while you are editing, and ask it to detect and compile changes to Scala files.
To do that, start sbt and enter the following to the SBT prompt:. When you save a source file in your editor, SBT will detect this change, compile the file, and reload the web container. The first semicolon introduces a sequence of commands, where if the first command succeeds, the second will run. The second semicolon means the reload command will run if the start command ran OK. The start command will recompile any Scala source files that have changed. However, while SBT is watching for changes, the output will indicate when this happens with something that looks a little like this:.
This works out just fine, because Jetty will use your modified HTML file when you reload the browser page. You can reduce the need for restarts by integrating JRebel into your development environment, as described in Incorporating JRebel. However, if you are making a serious number of edits, you may prefer to issue a container: This will prevent SBT compiling and restarting your application over and over.
The SBT console has a command history, and using the up and down keyboard arrows allows you to navigate to previous commands and run them by pressing the Return key. That takes some of the tedium out of these long commands.
The permanent generation is a Java Virtual Machine concept. As you might imagine, continually restarting a container causes many classes to be loaded and unloaded, but the process is not perfect, effectively leaking memory. The best you can do is stop and then restart SBT. MaxPermSize inside the sbt or sbt. Triggered execution has a number of settings you can adjust, as described in the SBT documentation. There are three steps required: First, visit https: To apply the token to your local install, run the JRebel configuration script:.
In the "Activation" setting, select "I want to use myJRebel" and then in the "License" section, paste in your activation token. Click the "Activate" button, and once you see the license status change to "You have a valid myJRebel token," click "Finish.
This means setting the -javaagent and -noverify flags for Java, and enabling the JRebel Lift plugin. With JRebel installed, you can now container: JRebel is very likely to speed up your development. It updates code in a running Java Virtual Machine, without having to stop and restart it. The effect is that, on the whole, you can compile a class, then hit reload in your browser to see the change in your Lift application.
Even with JRebel you will need to restart your applications from time to time, but JRebel usually reduces the number of restarts. For example, Boot. But there are also other situations that JRebel cannot help with, such as when a superclass changes.
Generally, JRebel will emit a warning about this in the console window. If that happens, stop and start your application. The -Drebel. This means you can change fields or screens, and change REST serve code. This recipe uses a free Scala license for a service called myJRebel. This communicates with JRebel servers via the activation code.
If you have downloadd a license from ZeroTurnaround, the situation is slightly different. In this case, you will have a license key that you store in a file called jrebel.
You can place the file in a. For the latter option, modify the sbt script and specify the location of the file by adding another Java setting:. You want to develop your Lift application using the Eclipse IDE, hitting reload in your browser to see changes. This will give Eclipse the ability to understand Scala, and SBT the ability to create project files that Eclipse can load. The instructions for the Eclipse plugin are given at http: There are a number of options to be aware of when picking an update site to use: Start with the stable version of the plugin rather than a nightly or milestone version.
This will give you an Eclipse perspective that knows about Scala. Once the Eclipse plugin is installed and restarted, you need to create the project files to allow Eclipse to load your Lift project. You can then create Eclipse project files. You are now set up to develop your application in Eclipse.
To see live changes as you edit and save your work, run SBT in a separate terminal window. That is, start sbt from a terminal window outside of Eclipse and enter the following:. You can then edit in Eclipse, save to compile, and in your web browser, hit reload to see the changes. You can ask the SBT eclipse command to download the Lift source and Scaladoc, allowing you to click through to the Lift source from methods and classes, which is a useful way to discover more about Lift.
If you find yourself using the plugin frequently, you may wish to declare it in your global SBT configuration files so it applies to all projects. Note the blank line between the resolvers and the addSbtPlugin. There are other useful settings for sbteclipse. The details may vary between releases of the IDE, but the basic idea is to find the JetBrains Scala plugin, and download and install it. Click the "Install Plugin" button, confirm you want to install, then "Close" the repository browser, and finally OK out of the plugins window.
This will generate the. Inside IntelliJ you can open the project from the "File" menu, picking "Open…" and then navigating to your project and selecting the directory. To see live changes as you edit and save your work, run SBT in a separate Terminal window. That is, start sbt from a Terminal window outside of IntelliJ and enter the following:. Each time you compile or make the project, the container will pick up the changes, and you can see them by reloading your browser window.
By default, the gen-idea command will fetch source for dependent libraries. That means out of the box you can click through to Lift source code to explore it and learn more about the framework. One way to discover the features is to browse the release notes in the notes folder of that project.
JetBrains has a blog for the Scala plugin with feature news and tips. Locate the H2 JAR file. For me, this was: Start the server from a Terminal window using the JAR file: Enter jdbc: This means you can create a database in memory, and throw it away when your unit test ends. The H2 site lists the features and configuration options for database engine.
This is described by Diego Medina in a blog post. You want to use the latest "snapshot" build of Lift. You need to make two changes to your build. First, reference the snapshot repository: Second, change the liftVersion in your build to be the latest version. Restarting SBT or issuing a reload command will trigger a download of the latest build.
Production releases of Lift e. When SBT downloads them, they are downloaded once. Snapshot releases are different: You can force SBT to resolve the latest versions by running the command clean and then update. To learn the detail of snapshot versions, dig into the Maven Complete Reference. A new Scala version has just been released and you want to immediately use it in your Lift project. Providing that the Scala version is binary compatible with the latest version used by Lift, you can change your build file to use the latest version of Scala.
Dependencies have a particular naming convention. For example, the lift-webkit library for Lift 2. Normally, in build. Please note this only works for minor releases of Scala: For example, Scala 2. Binary compatibility in Scala is discussed on the Scala user mailing list. Using the Latest Lift Build describes how to use a snapshot version of Lift. Generating HTML is often a major component of web applications.
Code for this chapter is at https: You want to explore or debug CSS selectors interactively. The Helpers. CSS selector transforms are one of the distinguishing features of Lift.
They succinctly describe a node in your template lefthand side and give a replacement operation, the righthand side. It may help to know that prior to CSS selectors, Lift snippets were typically defined in terms of a function that took a NodeSeq and returned a NodeSeq , often via a method called bind.
Lift would take your template, which would be the input NodeSeq , apply the function, and return a new NodeSeq. We exploit this in the previous example by constructing an input NodeSeq called in , then creating a CSS function called f. The syntax for selectors is best described in Simply Lift. You want your CSS selector binding to apply to the results of earlier binding expressions. In contrast, andThen is a method of all Scala functions that composes two functions together, with the first being called before the second.
You want to set the content of an HTML meta tag from a snippet. Use the CSS binding name selector. For example, given:. The selector selects all elements with the given name. The [content] part is an example of a replacement rule that can follow a selector.
In this example, it replaces the value of the attribute called "content. Although not directly relevant to meta tags, you should be aware that there is one convenient special case for appending to an attribute.
If the attribute is class , a space is added together with your class value. This example uses an element selector, which picks out tags in the HTML template and replaces the content. To do that, make use of Menu. The Menu. This means the following will have the phrase "Site Title - " in the title, followed by the page title:. This example uses a custom snippet to put the site title after the page title:. This is a perfectly normal thing to do in Lift, and snippet invocations returned from snippets will be processed by Lift as normal.
Put the markup in a snippet and include the snippet in your page or template. To do that, our snippet would be:. We deal with this by generating unparsed markup from a snippet. Normally, Lift would cause the markup to be escaped, but in this case, we really do want unparsed XML content the comment tag included in the output. Notice that the condition test defaults to IE , but first tries to look for an attribute called cond. This allows you to write:. The html5shim project can be downloaded from its Google Code site.
You want a snippet to return the original markup associated with the snippet invocation. Suppose you have a snippet that performs a transform when some condition is met, but if the condition is not met, you want the snippet to return the original markup. It returns the input it is given:. The pattern of converting one NodeSeq to another is simple, but also powerful enough to get you out of most situations, as you can always arbitrarily rewrite the NodeSeq.
Switch to the designer-friendly snippet invocation mechanism. In particular, the HTML5 parser converts elements and attribute names to lowercase when looking up snippets. Switching to the designer-friendly mechanism is the solution here, and you gain validating HTML as a bonus. However, it works just fine outside of a template, for example when embedding a snippet invocation in your server-side code Setting the Page Title includes an example of this for Menu.
Add the with-resource-id attribute to script or link tags:. The addition of this attribute will cause Lift to append a resource ID to your src or href , and as this resource ID changes each time Lift starts, it defeats browser caching.
The random value that is appended to the resource is computed when your Lift application boots. This means it should be stable between releases of your application.
Note that some proxies may choose not to cache resources with query parameters at all. Finally we need a way to rewrite URLs like this back to the original path. There are a few ways to achieve this. There is support for URL rewriting, described on the Lift wiki.
Rewriting is used rarely, and only for special cases. Many problems that look like rewriting problems are better solved with a Menu Param. Grunt and similar tools can modify paths. Also suppose you have index. Do so by including the CSS in the part of the page that will get processed, and mark it with the head snippet:. Note that this index. The head snippet is a built-in snippet, but otherwise no different from any snippet you might write.
You can, but that would not necessarily be valid HTML5 markup. You want to show a customised "" not found page. This allows you to customise the response based on the request and the type of failure.
However, this means that if you display an error page using a template that contains Menu. As an alternative, you could include the page in your site map but make it hidden when the site map is displayed via the Menu. Catch Any Exception shows how to catch any exception thrown from your code. You want to show a customised page for certain HTTP status codes.
Use LiftRules. As an example, suppose we want to provide a custom page for "Forbidden" statuses created in our Lift application. Further, suppose that this page might contain snippets so will need to pass through the Lift rendering flow. To do this in Boot. Other non— responses are left untouched.
This is a very general mechanism: In the recipe, we respond with a template, but you may find situations where other kinds of responses make sense, such as an InMemoryResponse. One way to test the previous examples is to add the following to Boot.
Custom Page explains the built-in support for custom messages. You want to include a clickable link in your S. You may be more familiar with the S.
Text kind of NodeSeq. Lift notices are described on the wiki. You want a button or a link that, when clicked, will trigger a download in the browser rather than visiting a page. Create a link using SHtml.
As an example, we will create a snippet that shows the user a poem and provides a link to download the poem as a text file. The snippet itself will render the poem and replace the download link with one that will send a response that the browser will interpret as a file to download:.
Recall that SHtml. The browser is happy: On a page called downloadlink , the URL will look something like:. When that link is followed, Lift looks up the function and executes it, before processing the linked-to resource.
However, in this case, we are shortcutting the Lift pipeline by throwing this particular exception. This is caught by Lift, and the response wrapped by the exception is taken as the final response from the request. This shortcutting is used by S. This companion object also defines shortcutResponse , which you can use like this:.
In this case, the notice will not appear when the user downloads the file, but it will be included the next time notices are shown, such as when the user navigates to another page.
For many situations, the difference is immaterial. You can see how useful it is to be able to close over state the poem , and offer the data for download from memory. However, in other situations you might want to avoid holding this data as a function on a link. Streaming Content discusses InMemoryResponse and similar responses to return content to the browser.
You want to be able to test a function that needs a Req. To demonstrate how to use testReq , we will test a function that detects a Google crawler. Google identifies crawlers via various User-Agent header values, so the function we want to test would look like this:.
Although MockWeb. To configure a request, create an instance of the mock and mutate the state of it as required before using it with testReq. There are variations on the body assignment, which conveniently set the content type depending on the value you assign:.
In the example test shown earlier, it would be tedious to have to set up the same code repeatedly for different user agents. Specs2's Data Table provides a compact way to run different example values through the same test:. The core of this test is essentially unchanged: The difference is that Specs2 is providing a neat way to list out the various scenarios and pipe them through a function.
The Lift wiki discusses this topic and also other approaches such as testing with Selenium. You want to render Textile markup in your web application.
Install the Lift Textile module in your build. For example, starting SBT after adding the module and running the SBT console command allows you to try out the module:.
Anyone can create and publish a Lift module, and anyone can contribute to existing modules. In the end, they are declared as dependencies in SBT, and pulled into your code just like any other dependency.
The dependency name is made up of two elements: By "edition" we just mean the first part of the Lift version number. This structure has been adopted because modules have their own release cycle, independent of Lift. However, modules may also depend on certain features of Lift, and Lift may change APIs between major releases, hence the need to use part of the Lift version number to identify the module. The unit tests for the Textile module give you a good set of examples of what is supported.
You want to process form data in a regular, old-fashioned, non-Ajax way. Extract form values with S. For example, we can show a form, process an input value, and give a message back as a notice.
The template is a regular HTML form, with the addition of a snippet:. In the snippet, we can pick out the value of the field name with S. The first time through this snippet, there will be no parameter, so we just pass back the form unchanged to the browser, which is what PassThru is doing.
You can then enter a value into the name field and submit the form. This will result in Lift processing the template again, but this time, with a value for the name input. The result will be your browser redirected to a page with a message set for display. The result of S. If both name and petName are provided, the body of the for will be evaluated. Related functions on S include:.
As an example of using S. Note that by opening up S. Screen or Wizard provide alternatives for form processing, but sometimes you just want to pull values from a request, as demonstrated in this recipe. Simply Lift covers a variety of ways of processing forms. You want to process a form on the server via Ajax, without reloading the whole page. The render method is binding the name input field to a function that will assign whatever the user enters to the variable name.
When the button is pressed, the process function is called, which will return the value of the name back to the element in the HTML with an ID of result. In other words, when the form is asked to submit, Lift will serialise the form via Ajax. In this example with a single text field, if you omit the submit button you can trigger serialisation by pressing Return. In other words, the value name will be assigned even without a submit button. This serialises fields except submit buttons and file uploads.
The SHtml. You may prefer to use a styled button for submit. For example, with Twitter Bootstrap, a button with an icon would require the following markup:. However, if you bound that button with SHtml.
To fix this, you can assign a function to a hidden field. This function will be called when the form is submitted just like any other field.
The only part of our snippet that changes is the CSS selector binding:. This will include a hidden field in the form, something like this:. When the form is submitted, the hidden field is submitted, and like any field, Lift will call the function associated with it: The effect is something like ajaxSubmit , but not exactly the same. Is it before the name has been assigned or after? That depends on the order in which the fields are rendered. There are a couple of ways around that.
Either, ensure your hidden fields used in this way appear late in your form, or make sure the function is called late with a formGroup:. The formGroup addition manipulates the function identifier to ensure it sorts later, resulting in the function process being called later than fields in the default group 0.
Lift 2. If you want to try it in Lift 2. For more details about the form serialisation process, take a look at the jQuery documentation.
This is the value of the all parameter in the JsonCmd being pattern matched against in MottoServer. Lift has taken care of the plumbing to make this happen. The JsonHandler class and the SHtml. The MottoServer.
As we will see later, this is providing a general purpose function we can use to send different JSON values and commands to the server. Notice also, from the network traffic, that the form fields sent are serialised with the names they are given on the page. There are no "F…" values sent that map to function calls on the server. A consequence of this is that any fields dynamically added to the page will also be serialised to the server, where they can be picked up in the MottoServer.
In the previous example, we match on a JsonCmd with a command name of "processForm". You may be wondering what other commands can be supplied, or what the meaning of the target value is. To demonstrate how you can implement other commands, we can add two additional buttons. These buttons will just convert the motto to upper- or lowercase.
When is the changeCase function called? When either of these buttons are pressed, the result will be a JSON value sent to the server with the command of processCase and the direction and params set accordingly. All that is left is to modify our MottoServer to pick up this JsonCmd on the server:. The first JsonCmd is unchanged. The second matches on the parameters sent and results in updating the form fields with an upper- or lowercase version of the motto.
The Lift demo site contains further examples of JsonHandler. Lift in Action , section 9. You want to provide a date picker to make it easy for users to supply dates to your forms.
Dive into HTML5 describes how to detect browser features. You want to provide an autocomplete widget, to give users suggestions as they type into a text field. Connect the AutoComplete class to the element with the ID of autocomplete:. The last line of this snippet shows the binding of the AutoComplete class, which takes:. A function that will produce suggestions from the text value entered—the result is a Seq[String] of suggestions.
When the form is submitted, the submit function will be passed the selected value. The submit function is simply logging this value:. The autocomplete widget uses jQuery autocomplete. This can be seen by examining the NodeSeq produced by the AutoComplete. This chunk of markup is generated from the AutoComplete default, suggest, submit call.
All suggest needs to do is return a Seq[String] of values for the jQuery autocomplete code to display to the user. The work-around for this is to include the jQuery migration package in your template:. One peculiarity of the AutoComplete widget is that if you type in a new value—one not suggested—and press submit, it is not sent to the server.
Of course, if you only have a few items for the user to pick from, you could just include those items on the page, rather than making a round trip to the server. As an example of server-generated suggestions, we can look at the Typeahead component that is included in Twitter Bootstrap.
To incorporate Typeahead, the template needs to change to include the library and mark the input field in the way Typeahead expects:.
Working from the bottom of the snippet, we bind a regular Lift SHtml. This will receive the selected value when the form is submitted. This is the function that Typeahead will call when it wants suggestions. The body of askServer causes it to run something called runSuggestion , which is a jsonCall to the server, with the value of the query. The suggestions are made by the suggest function, which expects to be able to find a String in the passed in JSON value.
It uses this value to find matches in the list of languages. What does the client do with the data? It calls the callback function with the suggestions, which results in the display updating. We specify its callback via JsonContext , which is a class that lets us specify a custom function to call on success of the request to the server. As the user types into the text field, Typeahead calls askServer with the input supplied.
At that point, Typeahead takes over again and displays the suggestions. Typing Scala to the text field and pressing submit will produce a sequence like this on the server:.
Enhancing modules is one route to get involved with Lift, and Contributing, Bug Reports, and Getting Help describes other ways to contribute. The jQuery UI Autocomplete documentation describes how to configure the widget.
The version included with the Lift widgets module is version 1. The Typeahead widget is part of Twitter Bootstrap. You want users to select an option using radio buttons. The toString of the class will be used as the label shown to the user.
To present these options and handle the selection of an option, we use this enumeration in a snippet:. The radio. For example, if no radio button is selected:. The first is the set of options to show, as a Seq[T].
The second is the value to be preselected, as a Box[T]. In the example, we have no preselected value, which is represented as Empty. Note that even if the user selects no value, your function will be called, and it will be passed the value Empty. Each of the random radio button values is associated, on the server, with a BirthGender value from our options sequence.
When the form is submitted, Lift picks out the selected value if any , looks up the corresponding BirthGender value, and calls our function. The hidden field ensures that the function will be called even if no radio button is selected. This is because the browser will at least submit the hidden field, and this is enough to trigger the server-side function.
Each item is a ChoiceItem:. The key in our example is a BirthGender instance, and the xhtml is the radio button input field plus the hidden field for the first option. With this knowledge, we can write a helper to generate a NodeSeq in the style we want:. The toForm is applying the htmlize function to all the choices. As a consequence of this, we could make LabelStyle the default across our Lift application:.
If you want to work directly with String values for options, you can use SHtml. Although it too produces a ChoiceHolder , it differs from radioElem in that it uses the same String as both the label and the value. The function associated with each option is called only if a value is selected by the user.
This is a similar structure to radioElem: When a form is submitted, our function is passed the String value of the selected option. If no radio buttons are selected, the function is not called.
You want to add the disabled attribute to a SHtml. Create a CSS selector transform to add the disabled attribute, and apply it to your checkbox transform. We could do that by adjusting the NodeSeq generated from SHtml. What this combination means is that half the time the disabled attribute will be set on the checkbox, and half the time the checkbox NodeSeq will be left untouched because PassThru does not change the NodeSeq.
You want to show a number of options in a select box, and allow the user to select multiple values. Use SHtml. When the form is submitted, the selection function is called, with a list of the selected option values.
Recall that an HTML select consists of a set of options, each of which has a value and a name. To reflect this, the previous example takes our inventory of objects and turns it into a list of string pairs, called options. The function given to SHtml. That is, if you ran the code, and selected "Coffee" and "Milk," the function would see List "a", "b". Be aware that if no options are selected, your handling function is not called. This is described in issue One way to work around this is to add a hidden function to reset the list.
For example, we could modify the previous code to be a stateful snippet and remember the values we selected:.
The template is unchanged, and the snippet has been modified to introduce a current value and a hidden function to reset the value. Each time the form is submitted the current list of IDs is set to whatever you have selected in the browser.
But note that we have started with a hidden function that resets current to the empty list. This means that if the receiving function in multiSelect is never called, because nothing is selected, the value stored in current would reflect this and be Nil. In this variation, the list of options still provides a text name, but the value is in terms of a class. Likewise, the list of default values will be a list of class instances. The only changes to the code are to produce a List[ Item,String ] for the options, and use an Item as a default:.
The call to generate the multiselect from this data is similar, but note our selection function now receives a list of Item:.
You can use multiSelectObj with enumerations:. The "Submit styling" discussion in Ajax Form Processing discusses the use of hidden fields as function calls. Call Server When Select Option Changes describes how to trigger a server-side action when a selection changes in the browser. Chapter 6 of Exploring Lift , "Forms in Lift," discusses multiselect and other types of form elements.
You want a snippet to allow users to upload a file to your Lift application. Use a FileParamHolder in your snippet, and extract file information from it when the form is submitted. We bind the file input to SHtml. The fileUpload binding ensures that the file is assigned to the upload variable.
This allows us to access the Array[Byte] of the file in the processForm method when the form is submitted.
These are available as uploadedFiles on a Req object, for example:. If the file is zero length, the function is not called. The default behaviour for Lift is to read the file into memory and present it as a FileParamHolder. In fact, LiftRules provides a number of size restrictions that you can control:. Why two settings? Because when the form is submitted, there may be a number of fields on the form. For example, in the recipe, the value of the submit button is sent as one of the parts, and the file is sent as another.
Hence, you might want to limit file size, but allow for some field values, or multiple files, to be submitted. If you hit the size limit, an exception will be thrown from the underlying file upload library. You can catch the exception, as described in Catch Any Exception:. Be aware that the container Jetty, Tomcat or any web server Apache, Nginx may also have limits on file upload sizes.
Uploading a file into memory may be fine for some situations, but you may want to upload larger items to disk and then process them in Lift as a stream. Lift supports this via the following setting:.
The handleMimeFile variable expects to be given a function that takes a field name, mime type, filename, and InputStream and returns a FileParamHolder.
For example, our snippet could change to:. If you want to monitor the progress of the upload on the server side, you can. This is the progress of the whole multipart upload, not just the file being uploaded. In particular, the contentLength may not be known in which case, it will be -1 , but if it is known, it is the size of the complete multipart upload.
In the example in this recipe, that would include the size of the file, but also the submit button value. This also explains the fieldIndex , which is a counter as to which part is being processed. It will take on the values of 0 and 1 for the two parts in this example.
This snippet will present a hypothetical user account record, allowing a user to edit three fields. The fields have validation, and will be bound into a template. Running the snippet will cause CssBoundLiftScreen to apply the defaultFieldNodeSeq layout to each field, with the exception of the "address" field that we have customised inside the template.
Pressing the "Finish" button triggers validations, presents errors if any , or completes the edit via the finish method. This powerful mechanism eliminates repetition in both code and HTML; however, LiftScreen sacrifices flexibility in that there is no way to make highly customized forms. This restriction is removed in CssBoundLiftScreen by allowing you to control every element of the form rendering. You can control everything form field placement to the layout of a single field.
You do so by embedding the custom template at the snippet usage site:. The form is still very minimal, while being completely under the control of the designer. The example in the solution section demonstrates the most important aspects. In particular, you should note that you must still supply a source for the template, and that you can designate alternatives for sub-portions of the template.
The rest is very easy. This, combined with an internal function that you can override , will generate unique but known names that can be used in the template.
The default pattern is: That is all you need for normal bindings that use your field template.
To tweak the field layout for a particular field, you may specify Self in the Scala field binding. For an introduction, take a look at the Lift wiki page and Chapter 5 of Simply Lift. The sample code from this chapter is at https: This is why the cURL request includes a header with with the -H flag. Your RestHelper expects a filename as part of the URL, but the suffix extension is missing, and you need it.
We are matching on download but rather than using the file value directly, we pass it through the reunite function first to attach the suffix back on if any. When Lift parses a request, it splits the request into constituent parts e. This includes a separation of some suffixes. This is good for pattern matching when you want to change behaviour based on the suffix, but a hindrance in this particular situation.
Only those suffixes defined in LiftRules. This includes many of the common file suffixes such as. Note that if the suffix is not in explicitlyParsedSuffixes , the suffix will be an empty string and the name in the previous example will be the filename with the suffix still attached.
Depending on your needs, you could alternatively add a guard condition to check for the file suffix:. Likewise, the web. Given these conventions, you should have a directory structure looking quite, if not exactly, like this: - project root directory build. The first semicolon introduces a sequence of commands, where if the first command succeeds, the second will run.
The second semicolon means the reload command will run if the start command ran OK. The start command will recompile any Scala source files that have changed.
Waiting for source changes LiftServlet - Destroyed Lift handler. JspServlet [info] started o. This works out just fine, because Jetty will use your modified HTML file when you reload the browser page. You can reduce the need for restarts by integrating JRebel into your development environment, as described in Incorporating JRebel.
This will prevent SBT compiling and restarting your application over and over. The SBT console has a command history, and using the up and down keyboard arrows allows you to navigate to previous commands and run them by pressing the Return key. That takes some of the tedium out of these long commands.
If you are using Java before Java 8, one error you may run into is: java. As you might imagine, continually restarting a container causes many classes to be loaded and unloaded, but the process is not perfect, effectively leaking memory.
The best you can do is stop and then restart SBT. In the "Activation" setting, select "I want to use myJRebel" and then in the "License" section, paste in your activation token. Click the "Activate" button, and once you see the license status change to "You have a valid myJRebel token," click "Finish.
This means setting the -javaagent and -noverify flags for Java, and enabling the JRebel Lift plugin.
With JRebel installed, you can now container:start your application, modify and compile a Scala file, and reload a page in your application. That change is live, without having to restart the container. Discussion JRebel is very likely to speed up your development. It updates code in a running Java Virtual Machine, without having to stop and restart it. The effect is that, on the whole, you can compile a class, then hit reload in your browser to see the change in your Lift application.
Even with JRebel you will need to restart your applications from time to time, but JRebel usually reduces the number of restarts. For example, Boot. But there are also other situations that JRebel cannot help with, such as when a superclass changes. Generally, JRebel will emit a warning about this in the console window. If that happens, stop and start your application. The -Drebel. This means you can change fields or screens, and change REST serve code.
downloadd licenses This recipe uses a free Scala license for a service called myJRebel. This communicates with JRebel servers via the activation code. If you have downloadd a license from ZeroTurnaround, the situation is slightly different. In this case, you will have a license key that you store in a file called jrebel.
You can place the file in a. For the latter option, modify the sbt script and specify the location of the file by adding another Java setting : -Drebel.
This will give Eclipse the ability to understand Scala, and SBT the ability to create project files that Eclipse can load. There are a number of options to be aware of when picking an update site to use: there are different sites for Scala 2. Start with the stable version of the plugin rather than a nightly or milestone version. This will give you an Eclipse perspective that knows about Scala. Once the Eclipse plugin is installed and restarted, you need to create the project files to allow Eclipse to load your Lift project.