Example usage for com.google.gson.reflect TypeToken TypeToken

List of usage examples for com.google.gson.reflect TypeToken TypeToken

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken TypeToken.

Prototype

@SuppressWarnings("unchecked")
protected TypeToken() 

Source Link

Document

Constructs a new type literal.

Usage

From source file:airline.service.GeneratePDF.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Set content type to application / pdf
    //browser will open the document only if this is set
    response.setContentType("application/pdf");
    //Get the output stream for writing PDF object 

    OutputStream out = response.getOutputStream();
    try {//from w ww  . j av  a  2  s . co m
        RuntimeTypeAdapterFactory<Jsonable> rta = RuntimeTypeAdapterFactory.of(Jsonable.class, "_class")
                .registerSubtype(Reservacion.class, "Reservacion").registerSubtype(Tiquete.class, "Tiquete")
                .registerSubtype(Viaje.class, "Viaje");
        Gson gson = new GsonBuilder().registerTypeAdapterFactory(rta).setDateFormat("dd/MM/yyyy").create();
        String json;
        List<Viaje> viajes;

        String jsonReservacion = request.getParameter("reservacion");
        Reservacion reservacion = gson.fromJson(jsonReservacion, Reservacion.class);
        String jsonViajes = request.getParameter("viajes");
        viajes = gson.fromJson(jsonViajes, new TypeToken<ArrayList<Viaje>>() {
        }.getType());

        Document document = new Document();
        /* Basic PDF Creation inside servlet */
        PdfWriter.getInstance(document, out);
        document.open();
        document.add(new Paragraph(" FACTURA DE COMPRA"));
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Viajes"));
        document.add(Chunk.NEWLINE);
        document.add(createViajesTable(viajes));
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("Reservacion"));
        document.add(Chunk.NEWLINE);
        document.add(createReservacionTable(reservacion));
        document.close();
    } catch (DocumentException exc) {
        throw new IOException(exc.getMessage());
    } finally {
        out.close();
    }

}

From source file:alberto.avengers.model.rest.RestDataSource.java

License:Mozilla Public License

@Inject
public RestDataSource() {
    OkHttpClient client = new OkHttpClient();

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

    MarvelSigningIterceptor signingIterceptor = new MarvelSigningIterceptor(BuildConfig.MARVEL_PUBLIC_KEY,
            BuildConfig.MARVEL_PRIVATE_KEY);

    client.interceptors().add(signingIterceptor);
    client.interceptors().add(loggingInterceptor);

    Gson customGsonInstance = new GsonBuilder().registerTypeAdapter(new TypeToken<List<Character>>() {
    }.getType(), new MarvelResultsDeserializer<Character>())

            .registerTypeAdapter(new TypeToken<List<CollectionItem>>() {
            }.getType(), new MarvelResultsDeserializer<CollectionItem>())

            .create();//from   w  ww.j av a 2 s .  c  o  m

    Retrofit marvelApiAdapter = new Retrofit.Builder().baseUrl(MarvelApi.END_POINT)
            .addConverterFactory(GsonConverterFactory.create(customGsonInstance))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();

    mMarvelApi = marvelApiAdapter.create(MarvelApi.class);
}

From source file:alfio.manager.MollieManager.java

License:Open Source License

