/*
* Copyright 2012 Adaptrex, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptrex.core.rest.jaxrs;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import com.adaptrex.core.ext.ModelInstance;
import com.adaptrex.core.rest.RestModel;
import com.adaptrex.core.utilities.StringUtilities;
@Provider
@Produces({MediaType.APPLICATION_JSON, MediaType.WILDCARD})
public class ModelJsonBodyWriter implements MessageBodyWriter<RestModel> {
@Override
public long getSize(RestModel model, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return type.equals(RestModel.class);
}
@Override
public void writeTo(RestModel model, Class<?> clazz, Type type,
Annotation[] annotation, MediaType mediaType,
MultivaluedMap<String, Object> map, OutputStream out)
throws IOException, WebApplicationException {
final PrintStream printStream = new PrintStream(out);
/*
* We need to do some formatting on the response
*/
Map<String,Object> response = new HashMap<String,Object>();
ModelInstance modelInstance = model.getModelInstance();
if (modelInstance.getData().isEmpty()) {
response.put("success", false);
response.put("message", "Record Not Found");
} else {
response.put("data", modelInstance.getData());
response.put("id", modelInstance.getData().get("id"));
response.put("success", true);
}
try {
String json = StringUtilities.json(response);
printStream.print(json);
} catch (Exception e) {
throw new RuntimeException(e);
//printStream.print("{success:false}");
}
}
}