Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.romb.hashfon.helper; import com.romb.hashfon.domain.Hr; import com.romb.hashfon.domain.Student; import java.lang.reflect.Field; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author Marko */ public class Helper { AbstractTokenCreator tokenHelper; public AbstractTokenCreator getAbstractToken() { return tokenHelper; } public Helper() { tokenHelper = new Base64Token(); } public String getJson(List list) { JSONArray jsonList = new JSONArray(); for (Object o : list) { JSONObject obj1 = new JSONObject(); for (Field field : o.getClass().getDeclaredFields()) { if (!field.getName().equals("serialVersionUID")) { field.setAccessible(true); String s = ""; try { s = field.get(o) + ""; } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex); } obj1.put(field.getName(), s); } } jsonList.add(obj1); } return jsonList.toJSONString(); } public boolean isStudentLogged(String[] token) { try { EntityManager em = getEntityManager(); if (token[1].equals("STUDENT")) { Student s = em.find(Student.class, Long.parseLong(token[2])); return s != null; } else { return false; } } catch (Exception e) { return false; } } public boolean isKompanijaLogged(String[] token) { try { EntityManager em = getEntityManager(); if (token[1].equals("KOMPANIJA")) { Hr hr = (Hr) em.createNamedQuery("Hr.findById").setParameter("id", Long.parseLong(token[2])) .getSingleResult(); return hr != null; } else { return false; } } catch (Exception e) { return false; } } public boolean isLogged(String[] token) { try { EntityManager em = getEntityManager(); if (token[1].equals("STUDENT")) { Student s = em.find(Student.class, Long.parseLong(token[2])); return s != null; } else { Hr hr = (Hr) em.createNamedQuery("Hr.findById").setParameter("id", Long.parseLong(token[2])) .getSingleResult(); return hr != null; } } catch (Exception e) { return false; } } public EntityManager getEntityManager() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.romb_hashfon_war_1.0PU"); EntityManager ecm = emf.createEntityManager(); return ecm; } public void persistObject(EntityManager em, Object o) { em.getTransaction().begin(); em.persist(o); em.getTransaction().commit(); } public void removeObject(EntityManager em, Object o, Long id) { em.getTransaction().begin(); em.remove(o); em.getTransaction().commit(); } public void mergeObject(EntityManager em, Object o) { em.getTransaction().begin(); em.merge(o); em.getTransaction().commit(); } }