how to create CXF API for jbilling integration? - cxf

Can anyone tell me how to create CXF API? For jbilling integration, I want to create CXF API. But I don't know how to create it.

you can create a class in jbilling which call other evn and send headers and body as Json or string.
like this.
package com.cycle30.plugin.payment;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.log4j.Logger;
public class HttpJMSClient {
private PostMethod postMethod;
private String webUrl;
private List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
private static final Logger logger = Logger.getLogger(HttpJMSClient.class);
public HttpJMSClient() {
// TODO Auto-generated constructor stub
}
public void getConnection()
{
webUrl="http://localhost:8081";
nameValuePairs.add(new NameValuePair("x-force-user-id","abc1233"));
nameValuePairs.add(new NameValuePair("x-trans-id","123"));
}
public String makeCall( String body)
{
Object output=null;
try{
WebClient client = WebClient.create(webUrl);
for (NameValuePair h : nameValuePairs) {
client.header(h.getName(), h.getValue());
}
Response response = client.type(MediaType.APPLICATION_JSON).post(body,
Response.class);
logger.debug("Output from Server .... \n");
output = response.getEntity();
logger.debug(output);
System.out.println("my res: "+output.toString());
int statusCode = response.getStatus();
System.out.println("status code: "+statusCode);
return output.toString();
}catch(Exception e){
logger.error(e.getMessage());
logger.error(e.getCause());
}
return output.toString();
}
}

Related

How to fetch the uploaded file path as response from rest-api call