public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary,
        CustomerName customerName, String email, String billingAddress, Locale locale, boolean invoiceRequested,
        String vatCountryCode, String vatNr, PriceContainer.VatStatus vatStatus) throws Exception {

    String eventName = event.getShortName();

    String baseUrl = StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/");

    String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book";

    Map<String, Object> payload = new HashMap<>();
    payload.put("amount", orderSummary.getTotalPrice()); // quite ugly, but the mollie api require json floating point...

    ///*from w  w w  .  j  a va2 s  . c o  m*/
    String description = messageSource.getMessage(
            "reservation-email-subject", new Object[] {
                    configurationManager.getShortReservationID(event, reservationId), event.getDisplayName() },
            locale);
    payload.put("description", description);
    payload.put("redirectUrl", bookUrl);
    payload.put("webhookUrl",
            baseUrl + "/webhook/mollie/api/event/" + eventName + "/reservation/" + reservationId);

    Map<String, String> initialMetadata = new HashMap<>();
    initialMetadata.put("reservationId", reservationId);
    initialMetadata.put("email", email);
    initialMetadata.put("fullName", customerName.getFullName());
    if (StringUtils.isNotBlank(billingAddress)) {
        initialMetadata.put("billingAddress", billingAddress);
    }

    payload.put("metadata", initialMetadata);

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(payload));
    Request request = requestFor("https://api.mollie.nl/v1/payments", event).post(body).build();

    try (Response resp = client.newCall(request).execute()) {
        ResponseBody responseBody = resp.body();
        String respBody = responseBody != null ? responseBody.string() : "null";
        if (!resp.isSuccessful()) {
            String msg = "was not able to create a payment for reservation id " + reservationId + ": "
                    + respBody;
            log.warn(msg);
            throw new Exception(msg);
        } else {
            ticketReservationRepository.updateReservationStatus(reservationId,
                    TicketReservation.TicketReservationStatus.EXTERNAL_PROCESSING_PAYMENT.toString());
            Map<String, Object> res = Json.GSON.fromJson(respBody, (new TypeToken<Map<String, Object>>() {
            }).getType());
            @SuppressWarnings("unchecked")
            Map<String, String> links = (Map<String, String>) res.get("links");
            return links.get("paymentUrl");
        }
    }
}

From source file:alfio.manager.MollieManager.java

License:Open Source License

public void handleWebhook(String eventShortName, String reservationId, String paymentId) throws Exception {
    Event event = eventRepository.findByShortName(eventShortName);

    Request request = requestFor("https://api.mollie.nl/v1/payments/" + paymentId, event).get().build();
    Response resp = client.newCall(request).execute();

    try (ResponseBody responseBody = resp.body()) {
        String respBody = responseBody.string();
        if (!resp.isSuccessful()) {
            String msg = "was not able to get payment id " + paymentId + " for event " + eventShortName + " : "
                    + respBody;/*w ww .j a va2 s . c  o m*/
            log.warn(msg);
            throw new Exception(msg);
        } else {
            Map<String, Object> res = Json.GSON.fromJson(respBody, (new TypeToken<Map<String, Object>>() {
            }).getType());

            //load metadata, check that reservationId match

            //see statuses: https://www.mollie.com/en/docs/status
            String status = (String) res.get("status");
            //open cancelled expired failed pending paid paidout refunded charged_back
            if ("paid".equals(status)) {
                //TODO: register payment -> fetch reservationId from metadata -> switch as paid etc...
            } else if ("expired".equals(status)) {
                //TODO: set reservation to expired so it can be handled by the job
            }
        }
    }
}

From source file:alfio.model.DynamicFieldTemplate.java

License:Open Source License

public DynamicFieldTemplate(@Column("id") int id, @Column("field_name") String name,
        @Column("field_type") String type, @Column("field_restricted_values") String restrictedValuesJson,
        @Column("field_description") String descriptionJson, @Column("field_maxlength") Integer maxLength,
        @Column("field_minlength") Integer minLength) {
    this.id = id;
    this.name = name;
    this.type = type;
    this.restrictedValues = Optional.ofNullable(restrictedValuesJson).map(parseRestrictedValues())
            .orElse(Collections.emptyList());
    this.description = Json.GSON.fromJson(descriptionJson, new TypeToken<Map<String, Object>>() {
    }.getType());//from   w w  w  .  j a  v a2s. co m
    this.maxLength = maxLength;
    this.minLength = minLength;
}

From source file:alfio.model.DynamicFieldTemplate.java

License:Open Source License

private static Function<String, List<String>> parseRestrictedValues() {
    return v -> Json.GSON.fromJson(v, new TypeToken<List<String>>() {
    }.getType());/*from  w ww .j  a  va2 s  .c  om*/
}

