Struts2 request as null - struts2

Very strange error I have, I am getting request as null when I try to access it. I always used the same method to get it, but now I am having this error.
My Action look like this:
package com.deveto.struts.actions;
import com.deveto.hibernate.mappings.Slider;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;
/**
*
* #author denis
*/
public class ContentAction extends ActionSupport implements ServletContextAware {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
ActionContext ac = ActionContext.getContext();
ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
#Override
public String execute() throws Exception {
System.out.println("request: " + request);
return SUCCESS;
}
public ActionContext getAc() {
return ac;
}
public void setAc(ActionContext ac) {
this.ac = ac;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public ServletContext getSc() {
return sc;
}
public void setSc(ServletContext sc) {
this.sc = sc;
}
public void setServletContext(ServletContext sc) {
this.sc = sc;
}
}
And now I can't do nothing, the request is always null
request: null

Implement the ServletRequestAware Interface and set your request variable there instead of doing that during construction.
But normally you don't need access to the request as the params interceptor of struts does all the work the request object is needed for.
From the documentation of the ServletRequestAware-Interface:
All Actions that want to have access to the servlet request object must implement this interface.
This interface is only relevant if the Action is used in a servlet environment.
Note that using this interface makes the Action tied to a servlet environment, so it should be avoided if possible since things like unit testing will become more difficult.

Related

Whitelisting application properties in Spring Cloud Data Flow

When I create a custom app for SCDF I can, according to the reference define relevant properties that are visible through the dashboard when creating a new stream/task. I created a spring-configuration-metadata-whitelist.properties file like this:
configuration-properties.classes=com.example.MySourceProperties
configuration-properties.names=my.prop1,my.prop2
When I create a new stream definition through the dashboard all properties defined in com.example.MySourceProperties are displayed in the properties dialog, but my.prop1 and my.prop2 are not. Both properties aren't optional and must always be set by the user. How can I include them in the properties dialog?
This tells it which class to pull these properties from Task1 properties class
That we can use with "#EnableConfigurationProperties(Task1Properties.class) declaration
configuration-properties.classes=com.shifthunter.tasks.Task1Properties
Task1Properties.java
package com.shifthunter.tasks;
import org.springframework.boot.context.properties.ConfigurationProperties;
#ConfigurationProperties("pulldata-task")
public class Task1Properties {
/**
* The path to get the source doc from
*/
private String sourceFilePath;
/**
* The path to put the destination doc
*/
private String destinationFilePath;
/**
* Property to drive the exit code
*/
private String controlMessage;
public String getSourceFilePath() {
return sourceFilePath;
}
public void setSourceFilePath(String sourceFilePath) {
this.sourceFilePath = sourceFilePath;
}
public String getDestinationFilePath() {
return destinationFilePath;
}
public void setDestinationFilePath(String destinationFilePath) {
this.destinationFilePath = destinationFilePath;
}
public String getControlMessage() {
return controlMessage;
}
public void setControlMessage(String controlMessage) {
this.controlMessage = controlMessage;
}
}
ShiftHunterTaskPullDataApp.java
package com.shifthunter.tasks;
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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#EnableTask
#EnableConfigurationProperties(Task1Properties.class)
#SpringBootApplication
public class ShiftHunterTaskPullDataApp {
public static void main(String[] args) {
SpringApplication.run(ShiftHunterTaskPullDataApp.class, args);
}
#Bean
public Task1 task1() {
return new Task1();
}
public class Task1 implements CommandLineRunner {
#Autowired
private Task1Properties config;
#Override
public void run(String... strings) throws Exception {
System.out.println("source: " + config.getSourceFilePath());
System.out.println("destination: " + config.getDestinationFilePath());
System.out.println("control message: " + config.getControlMessage());
if(config.getControlMessage().equals("fail")) {
System.out.println("throwing an exception ...");
throw new Exception("I'm ANGRY");
}
System.out.println("pulldata-task complete!");
}
}
}
Sream Dataflow task-pull-data
app register --name task-pull-data --type task --uri maven://com.shifthunter.tasks:shifthunter-task-pulldata:jar:0.0.1-SNAPSHOT
task-pull-data - Details

How do I get Jersey to call a resource method with an HttpServletResponse wrapper?

I am trying to systematically address HTTP response splitting. I have developed a wrapper class for HttpServletResponse called HardenedHttpServletResponse that mitigates splitting attempts.
Regrettably, I cannot get Jersey to call my resource method with my HardenedHttpServletResponse. I get nulls when I try.
Here is a contrived JAX-RS resource with a HTTP response splitting vulnerability which is exploitable by putting percent-encoded CRLFs (%0d%0a) in the filename query parameter:
AttachmentResource.java:
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
#Path("/attachment")
#Produces(MediaType.APPLICATION_JSON)
public final class AttachmentResource {
#GET
#Path("/file")
public StreamingOutput getAttachment(
#Context HttpServletResponse response,
#QueryParam("filename") String filename
) throws Exception {
response.setHeader(
"content-disposition",
"attachment; filename=" + filename
);
return new DummyStreamingOutput();
}
}
Here is a dummy implementation of StreamingOutput to make it a somewhat full example:
DummyStreamingOutput.java:
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
private static DummyFileStreamingOutput implements StreamingOutput {
#Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
String message = "Hello, World!";
byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
}
Here is the HttpServletResponse wrapper class that mitigates HTTP response splitting by throwing an exception if it detects CR or LF characters in header names or values:
HardenedHttpServletResponse.java:
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.ws.rs.core.Context;
final class HardenedHttpServletResponse extends HttpServletResponseWrapper {
#Inject
HardenedHttpServletResponse(#Context HttpServletResponse response) {
super(response);
}
#Override
public void setHeader(String name, String value) {
mitigateResponseSplitting(name);
mitigateResponseSplitting(value);
super.setHeader(name, value);
}
#Override
public void addHeader(String name, String value) {
mitigateResponseSplitting(name);
mitigateResponseSplitting(value);
super.setHeader(name, value);
}
#Override
public void setIntHeader(String name, int value) {
mitigateResponseSplitting(name);
super.setIntHeader(name, value);
}
#Override
public void setDateHeader(String name, long date) {
mitigateResponseSplitting(name);
super.setDateHeader(name, date);
}
private void mitigateResponseSplitting(String value) {
if (value != null && (value.contains("\r") || value.contains("\n"))) {
throw new HttpResponseSplittingException();
}
}
}
Jersey supplies the actual response object if the response parameter has type #Context HttpServletResponse, but null if the response parameter has type #Context HardenedHttpServletResponse.
How do I get Jersey to call a resource method with an HttpServletResponse wrapper?
You can just make it injectable by adding it the DI system.
resourceConfig.register(new AbstractBinder() {
#Override
public void configure() {
bindAsContract(HardenedHttpServletResponse.class)
.proxy(false)
.proxyForSameScope(false)
.in(RequestScoped.class);
}
});
You will need to make the class public and also its constructor public, so that the DI system can create it. This will allow you to inject HardenedHttpServletResponse
See also:
Dependency injection with Jersey 2.0

which is better approach while getting data from server and display on list?

Hi can you please tell me which is a better approach while getting data from server and displaying on a list?
package mypackage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.ui.component.Dialog;
public class ConnectJson extends Thread {
private String url;
public String response;
private String myinterface = ";deviceside=true";
private JsonObserver observer;
public void run() {
HttpConnection conn = null;
InputStream in = null;
int code;
try {
conn = (HttpConnection) Connector.open(this.url + this.myinterface, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
code = conn.getResponseCode();
System.out.println("naveen-------------------------");
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
byte[] buffer = IOUtilities.streamToBytes(in);
this.response = new String(buffer,"UTF-8");
if (observer != null) {
observer.onResponseReceived(this.response);
}
if (in != null){
in.close();
}
if (conn != null){
conn.close();
}
}
} catch (Exception e) {
Dialog.inform(e.toString());
}
}
public String jsonResult(String url){
this.url = url;
this.start();
// this.run();
return response;
}
public void setObserver(JsonObserver o) {
this.observer = o;
}
}
package mypackage;
import java.util.Vector;
import xjson.me.JSONArray;
import xjson.me.JSONException;
import xjson.me.JSONObject;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements JsonObserver
{
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
ConnectJson connectJson = new ConnectJson();
System.out.println("------------------");
connectJson.setObserver(this);
connectJson.jsonResult("http://musicbrainz.org/ws/2/release/59211ea4-ffd2-4ad9-9a4e-941d3148024a?inc=artist-credits+labels+discids+recordings&fmt=json");
System.out.println("---------bbbbb---------");
}
public void onResponseReceived(String response) {
System.out.println("000000000000000000000000000000000"+response);
// TODO: create or update your ListField here!!!
}
}
package mypackage;
public interface JsonObserver {
public void onResponseReceived(String response);
}
Well, first of all, this will not work:
public String jsonResult(String url){
this.url = url;
this.start();
return response;
}
Calling start() will cause run() to be called on a background thread (that's good). However, immediately after you start the background thread, you return the response member variable. That won't work, because the run() method hasn't had time to actually assign the response variable.
What you need to do is assign the response variable at the end of the run() method, and then notify the UI on the main/UI thread, to let it update the user interface. Something like this:
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
byte[] buffer = IOUtilities.streamToBytes(in);
this.response = new String(buffer,"UTF-8");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// this code is run on the main/UI thread
if (observer != null) {
observer.onResponseReceived(this.response);
}
}
});
where you add a new observer interface
public interface JsonObserver {
public void onResponseReceived(String response);
}
and then you can let your MainScreen implement that interface:
public class MyScreen extends MainScreen implements JsonObserver {
public MyScreen()
{
connectJson.setObserver(this);
// start the json request
connectJson.jsonResult("http://musicbrainz.org/ws/2/release/59211ea4-ffd2-4ad9-9a4e-941d3148024a?inc=artist-credits+labels+d...");
}
public void onResponseReceived(String response) {
System.out.println("000000000000000000000000000000000"+response);
// TODO: create or update your ListField here!!!
}
Of course, you'll need a new member and method in the ConnectJson class, too:
private JsonObserver observer;
public void setObserver(JsonObserver o) {
observer = o;
}
Note: it also might be better, for thread safety, to change your response member variable to a simple local final variable. I can't know all the ways that you plan on using it, but if it's just a way to hold onto the JSON response, you probably don't need a member variable. Try this instead (inside of run()):
final String response = new String(buffer,"UTF-8");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
observer.onResponseReceived(response);

How to use open Id in jsp

Hi I am trying to build a login system like Stack Overflow but not find the right way to do this in JSP. I am working in struts2.
The following illustrate Single Sign On (SSO) using Oauth, for which you can create a SSO system similar to that of Stack Overflow.
Use scribe: https://github.com/fernandezpablo85/scribe-java/wiki/getting-started
The following example will demonstrate using Twitter...
1) Demonstrate an action to get twitter credentials.
package com.quaternion.struts2basic.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.SessionAware;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.Token;
import org.scribe.oauth.OAuthService;
#Results(value = {
#Result(name = "success", location = "${authorizationURL}", type = "redirect"),
#Result(name = "error", location = "/WEB-INF/content/error.jsp")
})
public class TwitterGrantAccess extends ActionSupport implements SessionAware {
private Map<String, Object> session;
private String authorizationURL = null;
#Override
public String execute() {
//Twitter twitter = new TwitterFactory().getInstance();
String consumer_key = "rUPV8tpIcFtyMeSDlnzclA";
String consumer_secret = "16omdjNoEYgwoXfZMc0XrXSxiHDaS0UZUxQzWhTFg";
OAuthService twitterService = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(consumer_key)
.apiSecret(consumer_secret)
.callback("http://127.0.0.1:8080/Struts2Basic/twitter-callback")
.build();
Token requestToken = twitterService.getRequestToken();
authorizationURL = twitterService.getAuthorizationUrl(requestToken);
session.put("twitterService", twitterService);
session.put("requestToken", requestToken);
return SUCCESS;
}
public String getAuthorizationURL() {
return this.authorizationURL;
}
#Override
public void setSession(Map<String, Object> map) {
this.session = map;
}
}
2) Action which twitter redirects back to...
package com.quaternion.struts2basic.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.SessionAware;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
#Results(value = {
#Result(name = "success", location = "/WEB-INF/content/twitter-callback-success.jsp"),
#Result(name = "error", location = "/WEB-INF/content/error.jsp")
})
public class TwitterCallback extends ActionSupport implements SessionAware {
private Map<String, Object> session;
private String key;
private String secret;
//returned from twitter
private String oauth_token;
private String oauth_verifier;
#Override
public String execute() {
if (session.containsKey("accessToken") && session.get("accessToken") != null) {
return SUCCESS; //accessToken already exists!
}
Token requestToken = (Token) session.get("requestToken");
if (requestToken == null) {
super.addActionError("requestToken is null");
return ERROR;
}
OAuthService twitterService = (OAuthService) session.get("twitterService");
System.out.println(requestToken.toString());
System.out.println(this.getOauth_verifier());
//Token accessToken = twitter.getOAuthAccessToken(requestToken, this.getOauth_verifier());
Token accessToken = twitterService.getAccessToken(requestToken, new Verifier(this.getOauth_verifier()));
session.put("accessToken", accessToken);
this.setKey(accessToken.getToken()); //just to see something happen
this.setSecret(accessToken.getSecret());//just to see something happen
return SUCCESS;
}
#Override
public void setSession(Map<String, Object> map) {
this.session = map;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getOauth_token() {
return oauth_token;
}
public void setOauth_token(String oauth_token) {
this.oauth_token = oauth_token;
}
public String getOauth_verifier() {
return oauth_verifier;
}
public void setOauth_verifier(String oauth_verifier) {
this.oauth_verifier = oauth_verifier;
}
}
I'll omit the views because they really don't do anything
3) An action which writes "Hello from Struts2!", which isn't very good because twitter will only let you run this once and because the status is the same will not let you post it again... but it gets the process across. After updating the status it redirects to your twitter page, if you change the "YOUR_USER_NAME" part of the url in the redirect of course.
package com.quaternion.struts2basic.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.SessionAware;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
#Results({
#Result(name = "success", location = "https://twitter.com/#!/YOUR_USER_NAME", type = "redirect")
})
public class Tweet extends ActionSupport implements SessionAware {
private Map<String, Object> session;
private String status;
#Override
public String execute() {
Token accessToken = (Token) session.get("accessToken");
OAuthService twitterService = (OAuthService) session.get("twitterService");
String url = "http://api.twitter.com/1/statuses/update.json?status=";
String twitterStatus = "hello!";
OAuthRequest request = new OAuthRequest(Verb.POST, url + twitterStatus);
twitterService.signRequest(accessToken, request);
Response response = request.send();
return SUCCESS;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return this.status;
}
#Override
public void setSession(Map<String, Object> map) {
session = map;
}
}
That is pretty much it. The nice things about scribe is it is so easy to configure for the different providers (for basic authentication, using their APIs after is another matter and that is up to you).
It dependents upon how you want to build it.There are certain number of library which you can use to build you login system and few of them are
Joid
openid4java
Here is a outline what all you have to do in order to make the complete flow
Create a JSP page where use can select a way to choose his login system.
Call an action class which Create an authentication request for this identifier.
Redirect user to the OpenId service provider and let him authorize themself.
Receive the OpenID Provider's authentication response at your callback action.
parse the response if you need to store some information.

