Any way I could use a boolean as text/plain in a MultipartBody?
Using Quarkus 1.10.5.Final,
#FormParam("myMap")
#PartType(MediaType.APPLICATION_JSON)
public Map<Integer, String> myMap;
works now.
But I still have issues with:
#PartType(MediaType.TEXT_PLAIN)
public boolean flag;
--
I got it to work as JSON like this:
#PartType(MediaType.APPLICATION_JSON)
public boolean flag;
But my frontend dev has some issues with json for a single field,
so I am trying to keep this just as text/plain.
Some more details:
public Response importData(#MultipartForm MultipartBody multipartBody) {
{...]
}
public class MultipartBody {
#PartType(MediaType.TEXT_PLAIN)
public boolean flag;
{...]
}
Thanks,
Marcus
Related
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.
The Intro
Hi there, I am doing a module on Go AppEngine and I have problems reading some models, that have nested models inside. The model is Party, and what I want is Permissions. But, when I get Party from datastore, Permissions struct field is of type string.
//And when I do fmt.Println(party.Permissions) show this:
%!(EXTRA string=jjrz�5878654076715008 *��jjrzshowOnMessages
*zcanInviteAssistants *zcanInviteOrganizers *zcanEditEvent
*zroleName * organizerzisAdmin *�z�4709220381360128
*��jjrzshowOnMessages *zcanInviteAssistants *zcanInviteOrganizers
*zcanEditEvent *zroleName *ownerzisAdmin *��
What is that string? There is a way to get the original struct?
The Models
Go
type Party struct {
Name string `datastore:"name"`
Permissions string `datastore:"permissions"`
}
type PartyPermission struct {
isAdmin bool
canInviteOrganizers bool
canInviteAssistants bool
canEditParty bool
showOnMessages bool
roleName string
}
Java
#Entity
public class Party implements Cloneable, Serializable {
#Id
private Long id;
private String name;
private Map<String, PartyPermission> permissions;
// constructor ...
// getters, setters, etc
}
public class PartyPermission implements Serializable {
private static final long serialVersionUID = 3019266092062869643L;
private boolean isAdmin;
private boolean canInviteOrganizers;
private boolean canInviteAssistants;
private boolean canEditEvent;
private boolean showsOnMessages;
private String roleName;
// constructor
// getters, setters, etc
}
What I've tried
I started with go, on monday 10, and I don't recognize what could be that string. I think that maybe that string was an interface and I could convert that string to an interface, and then to what I really wish, map[string]PartyPermission. So, reflection:
func (p *Party) GetPermissions() (map[string]PartyPermission) {
iPermissions := reflect.ValueOf(p.Permissions).Interface()
return iPermissions.(map[string]PartyPermission)
}
That compiles great, but Go said that string couldn't be converted to another thing. Something like:
interface conversion: interface is string, not map[string]packName.PartyPermission
Thanks for your time.
You can't, you have to create a decoder for that format.
You could use json or something.
Up until last week I have been running my GWT/AppEngine app with no problems using java.io.Serializable and implements Serializable on my classes in RPC calls.
Now I get this error on appengine: Type 'com.foobar.web.shared.RPCDTOclass' was not assignable to 'com.google.gwt.user.client.rpc.IsSerializable' and did not have a custom field serializer.
I still have the implements Serializable. If I fix/change that class and make it com.google.gwt.user.client.rpc.IsSerializable it works for that class but I get the same error for other classes used in RPC. I only have Strings in some of them, so it isn't that I have types that I can't serialize.
I don't see anyone else having this problem so I must have made some type of change that is causing it, but I don't know what. The error shows up on AppEngine, so I think it must be an appengine problem?
Thanks
Adding an example
public class UserLogInDTO implements IsSerializable {
private String Email;
private String PasswordHash;
public UserLogInDTO(){}
public UserLogInDTO(String email, String passwordhash){
setEmail(email);
setPasswordHash(passwordhash);
}
public void Set(String email, String passwordhash){
this.setEmail(email);
this.setPasswordHash(passwordhash);
}
/**
* #return the email
*/
public String getEmail() {
return Email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
Email = email.toLowerCase();
}
/**
* #return the passwordHash
*/
public String getPasswordHash() {
return PasswordHash;
}
/**
* #param passwordHash the passwordHash to set
*/
public void setPasswordHash(String passwordHash) {
PasswordHash = passwordHash;
}
}
If I have implements IsSerializable it works, if implements Serializable it used to work but now doesn't. I am using 1.7.2 SDK for AppEngine 2.4.0 for GWT
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();
}
}
}
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);
}
}