I'm trying to create an IPN listener by following this example:
public class IPNListenerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ConfigManager.getInstance().load(this.getClass().getResourceAsStream("/sdk_config.properties"));
IPNMessage ipnlistener = new IPNMessage(request);
boolean isIpnVerified = ipnlistener.validate();
String transactionType = ipnlistener.getTransactionType();
Map<String,String> map = ipnlistener.getIpnMap();
LoggingManager.info(IPNListenerServlet.class, "******* IPN (name:value) pair : "+ map + " " +
"######### TransactionType : "+transactionType+" ======== IPN verified : "+ isIpnVerified);
}
}
However ConfigManager.getInstance().load() is deprecated and, in my project, the config file is not in the default location so, what is the right way to load the configuration file?
Possible solution:
Provide an empty sdk_config.properties in the default location;
Load the property file manually, get the related map and pass it to the IPNMessage constructor;
More info here.
Related
I made an application which received 2 parts: a picture and some text. The start of the code is:
#WebServlet("/App")
#MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class App extends HttpServlet {
private static final long serialVersionUID = 205242440643911308L;
private static final String PREFIX = "stream2file";
private static final String SUFFIX = ".tmp";
private static final String UPLOAD_DIR = "uploads";
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
JsonObject servletResponse = new JsonObject();
System.out.println("------------------------------");
System.out.println(req.getContentType());
System.out.println("------------------------------");
String text = null;
String uuid = UUID.randomUUID().toString();
Properties props = new Properties();
File dbPropsFile = new File("/config.properties");
FileReader fileReader = new FileReader(dbPropsFile);
props.load(fileReader);
for (Part part : req.getParts()) {
if(getFileType(part).equals("image")) {
The code fails on
for (Part part : req.getParts()) {
It works completely fine if I'm running it with mvn jetty:run, but when deployed to the server, it just crashes. Please help!!!
When trying to do System.out.println(req.getContentType()); this comes as null on the Tomcat and on the Jetty server, but it comes with the expected value on the mvn jetty:run
If the HttpServletRequest.getContentType() is null, then your request isn't satisfying the requirements for #MultipartConfig which requires the Content-Type value to be multipart/form-data
Ensure that your form is being submitted properly on the network first.
Perhaps add some unit tests to your project to ensure that the servlet is behaving as expected, allowing you to focus your attention on the form submit / request side.
I am using an Android client to post data and some file in Google cloud storage:
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("file", file);
entityBuilder.addTextBody("author", author);
On the server side I am using a servlet to get that request.
However, while I am able to get the file and store it, I don't know how to get what's in the addTextBody (the "author" String in my case)
I have been searching for a while and just found someone that posted quite the same question but no one answered him. (How to get the text from a addTextBody in a miltipartentitybuilder)
Assuming you're using Servlet 3.0+, just use HttpServletRequest#getParts(). For example, if you wanted the content of the multipart part named author, you'd configure your servlet with #MultipartConfig, retrieve the appropriate Part object and consume its InputStream.
#MultipartConfig()
#WebServlet(urlPatterns = { "/upload" })
public class UploadServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
if (!part.getName().equals("author"))
continue;
try (InputStream in = part.getInputStream()){
String content = CharStreams.toString(new InputStreamReader(in));
System.out.println(content); // prints the value of author
}
}
}
}
When I try to send cross-domain jsonp request with:
$.getJSON(url + "?callback=?",
value : 'John',
record : {
value : 'a',
list : [ 1, 2 ]
});
Then i try to get it with java servlet like this:
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String output = request.getParameter("callback")
+ "({\"response\":\"test\"});";
response.setContentType("application/javascript;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(output);
}
}
Inside servlet request string has parameter names:
_=1353482336546
value=John
record[value]=a
How can i parse request string to original JSON?
Im using embedded jetty server and I want to use "JSON to Object" jetty parser on JSON string
You can apply flexjson to parse json string to an object. Please take a look at:
live example
flexjson library
I pass parameters to the server line
"login=testAva4&nick=testAvaNick&social=vk&saurl=http://domain.example?param1=1¶m2=2¶m3=3&maurl=1"
waiting as the value saurl="http://domain.example?param1=1¶m2=2¶m3=3"
but i get http://domain.example?param1=1 and param2=2 param3=3
From Eclipse debug
req->_parameters
{maurl=1, nick=testAvaNick, param2=2, saurl=http://domain.example?param1=1, param3=3, social=vk, login=testAva4}
Gets the parameters in the code like this:
public class AddProfileServlet extends PlacerServlet {
//Add new profile method
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//Receive variables from URL
String login = req.getParameter("login");
String nick = req.getParameter("nick");
String social = req.getParameter("social");
String saurl = req.getParameter("saurl");
You should use URLEncoding on the saurl parameter.
Look at URLCodec at the commons codec enter link description here project.
I don't think you will need to encode the entire parameters part, but just the value for this specific parameter.
You can encode a string using:
URLCodec codec = new URLCodec();
String encodedValue = codec.encode(valueToEncode);
And you should use encodedValue as the value passed to the saurl parameter.
In struts 2 there is a struts tag where you can specify an action name and it gives you the url to that action:
<s:url action="action_name" />
I've been looking for a while now to see if it is possible to do this in an Struts2 Action/Interceptor. I found the class that relates to this struts tag I think (org.apache.struts2.components.URL) but can't figure out how to use it.
This is as far as I got but it might not be how to use it (if its possible at all) but any method I call after this just gives me NullPointerExceptions.:
public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
URL url = new URL(ai.getStack(), request, response);
url.setAction("login");
//e.g. url.start(<with stringwriter>);
}
Hoping this can be done as it would save a lot of troube!
Thanks.
EDIT
URL url = new URL(invocation.getStack(), request, response);
url.setActionMapper(new DefaultActionMapper());
String redirectUrl = url.getUrlProvider().determineActionURL("action_name",
invocation.getProxy().getNamespace(), invocation.getProxy().getMethod(),
request, response, request.getParameterMap(), "http", true, true, false, false);
This code does work and gives me a redirect URL but I was wondering if there was a way to get the CURRENT ActionMapper rather than create a new one. I've done a quick google but can't find anything.
Well this is the method in the component class inside struts2 which is creating action URL
protected String determineActionURL(String action, String namespace, String method, HttpServletRequest req, HttpServletResponse res, Map parameters, String scheme,
boolean includeContext, boolean encodeResult, boolean forceAddSchemeHostAndPort, boolean escapeAmp)
{
String finalAction = findString(action);
String finalMethod = method == null ? null : findString(method);
String finalNamespace = determineNamespace(namespace, getStack(), req);
ActionMapping mapping = new ActionMapping(finalAction, finalNamespace, finalMethod, parameters);
String uri = actionMapper.getUriFromActionMapping(mapping);
return UrlHelper.buildUrl(uri, req, res, parameters, scheme, includeContext, encodeResult, forceAddSchemeHostAndPort, escapeAmp);
}
now the question is how we can get various values for this
action=invocation.getAction();
namespace=invocation.getProxy().getNamespace();
methos= invocation.getProxy().getMethod();
similar other values can be find out from ActionIvocation
This is just an idea and i have not applied it myself.Hope it might help you.
Here is how I get the CURRENT ActionMapper rather than create a new one:
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.inject.Inject;
#Namespace("MyNamespace")
public class MyAction extends ActionSupport {
private ActionMapper actionMapper;
private UrlHelper urlHelper;
#Inject
public void setActionMapper(ActionMapper mapper) {
this.actionMapper = mapper;
}
#Inject
public void setUrlHelper(UrlHelper urlHelper) {
this.urlHelper = urlHelper;
}
private String getAbsoluteUrl(String actionName, String namespace) {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ActionContext context = ActionContext.getContext();
ActionInvocation invocation = context.getActionInvocation();
URL url = new URL(invocation.getStack(), request, response);
url.setActionMapper(actionMapper);
url.setUrlHelper(urlHelper);
return url.getUrlProvider().determineActionURL( //
actionName, //
namespace, //
"" , /* Method name */
request, response, //
request.getParameterMap(), "http", //
true, true, true, false);
}
// ...
}