How to define the response url at OpenIDAuthenticationFilter?

I have a CustomOpenIDAuthenticationFilter extends org.springframework.security.openid.OpenIDAuthenticationFilter. I want to define the response url after the authentication is successful, but do not know how to do it. Any help you might have would be very much appreciated.
I have the following code at the moment:
public class CustomOpenIDAuthenticationFilter extends OpenIDAuthenticationFilter{
protected static Logger logger = Logger.getLogger("service");
public CustomOpenIDAuthenticationFilter(){
super();
ProxyProperties proxyProps = new ProxyProperties();
proxyProps.setProxyHostName(PROXYNAME);
proxyProps.setProxyPort(PROXYPORT);
HttpClientFactory.setProxyProperties(proxyProps);
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException {
//i think the response url should be defined here.
Authentication au = super.attemptAuthentication(request, response);
return au;
}
}
Edit
Sorry for your time, i did not explain my problem correctly.
So, when my login page is sending authentication request to openid provider, the request contains a returnToUrl, where is "The URL on the Consumer site where the OpenID Provider will return the user after generating the authentication response. ". On a non-spring application, i would do
AuthRequest authRequest = manager.authenticate(discovered, returnToUrl);
My question is how could I specify this returnToUrl at my CustomOpenIDAuthenticationFilter.
To specify the returnToUrl you can override the String buildReturnToUrl(HttpServletRequest request) method. An example of making this an arbitrary URL is given below:
public class CustomOpenIDAuthenticationFilter extends OpenIDAuthenticationFilter {
...
protected String buildReturnToUrl(HttpServletRequest request) {
// this URL needs to be processed by CustomOpenIDAuthenticationFilter to validate
// the OpenID response and authenticate the user
return "https://example.com";
}
}
As the comment mentions this URL should be a URL that CustomOpenIDAuthenticationFilter will process since it is what validates the OpenID response.
This can also be achieved by creating a custom filter an place it before OPENID_FILTER
</http>
...
<custom-filter before="OPENID_FILTER" ref="myBeforeOpenIDFilter" />
</http>
<beans:bean id="myBeforeOpenIDFilter"class="com.example.provider.openid.MyBeforeOpenIdFilter" />
And below there is my implementation of this custom filter
package com.example.provider.openid;
import java.io.IOException;
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 javax.servlet.http.HttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyBeforeOpenIdFilter implements Filter{
static Logger logger = LoggerFactory.getLogger(MyBeforeOpenIdFilter.class);
static class FilteredRequest extends HttpServletRequestWrapper {
public FilteredRequest(HttpServletRequest request) {
super(request);
}
#Override
public java.lang.StringBuffer getRequestURL(){
String baseUrl = (String) super.getSession().getServletContext().getAttribute("applicationBaseUrl");
StringBuffer sb = super.getRequestURL();
int index = sb.indexOf("/j_spring_openid_security_check");
if(index != -1){
// here replace the host etc with proper value
if(baseUrl.endsWith("/")){
baseUrl = baseUrl.substring(0, baseUrl.length()-1);
}
logger.debug("Changing the getRequestURL to inject the correct host so openid login could work behind proxy");
logger.debug("Original getRequestURL: "+sb.toString());
logger.debug("Replacing the baseUrl with: "+baseUrl);
sb.replace(0, index, baseUrl);
logger.debug("New getRequestURL: "+sb.toString());
}
return sb;
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
//No need to init
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new FilteredRequest((HttpServletRequest) request), response);
}
#Override
public void destroy() {
//No need to destroy
}
}
In this way you can define your openid provider using the default namespace
and have the filter plugin out if you need it. In my implementation I'm taking the baseUrl from the servlet context but it can be simply hardcoded
Hope this will help someone
Cheers
Szymon

Resources