Package com.adaptrex.core.ext.rest.provider

Source Code of com.adaptrex.core.ext.rest.provider.ModelJsonBodyWriter

/*
* 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.ext.rest.provider;

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.data.Model;
import com.adaptrex.core.ext.data.ModelInstance;
import com.adaptrex.core.ext.data.Store;
import com.adaptrex.core.utilities.StringUtilities;


@Provider
@Produces({MediaType.APPLICATION_JSON, MediaType.WILDCARD})
public class ModelJsonBodyWriter implements MessageBodyWriter<Model> {

  @Override
  public long getSize(Model 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(Model.class);
  }

  @Override
  public void writeTo(Model 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();
   
    response.put("data", modelInstance.getData());
    response.put("id", modelInstance.getData().get("id"))// TODO: We should have a way to get id's named other than "id"
    response.put("success", true);
   
    printStream.print(StringUtilities.json(response));
    printStream.close();
  }
}
TOP

Related Classes of com.adaptrex.core.ext.rest.provider.ModelJsonBodyWriter

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.