Example usage for com.google.gson Gson Gson

List of usage examples for com.google.gson Gson Gson

Introduction

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

Prototype

public Gson() 

Source Link

Document

Constructs a Gson object with default configuration.

Usage

From source file:AddUserController.java

public AddUserController() {
    //try{// w w w.ja  v a 2s .  c  o m
    post("/newuser", (req, res) -> {
        String id = UUID.randomUUID().toString();
        String username = req.queryParams("username");
        String name = req.queryParams("name");
        String email = req.queryParams("email");
        String bizname = req.queryParams("bizname");
        String website = req.queryParams("website");
        String craft = req.queryParams("craft");
        String about = req.queryParams("about");

        Map<String, Object> userData = new HashMap<>();
        userData.put("id", id);
        userData.put("username", username);
        userData.put("name", name);
        userData.put("email", email);
        userData.put("bizname", bizname);
        userData.put("website", website);
        userData.put("craft", craft);
        userData.put("about", about);
        Gson gson = new Gson();
        return gson.toJson(userData);
        /* 
                
                
        Map<String, Object> userData = new HashMap<>();
                
        Gson gson = new Gson();                
        return gson.toJson(userData);*/
    });

    /*}catch(Exception e){
    final JPanel panel = new JPanel();
            
    JOptionPane.showMessageDialog(panel, "Could not add user.", "Error", JOptionPane.ERROR_MESSAGE);
    }
    }*/
}

From source file:FriendController.java

public FriendController() {
    get("/friends", (req, res) -> {
        /*Map<String, User> userList = new HashMap<>();
        User user001 = new User("Summer Smith", "summer@randm.com", "Summer Sol", "rickandmorty.com");
        userList.put(user001.getId(), user001);
        Gson gson = new Gson();//from  w  w w  .ja va  2  s  . co  m
        return gson.toJson(userList);*/
        String id = UUID.randomUUID().toString();
        Map<String, Object> friendList = new HashMap<>();
        friendList.put("id", id);
        friendList.put("username", "schwiftytime");
        friendList.put("name", "Rick Sanchez");
        friendList.put("email", "rick@rick.com");
        friendList.put("bizname", "Curse Purge Plus!");
        friendList.put("website", "rickandmorty.com");
        friendList.put("craft", "Science");
        friendList.put("about", "*Burp*");
        /* friendList.put("id", "0001");
        friendList.put("username", "inferiorgenes");
        friendList.put("name", "Abradolf Lincler");
        friendList.put("email", "abe@rick.com");
        friendList.put("bizname", "Emancipation");
        friendList.put("website", "rickandmorty.com");
        friendList.put("craft", "Wood Burning");
        friendList.put("about", "Wood work is calming.");*/
        Gson gson = new Gson();
        return gson.toJson(friendList);
    });

    /*get("/users", (req, res) -> userService.getAllUsers(), json());
            
    get("/users/:id", (req, res) -> {
       String id = req.params(":id");
       User user = userService.getUser(id);
       if (user  != null) {
    return user;
       }
       res.status(400);
       return new ResponseError("No user with id '%s' found", id);
    }, json());
            
    wrote similar code elsewhere
        post("/users", (req, res) -> userService.createUser(
    req.queryParams("name"),
                        req.queryParams("email"),
                        req.queryParams("bizname"),
                        req.queryParams("website")
    ), json());
            
    exception(IllegalArgumentException.class, (e, req, res) -> {
       res.status(400);
       res.body(toJson(new ResponseError(e)));
    });*/
}

From source file:GetEmailServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        try {//from  ww w.  j av  a  2 s .c  om
            emf = Persistence.createEntityManagerFactory("FileUploadPU");
            em = emf.createEntityManager();

            List<String> email = new ArrayList<String>();

            for (User i : (List<User>) em.createNamedQuery("User.findAll").getResultList()) {
                email.add(i.getEmail());

            }

            String json = new Gson().toJson(email);
            out.write(json);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            em.close();
            emf.close();
        }
    }
}

