How take always first parameter when requested array type param in spring mvc using #RequestParam - arrays

I wrote this code.
#GetMapping("/test")
public Response search(#RequestParam String value) {
System.out.println(value);
return new Response(value)
}
Some body request like
/test?value=a&value=b&value=c
value binded a,b,c
I want always bind first parmeter. Take a, ignore b, c.
Is there way using #RequestParam?
Or have to use HttpServletRequest and parsing parameter?

In this case you can use #RequestParam List<String> value instead of #RequestParam String value, and get the first value value.get(0) ignore the rest of them
For Example
http://rentacar.com/api/v1/search?make=audi&model=A8&type=6&type=11&type=12&color=RED&color=GREY
Method
public List<Vehicle> search(
#RequestParam(value="make", required=false) String make,
#RequestParam(value="model", required=false) String model,
#RequestParam(value="type", required=false) List<String> types,
#RequestParam(value="color", required=false) List<String> colors)
{
....
}

Great question!
I wrote this code to find out how this works. I included it in the test packages.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles("test")
public class ControllerTest {
#LocalServerPort
private int port;
private URL url;
#Autowired
private TestRestTemplate template;
#Before
public void setUp() throws Exception {
this.url = new URL("http://localhost:" + port + "/test?value=a&value=b&value=c");
}
#Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity(url.toString(),
String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Assert.assertEquals(response.getBody(), "a");
System.out.println("response = " + response);
}
}
I then modified your code to accept an array of strings, and only pass the first element to your Response Constructor.
Notice the changes in your code in the signature and return statement.
#GetMapping("/test")
public String search(#RequestParam String[] value) {
System.out.println(value);
return new Response(value[0]);
}
With your test, you can now explore using a List type for your request param and quickly see how the behaviour has changed.

Related

Call another method in Spring Aspect

I would like to convert a parameter and then call second method with this parameter.
The convention would be that there is always the same method overloaded with the specific type. The idea is to solve it with Spring AOP.
#Component
public class ExampleAspect {
#Around( "#annotation(Example)" )
public Object test( final ProceedingJoinPoint joinPoint ) throws Throwable {
final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
final Method method = signature.getMethod();
final Example example = method.getAnnotation( Example.class );
final Object[] args = joinPoint.getArgs();
final String test = args[example.value()].toString();
final Bar bar = convertToBar(test)
args[example.value()] = bar;
//ReflectionUtils?
// call getBar(Bar bar)
//return joinPoint.proceed( args );
}
}
Here is the service
#Example(0)
public Object getBar(String test) {}
public Object getBar(Bar test) {}
Are there any better options or ideas?
EDIT:
Cannot inject the target bean, because this AOP should be used by more than specific target bean.
1 possible solution not sure if there is a smarter solution
#Around("#annotation(Example)")
public Object test(final ProceedingJoinPoint joinPoint) throws Throwable {
final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
final Method method = signature.getMethod();
final Example example = method.getAnnotation(Example.class);
final Object[] args = joinPoint.getArgs();
final String bar = args[example.value()].toString();
final Bar aspectModelUrn = convertFromStringToBar(bar);
args[example.value()] = bar;
final Class<?>[] parameterTypes = method.getParameterTypes();
parameterTypes[example.value()] = Bar.class;
final Method newMethod = ReflectionUtils.findMethod(joinPoint.getTarget().getClass(), method.getName(), parameterTypes);
if (newMethod == null) {
throw new IllegalArgumentException("There is no method blubb. Have you forget to create the delegate method");
}
return newMethod.invoke(joinPoint.getTarget(), args);
}
Following code would provide a handle to the annotation and the target bean (for example , here TestComponent)
A call to the TestComponent.getBar() annotated with #Example would be intercepted and advised.
#Aspect
#Component
public class ExampleAspect {
#Around("#annotation(example) && target(bean)")
public Object test(final ProceedingJoinPoint joinPoint,Example example,TestComponent bean) throws Throwable {
String value = String.valueOf(example.value());
Bar bar = convertToBar(value);
bean.getBar(bar);
return joinPoint.proceed();
}
}
Do go through Spring AOP documentation : Passing Parameters to Advice for more details.
Note : For better performance it is a good idea to limit the scope of the expression as follows.
#Around("#annotation(example) && within(com.xyz.service..*) && target(bean)")
where com.xyz.service..* will limit the expression scope only to the beans with in the package com.xyz.service..* and its sub-packages.

