JSF file upload on GAE - google-app-engine

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...)

Related

Whitelabel Error Page error (Spring Boot + React)

localhost:9000 is opening fine on the browser. And if I navigate to a link from the menu like localhost:9000/about, it is working fine.
But if I hit localhost:9000/about directly without going to localhost:9000 then nothing happens on the local and if I do the same on server, following error is produced:
Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback.
Mon Feb 12 14:09:05 IST 2018 There was an unexpected error (type=Not
Found, status=404). No message available
Please help!!
This is happening because in your application you have not defined what your application should do when it will get url request localhost:9000.
For every Request mapping you need to define the operation you want to perform. In your case for localhost:9000 you have to write what you want to do as you have done for local:9000/about.
#RequestMapping("")
#ResponseBody
Function_For_HandlingRequest{}
When you hit http://localhost:9090/about directly, SpringBoot redirect To a /login.html.
So, Redirect every page to index.html .
https://github.com/geowarin/boot-react/blob/master/backend/src/main/java/react/config/SinglePageAppConfig.java
The WebMvcConfigurer interface, starting with Spring 5, contains default implementations for all its methods. As a result, the abstract adapter (WebMvcConfigurerAdapter) class was marked as deprecated.
package your.package.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Redirects every page to index.html
* Used to handle the router
*/
#Configuration
public class SinglePageAppConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.resourceChain(false)
.addResolver(new PushStateResourceResolver());
}
private class PushStateResourceResolver implements ResourceResolver {
private Resource index = new ClassPathResource("/static/index.html");
private List<String> handledExtensions = Arrays.asList("html", "js", "json", "csv", "css", "png", "svg", "eot", "ttf", "woff", "appcache", "jpg", "jpeg", "gif", "ico");
private List<String> ignoredPaths = Arrays.asList("api");
#Override
public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
return resolve(requestPath, locations);
}
#Override
public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resolvedResource = resolve(resourcePath, locations);
if (resolvedResource == null) {
return null;
}
try {
return resolvedResource.getURL().toString();
} catch (IOException e) {
return resolvedResource.getFilename();
}
}
private Resource resolve(String requestPath, List<? extends Resource> locations) {
if (isIgnored(requestPath)) {
return null;
}
if (isHandled(requestPath)) {
return locations.stream()
.map(loc -> createRelative(loc, requestPath))
.filter(resource -> resource != null && resource.exists())
.findFirst()
.orElseGet(null);
}
return index;
}
private Resource createRelative(Resource resource, String relativePath) {
try {
return resource.createRelative(relativePath);
} catch (IOException e) {
return null;
}
}
private boolean isIgnored(String path) {
return ignoredPaths.contains(path);
}
private boolean isHandled(String path) {
String extension = StringUtils.getFilenameExtension(path);
return handledExtensions.stream().anyMatch(ext -> ext.equals(extension));
}
}
}
in Application
#Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
};
}
enter image description here

how to create CXF API for jbilling integration?

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();
}
}

Google App Engine (GAE) message.getContent() using javamail and IMAP not works