I have a reactjs page that uploads a file to server. The server is just a spring-boot app that hosts rest api to serve the upload. Once the file is uploaded, i want to return the absolute path of the uploaded file as part of my response. I am able to achieve that as well but the response body shows just ReadableStream when i console logged it. I am not getting the actual path of the file that am setting in spring before sending out the response.
I Have tried to set the response entity object with body containing the response json in string format.
React Code:
import React from 'react';
class UploadImage extends React.Component{
constructor(props){
super(props);
this.state={
uploadData:''
}
this.handleFileUpload=this.handleFileUpload.bind(this);
}
handleFileUpload=(event)=>{
event.preventDefault();
//alert('uploaded file')
//console.log(this.uploadedFile.files[0]);
const data = new FormData();
data.append('uploadedFile',this.uploadedFile.files[0]);
fetch('http://localhost:8080/laptops/upload',{
method:'POST',
body:data
}).then((response) => {
console.log(response);
console.log(response.json);
});
}
render(){
return (
<div>
<form onSubmit={this.handleFileUpload}>
<input type='file' ref={(ref)=>{this.uploadedFile=ref}}/>
<input type='submit' value='upload'/>
</form>
</div>
);
}
}
export default UploadImage;
Boot code: (only look into the post mapping function)
package react.demo.app;
import oracle.jdbc.proxy.annotation.Post;
import org.apache.commons.io.FilenameUtils;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.persistence.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
#Entity
class Laptop{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String brand;
private double price;
private String image;
public Laptop(){
}
public Laptop(String name,String brand,double price,String image){
this.name=name;
this.brand=brand;
this.price=price;
this.image=image;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
#Repository
interface LaptopRepository extends JpaRepository<Laptop,Long>{}
#Service
class LaptopService{
#Autowired
LaptopRepository laptopRepository;
public void addLaptop(Laptop laptop){
laptopRepository.save(laptop);
}
public Laptop getLaptopById(long id){return laptopRepository.getOne(id); }
public List<Laptop> getAllLaptops(){
return laptopRepository.findAll();
}
}
#RestController
#RequestMapping("/laptops")
class LaptopApi{
#Autowired LaptopService laptopService;
private String uploadDir = "C:\\Users\\rajen\\Development\\upload_images\\";
#CrossOrigin(origins = "http://localhost:3000")
#GetMapping(value="/",produces="application/json")
public List<Laptop> getAllLaptops(){
return laptopService.getAllLaptops();
}
#CrossOrigin(origins = "http://localhost:3000")
#PostMapping(value = "/upload")
public ResponseEntity upload(#RequestParam("uploadedFile") MultipartFile uploadedFile) throws IOException {
System.out.println("invoked upload");
File f = new File(uploadDir+uploadedFile.getOriginalFilename());
uploadedFile.transferTo(f);
System.out.println("return uploaded file:"+f.toURI());
HttpHeaders responseHeaders = new HttpHeaders();
return ResponseEntity.ok().headers(responseHeaders).body("{uploadedfile:"+f.getAbsolutePath()+"}");
}
#GetMapping(value="/getLaptopById",produces="application/json")
public Laptop getLaptopById(#RequestParam long id){
System.out.println("laptop by id:"+id);
return laptopService.getLaptopById(id);
}
#PostMapping(value="/addLaptop")
public void addLaptop(#RequestBody Laptop laptop){
laptopService.addLaptop(laptop);
}
}
#SpringBootApplication
public class AppApplication implements CommandLineRunner {
#Autowired LaptopService laptopService;
public static void main(String[] args){
SpringApplication.run(AppApplication.class,args);
}
#Override
public void run(String... args) throws Exception {
Laptop laptop = new Laptop("Dell Inspiron","Dell",new Double(25990),"https://i.pinimg.com/564x/4a/bb/86/4abb8659d4d951a6fefefe401a02aeb7.jpg");
laptopService.addLaptop(laptop);
System.out.println("Laptop Added");
}
}
i expect to see the file path as part of the response body but am getting only Readablestream as the body.
Refer to console log here
Assuming you are receiving a json payload, you need to call the .json() method method on the promise to extract the body data, and return that value (as opposed to just .json, an attempt to access property on the response). Alternatively, if the body data is simply text -- which it may be given the value you are attempting to return, you may need to call the .text() method.
fetch('http://localhost:8080/laptops/upload', {
method:'POST',
body:data
}).then((response) => {
return response.json();
}).then(finalRes => console.log(finalRes))
.catch(e)
}

Spring Boot OAuth2 - authenticate with Facebook using custom filter

I am working on Rest Api, I want to implement facebook Login/Signup in my application.
My client is angularjs based application that sends request to facebook and get the authentication code, so far I have used custom filter that calls facebook and fetches user data after validating the Access Token.
I can now get the user details from Facebook and persist in my local database, but when i try to signup from my application for it moves to the custom filter that i made for facebook integration.Here is my SecurityConfiguration.java
package io.aurora.ams.config;
import io.aurora.ams.security.AuthoritiesConstants;
import io.aurora.ams.web.filter.MDCFilter;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import javax.inject.Inject;
import static io.aurora.ams.sharedkernel.support.RestPath.*;
#Configuration
#EnableWebSecurity(debug = true)
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#ImportResource("classpath:acl-config.xml")
#SuppressWarnings("ALL")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
#Bean
public AuthFilter authFilter()
{
return new AuthFilter();
}
#Inject
private UserDetailsService userDetailsService;
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
#Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
public MDCFilter mdcFilter()
{
return new MDCFilter();
}
#Bean
public FilterRegistrationBean mySecurityFilter()
{
FilterRegistrationBean registration = new FilterRegistrationBean(authFilter());
registration.setOrder(10);
return registration;
}
#Override
public void configure(WebSecurity web) throws Exception
{
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers(API_VERSION_1_ACCOUNT_REGISTER_PATIENT)
.antMatchers(API_VERSION_1_ACCOUNT_ACTIVATE)
.antMatchers(API_VERSION_1_ACCOUNT_RECOVER_PASSWORD)
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
#Override
#Order(Ordered.HIGHEST_PRECEDENCE)
public void configure(HttpSecurity http) throws Exception
{
http
.addFilterBefore(authFilter(), OAuth2ClientAuthenticationProcessingFilter.class)
.addFilterAfter(mdcFilter(), SecurityContextPersistenceFilter.class)
.httpBasic().realmName("pliro")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").permitAll()
.antMatchers("api/v1/auth/facebook").permitAll()
.antMatchers("api/v1/code").permitAll()
.and()
.authorizeRequests()
.antMatchers(API_VERSION_1_DOCTOR).permitAll()
.antMatchers(API + "/**").authenticated();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension()
{
return new SecurityEvaluationContextExtension();
}
}
This is my CustomFilter AuthFilter.java
package io.aurora.ams.config;
import io.aurora.ams.account.domain.model.user.User;
import io.aurora.ams.account.dto.UserDTO;
import io.aurora.ams.account.mapper.UserMapper;
import io.aurora.ams.account.repository.UserRepository;
import io.aurora.ams.sharedkernel.domain.model.Gender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.InvalidAuthorizationException;
import org.springframework.social.connect.Connection;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.inject.Inject;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by ozair on 16/6/16.
*/
#Component
public class AuthFilter extends OncePerRequestFilter
{
#Autowired
private UserRepository userRepository;
#Autowired
private FacebookConnectionFactory facebookConnectionFactory;
#Inject
private UserMapper userMapper;
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException
{
String xAuth = request.getHeader("fbToken");
try
{
User user = validateToken(xAuth);
// Create our Authentication and let Spring know about it
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
catch (InvalidAuthorizationException ex)
{
logger.error(ex.getMessage());
}
filterChain.doFilter(request, response);
}
private User validateToken(String fbToken)
{
AccessGrant accessGrant = new AccessGrant(fbToken);
Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);
org.springframework.social.facebook.api.User fbUser = connection.getApi().userOperations().getUserProfile();
String facebookId = fbUser.getId();
User user = userRepository.findBySocialId(facebookId);
if (user == null)
{
User userByEmail = userRepository.findByEmail(fbUser.getEmail());
if (userByEmail != null)
{
userByEmail.setSocialAccessGrant(accessGrant.getAccessToken());
userByEmail.setSocialId(facebookId);
userRepository.save(userByEmail);
return userByEmail;
}
else
{
String firstName = fbUser.getFirstName();
String lastName = fbUser.getLastName();
String email = fbUser.getEmail() == null ? "" : fbUser.getEmail();
UserDTO userDTO = new UserDTO();
userDTO.setFirstName(firstName);
userDTO.setLastName(lastName);
userDTO.setEmail(email);
userDTO.setPassword("123456");
userDTO.setPhoneNumber("03222211112");
userDTO.setGender(Gender.MALE);
userDTO.setSocialId(facebookId);
userDTO.setAccessGrant(accessGrant);
User userData = userMapper.userDTOtoUser(userDTO);
userRepository.save(userData);
return userData;
}
}
else
{
//update fbToken if not the same
if (user.getSocialAccessGrant() != null
&& !user.getSocialAccessGrant().equals(accessGrant.getAccessToken()))
{
user.setSocialAccessGrant(accessGrant.getAccessToken());
userRepository.save(user);
}
return user;
}
}
}

How to use #DataProvider in TestNG

package com.xchanging.selenium.testcases.testng;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.xchanging.selenium.utility.CaptureScreenShot;
import com.xchanging.selenium.utility.ClearText;
import com.xchanging.selenium.utility.ClickEvent;
import com.xchanging.selenium.utility.GlobalVariables;
import com.xchanging.selenium.utility.ReadRows;
import com.xchanging.selenium.utility.SelectCheckBox;
import com.xchanging.selenium.utility.SelectDropDown;
import com.xchanging.selenium.utility.Text;
import com.xchanging.selenium.utility.VerifyText;
public class RegisterAccount extends GlobalVariables {
#Test(dataProvider = "getData")
public static void register() throws IOException {
ClickEvent.clickAt("createAccount_xpath");
Text.enterText("username_name", "username");
Text.enterText("password_name", "machans");
Text.enterText("confirmPassword_name", "machans");
ClickEvent.clickAt("securityquestion_name");
SelectDropDown.select("securityquestion_name", "petname");
Text.enterText("securityanswer_xpath", "vsbhss");
Text.enterText("fullName_name", "Chandrasekaran");
Text.enterText("email_name", "xx#gmail.com");
ClearText.clear("dob_name");
Text.enterText("dob_name", "11/11/1982");
SelectDropDown.select("gender_name", 1);
SelectDropDown.select("marital_name", 1);
SelectDropDown.select("country_name", "India");
SelectCheckBox.selectchkbox("checkbox_xpath");
ClickEvent.clickAt("register_xpath");
VerifyText.verify("Congratulations.. You have registered successfully");
VerifyText.verify("Login now");
CaptureScreenShot.screenshot("Registration_Successful");
ClickEvent.clickAt("closebutton_xpath");
}
#DataProvider
public ArrayList<HashMap> getData() throws IOException {
ArrayList<HashMap> table = ReadRows.readExcel("Sheet1");
return table;
}
}
Now I wanted to use this DataProvider and get values from xls and have to use it in my #Test Part.
Can any one help out???
If I use, this way it is working fine..
ArrayList<HashMap> table = ReadRows.readExcel("Sheet1");
table.get(0).get("email")
But I wanted to use #DataProvider..
Some How managed..
#Test(dataProvider="getData")
public static void register(ArrayList<HashMap> table) throws IOException {
}
This solves my problem.
If you want to use dataProvider annotation. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method.
You can try something like this:
#DataProvider
public Object[][] getData() throws IOException {
Object[][] data = new Object[3][2] // based on the size of your excel rows & cols.
// Write the code to read data from excel and store.
data[][] = //your Code.
return data;
}
And your test method can use the data.
//Lets say your Object[][] data returns 2 arguments.
#Test(dataProvider="getData")
public void testMethod(firstArgument, secondArgument){
// your code to use the arguments supplied by data.
}

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

JSF file upload on GAE

I'm trying to have a file upload element in my JSF over Google App Engine.
I have browsed the web for several alternatives but none seem to work with GAE.
I was able to do so using JSP and servlet with BlobstoreService but couldn't find a way to make it working with JSF.
As a workaround I was trying to see if there is a way to include a JSP within a JSF but I guess this isn't doable as well.
Would be thankful to get a working example.
Thanks!
First get library http://code.google.com/p/gmultipart/ and add to your project.
And than override class org.primefaces.webapp.filter.FileUploadFilter (just put in your src).
There is code of class org.primefaces.webapp.filter.FileUploadFilter:
package org.primefaces.webapp.filter;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.gmr.web.multipart.GFileItemFactory;
import org.primefaces.webapp.MultipartRequest;
public class FileUploadFilter implements Filter {
private final static Logger logger = Logger.getLogger(FileUploadFilter.class.getName());
private final static String THRESHOLD_SIZE_PARAM = "thresholdSize";
private final static String UPLOAD_DIRECTORY_PARAM = "uploadDirectory";
private String thresholdSize;
private String uploadDir;
public void init(FilterConfig filterConfig) throws ServletException {
thresholdSize = filterConfig.getInitParameter(THRESHOLD_SIZE_PARAM);
uploadDir = filterConfig.getInitParameter(UPLOAD_DIRECTORY_PARAM);
if(logger.isLoggable(Level.FINE))
logger.fine("FileUploadFilter initiated successfully");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
if(isMultipart) {
if(logger.isLoggable(Level.FINE))
logger.fine("Parsing file upload request");
//start change
FileItemFactory diskFileItemFactory = new GFileItemFactory();
/* if(thresholdSize != null) {
diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
}
if(uploadDir != null) {
diskFileItemFactory.setRepository(new File(uploadDir));
}*/
//end change
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);
if(logger.isLoggable(Level.FINE))
logger.fine("File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");
filterChain.doFilter(multipartRequest, response);
} else {
filterChain.doFilter(request, response);
}
}
public void destroy() {
if(logger.isLoggable(Level.FINE))
logger.fine("Destroying FileUploadFilter");
}
}
In managed bean write method like:
public void handleFileUpload(FileUploadEvent event) {
UploadedFile uploadedFile = event.getFile();
try {
String blobKey = BlobUtils.uploadImageToBlobStore(uploadedFile.getContentType(), uploadedFile.getFileName(), uploadedFile.getContents());
this.iconKey = blobKey;
} catch (IOException e) {
log.log(Level.SEVERE, "Ошибка при попытке загрузить файл в blob-хранилище", e);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ошибка при попытке загрузить файл", event.getFile().getFileName() + " не загружен!");
FacesContext.getCurrentInstance().addMessage(null, msg);
return;
}
FacesMessage msg = new FacesMessage("Успешно.", event.getFile().getFileName() + " загружен.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
And that all.
First of all , I think that whatever you are doing with JSP should eventually work with JSF as well..
BUT,
If you are looking for a file upload component for JSF , that works on GAE ,
take a look at the PrimeFaces FileUpload
Here is another link that got an explanation on what to do in order it to work on GAE :Primefaces File Upload Filter
(haven't tried it myself...)

Resources