org.debux.webmotion.server.render.RenderJsonP Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of toolkit-server Show documentation
Show all versions of toolkit-server Show documentation
ObServe Toolkit Server module
/*
* #%L
* Toolkit :: Server
* %%
* Copyright (C) 2017 - 2024 Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* .
* #L%
*/
package org.debux.webmotion.server.render;
import com.google.gson.Gson;
import org.debux.webmotion.server.call.Call;
import org.debux.webmotion.server.call.HttpContext;
import org.debux.webmotion.server.mapping.Mapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/**
* Render use to manage JsonP.
*
* @author julien
*/
public class RenderJsonP extends Render {
protected String callback;
protected Map model;
public RenderJsonP(String callback, Map model) {
this.callback = callback;
this.model = model;
}
public String getCallback() {
return callback;
}
public Map getModel() {
return model;
}
@Override
public void create(Mapping mapping, Call call) throws IOException {
HttpContext context = call.getContext();
HttpServletResponse response = context.getResponse();
Object object = model;
if (model != null && model.size() == 1
&& model.keySet().contains(DEFAULT_MODEL_NAME)) {
object = model.values().toArray()[0];
}
response.setContentType("application/javascript");
Gson gson = new Gson();
String json = gson.toJson(object);
PrintWriter out = context.getOut();
out.print(callback + "(" + json + ");");
}
}