From source file:alfio.model.EmailMessage.java

License:Open Source License

public EmailMessage(@Column("id") int id, @Column("event_id") int eventId, @Column("status") String status,
        @Column("recipient") String recipient, @Column("subject") String subject,
        @Column("message") String message, @Column("attachments") String attachments,
        @Column("checksum") String checksum, @Column("request_ts") ZonedDateTime requestTimestamp,
        @Column("sent_ts") ZonedDateTime sentTimestamp, @Column("attempts") int attempts,
        @Column("email_cc") String emailCC) {
    this.id = id;
    this.eventId = eventId;
    this.requestTimestamp = requestTimestamp;
    this.sentTimestamp = sentTimestamp;
    this.status = Status.valueOf(status);
    this.recipient = recipient;
    this.subject = subject;
    this.message = message;
    this.attachments = attachments;
    this.checksum = checksum;
    this.attempts = attempts;

    if (emailCC != null && StringUtils.isNotBlank(emailCC)) {
        this.cc = Json.GSON.fromJson(emailCC, new TypeToken<List<String>>() {
        }.getType());//www .  j a  v  a  2s  . co m
    } else {
        this.cc = new ArrayList<>();
    }
}

From source file:alfio.model.FileBlobMetadata.java

License:Open Source License

public FileBlobMetadata(@Column("id") String id, @Column("name") String name,
        @Column("content_size") int contentSize, @Column("content_type") String contentType,
        @Column("attributes") String attributes) {
    this.id = id;
    this.name = name;
    this.contentSize = contentSize;
    this.contentType = contentType;
    Map<String, String> parsed = Json.GSON.fromJson(attributes, new TypeToken<Map<String, String>>() {
    }.getType());/*from   ww  w.  j ava  2s .c o m*/
    this.attributes = Optional.ofNullable(parsed).orElse(Collections.emptyMap());
}

From source file:alfio.model.PromoCodeDiscount.java

License:Open Source License

public PromoCodeDiscount(@Column("id") int id, @Column("promo_code") String promoCode,
        @Column("event_id_fk") int eventId, @Column("valid_from") ZonedDateTime utcStart,
        @Column("valid_to") ZonedDateTime utcEnd, @Column("discount_amount") int discountAmount,
        @Column("discount_type") DiscountType discountType, @Column("categories") String categories) {
    this.id = id;
    this.promoCode = promoCode;
    this.eventId = eventId;
    this.utcStart = utcStart;
    this.utcEnd = utcEnd;
    this.discountAmount = discountAmount;
    this.discountType = discountType;
    if (categories != null) {
        List<Integer> categoriesId = Json.GSON.<List<Integer>>fromJson(categories,
                new TypeToken<List<Integer>>() {
                }.getType());//from   w  w w .  j  a  va 2 s.  c o  m
        this.categories = categoriesId == null ? Collections.emptySet() : new TreeSet<>(categoriesId);
    } else {
        this.categories = Collections.emptySet();
    }
}

From source file:alfio.model.TicketFieldConfiguration.java

License:Open Source License

public TicketFieldConfiguration(@Column("id") int id, @Column("event_id_fk") int eventId,
        @Column("field_name") String name, @Column("field_order") int order, @Column("field_type") String type,
        @Column("field_maxlength") Integer maxLength, @Column("field_minlength") Integer minLength,
        @Column("field_required") boolean required, @Column("field_restricted_values") String restrictedValues,
        @Column("context") Context context, @Column("additional_service_id") Integer additionalServiceId) {
    this.id = id;
    this.eventId = eventId;
    this.name = name;
    this.order = order;
    this.type = type;
    this.maxLength = maxLength;
    this.minLength = minLength;
    this.required = required;
    this.restrictedValues = restrictedValues == null ? Collections.emptyList()
            : Json.GSON.fromJson(restrictedValues, new TypeToken<List<String>>() {
            }.getType());/* www . jav  a2 s.c  om*/
    this.context = context;
    this.additionalServiceId = additionalServiceId;
}