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:abtlibrary.utils.as24ApiClient.api.VehiclesApi.java

License:Apache License

/**
 *  (asynchronously)// w  ww .  ja  va 2  s .  c o  m
 * 
 * @param vehicleId  (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call gETpublicV41VehiclesVehicleidLeasingAsync(Integer vehicleId,
        final ApiCallback<ResponseMessageLeasing> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = gETpublicV41VehiclesVehicleidLeasingCall(vehicleId, progressListener,
            progressRequestListener);
    Type localVarReturnType = new TypeToken<ResponseMessageLeasing>() {
    }.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}

From source file:account.UpdateNlc.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww.  j a v a  2  s.  c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String detailJson = request.getParameter("detail");
    TypeToken<List<NlcModel>> token = new TypeToken<List<NlcModel>>() {
    };
    final List<NlcModel> detail = new Gson().fromJson(detailJson, token.getType());
    final ArrayList<NlcModel> data = (ArrayList<NlcModel>) detail;
    final DBHelper helper = DBHelper.GetDBHelper();
    final Connection dataConnection = helper.getConnMpAdmin();
    final Library lb = Library.getInstance();
    final JsonObject jResultObj = new JsonObject();
    if (dataConnection != null) {
        try {
            dataConnection.setAutoCommit(false);
            PreparedStatement pstUpdate1 = null;
            String sql1 = "update tag set disc_per=?,extra_support=?,backend=?,activation=?,prize_drop=? where ref_no=?";
            pstUpdate1 = dataConnection.prepareStatement(sql1);
            for (int i = 0; i < data.size(); i++) {
                pstUpdate1.setDouble(1, data.get(i).getDisc_per());
                pstUpdate1.setDouble(2, data.get(i).getExtra_support());
                pstUpdate1.setDouble(3, data.get(i).getBackend());
                pstUpdate1.setDouble(4, data.get(i).getActivation());
                pstUpdate1.setDouble(5, data.get(i).getPrize_drop());
                pstUpdate1.setString(6, data.get(i).getRef_no());
                pstUpdate1.executeUpdate();
            }

            String sql = "update oldb2_1 set dr_" + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "=dr_"
                    + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "+? where ac_CD=?";
            PreparedStatement pstUpdate = dataConnection.prepareStatement(sql);
            pstUpdate.setDouble(1, data.get(0).getCnAmount());
            pstUpdate.setString(2, data.get(0).getAc_cd());
            pstUpdate.executeUpdate();

            sql = "insert into oldb2_2 (doc_ref_no,doc_date,doc_cd,ac_cd,"
                    + "val,crdr,particular,opp_ac_cd,time_stamp,INV_NO) values(?,CURRENT_DATE,?,?,?,?,?,?,CURRENT_TIMESTAMP,?)";

            pstUpdate = dataConnection.prepareStatement(sql);
            pstUpdate.setString(1, "PD");
            pstUpdate.setString(2, "PD");
            pstUpdate.setString(3, data.get(0).getAc_cd());
            pstUpdate.setDouble(4, data.get(0).getCnAmount());
            pstUpdate.setString(5, "0");
            pstUpdate.setString(6, data.get(0).getRemark());
            pstUpdate.setString(7, "");
            pstUpdate.setString(8, "0");
            pstUpdate.executeUpdate();

            sql = "insert into prize_drop (pur_tag_no,sr_no,voucher_no,v_date,remark,prev_rate,rate,ac_cd) values (?,?,?,CURRENT_DATE,?,?,?,?)";
            pstUpdate = dataConnection.prepareStatement(sql);
            for (int i = 0; i < data.size(); i++) {
                pstUpdate.setString(1, data.get(i).getRef_no());
                pstUpdate.setInt(2, i + 1);
                pstUpdate.setString(3, lb.generateKey(dataConnection, "prize_drop", "voucher_no", "PZ", 7));
                pstUpdate.setString(4, data.get(i).getRemark());
                pstUpdate.setDouble(5, 0.00);
                pstUpdate.setDouble(6, data.get(i).getExtra_support() + data.get(i).getBackend()
                        + data.get(i).getBackend() + data.get(i).getActivation() + data.get(i).getPrize_drop());
                pstUpdate.setString(7, data.get(i).getAc_cd());
                pstUpdate.executeUpdate();
            }
            dataConnection.commit();
            dataConnection.setAutoCommit(true);
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
        } catch (SQLNonTransientConnectionException ex1) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", "Server is down");
            try {
                dataConnection.rollback();
                dataConnection.setAutoCommit(true);
            } catch (SQLException ex) {
                Logger.getLogger(UpdatePrize.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", ex.getMessage());
            try {
                dataConnection.rollback();
                dataConnection.setAutoCommit(true);
            } catch (SQLException ex2) {
                Logger.getLogger(UpdatePrize.class.getName()).log(Level.SEVERE, null, ex2);
            }
        }
    }
    response.getWriter().print(jResultObj);

}

From source file:account.UpdatePrize.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  w  . j  a v  a2s .  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String detailJson = request.getParameter("detail");
    TypeToken<List<PrizeDrop>> token = new TypeToken<List<PrizeDrop>>() {
    };
    final List<PrizeDrop> detail = new Gson().fromJson(detailJson, token.getType());
    final ArrayList<PrizeDrop> data = (ArrayList<PrizeDrop>) detail;
    final DBHelper helper = DBHelper.GetDBHelper();
    final Connection dataConnection = helper.getConnMpAdmin();
    final Library lb = Library.getInstance();
    final JsonObject jResultObj = new JsonObject();
    if (dataConnection != null) {
        try {
            dataConnection.setAutoCommit(false);
            PreparedStatement pstLocal = null;
            PreparedStatement pstLocal1 = null;
            String sql = "insert into prize_drop (pur_tag_no,sr_no,voucher_no,v_date,remark,prev_rate,rate,ac_cd) values (?,?,?,CURRENT_DATE,?,?,?,?)";
            String sql1 = "update tag set pur_rate=pur_rate-? where ref_no=?";
            pstLocal = dataConnection.prepareStatement(sql);
            pstLocal1 = dataConnection.prepareStatement(sql1);
            for (int i = 0; i < data.size(); i++) {
                pstLocal.setString(1, data.get(i).getPur_tag_no());
                pstLocal.setInt(2, i + 1);
                if (data.get(i).getVoucher_no().equalsIgnoreCase("")) {
                    pstLocal.setString(3, lb.generateKey(dataConnection, "prize_drop", "voucher_no", "PZ", 7));
                } else {
                    pstLocal.setString(3, data.get(i).getVoucher_no());
                }
                pstLocal.setString(4, data.get(i).getRemark());
                pstLocal.setDouble(5, data.get(i).getPrevious_rate());
                pstLocal.setDouble(6, data.get(i).getRate());
                pstLocal.setString(7, data.get(i).getAc_cd());
                pstLocal.executeUpdate();

                pstLocal1.setDouble(1, data.get(i).getRate());
                pstLocal1.setString(2, data.get(i).getPur_tag_no());
                pstLocal1.executeUpdate();

                sql = "update oldb2_1 set dr_" + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "=dr_"
                        + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "+? where ac_CD=?";
                PreparedStatement pstUpdate = dataConnection.prepareStatement(sql);
                pstUpdate.setDouble(1, data.get(i).getRate());
                pstUpdate.setString(2, data.get(i).getAc_cd());
                pstUpdate.executeUpdate();

                sql = "insert into oldb2_2 (doc_ref_no,doc_date,doc_cd,ac_cd,"
                        + "val,crdr,particular,opp_ac_cd,time_stamp,INV_NO) values(?,CURRENT_DATE,?,?,?,?,?,?,CURRENT_TIMESTAMP,?)";

                pstUpdate = dataConnection.prepareStatement(sql);
                pstUpdate.setString(1, "PD");
                pstUpdate.setString(2, "PD");
                pstUpdate.setString(3, data.get(i).getAc_cd());
                pstUpdate.setDouble(4, data.get(i).getRate());
                pstUpdate.setString(5, "0");
                pstUpdate.setString(6, data.get(i).getRemark());
                pstUpdate.setString(7, "");
                pstUpdate.setString(8, "0");
                pstUpdate.executeUpdate();
            }
            dataConnection.commit();
            dataConnection.setAutoCommit(true);
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
        } catch (SQLNonTransientConnectionException ex1) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", "Server is down");
            try {
                dataConnection.rollback();
                dataConnection.setAutoCommit(true);
            } catch (SQLException ex) {
                Logger.getLogger(UpdatePrize.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", ex.getMessage());
            try {
                dataConnection.rollback();
                dataConnection.setAutoCommit(true);
            } catch (SQLException ex2) {
                Logger.getLogger(UpdatePrize.class.getName()).log(Level.SEVERE, null, ex2);
            }
        }
    }
    response.getWriter().print(jResultObj);

}

From source file:actforothers.VolunteerDB.java

String importDrivers(JFrame pFrame, Date today, String user, ImageIcon oncIcon) {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Select Volunteer .csv file to import");
    chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));

    int volunteersAddedCount = 0;
    File volFile = null;/* w  w  w . jav a2s . c  o m*/

    int returnVal = chooser.showOpenDialog(pFrame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        volFile = chooser.getSelectedFile();
        CSVReader reader = null;
        try {
            reader = new CSVReader(new FileReader(volFile.getAbsoluteFile()));
            String[] nextLine, header;

            if ((header = reader.readNext()) != null) {
                //Read the ONC CSV File
                if (header.length == DRIVER_CSVFILE_HEADER_LENGTH) {
                    //build a list of ONCVolunteers from the file.
                    List<ONCVolunteer> volList = new ArrayList<ONCVolunteer>();

                    while ((nextLine = reader.readNext()) != null) // nextLine[] is an array of values from the line
                    {
                        //don't process records that don't have at least a first or last name
                        if (nextLine.length > 8 && nextLine[6].length() + nextLine[7].length() > 2) {
                            //                         System.out.println(String.format("fn %s ln %s", nextLine[6], nextLine[7]));
                            ONCVolunteer currVol = searchVolunteerListForMatch(nextLine[6], nextLine[7],
                                    volList);

                            if (currVol != null) {
                                //update the volunteer with the activity from this line
                                currVol.setActivityCode(
                                        updateActivityCode(nextLine[4], currVol.getActivityCode()));
                            } else {
                                //create a new volunteer and add it
                                int newActivityCode = updateActivityCode(nextLine[4], 0);
                                ONCVolunteer newVol = new ONCVolunteer(nextLine, today, user, newActivityCode);

                                volList.add(newVol);
                            }
                        }
                    }

                    Collections.sort(volList);

                    //now that we have a list of volunteers from the file, send the to the
                    //server to add to the existing database
                    //create the request to the server to import the families
                    Gson gson = new Gson();
                    Type listtype = new TypeToken<ArrayList<ONCVolunteer>>() {
                    }.getType();

                    String response = serverIF
                            .sendRequest("POST<volunteer_group>" + gson.toJson(volList, listtype));

                    if (response != null && response.startsWith("ADDED_VOLUNTEER_GROUP")) {
                        //process the list of jsons returned, adding agent, families, adults
                        //and children to the local databases
                        Type jsonlisttype = new TypeToken<ArrayList<String>>() {
                        }.getType();
                        ArrayList<String> changeList = gson.fromJson(response.substring(21), jsonlisttype);

                        //loop thru list of changes, processing each one
                        for (String change : changeList)
                            if (change.startsWith("ADDED_DRIVER")) {
                                this.processAddedObject(this, change.substring("ADDED_DRIVER".length()));
                                volunteersAddedCount++;
                            }
                    } else {
                        JOptionPane.showMessageDialog(pFrame,
                                "An error occured, " + volFile.getName() + " cannot be imported by the server",
                                "ONC Server Britepath Import Error", JOptionPane.ERROR_MESSAGE,
                                GlobalVariables.getONCLogo());
                    }
                } else
                    JOptionPane.showMessageDialog(pFrame,
                            "Volunteer file corrupted, header length = " + Integer.toString(header.length),
                            "Invalid Volunteer File", JOptionPane.ERROR_MESSAGE, oncIcon);
            } else
                JOptionPane.showMessageDialog(pFrame, "Couldn't read header in file: " + volFile.getName(),
                        "Invalid Volunteer File", JOptionPane.ERROR_MESSAGE, oncIcon);
        } catch (IOException x) {
            JOptionPane.showMessageDialog(pFrame, "Unable to open Volunteer file: " + volFile.getName(),
                    "Volunteer file not found", JOptionPane.ERROR_MESSAGE, oncIcon);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    //If no drivers were in the file
    if (volFile == null || volunteersAddedCount == 0)
        return "No Delivery Drivers were imported";
    else
        return String.format("%d Delivery Drivers imported from %s", volunteersAddedCount, volFile.getName());

}

From source file:actforothers.VolunteerDB.java

String importDriverDatabase() {
    String response = "NO_DRIVERS";

    if (serverIF != null && serverIF.isConnected()) {
        Gson gson = new Gson();
        Type listtype = new TypeToken<ArrayList<ONCVolunteer>>() {
        }.getType();/*from   w w w .ja  v a  2s .  co m*/

        response = serverIF.sendRequest("GET<drivers>");
        volunteerList = gson.fromJson(response, listtype);

        if (!response.startsWith("NO_DRIVERS")) {
            response = "DRIVERS_LOADED";
            fireDataChanged(this, "LOADED_DRIVERS", null);
        }
    }

    return response;
}

From source file:actforothers.VolunteerDB.java

List<ONCWarehouseVolunteer> getWarehouseHistory(int volID) {
    List<ONCWarehouseVolunteer> whList = new ArrayList<ONCWarehouseVolunteer>();
    Gson gson = new Gson();

    String response = serverIF.sendRequest("GET<warehousehistory>" + Integer.toString(volID));

    if (response != null) {
        Type listtype = new TypeToken<ArrayList<ONCWarehouseVolunteer>>() {
        }.getType();//from  www.ja v  a  2 s  .  com
        whList = gson.fromJson(response, listtype);
    }

    return whList;
}

From source file:actions.toClassesSupervisorAction.java

public String execute() {
    HTTPPost post = new HTTPPost("ClassGrades", "getAll");

    String gsonToParse = post.sendGet();
    System.out.println(gsonToParse);
    Type type = new TypeToken<List<ClassGrades>>() {
    }.getType();/*from   ww  w.j a va 2 s  .co m*/
    sub = new Gson().fromJson(gsonToParse, type);
    return SUCCESS;
}

From source file:actions.ToRegisterSupervisorAction.java

public String execute() throws Exception {
    HTTPPost post = new HTTPPost("school", "getAll");
    String gsonToParse = post.sendGet();

    Type type = new TypeToken<List<Schools>>() {
    }.getType();/*from w w w .  j a  va2  s  .com*/
    sch = new Gson().fromJson(gsonToParse, type);

    return SUCCESS;
}

From source file:administracion.actions.OperacionesDatosRestauranteAction.java

@Override
public String execute() throws Exception {
    //Obtenemos los datos del request
    String operacion = request.getParameter("operacion");

    GestorOperacionesDatosRestaurante gdt = new GestorOperacionesDatosRestaurante();
    int resultadoOperacion = 0;

    Gson gson = new GsonBuilder().create();

    switch (operacion) {
    case "modificarDatosLocal":
        String datosLocalRequest = request.getParameter("datosLocal");
        //Reconstruimos el objeto JSON usuario del request
        Restaurante restaurante = gson.fromJson(datosLocalRequest, Restaurante.class);

        //Realizamos la operacion
        resultadoOperacion = gdt.actualizarDatosRestaurante(restaurante);

        try {// ww  w.j a v a 2 s  . c o  m
            montarVistaDatosRestaurante(resultadoOperacion, restaurante);
        } catch (IOException e) {
            System.out.println(
                    "OperacionesDatosRestauranteAction. Error al montar la vista datos restaurante: " + e);
        }

        break;

    case "modificarNumeroMesas":
        int numeroMesas = Integer.parseInt(request.getParameter("numeroMesas"));
        int numeroMesasInicial = Integer.parseInt(request.getParameter("numeroMesasInicial"));

        //Realizamos la operacion
        resultadoOperacion = gdt.actualizarNumeroMesas(numeroMesasInicial, numeroMesas);

        try {
            montarVistaNumeroMesas(resultadoOperacion, numeroMesas, numeroMesasInicial);
        } catch (IOException e) {
            System.out.println(
                    "OperacionesDatosRestauranteAction. Error al montar la vista numero de mesas: " + e);
        }

        break;

    case "modificarImpuestos":
        String listaImpuestosRequest = request.getParameter("listaImpuestos");
        String listaImpuestosInicialesRequest = request.getParameter("listaImpuestosIniciales");

        //Reconstruimos el objeto JSON usuario del request y obtenemos una lista
        Type listTypeImpuesto = new TypeToken<ArrayList<Impuesto>>() {
        }.getType();
        List<Impuesto> listaImpuestos = gson.fromJson(listaImpuestosRequest, listTypeImpuesto);
        List<Impuesto> listaImpuestosIniciales = gson.fromJson(listaImpuestosInicialesRequest,
                listTypeImpuesto);

        //Realizamos la operacion
        //Por este motivo tenemos los valores iniciales porque si recibimos 4 impuestos en la lista pero solo se ha modificado 1, solo modificamos ese
        for (int i = 0; i < listaImpuestos.size(); i++) {
            if (listaImpuestos.get(i).getValor() != listaImpuestosIniciales.get(i).getValor()) {
                resultadoOperacion = gdt.insertarImpuesto(listaImpuestos.get(i));
                if (resultadoOperacion != 1) {
                    break;
                }
            }
        }

        try {
            montarVistaImpuestos(resultadoOperacion, listaImpuestos);
        } catch (IOException e) {
            System.out.println("OperacionesDatosRestauranteAction. Error al montar la vista impuestos: " + e);
        }

        break;
    }

    return null; //Devilvemos null para no tener na vista
}

From source file:ai.olami.nli.NLIResult.java

License:Apache License

/**
 * @return List of data object/*  w  w  w  . ja  va  2 s  .  c  om*/
 *         or list of JsonElement if the object type is not defined.
 */
public <T> ArrayList<T> getDataObjects() {
    if (isFromIDS()) {
        String typeName = mType;
        switch (IDSResult.Types.getByName(mType)) {
        case QUESTION:
            typeName = this.getDescObject().getType();
            break;
        case CONFIRMATION:
            typeName = this.getDescObject().getType();
            break;
        case SELECTION:
            typeName = this.getDescObject().getType();
            break;
        default:
            break;
        }
        return mGson.fromJson(mDataObjs, IDSResult.Types.getDataArrayListType(typeName));
    } else if (hasDataObjects()) {
        return mGson.fromJson(mDataObjs, new TypeToken<ArrayList<JsonElement>>() {
        }.getType());
    }
    return null;
}