i will have few multipart forms in jsp and have to process them using servlet. All work fine with the first form, but if i try to add switch in servlet's doPost method, it stops to recognize fields value: userName cannot be null.
jsp form:
<form action="ServletMultipartForm" method="post" name="Form" enctype="multipart/form-data">
<br>
<label>NAME</label><br>
<input type="text" name="instrName">
<label>IMAGE</label><br>
<input type="file" name="instrImage">
<input type="submit" value="Submit Instructor" name="action">
</form>
ServletMultipartForm.java
#MultipartConfig
public class ServletMultipartForm extends HttpServlet {
private final String UPLOAD_DIRECTORY = "F:/OLD/JAVAJSP - Copy/PROGRAMMING_ASSIGNMENT3/ASpace/web/img/instructors";
String userImage = null;
String userName = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(ServletMultipartForm.class.getName()).log(Level.SEVERE, null, ex);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
if (fieldname.equalsIgnoreCase("instrName")) {
userName = fieldvalue;
}
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List<FileItem> multiparts = upload.parseRequest(request);
userImage = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + userImage));
System.out.println("User Image Name " + userImage);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
} catch (Exception ex) {
Logger.getLogger(ServletMultipartForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
User in=new User(userName, userImage);
UserDB.insert(in);
String FeedbackMessage = "New Instructor " + in.getUserName()+" was added";
request.setAttribute("FeedbackMessage", FeedbackMessage);
getServletContext()
.getRequestDispatcher("/adminPanel.jsp")
.forward(request, response);
gotoPage("/adminPanel.jsp", request, response);
}
private void gotoPage(String address, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
I have tried to add switch statement depending on "action", smth:
String selection = request.getParameter("action");
but then start to get that error: userName cannot be null.
Thanks for any advice.
Related
We have a requirement as below
Integration System needs to call our service
Our service needs to call FlipKart service appending the token in the request
Get the response back to Integration system
The above should work seamlessly for both GET and PUT requests.
I had developed a REST-project in eclipse and was able to get the GET and PUT response back to Integration.
However have few problems
In Get Requests, we are explicitly setting the headers and produces annotation to appication/json. How do we set it for all kind of requests?
In Post Response, we do not get the entire response and we are not able to set the application type in the response (Not sure how!)
All these requests are failing if the application type is pdf, img etc.
Can someone please help on the same?
Code implemented so far:
#GET
#Path("{pathvalue : (.+)?}")
#Produces("{application/json;application/octet-stream}")
public String getFlipKartResponse(#Context UriInfo uriInfo, #PathParam("pathvalue") String pathValue, #Context HttpServletRequest request) throws ClassNotFoundException,IOException {
String methodName = "getFlipKartResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
//if(null == flipkartUrl || flipkartUrl.isEmpty())
flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
String queryParam = new String();
Iterator<String> iterator = queryParams.keySet().iterator();
while (iterator.hasNext()) {
String parameter = iterator.next();
queryParam = queryParam.concat(parameter + ServiceConstants.EQUALS + queryParams.getFirst(parameter) + ServiceConstants.AMPERSAND);
}
String modifiedflipkartUrl = flipkartUrl.concat(pathValue).concat(ServiceConstants.QUESTION).concat(queryParam);
if (modifiedflipkartUrl.endsWith(ServiceConstants.QUESTION) || modifiedflipkartUrl.endsWith(ServiceConstants.AMPERSAND)) {
modifiedflipkartUrl = modifiedflipkartUrl.substring(0, modifiedflipkartUrl.length()-1);
}
LOGGER.log(Level.INFO, "Flipkart URL framed : "+ modifiedflipkartUrl);
url = new URL(modifiedflipkartUrl);
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, request.getMethod());
return handleInvalidToken(connection.getResponseCode(), request);
}
private String handleInvalidToken(int responseCode, HttpServletRequest request){
try {
if (connection.getResponseCode() == 401) {
LOGGER.log(Level.INFO, "ResponseCode " + connection.getResponseCode());
connection.disconnect();
regenerateAccessToken();
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, request.getMethod());
inputLine = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else if (connection.getResponseCode() == 200) {
inputLine = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
inputLine = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String responseInputLine;
String responseMessage = "";
while (null != (responseInputLine = inputLine.readLine())) {
responseMessage = responseMessage + responseInputLine;
}
inputLine.close();
connection.disconnect();
return responseMessage;
} catch (Exception e) {
LOGGER.log(Level.SEVERE,"Exception occured while calling service.Please try again after sometime : ", e);
return this.handleErrorResponse("Exception occured while calling service.Please try again after sometime.");
}
}
private void regenerateAccessToken() throws ClassNotFoundException, IOException, SQLException{
TokenGenerator tokenGenerator = new TokenGenerator();
accessToken= tokenGenerator.getAccessToken();
}
#POST
#Path("{pathvalue : (.+)?}")
#Produces({"application/json;application/octet-stream"})
public String getFlipKartPostResponse(#Context UriInfo uriInfo, #PathParam("pathvalue") String pathValue,#Context HttpServletRequest requestBody) throws ClassNotFoundException,IOException, SQLException {
String methodName = "getFlipKartPostResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
//if(null == flipkartUrl || flipkartUrl.isEmpty())
flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
String modifiedflipkartUrl = flipkartUrl + pathValue;
url = new URL(modifiedflipkartUrl);
LOGGER.log(Level.INFO, "Flipkart URL framed : "+ flipkartUrl);
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, requestBody.getMethod());
InputStream requestInputStream = requestBody.getInputStream();
String reqBody = getStringFromInputStream(requestBody.getInputStream());
OutputStream outputStream = connection.getOutputStream();
outputStream.write(reqBody.getBytes());
outputStream.flush();
if(connection.getResponseCode() == 401) {
connection.disconnect();
regenerateAccessToken();
connection = (HttpsURLConnection) url.openConnection();
setHeadersInConnectionObject(url, connection, requestBody.getMethod());
outputStream = connection.getOutputStream();
outputStream.write(reqBody.getBytes());
outputStream.flush();
}
String output = getStringFromInputStream (connection.getInputStream());
connection.disconnect();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return output;
}
private static String getStringFromInputStream(InputStream is) {
String methodName = "getStringFromInputStream";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return sb.toString();
}
/**
* Method to generate the access token
* #return String - Access token
* #throws IOException
*/
private String getAccessToken() throws IOException {
if (null != accessToken) {
return accessToken;
} else {
url = getClass().getResource(ServiceConstants.ACCESS_TOKEN_CONFIG_PATH);
file = new File(url.getPath());
reader = new BufferedReader (new InputStreamReader (new FileInputStream (file), ServiceConstants.UTF_ENCODING));
accessToken = reader.readLine();
reader.close();
return accessToken;
}
}
/**
* Method to construct error response for exception scenario
* #param errorMessage
* #return
*/
private String handleErrorResponse(String errorMessage) {
String methodName = "handleErrorResponse";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
JSONObject errorResponse = new JSONObject();
JSONArray errorMsg = new JSONArray();
errorResponse.put(ServiceConstants.STATUS, ServiceConstants.STATUS_FAILED);
errorResponse.put(ServiceConstants.ERROR_MESSAGE, errorMessage);
errorMsg.add(errorResponse);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
return errorResponse.toString();
}
/**
* Method to form the connection object
* #param url
* #param connection
* #param requestType
* #throws IOException
*/
private void setHeadersInConnectionObject(URL url, HttpsURLConnection connection, String requestType) throws IOException {
String methodName = "setHeadersInConnectionObject";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.entering(CLASSNAME, methodName);
}
if (null == accessToken) {
getAccessToken();
}
connection.setRequestMethod(requestType);
connection.setRequestProperty(ServiceConstants.AUTHORIZATION, ServiceConstants.BEARER + accessToken);
connection.setDoOutput(true);
if (requestType.equals(ServiceConstants.REQUEST_TYPE_GET)) {
connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.ACCEPT_ALL);
//connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
}
if (requestType.equals(ServiceConstants.REQUEST_TYPE_POST)) {
connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
connection.setRequestProperty(ServiceConstants.CONTENT_TYPE_HEADER, ServiceConstants.APPLICATION_JSON);
//connection.setDoInput(true);
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.exiting(CLASSNAME, methodName);
}
}
I have a trouble with output data in response.
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse response = new ResourceResponse();
response.setContentDisposition(ContentDisposition.INLINE);
response.disableCaching();
StringBuilder stringBuilder = new StringBuilder(DEFAULT_CONTENT_TYPE);
stringBuilder.append(";").append(charset == null ? DEFAULT_CHARSET : charset);
response.setContentType(stringBuilder.toString());
response.setLastModified(Time.now());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
fillOutputStream(outputStream);
} catch (IOException e) {
logger.error("Error when try to fill data for html report", e);
}
String message = null;
try {
message = outputStream.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Unknown encoding");
message = outputStream.toString();
}
final CharSequence data = message;
response.setContentLength(data.length());
response.setWriteCallback(new WriteCallback() {
#Override
public void writeData(Attributes attributes) {
attributes.getResponse().write(data);
}
});
configureResponse(response, attributes);
return response;
}
Here data is html page which has been generated in fillOutputStream() method and transform to CharSequence.
I've logged the data and it have correct content which I expect but in the result I have trimmed at the end page.
The length of String is not necessarily equal to its byte count.
Use a CountingOutputStream instead (e.g. from guava).
I'm having problems to figure out this problem. The exception is thrown when I try to go to /users/add url which should show the empty form for creating user entry. After that this exception is propagated throught the whole application.
Here is the controller code:
#Controller
#SessionAttributes(value = "user")
#RequestMapping(value = "/users")
public class UserController {
#Inject
private UserService userService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getAllUsers() {
List<User> users = userService.getAllUsers();
return new ModelAndView("allUsers", "users", users);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addUser(ModelMap map, #RequestParam(value = "id", required = false) Long id) throws EntityNotFoundException {
User user = null;
if(id != null) {
user = userService.findById(id);
if(user == null)
throw new EntityNotFoundException("Can't find user!");
}
else {
user = new User();
user.setGender(Gender.MALE);
}
map.addAttribute("genders", generateGenders());
return new ModelAndView("addUser", "user", user);
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView addUser(ModelMap map, #Valid #ModelAttribute(value = "user") User user, BindingResult result,
HttpServletResponse response, final RedirectAttributes redirectAttributes) throws IOException {
if(!result.hasErrors()) {
try {
String userStatus = user.getId() != null ? "User Updated: " : "User Created: ";
userService.saveOrUpdateUser(user);
redirectAttributes.addFlashAttribute("userStatusMessage", userStatus + user.toString());
return new ModelAndView(new RedirectView("/users"));
} catch (EntityNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
return null;
}
}
else {
for (ObjectError error : result.getAllErrors()) {
System.out.println(error.getObjectName() + ": " + error.getDefaultMessage());
}
}
map.addAttribute("genders", generateGenders());
return new ModelAndView("addUser", "user", user);
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView deleteUser(#RequestParam(value = "id", required = true) Long id,
HttpServletResponse response, final RedirectAttributes redirectAttributes) throws IOException {
try {
User user = userService.deleteUser(id);
redirectAttributes.addFlashAttribute("userStatusMessage", "Deleted User: " + user);
} catch (EntityNotFoundException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return null;
}
return new ModelAndView(new RedirectView("/users"));
}
private Map<String, String> generateGenders() {
Map<String,String> genders = new HashMap<String,String>();
for (Gender gender : Gender.values()) {
genders.put(gender.toString(), gender.getDisplayName());
}
return genders;
}
}
And here is the error I get when I go to /users/add:
HTTP ERROR 500
Problem accessing /users/add. Reason:
Server Error
Caused by:
java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at com.code9.data.User.toString(User.java:157)
at java.lang.String.valueOf(String.java:2854)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:146)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:533)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:475)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:514)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:920)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:403)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:184)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:856)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:247)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:151)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:114)
at org.eclipse.jetty.server.Server.handle(Server.java:352)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:596)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1049)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:590)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:212)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:426)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:510)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.access$000(SelectChannelEndPoint.java:34)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:450)
at java.lang.Thread.run(Thread.java:744)
Any suggestions?
I have found the problem. It's inside toString() method of User class. I'm still not shure when it's called, because I don't call it explicitly. Sorry for inconvenience.
This is User toString() method before:
#Override
public String toString() {
return String.format("%d, %s %s, %s, %s, %s, %s", this.getId(), this.getFirstName(), this.getLastName(),
new SimpleDateFormat("yyyy-MM-dd").format(this.getBirthday()), this.getGender().getDisplayName(), this.getPersonalNumber(),
this.getEmail());
}
And this is a fix:
#Override
public String toString() {
return String.format("%d, %s %s, %s, %s, %s, %s", this.getId(), this.getFirstName(), this.getLastName(),
this.getBirthday() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(this.getBirthday()), this.getGender().getDisplayName(), this.getPersonalNumber(),
this.getEmail());
}
I'm trying to do a 'login with facebook' button, which works ok, but I would like to redirect to another page with the user data filled in a form.
SocialFacebook Controller
public void login(){
try {
//Create an instance of SocialAuthConfig object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load();
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
String successUrl = "http://localhost:8080/cc/pages/system/register.xhtml";
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl("facebook", successUrl);
// Store in session
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.setAttribute("authManager", manager);
//after check out in facebook, redirect to the proper page
logged();
//redirect to the successful login page
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So when the user hit the button, 'log in with facebook' in my index.xhtml:
<h:body>
<h:form id="login-facebook">
<h:commandButton id="login" action="#{socialFacebook.login}" value="Login"/>
</h:form>
</h:body>
It redirects to register.xhtml page with the URL like this:
http://localhost:8080/cc/pages/system/register.xhtml?code=AQC_3oCPjlyvZ51dpzxVdBNS1JfgwwZluBSduU7FG01esgVQT6Qxq8gWYRUsGz64aXDvXB1195m0CHZGmdvsmjLxtmbuUSSSqH7i49pcb6g9Begt4Yol1rqWFQGGGGGGGGGGGJ9mlWiEq4Aknlh1J2su2a9l0GzyLB21J4BgNgfBw3DUtwn-RkT00E7BsFpISiXKE7EVsT5NgxPBtOWIUY#_=_
The thing is now, I would like to get this code in my bean and do the checking and fill the form in register.xhtml
So I create this method at the same bean :
private void logged(){
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
try {
// get the auth provider manager from session
if (manager != null){
// call connect method of manager which returns the provider object.
// Pass request parameter map while calling connect method.
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
session.setAttribute("profile", p);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But it I'm not able to get the parameter code from my request.
How can I get this code, do the checking and fill the form after that ?
**
EDIT
SocialFacebook.java
package jpa.control;
// imports..
#ManagedBean(name="socialFacebook")
#RequestScoped
public class SocialFacebook implements Serializable{
private static final long serialVersionUID = -4787254243136316495L;
#ManagedProperty("#{param.code}")
private String code;
public void login(){
try {
//Create an instance of SocialAuthConfig object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load();
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
String successUrl = "http://localhost:8080/cc/pages/system/register.xhtml";
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl("facebook", successUrl);
// Store in session
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.setAttribute("authManager", manager);
//after check out in facebook, redirect to the proper page
logged();
//redirect to the successful login page
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void logged(){
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
System.out.println("*******************************");
System.out.println(code); // keeps return NULL everytime
System.out.println("*******************************");
try {
// get the auth provider manager from session
if (manager != null){
// call connect method of manager which returns the provider object.
// Pass request parameter map while calling connect method.
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
session.setAttribute("profile", p);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Get's and Set's
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
I solve my problem creating a webfilter which gets the request and responde then I could fill the user date in my url and get then in my form page:
#WebFilter("/facebook/*")
public class LoginFilter implements Filter {
#EJB UserEAO userEAO;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
if (userEAO.find(p.getEmail()) == null){
response.sendRedirect
(
request.getContextPath() +
"/pages/system/register.xhtml?" +
"firstName=" + p.getFirstName()
);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my register page:
<ui:composition template="/resources/jsf/include/default.xhtml">
<ui:define name="title">
</ui:define>
<ui:define name="header">
</ui:define>
<ui:define name="content">
<h:form id="register_form">
<f:metadata>
<f:viewParam name="firstName" value="#{userc.userb.user.firstName}" />
</f:metadata>
Name: <h:message id="m_name" for="name" styleClass="red" />
<h:inputText id="name" value="#{userc.userb.user.firstName}">
<f:validateLength minimum="1" maximum="20" />
<f:ajax event="blur" render="m_name" />
</h:inputText>
i have created fileupload widget using UI.xml. Written Servlet. My servlet is calling but no file contents are retrieving. I have pasted my code here. can you please answer what is the problem and how to retrieve the contents? This is first time using this. Please let me know .
UI
<g:FormPanel ui:field="uploadDPAFormPanel">
<g:HorizontalPanel>
<g:Label> File
Upload: </g:Label>
<g:FileUpload ui:field="fileUpload" />
<g:Button ui:field="uploadButton" title="Upload"
Upload</g:Button>
</g:HorizontalPanel>
</g:FormPanel>
Following is my imple class:
#UiHandler("uploadButton")
void onClickUploadButton(ClickEvent event) {
GWT.log("You selected: " + fileUpload.getFilename(), null);
uploadDPAFormPanel.submit();
}
public void init() {
uploadDPAFormPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadDPAFormPanel.setMethod(FormPanel.METHOD_POST);
uploadDPAFormPanel.setAction(GWT.getHostPageBaseURL()
+ uploadServlet);
uploadDPAFormPanel.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
if (!"".equalsIgnoreCase(fileUpload.getFilename())) {
GWT.log("UPLOADING FILE????", null);
// NOW WHAT????
}
else{
GWT.log("UPLOA event cancel");
event.cancel(); // cancel the event
}
}
});
uploadDPAFormPanel
.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
//TODO need to write code to refresh the page
doAlert("Uploaded sucessfully");
}
});
}
Following is my servlet class:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
log.debug("UploadServlet upload:"+upload);
try {
FileItemIterator iter = upload.getItemIterator(request);
log.debug("UploadServlet iter:"+iter);
System.out.println("UploadServlet iter:"+iter);
while (iter.hasNext()) {
FileItemStream item = iter.next();
log.debug("UploadServlet iter:Field Name:"+item.getFieldName());
System.out.println(":Field Name:"+item.getFieldName());
System.out.println(":Name:"+item.getName());
System.out.println(":is form field:"+item.isFormField());
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10 * (1024 * 2); // 10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
You should set a name="..." on your FileUpload.