Passing data using dataprovider in PageObjectModel in TestNG

i have a scenario where in im calling a method(which has code to create workflow - defined in pages POM framework), i have written a generic method to get the data from excel file using dataProvider in testNG
Now i have a #Test method which perform the action of creating the workflow as below
#DataProvider(name="wf")
public static String[][] getExcelData() throws Exception{
ExcelReader read = new ExcelReader();
String filePath = "path of excelfile";
return read.getCellData(filePath, "Sheet1");
}
#Test(dataProviderClass = ExcelReader.class, dataProvider="wf")
public void testing(String workflow, String type, String unit){
System.out.println("-------------Test case started -------------");
System.out.println("Call to login to the application");
System.out.println("Navigating to Some Page");
System.out.println("Navigating to WorkflowPage");
SampleClass s = new SampleClass();
s.createWorkflow(workflow,type,unit);
System.out.println("-----'--------Test case Ended ----------------");
System.out.println();
}
public void createWorkflow(String wf, String wf, String unit){
System.out.println("Creating WF");
System.out.println(wf);
System.out.println(type);
System.out.println(unit);
System.out.println("CREATED wf");
}
now if i run the #Test fails after creating the 1st workflow, becoz the #test method is run again from beginning instead of creating multiple workflow's, for 'createWorkflow method.
Can you let me know how can i achieve this or a better solution.
#BeforeMethod
public void beforeMethod(){
System.out.println("Call to login to the application");
System.out.println("Navigating to Some Page");
System.out.println("Navigating to WorkflowPage");
}
#Test(dataProviderClass = ExcelReader.class, dataProvider="wf")
public void testing(String workflow, String type, String unit){
System.out.println("-------------Test case started -------------");
SampleClass s = new SampleClass();
s.createWorkflow(workflow,type,unit);
System.out.println("-----'--------Test case Ended ----------------");
System.out.println();
}
public void createWorkflow(String wf, String wf, String unit){
System.out.println("Creating WF");
System.out.println(wf);
System.out.println(type);
System.out.println(unit);
System.out.println("CREATED wf");
}

Sending a complex object as a parameter in Resteasy

