I use thymlead for the first time. I would like to have header body and footer.
I'm getting exception whetever I try.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "templates/layout", template might not exist or might not be accessible by any of the configured Template Resolvers
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
Here is my tiles configuration files :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="base.definition" template="templates/layout">
<put-attribute name="title" value="" />
<put-attribute name="header" value="templates/header" />
<put-attribute name="menu" value="" />
<put-attribute name="body" value="templates/index" />
<put-attribute name="footer" value="templates/footer" />
</definition>
<definition name="index" extends="base.definition">
</definition>
</tiles-definitions>
This is my mvc configuration class.
package com.myproj.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.extras.tiles2.dialect.TilesDialect;
import org.thymeleaf.extras.tiles2.spring4.web.configurer.ThymeleafTilesConfigurer;
import org.thymeleaf.extras.tiles2.spring4.web.view.ThymeleafTilesView;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
#Configuration
#ComponentScan("com.myproj.spring")
#PropertySource("classpath:myproj.properties")
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/").setCachePeriod(31556926);
}
#Bean
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver result = new ClassLoaderTemplateResolver();
result.setPrefix("/WEB-INF/views/");
result.setSuffix(".html");
result.setTemplateMode("HTML5");
result.setOrder(1);
return result;
}
#Bean
public ThymeleafTilesConfigurer tilesConfigurer() {
ThymeleafTilesConfigurer tilesConfigurer = new ThymeleafTilesConfigurer();
tilesConfigurer.setDefinitions(new String[] { "classpath:tiles/tiles-def.xml" });
return tilesConfigurer;
}
#Bean
public SpringTemplateEngine templateEngine(ClassLoaderTemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.addDialect(new TilesDialect());
return templateEngine;
}
#Bean
public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
viewResolver.setViewClass(ThymeleafTilesView.class);
return viewResolver;
}
}
and my controller
package com.myproj.spring.config;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class DefaultController {
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String index(HttpServletRequest request) {
System.out.println("index page");
return "index";
}
#RequestMapping(value="/login", method = RequestMethod.GET)
public String login(HttpServletRequest request) {
System.out.println("login page");
return "login";
}
}
Here is my project structure
I'm using Spring Tools Suite and embedded Tomcat 8.
Any help please?
The solution is to put templates in src\main\resources.
Related
How can Univocity Parsers be used from within JavaFX 8?
IntelliJ is being used for this. There are no warnings given by IntelliJ in the coding context, but when running the code there are errors.
Here is the code, and stack trace(abbreviated):
Main.java:
package parse;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("parse.fxml"));
primaryStage.setTitle("Parse Test");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java:
package parse;
import com.univocity.parsers.common.processor.RowListProcessor;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class Controller {
#FXML
private TextArea textArea;
public Controller() {
}
#FXML
private void initialize() {
}
public void print(String message) {
textArea.appendText(message);
}
public Reader getReader(String relativePath) {
try {
return new InputStreamReader(this.getClass().getResourceAsStream(relativePath), "Windows-1252");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unable to read input", e);
}
}
#FXML
public void columnSelection() {
print("this is the parsing method" + System.getProperty("line.separator"));
RowListProcessor rowProcessor = new RowListProcessor();
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setLineSeparatorDetectionEnabled(true);
parserSettings.setSkipEmptyLines(true);
parserSettings.getFormat().setDelimiter(',');
// Here we select only the columns "Price", "Year" and "Make".
// The parser just skips the other fields
parserSettings.selectFields("AUTHOR", "ISBN");
CsvParser parser = new CsvParser(parserSettings);
parser.parse(getReader("list3.csv"));
List<String[]> rows = rowProcessor.getRows();
String[] strings = rows.get(0);
print(strings[0]);
}
}
parse.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="279.0" prefWidth="322.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="parse.Controller">
<center>
<Button mnemonicParsing="false" onAction="#columnSelection" text="Parse" BorderPane.alignment="CENTER" />
</center>
<top>
<TextArea fx:id="textArea" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</top>
</BorderPane>
Stack Trace:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:97)
at parse.Controller.getReader(Controller.java:34)
at parse.Controller.columnSelection(Controller.java:60)
... 56 more
Does anyone know how to configure a persistent token store for Mule OAuth Provider module?
Adding a normal object store does not support the org.mule.modules.oauth2.provider.token.TokenStore interface.
EDIT
I want to persist to file - disk.
EDIT 2
Flow with OAuth provider setup:
<mule xmlns:objectstore="http://www.mulesoft.org/schema/mule/objectstore" xmlns:context="http://www.springframework.org/schema/context"
xmlns:https="http://www.mulesoft.org/schema/mule/https" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:json="http://www.mulesoft.org/schema/mule/json"
xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml"
xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.5.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ss="http://www.springframework.org/schema/security" xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security"
xmlns:oauth2-provider="http://www.mulesoft.org/schema/mule/oauth2-provider"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-current.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/https http://www.mulesoft.org/schema/mule/https/current/mule-https.xsd
http://www.mulesoft.org/schema/mule/oauth2-provider http://www.mulesoft.org/schema/mule/oauth2-provider/current/mule-oauth2-provider.xsd
http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/current/mule-spring-security.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.mulesoft.org/schema/mule/objectstore http://www.mulesoft.org/schema/mule/objectstore/current/mule-objectstore.xsd">
<spring:beans>
<spring:bean id="oauthTokenStore" name="oauthTokenStore" class="org.mule.util.store.TextFileObjectStore"/>
</spring:beans>
<spring:beans>
<ss:authentication-manager id="resourceOwnerAuthenticationManager">
<ss:authentication-provider>
<ss:user-service id="resourceOwnerUserService">
<ss:user name="${username}" password="${password}" authorities="RESOURCE_OWNER" />
</ss:user-service>
</ss:authentication-provider>
</ss:authentication-manager>
</spring:beans>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="resourceOwnerSecurityProvider" delegate-ref="resourceOwnerAuthenticationManager" />
</mule-ss:security-manager>
<oauth2-provider:config name="blazeOauth2Provider"
providerName="Blaze" host="0.0.0.0" port="${blaze.esb.port.https}"
authorizationEndpointPath="api/1.0/authorize" accessTokenEndpointPath="api/1.0/token"
resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider"
scopes="BLAH" doc:name="OAuth provider module"
tokenTtlSeconds="${blaze.security.token.lifespan}" connector-ref="httpsServerConnector" supportedGrantTypes="AUTHORIZATION_CODE IMPLICIT" enableRefreshToken="true" tokenStore-ref="oauthTokenStore" >
<oauth2-provider:clients>
<oauth2-provider:client clientId="${blaze.client.id}" secret="${blaze.client.secret}" type="CONFIDENTIAL" clientName="Client" description="Service Front-End">
<oauth2-provider:redirect-uris>
<oauth2-provider:redirect-uri>http://localhost*</oauth2-provider:redirect-uri>
</oauth2-provider:redirect-uris>
<oauth2-provider:authorized-grant-types>
<oauth2-provider:authorized-grant-type>AUTHORIZATION_CODE</oauth2-provider:authorized-grant-type>
<oauth2-provider:authorized-grant-type>TOKEN</oauth2-provider:authorized-grant-type>
</oauth2-provider:authorized-grant-types>
<oauth2-provider:scopes>
<oauth2-provider:scope>BLAH</oauth2-provider:scope>
</oauth2-provider:scopes>
</oauth2-provider:client>
</oauth2-provider:clients>
</oauth2-provider:config>
</mule>
ok, after performing a simple test, I recommend developing your own FileObjectStore for more control.
Create public class, for example:
public class MyFileObjectStore extends AbstractObjectStore { ..}
Use a properties file to store the token, key=value
Implement the methods: doStore, doRetrieve, doRemove, basically to update on a properties files.
Change in you flow:
<spring:bean id="accessTokenStore" class="test.MyFileObjectStore"/>
<spring: bean name="tokenStore" class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">
<spring:property name="accessTokenObjectStore" ref="accessTokenStore" />
There are several ways to set the tokenStore for oauth. You can use for example (the most common):
org.mule.util.store.PartitionedPersistentObjectStore or
org.mule.transport.jdbc.store.JdbcObjectStore
For your requirement, you can use:
org.mule.util.store.TextFileObjectStore
I hope to help;
Based on #Julio answer:
Added a class, that implements a map <String, AccessTokenStoreHolder>:
package xxx;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.mule.api.lifecycle.InitialisationException;
import org.mule.api.store.ObjectDoesNotExistException;
import org.mule.api.store.ObjectStoreException;
import org.mule.config.i18n.CoreMessages;
import org.mule.util.FileUtils;
import org.mule.util.IOUtils;
import org.mule.util.StringUtils;
import org.mule.util.store.InMemoryObjectStore;
import org.mule.modules.oauth2.provider.token.AccessTokenStoreHolder;
public class PersistantOAuthObjectStore extends InMemoryObjectStore<AccessTokenStoreHolder> {
protected File fileStore;
protected String directory;
private Map<String, AccessTokenStoreHolder> tokenStore;
private FileOutputStream output;
public PersistantOAuthObjectStore() {
super();
}
private Map<String, AccessTokenStoreHolder> getTokenStore() {
if (tokenStore == null)
tokenStore = new HashMap<>();
return tokenStore;
}
#Override
public void initialise() throws InitialisationException
{
super.initialise();
if (directory == null)
directory = context.getConfiguration().getWorkingDirectory() + "/objectstore";
try
{
File dir = FileUtils.openDirectory(directory);
fileStore = new File(dir, name + ".dat");
if (fileStore.exists())
loadFromStore();
}
catch (Exception e)
{
throw new InitialisationException(e, this);
}
}
#SuppressWarnings("unchecked")
protected synchronized void loadFromStore() throws Exception
{
ObjectInputStream stream = new ObjectInputStream(new FileInputStream(fileStore));
Object result = stream.readObject();
tokenStore = (Map<String, AccessTokenStoreHolder>)result;
for (Map.Entry<String, AccessTokenStoreHolder> entry : getTokenStore().entrySet())
super.store(entry.getKey().toString(), entry.getValue());
stream.close();
}
#Override
public void store(Serializable id, AccessTokenStoreHolder item) throws ObjectStoreException
{
super.store(id, item);
try
{
synchronized(getTokenStore()) {
getTokenStore().put(id.toString(), item);
saveMap();
}
}
catch (IOException e)
{
throw new ObjectStoreException(e);
}
}
private void saveMap() throws IOException {
if (output == null)
output = new FileOutputStream(fileStore, false);
ObjectOutputStream stream = new ObjectOutputStream(output);
stream.writeObject(getTokenStore());
}
#Override
public AccessTokenStoreHolder remove(Serializable key) throws ObjectStoreException
{
super.retrieve(key);
try
{
synchronized (getTokenStore())
{
if (getTokenStore().containsKey(key)) {
AccessTokenStoreHolder val = getTokenStore().get(key);
getTokenStore().remove(key);
saveMap();
return val;
}
}
throw new ObjectDoesNotExistException(CoreMessages.objectNotFound(key));
}
catch (IOException e)
{
throw new ObjectStoreException(e);
}
}
#Override
public void clear() throws ObjectStoreException
{
super.clear();
try
{
synchronized (getTokenStore()) {
getTokenStore().clear();
saveMap();
}
}
catch (IOException e)
{
throw new ObjectStoreException(e);
}
}
public String getDirectory()
{
return directory;
}
public void setDirectory(String directory)
{
this.directory = directory;
}
#Override
public boolean isPersistent() {
return true;
}
}
Then add 2 spring beans to xml:
<spring:bean id="oauthTokenStore" name="oauthTokenStore" class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">
<spring:property name="accessTokenObjectStore" ref="oauthObjectStore"/>
</spring:bean>
<spring:bean id="oauthObjectStore" class="com.vatit.blaze.esb.utils.objectStore.BlazePersistantObjectStore" init-method="initialise" destroy-method="dispose" name="oauthObjectStore">
<spring:property name="name" value="oauthObjectStore"/>
</spring:bean>
Then ref the tokenStore in your OAuth 2 provider config:
tokenStore-ref="oauthTokenStore"
I think the above answers are correct but not ideal. ObjectStoreTokenStore can be composed of multiple persistent object stores. I am not sure if you even need to write any Java code to have this done.
<spring:bean name="tokenStore" class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">
<spring:property name="accessTokenObjectStore" ref="accessTokenFileObjectStore"/>
<spring:property name="refreshTokenObjectStore" ref="refreshTokenFileObjectStore"/>
</spring:bean>
Here accessTokenFileObjectStore and refreshTokenFileObjectStore can be spring beans created out from TextFileObjectStore
I'm trying to understand how to program composite components, and have followed the great example by balusc, and others, but I'm missing something.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:cc="http://java.sun.com/jsf/composite">
<cc:interface componentType="simpleComponent">
<cc:attribute name="value" required="true" type="example.LanguageDefinition"/>
<cc:attribute name="possibilities" default="de_DE" type="java.lang.String"/>
</cc:interface>
<cc:implementation>
<p:selectOneMenu binding="#{cc.inputComponent}" converter="omnifaces.SelectItemsConverter" var="l"
value="#{cc.attrs.value}">
<p:ajax update="#form"/>
<f:selectItems value="#{cc.languages}" var="l" itemLabel="#{l.label}"
itemValue="#{l}" />
<p:column>#{l.label}</p:column>
<p:column>
<p:graphicImage name="#{l.imgPath}" />
</p:column>
</p:selectOneMenu>
</cc:implementation>
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIInput;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import example.LanguageDefinition;
#FacesComponent("simpleComponent")
public class SimpleComponent extends UIInput implements NamingContainer {
private UIInput inputComponent;
public UIInput getInputComponent() {
return inputComponent;
}
public void setInputComponent(UIInput inputComponent) {
this.inputComponent = inputComponent;
}
#Override
public Object getSubmittedValue() {
return inputComponent.getSubmittedValue();
}
#Override
protected Object getConvertedValue(FacesContext context, Object newSubmittedValue) {
return (String) newSubmittedValue;
}
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
#Override
public void encodeBegin(FacesContext context) throws IOException {
String possibilities = getAttributeValue("possibilities", "en_US");
// In theory, build based on incoming possibilities, now hard code
List<LanguageDefinition> languages = new ArrayList<LanguageDefinition>();
languages.add(new LanguageDefinition("pt_PT",
"images/flags/PT.gif", "Português (Portugal)"));
languages.add(new LanguageDefinition("cs_CZ",
"images/flags/CZ.gif", "Czech (Czech Republic)"));
getStateHelper().put("languages", languages);
super.encodeBegin(context);
}
#SuppressWarnings("unchecked")
public List<LanguageDefinition> getLanguages() {
return (List<LanguageDefinition>) getStateHelper().get("languages");
}
/**
* Return specified attribute value or otherwise the specified default if it's null.
*/
#SuppressWarnings("unchecked")
private <T> T getAttributeValue(String key, T defaultValue) {
T value = (T) getAttributes().get(key);
return (value != null) ? value : defaultValue;
}
}
This isn't working calling like this:
<ex:simpleComponent value="#{compBean.selected}"/>
Everything renders fine, but the submitted value is never passed back to my "compBean". However, if I set the selectItems "languages" in any other way other than doing it in encodeBegin it works... as a member variable with getters and setters, or using this code:
<c:set target="#{cc}" property="possibilities" value="#{cc.attrs.possibilities}"/>
In combination with this much simpler class:
import java.util.ArrayList;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIInput;
import javax.faces.component.UINamingContainer;
import example.LanguageDefinition;
#FacesComponent("simpleComponent")
public class SimpleComponent extends UIInput implements NamingContainer {
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
public void setPossibilities(String possibilities) {
if (getStateHelper().get("possibilities") == null) {
List<LanguageDefinition> languages = new ArrayList<LanguageDefinition>();
languages.add(new LanguageDefinition("pt_PT",
"images/flags/PT.gif", "Português (Portugal)"));
languages.add(new LanguageDefinition("cs_CZ",
"images/flags/CZ.gif", "Czech (Czech Republic)"));
getStateHelper().put("languages", languages);
getStateHelper().put("possibilities", possibilities);
}
}
public String getPossibilities() {
return (String) getStateHelper().get("possibilities");
}
#SuppressWarnings("unchecked")
public List<LanguageDefinition> getLanguages() {
return (List<LanguageDefinition>) getStateHelper().get("languages");
}
}
But, it doesn't seem right to do it this way (wasn't the way balusc did it), so I'm just trying to understand. Which way is better? Assuming the first, why is mine not working?
Thanks!
So... the reason this wasn't working was because I forgot to implement Serializable on my custom drop down list value object "example.LanguageDefinition".
Hopefully the next person won't have to look for this needle in the haystack as long as I did :)
I have problem when upload image in Struts2.
I am trying to upload an image from jsp page to action class in struts2
My code is successfully run but executes up to System.out.println("2") and the image is not copied to the specified location.
Please help me to solve this problem
My Action class is below:
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import com.opensymphony.xwork2.ActionSupport;
public class upload extends ActionSupport {
public String execute()throws Exception
{
try{
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("1");
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
System.out.println("2");
for (FileItem item : items)
{
System.out.println("3");
if (!item.isFormField()){
String fieldname = item.getFieldName();
System.out.println(fieldname);
System.out.println("4");
File file = new File("F:/www/test/Rohit/workspace_Rohit/uploadWithStruts2/WebContent/uploadimage","hi.jpg");
item.write(file);
}
}
}
catch (Exception e) {
System.out.println(e);
}
return SUCCESS;
}
}
My jsp page is:
<form action="test.action" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="upload"/>
</form>
// For upload Image in Struts2
// Jsp Page is:
<s:form method="post" action="test.action" enctype="multipart/form-data">
<s:file name="imageFile" label="User Image" />
<s:submit value="submit"></s:submit>
//Struts.xml
<struts>
<package name="default" extends="struts-default">
<action name="test" class="Test">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
//Test.java
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
public class test extends ActionSupport{
private static final long serialVersionUID = 1L;
private File imageFile;
public File getImageFile() {
return imageFile;
}
public void setImageFile(File imageFile) {
this.imageFile = imageFile;
}
public String execute()throws Exception
{
try{
//code for image random name
// start from here to
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String dt = format.format(date);
String name = "";
StringTokenizer str = new StringTokenizer(dt);
while (str.hasMoreElements())
{
String nm=(String) str.nextElement();
name+=nm;
}
String name1="";
StringTokenizer strg = new StringTokenizer(name,"/");
while (strg.hasMoreElements())
{
String nam=(String) strg.nextElement();
name1+=nam;
}
String imgname="";
StringTokenizer strge = new StringTokenizer(name1,":");
while (strge.hasMoreElements())
{
String na=(String) strge.nextElement();
imgname+=na;
}
//code for copy image to specific path
String sourceFilePath=imageFile.getAbsolutePath();
//System.out.println(sourceFilePath);
File sourceFile=new File(sourceFilePath);
File destnationFile=new File("E:/Jaydip_Baldha/workspace_new/Struts2Upload/WebContent/upload_image/"+imgname+".jpg");
FileUtils.copyFile(sourceFile, destnationFile);
}
catch(Exception e)
{
e.printStackTrace();
}
return SUCCESS;
}
}
I am using Primefaces 3.2 and developing the file download functionality and I am getting list of file names from my local which i wanted to display them in jsf datatable with clickable option(h:commandlink).
When I excute my Code I am getting following exception.
javax.el.PropertyNotFoundException: /faces/fileDownload.xhtml at line
33 and column 115 value="#{x.fileName}": Property 'fileName' not found
on type java.io.File
My Code looks like this Java File
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
#ManagedBean(name="fileDownloadController")
#SessionScoped
public class FileDownloadController {
private StreamedContent file;
private List<File> listfiles=new ArrayList<File>();
private String fileName;
public FileDownloadController() {
File filestream=new File("C:/temp.pdf");
InputStream stream=null;
try {
stream = new FileInputStream(filestream);
file = new DefaultStreamedContent(stream, "application/pdf", "temp.pdf");
stream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> getListfiles() {
File folder = new File("c:\\");
File[] listOfFiles = folder.listFiles();
listfiles=Arrays.asList(listOfFiles);
int i;
for(i=0;i<listfiles.size();i++){
System.out.println("The List of file are"+listfiles.get(i));
listfiles.get(i);
}
return listfiles;
}
public void setListfiles(List<File> listfiles) {
this.listfiles = listfiles;
}
public String getFileName() {
getListfiles();
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public StreamedContent getFile() {
return this. file;
}
}
My XHTML looks like this.
<h:form id="form">
<h:dataTable value="#{fileDownloadController.listfiles}" var="x"
bgcolor="#F1F1F1" border="10" cellpadding="5"
cellspacing="3" first="0" rows="4" width="50%"
summary="This is a JSF code to create dataTable.">
<h:column>
<f:facet name="header">
<h:outputText value="File Names"></h:outputText>
</f:facet>
<h:commandLink value="#{x.fileName}" onclick="PrimeFaces.monitorDownload(showStatus, hideStatus)">
<p:fileDownload value="#{fileDownloadController.file}" />
</h:commandLink>
</h:column>
</h:dataTable>
</h:form>
I am not able to figure out where i went Wrong.Please help me.
How did you come to using #{x.fileName}? Look carefully in the javadoc of the java.io.File class. Right, there's no such method like getFileName(). That's exactly what the exception is trying to tell you.
value="#{x.fileName}": Property 'fileName' not found on type java.io.File
Most likely you meant to use the getName() method instead.
#{x.name}
Unrelated to the concrete problem, your code would be more self-documenting if you used var="file" instead of the nonsensicial var="x".