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

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

Introduction

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

Prototype

public final Type getType() 

Source Link

Document

Gets underlying Type instance.

Usage

From source file:account.UpdateNlc.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww .  j  av a  2 s .com*/
 *
 * @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.//w w w . ja 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<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:apprenda.clientservices.tasks.ApprendaDeployTask.java

License:Apache License

private <T> T getObjectFromJson(String jsonString, TypeToken<T> conversionType) {
    Gson gson = getGsonBuilder();/*from  ww  w . j ava  2 s .c o m*/
    Type collectionType = conversionType.getType();
    T returnValue = gson.fromJson(jsonString, collectionType);
    return returnValue;
}

From source file:au.com.addstar.cellblock.utilities.Utilities.java

License:Open Source License

/**
 * The objects class must much the TypeTokens underlying class.
 *
 * @param file   the file to save to/*w  w w.ja v a  2  s.com*/
 * @param object the object to save
 * @param type   a TypeToken that is defined using the same class as the object.
 */
public static <T extends Serializable> void saveFile(File file, T object, TypeToken<T> type) {
    try {
        if (file.exists() || file.createNewFile()) {
            OutputStream out = new FileOutputStream(file);
            String encoded = gsonEncoder.toJson(object, type.getType());
            out.write(encoded.getBytes());
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:au.com.addstar.cellblock.utilities.Utilities.java

License:Open Source License

public static <T extends Serializable> T loadFile(File file, TypeToken<T> type) {
    if (!file.exists()) {
        return null;
    }//from  w ww.j  ava  2 s  . c  o m
    try {
        InputStream in = new FileInputStream(file);
        InputStreamReader inread = new InputStreamReader(in);
        JsonReader reader = new JsonReader(inread);
        return gsonEncoder.fromJson(reader, type.getType());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:bank.AddUpdateBankVoucher.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww  . j av 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<BankPaymentReceiptModel>> token = new TypeToken<List<BankPaymentReceiptModel>>() {
    };
    List<BankPaymentReceiptModel> detail = new Gson().fromJson(detailJson, token.getType());
    response.getWriter().print(saveVoucher((ArrayList<BankPaymentReceiptModel>) detail));

}

From source file:br.com.locadoraveiculodesktop.recurso.FabricanteRecurso.java

public List<Fabricante> pesquisar(String urlPart) {
    //casa//  ww w  .  j a v  a  2 s.co m
    String targetURL = servidorCasa + "locadoraveiculo/rest/" + urlPart;
    //servio
    //  String targetURL = "http://localhost:2411/locadoraveiculo/rest/" + urlPart;

    List<Fabricante> listaFabricante = new ArrayList<>();

    try {

        URL targetUrl = new URL(targetURL);

        HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.setRequestProperty("Accept", "application/json");

        if (httpConnection.getResponseCode() != 200) {
            throw new RuntimeException(
                    "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
        }

        BufferedReader responseBuffer = new BufferedReader(
                new InputStreamReader((httpConnection.getInputStream())));

        String output;
        System.out.println("Output from Server:  \n");

        while ((output = responseBuffer.readLine()) != null) {
            System.out.println(output);
            TypeToken<List<Fabricante>> token = new TypeToken<List<Fabricante>>() {
            };
            listaFabricante = new Gson().fromJson(output, token.getType());
            System.out.println("listaFabricante " + listaFabricante.size());
        }

        httpConnection.disconnect();

    } catch (IOException | RuntimeException e) {
        System.out.println("erro " + e.getMessage());
    }
    return listaFabricante;
}

From source file:cashPR.AddUpdateCashVoucher.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w w .j ava 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<CashPaymentReceiptModel>> token = new TypeToken<List<CashPaymentReceiptModel>>() {
    };
    List<CashPaymentReceiptModel> detail = new Gson().fromJson(detailJson, token.getType());
    response.getWriter().print(saveVoucher((ArrayList<CashPaymentReceiptModel>) detail));

}

From source file:cmput301w15t07.TravelTracker.util.DeletionFlagTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w  w w. j  a  va2  s  .  co  m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    // TODO technically isAssignableFrom is deprecated and we should change
    // it. Maybe some time in the future.
    if (!DeletionFlag.class.isAssignableFrom(type.getRawType())) {
        return null;
    }

    Log.d("TypeAdapter", "Good type: " + type.getRawType().getCanonicalName());
    for (Type param : ((ParameterizedType) type.getType()).getActualTypeArguments()) {
        Log.d("TypeAdapter", "Parameter type: " + param.toString());
    }

    // Get the parameterizing type
    Type elementType = ((ParameterizedType) type.getType()).getActualTypeArguments()[0];

    // Get adapters specific to the object we need so that we can delegate
    TypeAdapter<?> documentAdapter = gson.getAdapter(TypeToken.get(elementType));

    return (TypeAdapter<T>) new DeletionFlagAdapter<Document>((TypeAdapter<Document>) documentAdapter);
}

From source file:cn.fantasee.data.cache.serializer.JsonSerializer.java

License:Apache License

public String serialize(T entity, TypeToken<T> type) {
    String jsonString = gson.toJson(entity, type.getType());
    return jsonString;
}