I have several days trying to get the contents of a message through IMAP on a Google App Engine Project.
I managed to extract all the other information, but to extract the contents of jumps me an error message (not work even invoking message.getContent.tostring(), I've tried as MultiPart).
I perform the same action from a normal project , (not GAE and using javamail.1.4.7), the content of the messages shown perfectly.
This is the code of GAE project:
import java.util.Properties;
import java.util.logging.Logger;
import javax.mail.Session;
import java.io.IOException;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Store;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class nuevo extends HttpServlet {
private String User;
private String Pass;
private static final Logger log = Logger.getLogger(nuevo.class
.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
User = "User";
Pass = "Pass";
LlamaIMAP(resp);
}
public void LlamaIMAP(HttpServletResponse resp) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap.host", "imap.gmail.com");
props.put("mail.imap.user", User);
props.put("mail.imap.socketFactory", 993);
props.put("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.imap.port", 993);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(User, Pass);
}
});
try {
Store store = session.getStore("imap");
store.connect("imap.gmail.com", 993, User, Pass);
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.HOLDS_MESSAGES);
// HOLDS_MESSAGES);
Message[] ar = fldr.getMessages();
int count = fldr.getMessageCount();
resp.getWriter().println(count);
resp.getWriter().println(ar[0].getAllRecipients()[0].toString());
resp.getWriter().println(ar[0].getFrom()[0].toString());
resp.getWriter().println(ar[0].getSentDate().toString());
resp.getWriter().println(ar[0].getSubject());
resp.getWriter().println(ar[0].getContent().toString());
} catch (Exception exc) {
try {
resp.getWriter().println(exc + "error");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I managed to fix it.
Only you need to add this lines to the appengine-web.xml configuration file:
<class-loader-config>
<priority-specifier filename="imap.jar"/>
<priority-specifier filename="gimap.jar"/>
<priority-specifier filename="dsn.jar"/>
<priority-specifier filename="mailapi.jar"/>
</class-loader-config>
Thanks.

Return wsdl in a servlet implemented SOAP Web Service

I am implementing a SOAP web service in GAE. Since GAE does not support JAX-WS I have chosen to go this way, which is basically building the soap requests and responses myself from a servlet.
Everything works fine but how can I achieve to return the wsdl description in http://myurl/MyService?wsdl ?
I guess I must implement the GET method of my servlet but how?
I have enclosed a working implementation. Note that it's based on Servlet 3.0 spec. If you are using 2.5, the annotations wont work.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="MyWSServlet", urlPatterns={"/MyService"})
public class MyWSServlet extends HttpServlet {
private static final long serialVersionUID = 3605874163075522777L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean requestForWSDL = false;
Enumeration<String> params = req.getParameterNames();
while (params.hasMoreElements()) {
if ("wsdl".equalsIgnoreCase(params.nextElement())) {
requestForWSDL = true;
}
}
if (requestForWSDL) {
FileInputStream wsdlInputStream = new FileInputStream(req.getServletContext().getRealPath("/wsdl/TemperatureService.wsdl"));
byte[] buffer = new byte[1024];
resp.setContentType("application/xml");
int bytesRead = 0;
while ((bytesRead = wsdlInputStream.read(buffer)) != -1) {
resp.getOutputStream().write(buffer, 0, bytesRead);
}
wsdlInputStream.close();
resp.getOutputStream().flush();
}
}
}

Reading in a file from google cloud storage using java

I am new to google cloud storage api, as well as using servers. I'm trying to write a web application in Java using Eclipse's IDE to read in a file that is stored in google's cloud storage. I have the code to read in the file on the server side, and am not sure how to modify the sample code on the client side so that it supports an httpServlet instead of a RemoteServiceServlet. Any help or suggestions would be greatly appreciated!
Below is my code on the server side.
package com.google.gwt.sample.interfacecloud.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.Channels;
import java.util.ArrayList;
import javax.servlet.http.*;
import com.google.gwt.sample.interfacecloud.client.GreetingService;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
#SuppressWarnings("serial")
public class CloudInteraction extends HttpServlet implements GreetingService{
public static final String BUCKETNAME = "obd_data";
public static final String FILENAME = "data.txt";
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
resp.setContentType("text/plain");
String filename = "/gs/" + BUCKETNAME + "/" + FILENAME;
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile readableFile = new AppEngineFile(filename);
FileReadChannel readChannel =
fileService.openReadChannel(readableFile, false);
BufferedReader reader =
new BufferedReader(Channels.newReader(readChannel, "UTF8"));
String line = reader.readLine();
resp.getWriter().println("READ:"+line);
System.out.println(line);
readChannel.close();
}
#Override
public String greetServer(String name) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
}
You are mixing and matching RPC with plain Servlets. You should not be doing that. Do away with RPC interfaces for such interactions if you intend to you plain Servlets. You would be better served with RequestBuilder in this scenario. Note - it is not very clear what your are requirements are?

Resources