From source file:Check_Email.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*w  ww.ja v a  2  s  . c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    String email = request.getParameter("remail").replaceAll(" ", "");
    email = email.toLowerCase();
    System.out.println(email);
    Map<String, String> options = new LinkedHashMap<String, String>();
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String connectionURL = "jdbc:derby://localhost:1527/WTFtask";
        try {

            Connection conn = DriverManager.getConnection(connectionURL, "IS2560", "IS2560");
            String query1 = "SELECT * FROM WTFuser where email = '" + email + "'";
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(query1);
            //HttpServletResponse.sendRedirect("/your/new/location.jsp")
            boolean is = rs.next();
            if (!is) {
                options.put("valid", "true");
                String json = new Gson().toJson(options);
                response.getWriter().write(json);
            } else if (is) {
                options.put("valid", "false");
                String json = new Gson().toJson(options);
                response.getWriter().write(json);
            }
            st.close();
            rs.close();
            conn.close();

        } catch (SQLException ex) {
            out.print("Connection Failed!");
        }
    }

}

From source file:getNamesSv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  ww  .j  a v a  2s. 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 {
    response.setContentType("text/json;charset=UTF-8");
    try {
        PrintWriter out = response.getWriter();
        int estado = Integer.parseInt(request.getParameter("estado"));
        classList sr = new classList(estado);
        Gson gson = new Gson();
        out.println(gson.toJson(sr));
        out.close();
    } catch (Exception ex) {
        System.out.println("Error");
    }
}

From source file:BITalinoExample.java

License:Apache License

public static void main(String[] args) throws Throwable {
    // validate MAC address
    // if (!mac.matches("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$"))
    // throw new BITalinoException(BITalinoErrorTypes.MACADDRESS_NOT_VALID);
    final String mac = MAC.replace(":", "");

    final int samplerate = 100;
    final int[] analogs = { 0 };
    BITalinoDevice device = new BITalinoDevice(samplerate, analogs);

    // connect to BITalino device
    final StreamConnection conn = (StreamConnection) Connector.open("btspp://" + mac + ":1",
            Connector.READ_WRITE);/*w ww .  ja v a  2  s .  co  m*/
    device.open(conn.openInputStream(), conn.openOutputStream());

    // get BITalino version
    logger.info("Firmware Version: " + device.version());

    // start acquisition on predefined analog channels
    device.start();

    // read n samples
    final int numberOfSamplesToRead = 20;
    BITalinoFrame[] samplesRead = new BITalinoFrame[numberOfSamplesToRead];
    final String logFile = "bitalino_log.json";
    final FileWriter fileWriter = new FileWriter(logFile);
    logger.info("Reading " + numberOfSamplesToRead + " samples..");
    for (int counter = 0; counter < numberOfSamplesToRead; counter++) {
        final BITalinoFrame[] frames = device.read(1);
        samplesRead[counter] = frames[0];
        logger.info("FRAME: " + frames[0].toString());
        Thread.sleep(1000);
    }
    fileWriter.write(new Gson().toJson(samplesRead));
    fileWriter.close();
    logger.info("Generated " + logFile + " with frames encoded into JSON.");

    // trigger digital outputs
    // int[] digital = { 1, 1, 1, 1 };
    // device.trigger(digital);

    // stop acquisition and close bluetooth connection
    device.stop();
}

From source file:LoadPriceModel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  w  .j  a va2  s  . co  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 {
    response.setContentType("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        DAOFactory db = DAOFactory.getDAOFactory(1);
        SalesOrderDAO salesDB = db.getSalesOrderDAO();
        SalesOrder so = new SalesOrder();
        so.setOrder_id(Integer.parseInt(request.getParameter("orderid")));
        ArrayList<Product> products = salesDB.getPriceModel(so);
        String json = new Gson().toJson(products);
        response.getWriter().write(json);
    }
}

From source file:jsonSploit.java

/**
 * @param args the command line arguments
 *///from w  w w .  ja v  a 2  s  . c om
public static void main(String[] args) {
    // TODO code application logic here
    Gson gson = new Gson();
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println(sb.toString());
    System.out.println("\n\n--------------------JSON OBJECT DISPLAY----------------------------\n\n");
    // convertimos el string a json Object
    JSONObject jsonObj = new JSONObject(jsonResult);
    // System.out.println("LA CADENA JSON CONVERTIDA EN OBJETO ES>");
    System.out.println(jsonObj.toString());

    System.out
            .println("\n\n--------------------- OBTENER ARRAYS DEL OBJETO JSON---------------------------\n\n");

    JSONArray jsonArray = new JSONArray();
    jsonArray.put(jsonObj);
    gson = new Gson();
    Iterator x = jsonObj.keys();
    while (x.hasNext()) {
        String key = (String) x.next();
        jsonArray.put(jsonObj.get(key));
        System.out.println(key);

    }
    System.out
            .println("\n\n--------------------- OBTENER ARRAYS DEL OBJETO JSON---------------------------\n\n");
    JsonParser jsonParser = new JsonParser();
    JsonObject jo = (JsonObject) jsonParser.parse(jsonResult);
    JsonArray jsonArr = jo.getAsJsonArray("data");
    Gson googleJson = new Gson();
    ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
    System.out.println("Listas existentes en data : " + jsonObjList.size());
    System.out.println("los elementos de la lista son  : " + jsonObjList.toString());
    String dataResult = jsonObjList.toString();

    System.out.println("\n\n--------------------- EL OBJETO JSON  ARRAY---------------------------\n\n");
    /// jsonArr.remove(1);
    String elemento1 = null;

    Iterator<JsonElement> nombreIterator = jsonArr.iterator();
    JsonElement elemento = null;
    while (nombreIterator.hasNext()) {
        elemento = nombreIterator.next();
        System.out.print(elemento + " \n");
        elemento1 = elemento.toString();
        System.out.println("El elemento 1 es " + elemento1);
    }

    cData data = gson.fromJson(elemento1, cData.class);
    // Account account = gson.fromJson(jo, Account.class);
    if (data.getAccount().getFirst_name() == null) {
        System.out.println("Error");
    } else {
        System.out.print(data.getAccount().getFirst_name());
    }
    // System.out.println(data.acount.getNumber());

    System.out.println("\n\n--------------------- OBTENEMOS EL OBJETO ACCOUNT---------------------------\n\n");
    //JsonObject jObject = (JsonObject) jsonParser.parse(elemento1);
    // System.out.println(jObject.getAsJsonPrimitive("number"));

}

From source file:SubscriberBatch.java

License:Open Source License

private void applyReminderNotifications(Connection sd, Connection cResults, String basePath,
        String serverName) {/* w  w w . j a v a  2  s .  co m*/

    // Sql to get notifications that need a reminder
    String sql = "select " + "t.id as t_id, " + "n.id as f_id, " + "a.id as a_id, " + "t.survey_ident, "
            + "t.update_id," + "t.p_id," + "n.target," + "n.remote_user," + "n.notify_details "
            + "from tasks t, assignments a, forward n " + "where t.tg_id = n.tg_id " + "and t.id = a.task_id "
            + "and n.enabled " + "and n.trigger = 'task_reminder' " + "and a.status = 'accepted' "
            //+ "and a.assigned_date < now() - cast(n.period as interval) "   // use schedule at however could allow assigned date to be used
            + "and t.schedule_at < now() - cast(n.period as interval) "
            + "and a.id not in (select a_id from reminder where n_id = n.id)";
    PreparedStatement pstmt = null;

    // Sql to record a reminder being sent
    String sqlSent = "insert into reminder (n_id, a_id, reminder_date) values (?, ?, now())";
    PreparedStatement pstmtSent = null;

    try {

        pstmt = sd.prepareStatement(sql);
        pstmtSent = sd.prepareStatement(sqlSent);

        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        HashMap<Integer, ResourceBundle> locMap = new HashMap<>();
        MessagingManager mm = new MessagingManager();

        ResultSet rs = pstmt.executeQuery();
        int idx = 0;
        while (rs.next()) {

            if (idx++ == 0) {
                System.out.println("\n-------------");
            }
            int tId = rs.getInt(1);
            int nId = rs.getInt(2);
            int aId = rs.getInt(3);
            String surveyIdent = rs.getString(4);
            String instanceId = rs.getString(5);
            int pId = rs.getInt(6);
            String target = rs.getString(7);
            String remoteUser = rs.getString(8);
            String notifyDetailsString = rs.getString(9);
            NotifyDetails nd = new Gson().fromJson(notifyDetailsString, NotifyDetails.class);

            int oId = GeneralUtilityMethods.getOrganisationIdForNotification(sd, nId);

            // Send the reminder
            SubmissionMessage subMgr = new SubmissionMessage(tId, surveyIdent, pId, instanceId, nd.from,
                    nd.subject, nd.content, nd.attach, nd.include_references, nd.launched_only,
                    nd.emailQuestion, nd.emailQuestionName, nd.emailMeta, nd.emails, target, remoteUser,
                    "https", serverName, basePath);
            mm.createMessage(sd, oId, "reminder", "", gson.toJson(subMgr));

            // record the sending of the notification
            pstmtSent.setInt(1, nId);
            pstmtSent.setInt(2, aId);
            pstmtSent.executeUpdate();

            // Write to the log
            ResourceBundle localisation = locMap.get(nId);
            if (localisation == null) {
                Organisation organisation = GeneralUtilityMethods.getOrganisation(sd, oId);
                Locale orgLocale = new Locale(organisation.locale);
                localisation = ResourceBundle.getBundle("org.smap.sdal.resources.SmapResources", orgLocale);
            }

            String logMessage = "Reminder sent for: " + nId;
            if (localisation != null) {
                logMessage = localisation.getString("lm_reminder");
                logMessage = logMessage.replaceAll("%s1", GeneralUtilityMethods.getNotificationName(sd, nId));
            }
            lm.writeLogOrganisation(sd, oId, "subscriber", LogManager.REMINDER, logMessage);

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
        try {
            if (pstmtSent != null) {
                pstmtSent.close();
            }
        } catch (SQLException e) {
        }

    }
}

From source file:SecurePreferences.java

License:Open Source License

/**
 * This will initialize an instance of the SecurePreferences class
 * @param context your current context.//  w  w  w  .  j av a  2s  .  c om
 * @param preferenceName name of preferences file (preferenceName.xml)
 * @param secureKey the key used for encryption, finding a good key scheme is hard. 
 * Hardcoding your key in the application is bad, but better than plaintext preferences. Having the user enter the key upon application launch is a safe(r) alternative, but annoying to the user.
 * @param encryptKeys settings this to false will only encrypt the values, 
 * true will encrypt both values and keys. Keys can contain a lot of information about 
 * the plaintext value of the value which can be used to decipher the value.
 * @throws SecurePreferencesException
 */
public SecurePreferences(Context context, String preferenceName, String secureKey, boolean encryptKeys)
        throws SecurePreferencesException {
    try {
        this.writer = Cipher.getInstance(TRANSFORMATION);
        this.reader = Cipher.getInstance(TRANSFORMATION);
        this.keyWriter = Cipher.getInstance(KEY_TRANSFORMATION);
        GSON = new Gson();

        initCiphers(secureKey);

        this.preferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);

        this.encryptKeys = encryptKeys;
    } catch (GeneralSecurityException e) {
        throw new SecurePreferencesException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SecurePreferencesException(e);
    }
}