import java.util.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.sql.Timestamp; public class Main { public static void main(String[] args) throws Exception{ Date parsedDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").parse("2021-05-27T00:00:00-04:00"); System.out.println("Parsed Date:" +parsedDate); package com.broadridge.sleevesmaster.hibernate.config; package com.broadridge.sleevesmaster.hibernate; import jakarta.persistence.ParameterMode; import jakarta.persistence.StoredProcedureQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.query.NamedProcedureCallDefinition; import org.hibernate.jdbc.Work; import org.hibernate.procedure.ProcedureCall; import org.hibernate.query.Query; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import java.io.Serializable; import java.sql.BatchUpdateException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; public abstract class BaseHibernateDAO<KEY extends Serializable, ENTITY extends IModel> implements IHibernateDAO<KEY, ENTITY> { private static final Logger LOG = LoggerFactory.getLogger(BaseHibernateDAO.class); @Autowired private SessionFactory sessionFactory; public ENTITY fetchById(KEY id) { return this.getById(id); } protected ENTITY getById(KEY id) { LOG.debug("Inside HibernateDAO getById"); return this.sessionFactory.getCurrentSession().get(this.getEntityClazz(), id); } @Override public ENTITY insert(ENTITY entity) { LOG.debug("Inside HibernateDAO upsert"); if (entity != null) { this.getCurrentSession().persist(entity); } LOG.debug("Exiting HibernateDAO upsert"); return entity; } @Override public Collection<ENTITY> insertAll(Collection<ENTITY> entities) { LOG.debug("Inside HibernateDAO upsertAll"); if (!CollectionUtils.isEmpty(entities)) { Iterator var2 = entities.iterator(); while (var2.hasNext()) { ENTITY eachEntity = (ENTITY) var2.next(); this.insert(eachEntity); } } LOG.debug("Exiting HibernateDAO upsertAll"); return entities; } @Override public ENTITY update(ENTITY entity) { LOG.debug("Inside HibernateDAO upsert"); if (entity != null) { this.getCurrentSession().merge(entity); } LOG.debug("Exiting HibernateDAO upsert"); return entity; } @Override public Collection<ENTITY> updateAll(Collection<ENTITY> entities) { LOG.debug("Inside HibernateDAO upsertAll"); if (!CollectionUtils.isEmpty(entities)) { Iterator var2 = entities.iterator(); while (var2.hasNext()) { ENTITY eachEntity = (ENTITY) var2.next(); this.update(eachEntity); } } LOG.debug("Exiting HibernateDAO upsertAll"); return entities; } public Collection<ENTITY> findByHqlAndParmas(String hql, Map<String, Object> paramsmap) { return paramsmap != null && !paramsmap.isEmpty() ? this.findByHqlAndParmasAndGetEntity(hql, paramsmap, this.getEntityClazz()) : null; } public <T> Collection<T> findByHqlAndParmasAndGetEntity(String hql, Map<String, Object> paramsmap, Class<T> clazz) { LOG.debug("Inside HibernateDAO findByHqlAndParmasAndGetEntity"); return this.findByNamedParam(hql, paramsmap, clazz); } protected <T> Collection<T> findByNamedParam(String sql, Map<String, Object> paramsmap, Class<T> clazz) { LOG.debug("Inside HibernateDAO findByNamedParam"); if (paramsmap != null && !paramsmap.isEmpty()) { String[] paramNames = new String[paramsmap.size()]; Object[] paramValues = new Object[paramsmap.size()]; int i = 0; for (Iterator var7 = paramsmap.entrySet().iterator(); var7.hasNext(); ++i) { Map.Entry<String, Object> eachEntry = (Map.Entry) var7.next(); paramNames[i] = eachEntry.getKey(); paramValues[i] = eachEntry.getValue(); } Session session = this.sessionFactory.openSession(); try { //session = this.getSession(); Query<?> sqlQuery = session.createQuery(sql, clazz); for (int y = 0; y < paramValues.length; ++y) { sqlQuery.setParameter(paramNames[y], paramValues[y]); } List var = sqlQuery.getResultList(); return var; } catch (Exception e) { LOG.error("Error occurred while executing sql", e); } finally { this.closeSession(session); } LOG.debug("Exiting HibernateDAO findByNamedParam"); return null; } else { return null; } } protected abstract Class<ENTITY> getEntityClazz(); @Override public Collection findBySql(String sql) { return this.getSqlQuery(sql, this.getEntityClazz()); } @Override public Session getSession() { return this.sessionFactory.openSession(); } @Override public Session getCurrentSession() { return this.sessionFactory.getCurrentSession(); } @Override public void closeSession(Session session) { if (session != null) { session.close(); } } @Override public void deleteBySql(String sql) { LOG.debug("Inside HibernateDAO deleteBySql"); this.deleteBySqlWithParmas(sql, (Map) null); LOG.debug("Exiting HibernateDAO deleteBySql"); } @Override public void deleteBySql(String sql, Map params) { LOG.debug("Inside HibernateDAO deleteBySql"); deleteBySqlWithParmas(sql, params); LOG.debug("Inside HibernateDAO deleteBySql"); } private <T> Collection<T> getSqlQuery(String sql, Class<?> clazz) { Session session = this.sessionFactory.openSession(); try { session = this.getSession(); Query<?> sqlQuery = session.createQuery(sql, clazz); List list = sqlQuery.getResultList(); return list; } catch (Exception e) { LOG.error("Error occurred while executing sql", e); } finally { this.closeSession(session); } return null; } private void deleteBySqlWithParmas(String sql, Map<String, Object> paramsmap) { LOG.debug("Inside HibernateDAO deleteBySqlWithParmas"); Session session = this.sessionFactory.openSession(); try { // session = this.getSession(); session.beginTransaction(); Query<?> query = session.createQuery(sql, (Class) Object.class); if (!CollectionUtils.isEmpty(paramsmap)) { paramsmap.forEach(query::setParameter); } query.executeUpdate(); session.getTransaction().commit(); } catch (Exception var8) { LOG.error("Error occurred while deleting with sql records", var8); } finally { this.closeSession(session); } LOG.debug("Exiting HibernateDAO deleteBySqlWithParmas"); } public void bulkUpsert(Collection<ENTITY> entities) { LOG.debug("Inside HibernateDAO bulkUpsert"); if (!CollectionUtils.isEmpty(entities)) { Session session = null; try { session = this.sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); int counter = 1; try { for (Iterator var5 = entities.iterator(); var5.hasNext(); ++counter) { ENTITY eachEntity = (ENTITY) var5.next(); session.merge(eachEntity); if (counter % 10 == 0) { session.flush(); session.clear(); } } } catch (Exception var17) { LOG.error("Error occurred while inserting batch records", var17); if (this.isTransactionStatusActive(transaction)) { transaction.rollback(); } } finally { if (this.isTransactionStatusActive(transaction)) { transaction.commit(); } } } catch (Exception var19) { LOG.error("Error occurred while inserting batch records", var19); } finally { if (session != null) { session.close(); } } } LOG.debug("Exiting HibernateDAO bulkUpsert"); } private void addParameterToBatch(Map<String, Object> parameters, StoredProcedureQuery query) { if (!ObjectUtils.isEmpty(parameters)) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { String paramName = entry.getKey(); Object paramValue = entry.getValue(); query.registerStoredProcedureParameter(paramName, paramValue.getClass(), ParameterMode.IN) .setParameter(paramName, paramValue); } } } /** * executeStoredProc which will take only Parameter IN inputs * @param storedProcSql * @param parameters */ @Override public void executeStoredProc(final String storedProcSql, final Map<String, Object> parameters) { LOG.debug("Inside BaseHibernateDAO executeStoredProc"); try { Session session = this.getCurrentSession(); ProcedureCall query = session.createStoredProcedureCall(storedProcSql); BaseHibernateDAO.this.addParameterToBatch(parameters, query); query.execute(); } catch (Exception e) { BaseHibernateDAO.LOG.error("SQLException in BaseHibernateDAO.executeStoredProc : {}", e.getMessage()); throw e; } LOG.debug("Exiting BaseHibernateDAO executeStoredProc"); } private boolean isTransactionStatusActive(Transaction transaction) { return transaction.getStatus().equals(TransactionStatus.ACTIVE); } } } }
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |