我正在构建一个从日志文件中读取信息的应用程序,在读取信息时,它应该将这些数据保存到数据库中。我从日志中获取的信息是一组包,其中一些用户已添加到包中,如下所示:
Package: (Total: 14, Used: 11)
CSHC, 11/11
CTQ8, 11/11
CTQ8, 11/11
每次我从日志中读取一个包时,我都会调用将包保存到数据库中。问题是在保存第4个包之后,应用程序冻结了。我不知道为什么。这是我正在使用的代码。
日志处理功能:
boolean erasePack = false;
Package pack = new Package();
//System.out.println("Zerei? "+ petrelLicensesInUse);
while (i < reportContent.size()){
phrase = reportContent.get(i);
if(erasePack){
pack = new Package();
erasePack = false;
}
if(phrase.contains(Constants.licenseUsageIdentifier)){
licenseUsage = true;
licenseUser = false;
licenseIssued = phrase.substring((phrase.indexOf(Constants.totalLicenseAvailableId) + 10),phrase.indexOf(Constants.endLicensesIssued));
licenseUsed = phrase.substring((phrase.indexOf(Constants.totalLicenseUsedId) + 12),phrase.indexOf(Constants.endLicensesUsed));
licenseIssuedNum = Integer.parseInt(licenseIssued);
licenseUsedNum = Integer.parseInt(licenseUsed);
licenseUsageList.add(phrase.replaceAll("; Total of ", ", Used: ").replaceAll("Users of ", "")
.replaceAll(" licenses issued", "").replaceAll(" licenses in use", "").replaceAll("Total of", "Total:")
.replaceAll(" license in use", "").replaceAll(" license issued", "").replace(" ", " "));
if(licenseUsedNum != 0){
pack.setUsers(new ArrayList<PbrUser>());
}
}
if(phrase.contains(Constants.licenseUserIdentifier)){
licenseUsage = false;
licenseUser = true;
currPckg = phrase.substring((phrase.indexOf(Constants.licenseUserIdentifier) + 1),phrase.indexOf(Constants.licenseUserIdentifier + " "));
version = phrase.substring((phrase.indexOf(Constants.version) + 3),phrase.indexOf(Constants.endVersion));
vendorDaemon = phrase.substring((phrase.lastIndexOf(' ') + 1));
pack.setNamePackage(currPckg);
pack.setVersion(version);
pack.setVendorDaemon(vendorDaemon);
pack.setNumberOfPackageLicenses(licenseIssuedNum);
//PackageController.create(pack);
}
if(licenseUser && phrase.contains(Constants.userStartDateId)){
//System.out.println(phrase.indexOf(Constants.userStartDateId));
currDate = transformDate(phrase.substring((phrase.indexOf(Constants.userStartDateId)+Constants.userStartDateId.length()),phrase.length()));
//System.out.println(phrase.substring(Constants.spaceUntilUser +1,phrase.length()).indexOf(" "));
currName = phrase.substring(Constants.spaceUntilUser, (Constants.spaceUntilUser + phrase.substring(Constants.spaceUntilUser +1,phrase.length()).indexOf(" ")+1));
PbrUser pbrUser = new PbrUser(currName);
//PbrUserController.create(pbrUser);
reportMetadataList.add(new ReportMetadata(currName, currPckg, currDate));
if(licenseUsedNum != 0){
//PbrUser pbrUser = new PbrUser(currName);
pack.getUsers().add(pbrUser);
}
contSave++;
}
if(licenseUser && contSave == licenseUsedNum){
PackageController.create(pack);
contSave=0;
erasePack = true;
}
i++;
}
广告代码:
static protected void insert(Object object){
Transaction tx = null;
Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
try {
tx = session.beginTransaction();
session.saveOrUpdate(object);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
logger.debug("Error rolling back transaction");
}
// throw again the first exception
throw e;
}
}
}
Hibernate Session工厂:
public class SessionFactoryUtil {
/** The single instance of hibernate SessionFactory */
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
/**
* disable contructor to guaranty a single instance
*/
private SessionFactoryUtil() {
}
static{
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);
}
public static SessionFactory getInstance() {
return sessionFactory;
}
/**
* Opens a session and will not bind it to a session context
* @return the session
*/
public Session openSession() {
return sessionFactory.openSession();
}
/**
* Returns a session from the session context. If there is no session in the context it opens a session,
* stores it in the context and returns it.
* This factory is intended to be used with a hibernate.cfg.xml
* including the following property <property
* name="current_session_context_class">thread</property> This would return
* the current open session or if this does not exist, will create a new
* session
*
* @return the session
*/
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
/**
* closes the session factory
*/
public static void close(){
if (sessionFactory != null)
sessionFactory.close();
sessionFactory = null;
}
}
使用C3p0的Hibernate cfg管理连接池:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/licensecontrol</property>
<property name="connection.username">postgres</property>
<property name="connection.password">root</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="schlumberger.sis.licenseControl.model.PbrUser"/>
<mapping class="schlumberger.sis.licenseControl.model.LicenseUsage"/>
<mapping class="schlumberger.sis.licenseControl.model.LicenseUsagePK"/>
<mapping class="schlumberger.sis.licenseControl.model.Package"/>
</session-factory>
</hibernate-configuration>
这是日志文件:
11:02:58,435 DEBUG GooGooStatementCache:215 - com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache ----> CACHE HIT
11:02:58,435 DEBUG GooGooStatementCache:232 - checkoutStatement: com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 5; checked out: 1; num connections: 1; num keys: 5
11:02:58,435 DEBUG GooGooStatementCache:307 - checkinStatement(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 5; checked out: 0; num connections: 1; num keys: 5
11:02:58,435 DEBUG SQL:109 -
insert
into
license_usage
(id_package, id_user)
values
(?, ?)
Hibernate:
insert
into
license_usage
(id_package, id_user)
values
(?, ?)
11:02:58,435 DEBUG GooGooStatementCache:215 - com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache ----> CACHE HIT
11:02:58,435 DEBUG GooGooStatementCache:232 - checkoutStatement: com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 5; checked out: 1; num connections: 1; num keys: 5
11:02:58,435 DEBUG GooGooStatementCache:307 - checkinStatement(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 5; checked out: 0; num connections: 1; num keys: 5
11:02:58,445 INFO StatisticalLoggingSessionEventListener:275 - Session Metrics {
1332957 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
25918978 nanoseconds spent preparing 17 JDBC statements;
20022685 nanoseconds spent executing 17 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
0 nanoseconds spent performing 0 L2C puts;
0 nanoseconds spent performing 0 L2C hits;
0 nanoseconds spent performing 0 L2C misses;
43865256 nanoseconds spent executing 1 flushes (flushing a total of 6 entities and 1 collections);
0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}
11:02:58,445 DEBUG GooGooStatementCache:333 - checkinAll(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 5; checked out: 0; num connections: 1; num keys: 5
11:02:58,445 DEBUG ThreadPoolAsynchronousRunner:236 - com.mchange.v2.async.ThreadPoolAsynchronousRunner@c88b770: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@76faa8cc
11:02:58,445 DEBUG BasicResourcePool:1747 - trace com.mchange.v2.resourcepool.BasicResourcePool@66cb8aa5 [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@2c9b93b9)
11:02:58,445 DEBUG GooGooStatementCache:333 - checkinAll(): com.mchange.v2.c3p0.stmt.GlobalMaxOnlyStatementCache stats -- total size: 5; checked out: 0; num connections: 1; num keys: 5
11:03:08,358 DEBUG ThreadPoolAsynchronousRunner:730 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@b4ace91 -- Running DeadlockDetector[Exiting. No pending tasks.]