I am using resteasy, and till now I am just sending and receiving string as parameters and every thing was OK, but now I want to send a complex object ( List<Map<String, ObjectVal>> ) as one of my parameters. My objectVal class has two simple field ( id and value, with getters and setters).
I can find different question and answers for sending objects as parameters but all of them are missing something and not useful for me.
here is my functions with a simple string parameter
#GET
#Path("/isUserAuthorizedToDocument")
public Response isUserAuthorizedToDocumentService(
#QueryParam("userID") String userID){
.............
.............
}
and the client
private ClientRequest req =new ClientRequest(....url with path and ....)
req.queryParameter("userID", user.getUserId());
ClientResponse<Boolean> response = req.get(Boolean.class);
Now I want to send a parameter from my client in the form of List<Map<String,ObjectVal>> and recieve it in my rest function.
My ObjectVal class
#XmlRootElement(name = "objectValueDTO")
public class ObjectValueDTO implements Serializable {
/**
* Id for this class
*/
private static final long serialVersionUID = 164186789404269392L;
// Id on object type
private String objectTypeID = "";
// Selection
private String value = "";
/** Getter and Setters */
#XmlElement
public String getObjectTypeID() {
return objectTypeID;
}
public void setObjectTypeID(String objectTypeID) {
this.objectTypeID = objectTypeID;
}
#XmlElement
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
any help will be appreciated
I may be niave on this. But when you have to send complex parameters, you need to use PUT and send the parameters in the request.

Persistence with EJB3 doesn't work

I have a method to save a new object in an EJB bean. This method is called, without error, but nothing changes in the database. I can't understand why.
Here is the code:
#Stateless(name = "Ar", mappedName = "ManagementBean")
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
...
#Override
public int storeRawSms(String raw, String requestUid, String text, String service, boolean correctlyAnalysed, Date receivedTimestamp,
boolean toBeAnalysed, String phoneNumber) {
// Get phone number, create if it dosn't exist
PhoneNumber pn = getOrCreatePhoneNumberPrivate(phoneNumber);
// Create rawSMS
RawSms rawSms = new RawSms(raw, requestUid, text, service, correctlyAnalysed, receivedTimestamp, toBeAnalysed, pn);
// Store and return result
em.persist(rawSms);
int result = rawSms.getId();
em.flush();
em.clear();
return result;
}
...
And the caller:
#PersistenceContext private EntityManager em;
...
int rawSmsIs = bean.storeRawSms(raw, requestUid, message, service, false, new Date(), true, sender);
Do you have an idea?
I see that you inject a reference to the EntityManager in the client (not sure why), but I don't see it in the session bean (maybe simply because you did not include the line in your message). Is it possible that you forgot to use the annotation #PersistenceContext in your stateless session bean?
Also, be careful: depending on the JPA implementation you are using and the generation strategy for the ids, you should call flush() before calling getId(). Indeed, if you let the DB generate your IDs, then you need a flush() to have this happen before the method returns the value.
Thanks, the prposed solution worked!
I use the container-managed transactions like this:
#Stateless(name = "Ar", mappedName = "ManagementBean")
#TransactionManagement(TransactionManagementType.CONTAINER)
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
....
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int storeRawSms(String raw, String requestUid, String text, String service, boolean correctlyAnalysed, Date receivedTimestamp, boolean toBeAnalysed, String phoneNumber) {
....
Thanks again!
It seems that your transaction never commited, so try changing transaction management:
#Stateless(name = "Ar", mappedName = "ManagementBean")
#TransactionManagement(TransactionManagementType.BEAN)
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
#Resource
private UserTransaction utx;
#Override
public int storeRawSms(..) {
try {
utx.begin();
..
em.persist(rawSms);
int result = rawSms.getId();
utx.commit();
}
catch(Exception ex) {
//EXCEPTION HANDLING
utx.rollback();
}
}
}

Custom Date Format with jax-rs in apache cxf?

I have been googling to figure out how I can customize the Date format when I use jax-rs on apache CXF. I looked at the codes, and it seems that it only support primitives, enum and a special hack that assume the type associated with #FormParam has a constructor with a single string parameter. This force me to use String instead of Date if I want to use FormParam. it is kind of ugly. Is there a better way to do it?
#POST
#Path("/xxx")
public String addPackage(#FormParam("startDate") Date startDate)
{
...
}
Thanks
starting from CXF 2.3.2 registering ParameterHandler will do it. It is also always possible to override the date value (passed as part of the query, etc) using RequestHandler filters for default Date(String) to work
One simple apporach is take parameter as String and parse it in method body to convert it to java.util.Date
Another is create one class having constructor takes on parameter of type String. Perform same thing as I told in first approach.
here is the code for second approach.
#Path("date-test")
public class DateTest{
#GET
#Path("/print-date")
public void printDate(#FormParam("date") DateAdapter adapter){
System.out.println(adapter.getDate());
}
public static class DateAdapter{
private Date date;
public DateAdapter(String date){
try {
this.date = new SimpleDateFormat("dd/MM/yyyy").parse(date);
} catch (Exception e) {
}
}
public Date getDate(){
return this.date;
}
}
}
Hope this helps.
After reading the CXF codes (2.2.5), it is not possible, and it is hardcoded to use the Date(String) constructor, so whatever Date(String) support.
In Apache-cxf 3.0, you can use a ParamConverterProvider to convert a parameter to a Date.
The following code is copied from my answer to this question.
public class DateParameterConverterProvider implements ParamConverterProvider {
#Override
public <T> ParamConverter<T> getConverter(Class<T> type, Type type1, Annotation[] antns) {
if (Date.class.equals(type)) {
return (ParamConverter<T>) new DateParameterConverter();
}
return null;
}
}
public class DateParameterConverter implements ParamConverter<Date> {
public static final String format = "yyyy-MM-dd"; // set the format to whatever you need
#Override
public Date fromString(String string) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try {
return simpleDateFormat.parse(string);
} catch (ParseException ex) {
throw new WebApplicationException(ex);
}
}
#Override
public String toString(Date t) {
return new SimpleDateFormat(format).format(t);
}
}

Resources