Keep trailing zeros in bigdecimal in json - jsonserializer

I have created onse serializer class which should restrict Bigdecimal to tow digits after decimal. But its removing zeros too. For ex: if value is 95.50, its truncating zero and output as 95.5 in json.
public class PriceJsonSerializer extends JsonSerializer {
#Override
public void serialize(BigDecimal value, JsonGenerator jgen,
SerializerProvider provider) throws IOException, JsonProcessingException
{
jgen.writeNumber(value.setScale(2,
BigDecimal.ROUND_HALF_UP).toString());
}
}

To force the serializer to preserve your rounding without writing the value as a string, try "writeRawValue".
public class PriceJsonSerializer extends JsonSerializer {
#Override
public void serialize(BigDecimal value, JsonGenerator jgen,
SerializerProvider provider) throws IOException, JsonProcessingException
{
jgen.writeRawValue(value.setScale(2,
BigDecimal.ROUND_HALF_UP).toString());
}
}

Related

How do I get the rest path in a HandlerInterceptorAdapter without resolved path variables

I have a problem with my RestController interceptor.
My goal is to get the RestController path in a HandlerInterceptorAdapter and then use it to create metrics.
Via the interface HttpServletRequest I have access to the path, but it is resolved there.
Example of what I would like to get in my interceptor:
GET: object/123 // wrong
GET object/{id} // right
Is there any way to get the path without resolved variables?
Here is my implementation:
RestController:
#RestController
public class ObjectController
{
#GetMapping("object/{id}")
public String getObjectById(#PathVariable String id)
{
return id;
}
}
Config:
#Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
#Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addInterceptor(new RequestInterceptor());
}
}
Interceptor:
public class RequestInterceptor extends HandlerInterceptorAdapter
{
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception
{
System.out.println(request.getRequestURI());
return true;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
#Nullable ModelAndView modelAndView) throws Exception
{
System.out.println(request.getRequestURI());
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
#Nullable Exception ex) throws Exception
{
System.out.println(request.getRequestURI());
}
}

When writing a custom serialization, what is the difference between using SerializerProvider or jsonGenerator to generate the json

I was trying to write a custom implementation for serializing an object like explained in here: Jackson custom serialization
Where I have:
#Override
public void serialize(
Item value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
...
}
But, I noticed that I could also use the SerializerProvider to write the same thing in this other way:
#Override
public void serialize(
Item value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
provider.defaultSerializeField("id", value.id, jsonGenerator);
...
}
So I was wondering: what is the difference between:
jgen.writeNumberField("id", value.id);
and
provider.defaultSerializeField("id", value.id, jsonGenerator);

Avoid part-r-00***** from appending in the end of MapReduce job output file

I am running a MR code using Multioutputformat class. part**** is getting appended in the end of my output file. How can i avoid that?
public class MR_reducer extends
Reducer {
private MultipleOutputs multipleOutputs;
#Override
protected void setup(Context context) throws IOException,
InterruptedException {
multipleOutputs = new MultipleOutputs(context);
}
#Override
protected void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
for (Text value : values) {
multipleOutputs.write(value, new Text(""), key.toString());
}
}
#Override
protected void cleanup(Context context) throws IOException,
InterruptedException {
multipleOutputs.close();
}
}
This code snippet is working from me. You have few differences:
public static class Reduce extends Reducer<Text, Text, NullWritable, Text> {
private MultipleOutputs<NullWritable, Text> multipleOutputs;
protected void setup(Context context) throws IOException, InterruptedException {
multipleOutputs = new MultipleOutputs<NullWritable, Text>(context);
}
public void reduce(Text key, Iterable<Text> values, Context output) throws IOException, InterruptedException {
while (values.iterator().hasNext()) {
multipleOutputs.write(NullWritable.get(), values.iterator().next(), key.toString());
}
}
protected void cleanup(Context context) throws IOException, InterruptedException {
multipleOutputs.close();
}
}

I'm looking for the way to handle pre & post processing of Controller in Spring Boot + thymeleaf

I have been looking for the way to handle pre & post processing of controller.
I want to add a procedure for every request & response.
For example:
Checking every requested header or adding hidden field include hash code in every form tags we response.
If there is sample, or any idea,give me please.
Thanks for advice.
I was able to find the result from this page.
http://www.concretepage.com/spring/spring-mvc/spring-handlerinterceptor-annotation-example-webmvcconfigureradapter
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new ControllerHandler());
TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
}
}
public class ControllerHandler implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("---Before Method Execution---");
return true;
}
#Override
public void postHandle( HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("---method executed---");
}
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
System.out.println("---Request Completed---");
}
}
I found another way to do,using #ControllerAdvice.
This annotaion seems to focus Error Handling.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html1
#ControllerAdvice
public class ExceptionControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("controller advice: init binder");
}
#ExceptionHandler(Exception.class)
public String exception(Exception e) {
System.out.println("controller advice: exception Handler");
System.out.println(e.getMessage());
return "error";
}
#ModelAttribute
public void modelAttribute(){
System.out.println("controller advice:model Attribute");
}
}

Old API to New API

My Original Question
since only feasible ans to that question is found in This Question
And the answer is in old API . So that force me to put a stupid question of translating these line to New API :
private long mapperCounter;
#Override
public void configure(JobConf conf) {
JobClient client = new JobClient(conf);
RunningJob parentJob =
client.getJob(JobID.forName( conf.get("mapred.job.id") ));
mapperCounter = parentJob.getCounters().getCounter(MAP_COUNTER_NAME);
}
Note : I want this code in reducer so inherited functions available are :
#Override
protected void setup(Context context) throws IOException,
InterruptedException {
}
#Override
protected void cleanup(Context context) throws IOException,
InterruptedException {
}
#Override
public void run(Context context) throws IOException,
InterruptedException {
Job job=new Job(context.getConfiguration());
}
#Override
public void reduce(ImmutableBytesWritable key,Iterable<ImmutableBytesWritable> result,Context context )
{
}
Thanks :) :)
This presentation summarizes the changes between the old and new API.

Resources