Java tutorial
/* Copyright (c) 2015-2015, Michal Szczepanski All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ package pl.vane.http.resp; import com.sun.net.httpserver.HttpExchange; import org.apache.pdfbox.pdmodel.PDDocument; import pl.vane.factory.JSONFactory; import pl.vane.http.helper.RequestHelper; import pl.vane.http.helper.ResponseHelper; import pl.vane.pdf.factory.PDFFactory; import pl.vane.pdf.model.PDFDocument; import pl.vane.utils.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.util.UUID; /** * Author: Michal Szczepanski * Date: 28/03/15 * Time: 21:36 */ public class ApiHandler extends AbstractHandler { @Override public void handle(HttpExchange req) throws IOException { super.handle(req); if (req.getRequestMethod().equals("POST")) { OutputStream resp = req.getResponseBody(); try { // read json data String data = RequestHelper.readBodyAsString(req); // convert to PDFDcoument PDFDocument document = (PDFDocument) JSONFactory.toObject(data, PDFDocument.class); // create PDF and send name to client PDDocument pdf = PDFFactory.create(document); String name = UUID.randomUUID().toString(); pdf.save("web/pdf/" + name + ".pdf"); ResponseHelper.write(req, "{\"name\":\"" + name + "\"}"); } catch (Exception e) { e.printStackTrace(); String out = StringUtils.toString(e); resp.write(out.getBytes()); } } else { req.getResponseBody().write("Method not allowed".getBytes()); } } }