mirror of
https://github.com/ebean-orm/ebean.git
synced 2026-11-18 14:58:47 +00:00
initial add of EbeanORM server based on v2.8.1
This commit is contained in:
1 parent
2b74d0f9d9
commit
96ce4c0ddf
1188 files changed
+135034
No files matched your search
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.DataInput;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessage;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
public class BeanDelta {
|
||||
|
||||
private final List<BeanDeltaProperty> properties;
|
||||
|
||||
private final BeanDescriptor<?> beanDescriptor;
|
||||
|
||||
private final Object id;
|
||||
|
||||
public BeanDelta(BeanDescriptor<?> beanDescriptor, Object id) {
|
||||
this.beanDescriptor = beanDescriptor;
|
||||
this.id = id;
|
||||
this.properties = new ArrayList<BeanDeltaProperty>();
|
||||
}
|
||||
|
||||
public BeanDescriptor<?> getBeanDescriptor() {
|
||||
return beanDescriptor;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("BeanDelta[");
|
||||
sb.append(beanDescriptor.getName()).append(":");
|
||||
sb.append(properties);
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public Object getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void add(BeanProperty beanProperty, Object value) {
|
||||
this.properties.add(new BeanDeltaProperty(beanProperty, value));
|
||||
}
|
||||
|
||||
public void add(BeanDeltaProperty propertyDelta) {
|
||||
this.properties.add(propertyDelta);
|
||||
}
|
||||
|
||||
public void apply(Object bean) {
|
||||
|
||||
for (int i = 0; i < properties.size(); i++) {
|
||||
properties.get(i).apply(bean);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and return a BeanDelta from the binary input.
|
||||
*/
|
||||
public static BeanDelta readBinaryMessage(SpiEbeanServer server, DataInput dataInput) throws IOException {
|
||||
|
||||
String descriptorId = dataInput.readUTF();
|
||||
BeanDescriptor<?> desc = server.getBeanDescriptorById(descriptorId);
|
||||
Object id = desc.getIdBinder().readData(dataInput);
|
||||
BeanDelta bp = new BeanDelta(desc, id);
|
||||
|
||||
int count = dataInput.readInt();
|
||||
for (int i = 0; i < count; i++) {
|
||||
String propName = dataInput.readUTF();
|
||||
BeanProperty beanProperty = desc.getBeanProperty(propName);
|
||||
Object value = beanProperty.getScalarType().readData(dataInput);
|
||||
bp.add(beanProperty, value);
|
||||
}
|
||||
return bp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write this bean delta in binary message format.
|
||||
*/
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
|
||||
BinaryMessage m = new BinaryMessage(50);
|
||||
|
||||
DataOutputStream os = m.getOs();
|
||||
os.writeInt(BinaryMessage.TYPE_BEANDELTA);
|
||||
os.writeUTF(beanDescriptor.getDescriptorId());
|
||||
|
||||
beanDescriptor.getIdBinder().writeData(os, id);
|
||||
os.writeInt(properties.size());
|
||||
|
||||
for (int i = 0; i < properties.size(); i++) {
|
||||
properties.get(i).writeBinaryMessage(m);
|
||||
}
|
||||
|
||||
os.flush();
|
||||
msgList.add(m);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
public class BeanDeltaList {
|
||||
|
||||
private final BeanDescriptor<?> beanDescriptor;
|
||||
|
||||
private final List<BeanDelta> deltaBeans = new ArrayList<BeanDelta>();
|
||||
|
||||
public BeanDeltaList(BeanDescriptor<?> beanDescriptor) {
|
||||
this.beanDescriptor = beanDescriptor;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return deltaBeans.toString();
|
||||
}
|
||||
|
||||
public BeanDescriptor<?> getBeanDescriptor() {
|
||||
return beanDescriptor;
|
||||
}
|
||||
|
||||
public void add(BeanDelta b) {
|
||||
deltaBeans.add(b);
|
||||
}
|
||||
|
||||
public List<BeanDelta> getDeltaBeans() {
|
||||
return deltaBeans;
|
||||
}
|
||||
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
for (int i = 0; i < deltaBeans.size(); i++) {
|
||||
deltaBeans.get(i).writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
public class BeanDeltaMap {
|
||||
|
||||
private Map<String,BeanDeltaList> deltaMap = new HashMap<String,BeanDeltaList>();
|
||||
|
||||
public BeanDeltaMap() {
|
||||
}
|
||||
|
||||
public BeanDeltaMap(List<BeanDelta> deltaBeans) {
|
||||
if (deltaBeans != null){
|
||||
for (int i = 0; i < deltaBeans.size(); i++) {
|
||||
BeanDelta deltaBean = deltaBeans.get(i);
|
||||
addBeanDelta(deltaBean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return deltaMap.values().toString();
|
||||
}
|
||||
|
||||
public void addBeanDelta(BeanDelta beanDelta){
|
||||
BeanDescriptor<?> d = beanDelta.getBeanDescriptor();
|
||||
BeanDeltaList list = getDeltaBeanList(d);
|
||||
list.add(beanDelta);
|
||||
}
|
||||
|
||||
public Collection<BeanDeltaList> deltaLists() {
|
||||
return deltaMap.values();
|
||||
}
|
||||
|
||||
private BeanDeltaList getDeltaBeanList(BeanDescriptor<?> d) {
|
||||
BeanDeltaList deltaList = deltaMap.get(d.getFullName());
|
||||
if (deltaList == null){
|
||||
deltaList = new BeanDeltaList(d);
|
||||
deltaMap.put(d.getFullName(), deltaList);
|
||||
}
|
||||
return deltaList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessage;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
public class BeanDeltaProperty {
|
||||
|
||||
private final BeanProperty beanProperty;
|
||||
|
||||
private final Object value;
|
||||
|
||||
public BeanDeltaProperty(BeanProperty beanProperty, Object value) {
|
||||
this.beanProperty = beanProperty;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return beanProperty.getName()+":"+value;
|
||||
}
|
||||
|
||||
public void apply(Object bean) {
|
||||
beanProperty.setValue(bean, value);
|
||||
}
|
||||
|
||||
public void writeBinaryMessage(BinaryMessage m) throws IOException {
|
||||
|
||||
DataOutputStream os = m.getOs();
|
||||
os.writeUTF(beanProperty.getName());
|
||||
beanProperty.getScalarType().writeData(os, value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
public class BeanPathUpdate {
|
||||
|
||||
private final Map<String,BeanPathUpdateIds> map = new LinkedHashMap<String, BeanPathUpdateIds>();
|
||||
|
||||
public void add(BeanDescriptor<?> desc, String path, Object id) {
|
||||
|
||||
String key = desc.getFullName()+":"+path;
|
||||
BeanPathUpdateIds pathIds = map.get(key);
|
||||
if (pathIds == null){
|
||||
pathIds = new BeanPathUpdateIds(desc, path);
|
||||
map.put(key, pathIds);
|
||||
}
|
||||
pathIds.addId((Serializable)id);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.DataInput;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessage;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
|
||||
|
||||
public class BeanPathUpdateIds {
|
||||
|
||||
private transient BeanDescriptor<?> beanDescriptor;
|
||||
|
||||
private final String descriptorId;
|
||||
|
||||
private String path;
|
||||
|
||||
private ArrayList<Serializable> ids;
|
||||
|
||||
/**
|
||||
* Create the payload.
|
||||
*/
|
||||
public BeanPathUpdateIds(BeanDescriptor<?> desc, String path) {
|
||||
this.beanDescriptor = desc;
|
||||
this.descriptorId = desc.getDescriptorId();
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (beanDescriptor != null) {
|
||||
sb.append(beanDescriptor.getFullName());
|
||||
} else {
|
||||
sb.append("descId:").append(descriptorId);
|
||||
}
|
||||
sb.append(" path:").append(path);
|
||||
sb.append(" ids:").append(ids);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static BeanPathUpdateIds readBinaryMessage(SpiEbeanServer server, DataInput dataInput) throws IOException {
|
||||
|
||||
String descriptorId = dataInput.readUTF();
|
||||
String path = dataInput.readUTF();
|
||||
BeanDescriptor<?> desc = server.getBeanDescriptorById(descriptorId);
|
||||
BeanPathUpdateIds bp = new BeanPathUpdateIds(desc, path);
|
||||
bp.read(dataInput);
|
||||
return bp;
|
||||
}
|
||||
|
||||
private void read(DataInput dataInput) throws IOException {
|
||||
|
||||
IdBinder idBinder = beanDescriptor.getIdBinder();
|
||||
ids = readIdList(dataInput, idBinder);
|
||||
}
|
||||
|
||||
|
||||
private ArrayList<Serializable> readIdList(DataInput dataInput, IdBinder idBinder) throws IOException {
|
||||
|
||||
int count = dataInput.readInt();
|
||||
if (count < 1) {
|
||||
return null;
|
||||
}
|
||||
ArrayList<Serializable> idList = new ArrayList<Serializable>(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
Object id = idBinder.readData(dataInput);
|
||||
idList.add((Serializable) id);
|
||||
}
|
||||
return idList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the contents into a BinaryMessage form.
|
||||
* <p>
|
||||
* For a RemoteBeanPersist with a large number of id's note that this is
|
||||
* broken up into many BinaryMessages each with a maximum of 100 ids. This
|
||||
* enables the contents of a large RemoteTransactionEvent to be split up
|
||||
* across multiple Packets.
|
||||
* </p>
|
||||
*/
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
|
||||
IdBinder idBinder = beanDescriptor.getIdBinder();
|
||||
|
||||
int count = ids == null ? 0 : ids.size();
|
||||
if (count > 0) {
|
||||
int loop = 0;
|
||||
int i = 0;
|
||||
int eof = ids.size();
|
||||
do {
|
||||
++loop;
|
||||
int endOfLoop = Math.min(eof, loop * 100);
|
||||
|
||||
BinaryMessage m = new BinaryMessage(endOfLoop * 4 + 20);
|
||||
|
||||
DataOutputStream os = m.getOs();
|
||||
os.writeInt(BinaryMessage.TYPE_BEANPATHUPDATE);
|
||||
os.writeUTF(descriptorId);
|
||||
os.writeUTF(path);
|
||||
os.writeInt(count);
|
||||
|
||||
for (; i < endOfLoop; i++) {
|
||||
Serializable idValue = ids.get(i);
|
||||
idBinder.writeData(os, idValue);
|
||||
}
|
||||
|
||||
os.flush();
|
||||
msgList.add(m);
|
||||
|
||||
} while (i < eof);
|
||||
}
|
||||
}
|
||||
|
||||
public void addId(Serializable id) {
|
||||
ids.add(id);
|
||||
}
|
||||
|
||||
|
||||
public BeanDescriptor<?> getBeanDescriptor() {
|
||||
return beanDescriptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Descriptor Id. A more compact alternative to using the
|
||||
* beanType.
|
||||
*/
|
||||
public String getDescriptorId() {
|
||||
return descriptorId;
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public List<Serializable> getIds() {
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.avaje.ebeaninternal.server.core.PersistRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
/**
|
||||
* Organises the individual bean persist requests by type.
|
||||
*/
|
||||
public final class BeanPersistIdMap {
|
||||
|
||||
private final Map<String,BeanPersistIds> beanMap = new LinkedHashMap<String, BeanPersistIds>();
|
||||
|
||||
public String toString() {
|
||||
return beanMap.toString();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return beanMap.isEmpty();
|
||||
}
|
||||
|
||||
public Collection<BeanPersistIds> values() {
|
||||
return beanMap.values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a Insert Update or Delete payload.
|
||||
*/
|
||||
public void add(BeanDescriptor<?> desc, PersistRequest.Type type, Object id) {
|
||||
|
||||
BeanPersistIds r = getPersistIds(desc);
|
||||
r.addId(type, (Serializable)id);
|
||||
}
|
||||
|
||||
private BeanPersistIds getPersistIds(BeanDescriptor<?> desc) {
|
||||
String beanType = desc.getFullName();
|
||||
BeanPersistIds r = beanMap.get(beanType);
|
||||
if (r == null){
|
||||
r = new BeanPersistIds(desc);
|
||||
beanMap.put(beanType, r);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.DataInput;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.avaje.ebean.event.BeanPersistListener;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessage;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
import com.avaje.ebeaninternal.server.core.PersistRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
import com.avaje.ebeaninternal.server.deploy.id.IdBinder;
|
||||
|
||||
/**
|
||||
* Wraps the information representing a Inserted Updated or Deleted Bean.
|
||||
* <p>
|
||||
* This information is broadcast across the cluster so that remote BeanListeners
|
||||
* are notified of the inserts updates and deletes that occured.
|
||||
* </p>
|
||||
* <p>
|
||||
* You control it the data is broadcast and what data is broadcast by the
|
||||
* BeanListener.getClusterData() method. It is guessed that often just the Id
|
||||
* property or perhaps a few properties in a Map will be broadcast to reduce the
|
||||
* size of data sent around the network.
|
||||
* </p>
|
||||
*/
|
||||
public class BeanPersistIds implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 8389469180931531409L;
|
||||
|
||||
private transient BeanDescriptor<?> beanDescriptor;
|
||||
|
||||
private final String descriptorId;
|
||||
|
||||
private ArrayList<Serializable> insertIds;
|
||||
private ArrayList<Serializable> updateIds;
|
||||
private ArrayList<Serializable> deleteIds;
|
||||
|
||||
/**
|
||||
* Create the payload.
|
||||
*/
|
||||
public BeanPersistIds(BeanDescriptor<?> desc) {
|
||||
this.beanDescriptor = desc;
|
||||
this.descriptorId = desc.getDescriptorId();
|
||||
}
|
||||
|
||||
public static BeanPersistIds readBinaryMessage(SpiEbeanServer server, DataInput dataInput) throws IOException {
|
||||
|
||||
String descriptorId = dataInput.readUTF();
|
||||
BeanDescriptor<?> desc = server.getBeanDescriptorById(descriptorId);
|
||||
BeanPersistIds bp = new BeanPersistIds(desc);
|
||||
bp.read(dataInput);
|
||||
return bp;
|
||||
}
|
||||
|
||||
private void read(DataInput dataInput) throws IOException {
|
||||
|
||||
IdBinder idBinder = beanDescriptor.getIdBinder();
|
||||
|
||||
int iudType = dataInput.readInt();
|
||||
ArrayList<Serializable> idList = readIdList(dataInput, idBinder);
|
||||
|
||||
switch (iudType) {
|
||||
case 0:
|
||||
insertIds = idList;
|
||||
break;
|
||||
case 1:
|
||||
updateIds = idList;
|
||||
break;
|
||||
case 2:
|
||||
deleteIds = idList;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new RuntimeException("Invalid iudType "+iudType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the contents into a BinaryMessage form.
|
||||
* <p>
|
||||
* For a RemoteBeanPersist with a large number of id's note that this is
|
||||
* broken up into many BinaryMessages each with a maximum of 100 ids. This
|
||||
* enables the contents of a large RemoteTransactionEvent to be split up
|
||||
* across multiple Packets.
|
||||
* </p>
|
||||
*/
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
|
||||
writeIdList(beanDescriptor, 0, insertIds, msgList);
|
||||
writeIdList(beanDescriptor, 1, updateIds, msgList);
|
||||
writeIdList(beanDescriptor, 2, deleteIds, msgList);
|
||||
|
||||
}
|
||||
|
||||
private ArrayList<Serializable> readIdList(DataInput dataInput, IdBinder idBinder) throws IOException {
|
||||
|
||||
int count = dataInput.readInt();
|
||||
if (count < 1) {
|
||||
return null;
|
||||
}
|
||||
ArrayList<Serializable> idList = new ArrayList<Serializable>(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
Object id = idBinder.readData(dataInput);
|
||||
idList.add((Serializable) id);
|
||||
}
|
||||
return idList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a BinaryMessage containing the descriptorId, iudType and list of Id
|
||||
* values.
|
||||
* <p>
|
||||
* Note that a given BinaryMessage has a maximum of 100 Ids. This is due to
|
||||
* the limit of UDP packet sizes. We break up the RemoteBeanPersist into
|
||||
* potentially many smaller BinaryMessages which may be put into multiple
|
||||
* Packets.
|
||||
* </p>
|
||||
*/
|
||||
private void writeIdList(BeanDescriptor<?> desc, int iudType, ArrayList<Serializable> idList,
|
||||
BinaryMessageList msgList) throws IOException {
|
||||
|
||||
IdBinder idBinder = desc.getIdBinder();
|
||||
|
||||
int count = idList == null ? 0 : idList.size();
|
||||
if (count > 0) {
|
||||
int loop = 0;
|
||||
int i = 0;
|
||||
int eof = idList.size();
|
||||
do {
|
||||
++loop;
|
||||
int endOfLoop = Math.min(eof, loop * 100);
|
||||
|
||||
BinaryMessage m = new BinaryMessage(endOfLoop * 4 + 20);
|
||||
|
||||
DataOutputStream os = m.getOs();
|
||||
os.writeInt(BinaryMessage.TYPE_BEANIUD);
|
||||
os.writeUTF(descriptorId);
|
||||
os.writeInt(iudType);
|
||||
os.writeInt(count);
|
||||
|
||||
for (; i < endOfLoop; i++) {
|
||||
Serializable idValue = idList.get(i);
|
||||
idBinder.writeData(os, idValue);
|
||||
}
|
||||
|
||||
os.flush();
|
||||
msgList.add(m);
|
||||
|
||||
} while (i < eof);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (beanDescriptor != null) {
|
||||
sb.append(beanDescriptor.getFullName());
|
||||
} else {
|
||||
sb.append("descId:").append(descriptorId);
|
||||
}
|
||||
if (insertIds != null) {
|
||||
sb.append(" insertIds:").append(insertIds);
|
||||
}
|
||||
if (updateIds != null) {
|
||||
sb.append(" updateIds:").append(updateIds);
|
||||
}
|
||||
if (deleteIds != null) {
|
||||
sb.append(" deleteIds:").append(deleteIds);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void addId(PersistRequest.Type type, Serializable id) {
|
||||
switch (type) {
|
||||
case INSERT:
|
||||
addInsertId(id);
|
||||
break;
|
||||
case UPDATE:
|
||||
addUpdateId(id);
|
||||
break;
|
||||
case DELETE:
|
||||
addDeleteId(id);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void addInsertId(Serializable id) {
|
||||
if (insertIds == null) {
|
||||
insertIds = new ArrayList<Serializable>();
|
||||
}
|
||||
insertIds.add(id);
|
||||
}
|
||||
|
||||
private void addUpdateId(Serializable id) {
|
||||
if (updateIds == null) {
|
||||
updateIds = new ArrayList<Serializable>();
|
||||
}
|
||||
updateIds.add(id);
|
||||
}
|
||||
|
||||
private void addDeleteId(Serializable id) {
|
||||
if (deleteIds == null) {
|
||||
deleteIds = new ArrayList<Serializable>();
|
||||
}
|
||||
deleteIds.add(id);
|
||||
}
|
||||
|
||||
public BeanDescriptor<?> getBeanDescriptor() {
|
||||
return beanDescriptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Descriptor Id. A more compact alternative to using the
|
||||
* beanType.
|
||||
*/
|
||||
public String getDescriptorId() {
|
||||
return descriptorId;
|
||||
}
|
||||
|
||||
public List<Serializable> getInsertIds() {
|
||||
return insertIds;
|
||||
}
|
||||
|
||||
public List<Serializable> getUpdateIds() {
|
||||
return updateIds;
|
||||
}
|
||||
|
||||
public List<Serializable> getDeleteIds() {
|
||||
return deleteIds;
|
||||
}
|
||||
|
||||
public void setBeanDescriptor(BeanDescriptor<?> beanDescriptor) {
|
||||
this.beanDescriptor = beanDescriptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the cache and local BeanPersistListener of this event that came
|
||||
* from another server in the cluster.
|
||||
*/
|
||||
public void notifyCacheAndListener() {
|
||||
|
||||
BeanPersistListener<?> listener = beanDescriptor.getPersistListener();
|
||||
|
||||
// any change invalidates the query cache
|
||||
beanDescriptor.queryCacheClear();
|
||||
|
||||
if (insertIds != null) {
|
||||
if (listener != null) {
|
||||
// notify listener
|
||||
for (int i = 0; i < insertIds.size(); i++) {
|
||||
listener.remoteInsert(insertIds.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (updateIds != null) {
|
||||
for (int i = 0; i < updateIds.size(); i++) {
|
||||
Serializable id = updateIds.get(i);
|
||||
|
||||
// remove from cache
|
||||
beanDescriptor.cacheRemove(id);
|
||||
if (listener != null) {
|
||||
// notify listener
|
||||
listener.remoteInsert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (deleteIds != null) {
|
||||
for (int i = 0; i < deleteIds.size(); i++) {
|
||||
Serializable id = deleteIds.get(i);
|
||||
|
||||
// remove from cache
|
||||
beanDescriptor.cacheRemove(id);
|
||||
if (listener != null) {
|
||||
// notify listener
|
||||
listener.remoteInsert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.avaje.ebean.event.BulkTableEvent;
|
||||
import com.avaje.ebean.event.BulkTableEventListener;
|
||||
|
||||
public class BulkEventListenerMap {
|
||||
|
||||
private final HashMap<String,Entry> map = new HashMap<String,Entry>();
|
||||
|
||||
public BulkEventListenerMap(List<BulkTableEventListener> listeners) {
|
||||
|
||||
if (listeners != null) {
|
||||
for (BulkTableEventListener l : listeners) {
|
||||
Set<String> tables = l.registeredTables();
|
||||
for (String tableName : tables) {
|
||||
register(tableName, l);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return map.isEmpty();
|
||||
}
|
||||
|
||||
public void process(BulkTableEvent event) {
|
||||
|
||||
Entry entry = map.get(event.getTableName());
|
||||
if (entry != null){
|
||||
entry.process(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void register(String tableName, BulkTableEventListener l) {
|
||||
String upperTableName = tableName.trim().toUpperCase();
|
||||
Entry entry = map.get(upperTableName);
|
||||
if (entry == null){
|
||||
entry = new Entry();
|
||||
map.put(upperTableName, entry);
|
||||
}
|
||||
entry.add(l);
|
||||
}
|
||||
|
||||
private static class Entry {
|
||||
|
||||
List<BulkTableEventListener> listeners = new ArrayList<BulkTableEventListener>();
|
||||
private void add(BulkTableEventListener l) {
|
||||
listeners.add(l);
|
||||
}
|
||||
|
||||
private void process(BulkTableEvent event){
|
||||
for (int i = 0; i < listeners.size(); i++) {
|
||||
listeners.get(i).process(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import com.avaje.ebean.bean.PersistenceContext;
|
||||
import com.avaje.ebeaninternal.api.Monitor;
|
||||
import com.avaje.ebeaninternal.server.subclass.SubClassUtil;
|
||||
|
||||
/**
|
||||
* Default implementation of PersistenceContext.
|
||||
* <p>
|
||||
* Ensures only one instance of a bean is used according to its type and unique
|
||||
* id.
|
||||
* </p>
|
||||
* <p>
|
||||
* PersistenceContext lives on a Transaction and as such is expected to only have
|
||||
* a single thread accessing it at a time. This is not expected to be used concurrently.
|
||||
* </p>
|
||||
* <p>
|
||||
* Duplicate beans are ones having the same type and unique id value. These are
|
||||
* considered duplicates and replaced by the bean instance that was already
|
||||
* loaded into the PersistanceContext.
|
||||
* </p>
|
||||
*/
|
||||
public final class DefaultPersistenceContext implements PersistenceContext {
|
||||
|
||||
/**
|
||||
* Map used hold caches. One cache per bean type.
|
||||
*/
|
||||
private final HashMap<String,ClassContext> typeCache = new HashMap<String,ClassContext>();
|
||||
|
||||
private final Monitor monitor = new Monitor();
|
||||
|
||||
/**
|
||||
* Create a new PersistanceContext.
|
||||
*/
|
||||
public DefaultPersistenceContext() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Set an object into the PersistanceContext.
|
||||
*/
|
||||
public void put(Object id, Object bean) {
|
||||
synchronized (monitor) {
|
||||
getClassContext(bean.getClass()).put(id, bean);
|
||||
}
|
||||
}
|
||||
|
||||
public Object putIfAbsent(Object id, Object bean){
|
||||
synchronized (monitor) {
|
||||
return getClassContext(bean.getClass()).putIfAbsent(id, bean);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Return an object given its type and unique id.
|
||||
*/
|
||||
public Object get(Class<?> beanType, Object id) {
|
||||
synchronized (monitor) {
|
||||
return getClassContext(beanType).get(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of beans of the given type in the persistence context.
|
||||
*/
|
||||
public int size(Class<?> beanType) {
|
||||
synchronized (monitor) {
|
||||
ClassContext classMap = typeCache.get(beanType.getName());
|
||||
return classMap == null ? 0 : classMap.size();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the PersistenceContext.
|
||||
*/
|
||||
public void clear() {
|
||||
synchronized (monitor) {
|
||||
typeCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void clear(Class<?> beanType) {
|
||||
synchronized (monitor) {
|
||||
ClassContext classMap = typeCache.get(beanType.getName());
|
||||
if (classMap != null) {
|
||||
classMap.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void clear(Class<?> beanType, Object id) {
|
||||
synchronized (monitor) {
|
||||
ClassContext classMap = typeCache.get(beanType.getName());
|
||||
if (classMap != null && id != null) {
|
||||
//id = getUid(beanType, id);
|
||||
classMap.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
synchronized (monitor) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Iterator<Entry<String, ClassContext>> it = typeCache.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<String, ClassContext> entry = it.next();
|
||||
if (entry.getValue().size() > 0){
|
||||
sb.append(entry.getKey()+":"+entry.getValue().size()+"; ");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private ClassContext getClassContext(Class<?> beanType) {
|
||||
|
||||
// strip off $$EntityBean.. suffix...
|
||||
String clsName = SubClassUtil.getSuperClassName(beanType.getName());
|
||||
|
||||
ClassContext classMap = typeCache.get(clsName);
|
||||
if (classMap == null) {
|
||||
classMap = new ClassContext();
|
||||
typeCache.put(clsName, classMap);
|
||||
}
|
||||
return classMap;
|
||||
}
|
||||
|
||||
private static class ClassContext {
|
||||
|
||||
private final WeakValueMap<Object, Object> map = new WeakValueMap<Object, Object>();
|
||||
|
||||
private Object get(Object id){
|
||||
return map.get(id);
|
||||
}
|
||||
|
||||
private Object putIfAbsent(Object id, Object bean){
|
||||
|
||||
return map.putIfAbsent(id, bean);
|
||||
}
|
||||
|
||||
private void put(Object id, Object b){
|
||||
map.put(id, b);
|
||||
}
|
||||
|
||||
private int size() {
|
||||
return map.size();
|
||||
}
|
||||
|
||||
private void clear(){
|
||||
map.clear();
|
||||
}
|
||||
|
||||
private Object remove(Object id){
|
||||
return map.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
|
||||
/**
|
||||
* Manages the transaction scoping using a Ebean thread local.
|
||||
*/
|
||||
public class DefaultTransactionScopeManager extends TransactionScopeManager {
|
||||
|
||||
|
||||
public DefaultTransactionScopeManager(TransactionManager transactionManager){
|
||||
super(transactionManager);
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
DefaultTransactionThreadLocal.commit(serverName);
|
||||
}
|
||||
|
||||
public void end() {
|
||||
DefaultTransactionThreadLocal.end(serverName);
|
||||
}
|
||||
|
||||
public SpiTransaction get() {
|
||||
SpiTransaction t = DefaultTransactionThreadLocal.get(serverName);
|
||||
if (t == null || !t.isActive()){
|
||||
return null;
|
||||
} else {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
public void replace(SpiTransaction trans) {
|
||||
DefaultTransactionThreadLocal.replace(serverName, trans);
|
||||
}
|
||||
|
||||
public void rollback() {
|
||||
DefaultTransactionThreadLocal.rollback(serverName);
|
||||
}
|
||||
|
||||
public void set(SpiTransaction trans) {
|
||||
DefaultTransactionThreadLocal.set(serverName, trans);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionMap.State;
|
||||
|
||||
/**
|
||||
* Used by EbeanMgr to store its Transactions in a ThreadLocal. This way the
|
||||
* transaction objects don't have to passed around.
|
||||
*/
|
||||
public final class DefaultTransactionThreadLocal {
|
||||
|
||||
private static ThreadLocal<TransactionMap> local = new ThreadLocal<TransactionMap>() {
|
||||
protected synchronized TransactionMap initialValue() {
|
||||
return new TransactionMap();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Not allowed.
|
||||
*/
|
||||
private DefaultTransactionThreadLocal() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current TransactionState for a given serverName. This is for the
|
||||
* local thread of course.
|
||||
*/
|
||||
private static TransactionMap.State getState(String serverName) {
|
||||
return local.get().getStateWithCreate(serverName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a new Transaction for this serverName and Thread.
|
||||
*/
|
||||
public static void set(String serverName, SpiTransaction trans) {
|
||||
getState(serverName).set(trans);
|
||||
}
|
||||
|
||||
/**
|
||||
* A mechanism to get the transaction out of the thread local by replacing it
|
||||
* with a 'proxy'.
|
||||
* <p>
|
||||
* Used for background fetching. Replaces the current transaction with a
|
||||
* 'dummy' transaction. The current transaction is given to the background
|
||||
* thread so it can continue the fetch.
|
||||
* </p>
|
||||
*/
|
||||
public static void replace(String serverName, SpiTransaction trans) {
|
||||
getState(serverName).replace(trans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current Transaction for this serverName and Thread.
|
||||
*/
|
||||
public static SpiTransaction get(String serverName) {
|
||||
TransactionMap map = local.get();
|
||||
State state = map.getState(serverName);
|
||||
SpiTransaction t = (state == null) ? null : state.transaction;
|
||||
if (map.isEmpty()) {
|
||||
local.remove();
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the current transaction.
|
||||
*/
|
||||
public static void commit(String serverName) {
|
||||
TransactionMap map = local.get();
|
||||
State state = map.removeState(serverName);
|
||||
if (state == null) {
|
||||
throw new IllegalStateException("No current transaction for [" + serverName + "]");
|
||||
}
|
||||
state.commit();
|
||||
if (map.isEmpty()) {
|
||||
local.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback the current transaction.
|
||||
*/
|
||||
public static void rollback(String serverName) {
|
||||
TransactionMap map = local.get();
|
||||
State state = map.removeState(serverName);
|
||||
if (state == null) {
|
||||
throw new IllegalStateException("No current transaction for [" + serverName + "]");
|
||||
}
|
||||
state.rollback();
|
||||
if (map.isEmpty()) {
|
||||
local.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the transaction has not been committed then roll it back.
|
||||
* <p>
|
||||
* Designed to be put in a finally block instead of a rollback() in each catch
|
||||
* block.
|
||||
*
|
||||
* <pre>
|
||||
* Ebean.beingTransaction();
|
||||
* try {
|
||||
* // ... perform some actions in a single transaction
|
||||
*
|
||||
* Ebean.commitTransaction();
|
||||
*
|
||||
* } finally {
|
||||
* // ensure transaction ended. If some error occurred then rollback()
|
||||
* Ebean.endTransaction();
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* </p>
|
||||
*/
|
||||
public static void end(String serverName) {
|
||||
|
||||
TransactionMap map = local.get();
|
||||
State state = map.removeState(serverName);
|
||||
if (state != null) {
|
||||
state.end();
|
||||
}
|
||||
if (map.isEmpty()) {
|
||||
local.remove();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.avaje.ebeaninternal.server.core.PersistRequest;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
|
||||
|
||||
/**
|
||||
* Beans deleted by Id used for updating L2 Cache and Lucene indexes.
|
||||
*/
|
||||
public final class DeleteByIdMap {
|
||||
|
||||
private final Map<String,BeanPersistIds> beanMap = new LinkedHashMap<String, BeanPersistIds>();
|
||||
|
||||
public String toString() {
|
||||
return beanMap.toString();
|
||||
}
|
||||
|
||||
public void notifyCache() {
|
||||
for (BeanPersistIds deleteIds : beanMap.values()) {
|
||||
BeanDescriptor<?> d = deleteIds.getBeanDescriptor();
|
||||
List<Serializable> idValues = deleteIds.getDeleteIds();
|
||||
if (idValues != null){
|
||||
d.queryCacheClear();
|
||||
for (int i = 0; i < idValues.size(); i++) {
|
||||
d.cacheRemove(idValues.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return beanMap.isEmpty();
|
||||
}
|
||||
|
||||
public Collection<BeanPersistIds> values() {
|
||||
return beanMap.values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a Insert Update or Delete payload.
|
||||
*/
|
||||
public void add(BeanDescriptor<?> desc, Object id) {
|
||||
|
||||
BeanPersistIds r = getPersistIds(desc);
|
||||
r.addId(PersistRequest.Type.DELETE, (Serializable)id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a List of Insert Update or Delete Id's.
|
||||
*/
|
||||
public void addList(BeanDescriptor<?> desc, List<Object> idList) {
|
||||
|
||||
BeanPersistIds r = getPersistIds(desc);
|
||||
for (int i = 0; i < idList.size(); i++) {
|
||||
r.addId(PersistRequest.Type.DELETE, (Serializable) idList.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
private BeanPersistIds getPersistIds(BeanDescriptor<?> desc) {
|
||||
String beanType = desc.getFullName();
|
||||
BeanPersistIds r = beanMap.get(beanType);
|
||||
if (r == null){
|
||||
r = new BeanPersistIds(desc);
|
||||
beanMap.put(beanType, r);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.RollbackException;
|
||||
|
||||
import com.avaje.ebean.LogLevel;
|
||||
|
||||
/**
|
||||
* Transaction based on a java.sql.Connection supplied by an external
|
||||
* transaction manager such as Spring.
|
||||
* <p>
|
||||
* This means that the transaction demarcation [commit(), rollback(), end()]
|
||||
* must be controlled externally (by Spring etc) and so these methods [commit(),
|
||||
* rollback(), end()] can not be called on this ExternalJdbcTransaction.
|
||||
* </p>
|
||||
* <p>
|
||||
* That is, a transaction started externally (by Spring etc) must be committed
|
||||
* or rolled back externally as well.
|
||||
* </p>
|
||||
*/
|
||||
public class ExternalJdbcTransaction extends JdbcTransaction {
|
||||
|
||||
/**
|
||||
* Create a Transaction that will have no transaction logging support.
|
||||
* <p>
|
||||
* You need to create with a TransactionManager to have transaction logging.
|
||||
* </p>
|
||||
*/
|
||||
public ExternalJdbcTransaction(Connection connection) {
|
||||
super(null, true, LogLevel.NONE, connection, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Using the TransactionManager and its current LogLevel.
|
||||
*/
|
||||
public ExternalJdbcTransaction(String id, boolean explicit, Connection connection, TransactionManager manager) {
|
||||
super(id, explicit, manager.getTransactionLogLevel(), connection, manager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct will all explicit parameters.
|
||||
*/
|
||||
public ExternalJdbcTransaction(String id, boolean explicit, LogLevel logLevel, Connection connection, TransactionManager manager) {
|
||||
super(id, explicit, logLevel, connection, manager);
|
||||
}
|
||||
|
||||
/**
|
||||
* This will always throw a PersistenceException.
|
||||
* <p>
|
||||
* Externally created connections should be committed or rolled back externally.
|
||||
* </p>
|
||||
*/
|
||||
@Override
|
||||
public void commit() throws RollbackException {
|
||||
throw new PersistenceException("This is an external transaction so must be committed externally");
|
||||
}
|
||||
|
||||
/**
|
||||
* This will always throw a PersistenceException.
|
||||
* <p>
|
||||
* Externally created connections should be committed or rolled back externally.
|
||||
* </p>
|
||||
*/
|
||||
@Override
|
||||
public void end() throws PersistenceException {
|
||||
throw new PersistenceException("This is an external transaction so must be committed externally");
|
||||
}
|
||||
|
||||
/**
|
||||
* This will always throw a PersistenceException.
|
||||
* <p>
|
||||
* Externally created connections should be committed or rolled back externally.
|
||||
* </p>
|
||||
*/
|
||||
@Override
|
||||
public void rollback() throws PersistenceException {
|
||||
throw new PersistenceException("This is an external transaction so must be rolled back externally");
|
||||
}
|
||||
|
||||
/**
|
||||
* This will always throw a PersistenceException.
|
||||
* <p>
|
||||
* Externally created connections should be committed or rolled back externally.
|
||||
* </p>
|
||||
*/
|
||||
@Override
|
||||
public void rollback(Throwable e) throws PersistenceException {
|
||||
throw new PersistenceException("This is an external transaction so must be rolled back externally");
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Copyright (C) 2009 the original author or authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import com.avaje.ebean.config.ExternalTransactionManager;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
|
||||
/**
|
||||
* A TransactionScopeManager aware of external transaction managers.
|
||||
*/
|
||||
public class ExternalTransactionScopeManager extends TransactionScopeManager {
|
||||
|
||||
final ExternalTransactionManager externalManager;
|
||||
|
||||
/**
|
||||
* Instantiates transaction scope manager.
|
||||
*
|
||||
* @param transactionManager the transaction manager
|
||||
*/
|
||||
public ExternalTransactionScopeManager(TransactionManager transactionManager, ExternalTransactionManager externalManager) {
|
||||
super(transactionManager);
|
||||
this.externalManager = externalManager;
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
DefaultTransactionThreadLocal.commit(serverName);
|
||||
}
|
||||
|
||||
|
||||
public void end() {
|
||||
DefaultTransactionThreadLocal.end(serverName);
|
||||
}
|
||||
|
||||
public SpiTransaction get() {
|
||||
|
||||
return (SpiTransaction)externalManager.getCurrentTransaction();
|
||||
}
|
||||
|
||||
public void replace(SpiTransaction trans) {
|
||||
DefaultTransactionThreadLocal.replace(serverName, trans);
|
||||
}
|
||||
|
||||
public void rollback() {
|
||||
DefaultTransactionThreadLocal.rollback(serverName);
|
||||
}
|
||||
|
||||
public void set(SpiTransaction trans) {
|
||||
DefaultTransactionThreadLocal.set(serverName, trans);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.DataInput;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessage;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
|
||||
public class IndexEvent {
|
||||
|
||||
public static final int COMMIT_EVENT = 1;
|
||||
public static final int OPTIMISE_EVENT = 2;
|
||||
|
||||
private final int eventType;
|
||||
private final String indexName;
|
||||
|
||||
public IndexEvent(int eventType, String indexName) {
|
||||
this.eventType = eventType;
|
||||
this.indexName = indexName;
|
||||
}
|
||||
|
||||
public int getEventType() {
|
||||
return eventType;
|
||||
}
|
||||
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
|
||||
public static IndexEvent readBinaryMessage(DataInput dataInput) throws IOException {
|
||||
|
||||
int eventType = dataInput.readInt();
|
||||
String indexName = dataInput.readUTF();
|
||||
return new IndexEvent(eventType, indexName);
|
||||
}
|
||||
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
|
||||
BinaryMessage msg = new BinaryMessage(indexName.length()+10);
|
||||
DataOutputStream os = msg.getOs();
|
||||
os.writeInt(BinaryMessage.TYPE_INDEX);
|
||||
os.writeInt(eventType);
|
||||
os.writeUTF(indexName);
|
||||
|
||||
msgList.add(msg);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.DataInput;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessage;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
|
||||
public class IndexInvalidate {
|
||||
|
||||
private final String indexName;
|
||||
|
||||
public IndexInvalidate(String indexName) {
|
||||
this.indexName = indexName;
|
||||
}
|
||||
|
||||
public String getIndexName() {
|
||||
return indexName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hc = IndexInvalidate.class.hashCode();
|
||||
hc = hc * 31 + indexName.hashCode();
|
||||
return hc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o){
|
||||
if (o instanceof IndexInvalidate == false){
|
||||
return false;
|
||||
}
|
||||
return indexName.equals(((IndexInvalidate)o).indexName);
|
||||
}
|
||||
|
||||
public static IndexInvalidate readBinaryMessage(DataInput dataInput) throws IOException {
|
||||
|
||||
|
||||
String indexName = dataInput.readUTF();
|
||||
return new IndexInvalidate(indexName);
|
||||
}
|
||||
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
|
||||
BinaryMessage msg = new BinaryMessage(indexName.length()+10);
|
||||
DataOutputStream os = msg.getOs();
|
||||
os.writeInt(BinaryMessage.TYPE_INDEX_INVALIDATE);
|
||||
os.writeUTF(indexName);
|
||||
|
||||
msgList.add(msg);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.RollbackException;
|
||||
|
||||
import com.avaje.ebean.LogLevel;
|
||||
import com.avaje.ebean.bean.PersistenceContext;
|
||||
import com.avaje.ebeaninternal.api.DerivedRelationshipData;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.api.TransactionEvent;
|
||||
import com.avaje.ebeaninternal.server.persist.BatchControl;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionManager.OnQueryOnly;
|
||||
|
||||
/**
|
||||
* JDBC Connection based transaction.
|
||||
*/
|
||||
public class JdbcTransaction implements SpiTransaction {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(JdbcTransaction.class.getName());
|
||||
|
||||
private static final String illegalStateMessage = "Transaction is Inactive";
|
||||
|
||||
/**
|
||||
* The associated TransactionManager.
|
||||
*/
|
||||
final protected TransactionManager manager;
|
||||
|
||||
/**
|
||||
* The transaction id.
|
||||
*/
|
||||
final String id;
|
||||
|
||||
/**
|
||||
* Flag to indicate if this was an explicitly created Transaction.
|
||||
*/
|
||||
final boolean explicit;
|
||||
|
||||
/**
|
||||
* Set to true if the connection has autoCommit=true initially.
|
||||
*/
|
||||
final boolean autoCommit;
|
||||
|
||||
/**
|
||||
* Behaviour for ending query only transactions.
|
||||
*/
|
||||
final OnQueryOnly onQueryOnly;
|
||||
|
||||
/**
|
||||
* The status of the transaction.
|
||||
*/
|
||||
boolean active;
|
||||
|
||||
/**
|
||||
* The underlying Connection.
|
||||
*/
|
||||
Connection connection;
|
||||
|
||||
/**
|
||||
* Used to queue up persist requests for batch execution.
|
||||
*/
|
||||
BatchControl batchControl;
|
||||
|
||||
/**
|
||||
* The event which holds persisted beans.
|
||||
*/
|
||||
TransactionEvent event;
|
||||
|
||||
/**
|
||||
* Holder of the objects fetched to ensure unique objects are used.
|
||||
*/
|
||||
PersistenceContext persistenceContext;
|
||||
|
||||
/**
|
||||
* Used to give developers more control over the insert update and delete
|
||||
* functionality.
|
||||
*/
|
||||
boolean persistCascade = true;
|
||||
|
||||
/**
|
||||
* Flag used for performance to skip commit or rollback of query only
|
||||
* transactions in read committed transaction isolation.
|
||||
*/
|
||||
boolean queryOnly = true;
|
||||
|
||||
boolean localReadOnly;
|
||||
|
||||
LogLevel logLevel;
|
||||
|
||||
/**
|
||||
* Set to true if using batch processing.
|
||||
*/
|
||||
boolean batchMode;
|
||||
|
||||
int batchSize = -1;
|
||||
|
||||
boolean batchFlushOnQuery = true;
|
||||
|
||||
Boolean batchGetGeneratedKeys;
|
||||
|
||||
Boolean batchFlushOnMixed;
|
||||
|
||||
/**
|
||||
* The depth used by batch processing to help the ordering of statements.
|
||||
*/
|
||||
int depth = 0;
|
||||
|
||||
HashSet<Object> persistingBeans = new HashSet<Object>();
|
||||
HashSet<Integer> deletingBeansHash;
|
||||
|
||||
TransactionLogBuffer logBuffer;
|
||||
|
||||
HashMap<Integer, List<DerivedRelationshipData>> derivedRelMap;
|
||||
|
||||
private final Map<String, Object> userObjects = new ConcurrentHashMap<String, Object>();
|
||||
|
||||
/**
|
||||
* Create a new JdbcTransaction.
|
||||
*/
|
||||
public JdbcTransaction(String id, boolean explicit, LogLevel logLevel, Connection connection, TransactionManager manager) {
|
||||
try {
|
||||
this.active = true;
|
||||
this.id = id;
|
||||
this.explicit = explicit;
|
||||
this.logLevel = logLevel;
|
||||
this.manager = manager;
|
||||
this.connection = connection;
|
||||
this.autoCommit = connection.getAutoCommit();
|
||||
if (this.autoCommit) {
|
||||
connection.setAutoCommit(false);
|
||||
}
|
||||
this.onQueryOnly = manager == null ? OnQueryOnly.ROLLBACK : manager.getOnQueryOnly();
|
||||
this.persistenceContext = new DefaultPersistenceContext();
|
||||
|
||||
this.logBuffer = new TransactionLogBuffer(50, id);
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "Trans[" + id + "]";
|
||||
}
|
||||
|
||||
public List<DerivedRelationshipData> getDerivedRelationship(Object bean) {
|
||||
if (derivedRelMap == null) {
|
||||
return null;
|
||||
}
|
||||
Integer key = Integer.valueOf(System.identityHashCode(bean));
|
||||
return derivedRelMap.get(key);
|
||||
}
|
||||
|
||||
public void registerDerivedRelationship(DerivedRelationshipData derivedRelationship) {
|
||||
if (derivedRelMap == null) {
|
||||
derivedRelMap = new HashMap<Integer, List<DerivedRelationshipData>>();
|
||||
}
|
||||
Integer key = Integer.valueOf(System.identityHashCode(derivedRelationship.getAssocBean()));
|
||||
|
||||
List<DerivedRelationshipData> list = derivedRelMap.get(key);
|
||||
if (list == null) {
|
||||
list = new ArrayList<DerivedRelationshipData>();
|
||||
derivedRelMap.put(key, list);
|
||||
}
|
||||
list.add(derivedRelationship);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a bean to the registed list.
|
||||
* <p>
|
||||
* This is to handle bi-directional relationships where both sides Cascade.
|
||||
* </p>
|
||||
*/
|
||||
public void registerDeleteBean(Integer persistingBean) {
|
||||
if (deletingBeansHash == null) {
|
||||
deletingBeansHash = new HashSet<Integer>();
|
||||
}
|
||||
deletingBeansHash.add(persistingBean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister the persisted bean.
|
||||
*/
|
||||
public void unregisterDeleteBean(Integer persistedBean) {
|
||||
if (deletingBeansHash != null) {
|
||||
deletingBeansHash.remove(persistedBean);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this is a bean that has already been saved/deleted.
|
||||
*/
|
||||
public boolean isRegisteredDeleteBean(Integer persistingBean) {
|
||||
if (deletingBeansHash == null) {
|
||||
return false;
|
||||
} else {
|
||||
return deletingBeansHash.contains(persistingBean);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister the persisted bean.
|
||||
*/
|
||||
public void unregisterBean(Object bean) {
|
||||
persistingBeans.remove(bean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this is a bean that has already been saved. This will
|
||||
* register the bean if it is not already.
|
||||
*/
|
||||
public boolean isRegisteredBean(Object bean) {
|
||||
return !persistingBeans.add(bean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the depth of the current persist request plus the diff. This has the
|
||||
* effect of changing the current depth and returning the new value. Pass
|
||||
* diff=0 to return the current depth.
|
||||
* <p>
|
||||
* The depth of 0 is for the initial persist request. It is modified as the
|
||||
* cascading of the save or delete traverses to the the associated Ones (-1)
|
||||
* and associated Manys (+1).
|
||||
* </p>
|
||||
* <p>
|
||||
* The depth is used to help the ordering of batched statements.
|
||||
* </p>
|
||||
*
|
||||
* @param diff
|
||||
* the amount to add or subtract from the depth.
|
||||
* @return the current depth plus the diff
|
||||
*/
|
||||
public int depth(int diff) {
|
||||
depth += diff;
|
||||
return depth;
|
||||
}
|
||||
|
||||
public boolean isReadOnly() {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
try {
|
||||
return connection.isReadOnly();
|
||||
} catch (SQLException e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void setReadOnly(boolean readOnly) {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
try {
|
||||
localReadOnly = readOnly;
|
||||
connection.setReadOnly(readOnly);
|
||||
} catch (SQLException e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void setBatchMode(boolean batchMode) {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
this.batchMode = batchMode;
|
||||
}
|
||||
|
||||
public void setBatchGetGeneratedKeys(boolean getGeneratedKeys) {
|
||||
this.batchGetGeneratedKeys = getGeneratedKeys;
|
||||
if (batchControl != null) {
|
||||
batchControl.setGetGeneratedKeys(getGeneratedKeys);
|
||||
}
|
||||
}
|
||||
|
||||
public void setBatchFlushOnMixed(boolean batchFlushOnMixed) {
|
||||
this.batchFlushOnMixed = batchFlushOnMixed;
|
||||
if (batchControl != null) {
|
||||
batchControl.setBatchFlushOnMixed(batchFlushOnMixed);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the batchSize specifically set for this transaction or 0.
|
||||
* <p>
|
||||
* Returning 0 implies to use the system wide default batch size.
|
||||
* </p>
|
||||
*/
|
||||
public int getBatchSize() {
|
||||
return batchSize;
|
||||
}
|
||||
|
||||
public void setBatchSize(int batchSize) {
|
||||
this.batchSize = batchSize;
|
||||
if (batchControl != null) {
|
||||
batchControl.setBatchSize(batchSize);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isBatchFlushOnQuery() {
|
||||
return batchFlushOnQuery;
|
||||
}
|
||||
|
||||
public void setBatchFlushOnQuery(boolean batchFlushOnQuery) {
|
||||
this.batchFlushOnQuery = batchFlushOnQuery;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this request should be batched. Returning false means that
|
||||
* this request should be executed immediately.
|
||||
*/
|
||||
public boolean isBatchThisRequest() {
|
||||
if (!explicit && depth <= 0) {
|
||||
// implicit transaction ... no gain
|
||||
// by batching where depth <= 0
|
||||
return false;
|
||||
}
|
||||
return batchMode;
|
||||
}
|
||||
|
||||
public BatchControl getBatchControl() {
|
||||
return batchControl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the BatchControl to the transaction. This is done once per transaction
|
||||
* on the first persist request.
|
||||
*/
|
||||
public void setBatchControl(BatchControl batchControl) {
|
||||
queryOnly = false;
|
||||
this.batchControl = batchControl;
|
||||
// in case these parameters have already been set
|
||||
if (batchGetGeneratedKeys != null) {
|
||||
batchControl.setGetGeneratedKeys(batchGetGeneratedKeys);
|
||||
}
|
||||
if (batchSize != -1) {
|
||||
batchControl.setBatchSize(batchSize);
|
||||
}
|
||||
if (batchFlushOnMixed != null) {
|
||||
batchControl.setBatchFlushOnMixed(batchFlushOnMixed);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush any queued persist requests.
|
||||
* <p>
|
||||
* This is general will result in a number of batched PreparedStatements
|
||||
* executing.
|
||||
* </p>
|
||||
*/
|
||||
public void flushBatch() {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
if (batchControl != null) {
|
||||
batchControl.flush();
|
||||
}
|
||||
}
|
||||
|
||||
public void batchFlush() {
|
||||
flushBatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the persistence context associated with this transaction.
|
||||
*/
|
||||
public PersistenceContext getPersistenceContext() {
|
||||
return persistenceContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the persistence context to this transaction.
|
||||
* <p>
|
||||
* This could be considered similar to EJB3 Extended PersistanceContext. In
|
||||
* that you get the PersistanceContext from a transaction, hold onto it, and
|
||||
* then set it back later to a second transaction.
|
||||
* </p>
|
||||
*/
|
||||
public void setPersistenceContext(PersistenceContext context) {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
this.persistenceContext = context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying TransactionEvent.
|
||||
*/
|
||||
public TransactionEvent getEvent() {
|
||||
queryOnly = false;
|
||||
if (event == null) {
|
||||
event = new TransactionEvent();
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether transaction logging is on for this transaction.
|
||||
*/
|
||||
public void setLoggingOn(boolean loggingOn) {
|
||||
if (loggingOn) {
|
||||
logLevel = LogLevel.SQL;
|
||||
} else {
|
||||
logLevel = LogLevel.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this was an explicitly created transaction.
|
||||
*/
|
||||
public boolean isExplicit() {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
public boolean isLogSql() {
|
||||
return logLevel.ordinal() >= LogLevel.SQL.ordinal();
|
||||
}
|
||||
|
||||
public boolean isLogSummary() {
|
||||
return logLevel.ordinal() >= LogLevel.SUMMARY.ordinal();
|
||||
}
|
||||
|
||||
public LogLevel getLogLevel() {
|
||||
return logLevel;
|
||||
}
|
||||
|
||||
public void setLogLevel(LogLevel logLevel) {
|
||||
this.logLevel = logLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a message to the transaction log - for PUBLIC use.
|
||||
*/
|
||||
public void log(String msg) {
|
||||
if (isLogSummary()) {
|
||||
logInternal(msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a message to the transaction log - for Ebean INTERNAL use. The LogLevel
|
||||
* should be explicitly checked before calling this method.
|
||||
*/
|
||||
public void logInternal(String msg) {
|
||||
if (manager != null) {
|
||||
if (logBuffer.add(msg)) {
|
||||
// buffer full so flush it
|
||||
manager.log(logBuffer);
|
||||
logBuffer = logBuffer.newBuffer();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the transaction id.
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying connection for internal use.
|
||||
*/
|
||||
public Connection getInternalConnection() {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying connection for public use.
|
||||
*/
|
||||
public Connection getConnection() {
|
||||
queryOnly = false;
|
||||
return getInternalConnection();
|
||||
}
|
||||
|
||||
protected void deactivate() {
|
||||
try {
|
||||
if (localReadOnly) {
|
||||
// reset readOnly status prior to returning to pool
|
||||
connection.setReadOnly(false);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Error setting to readOnly?", e);
|
||||
}
|
||||
try {
|
||||
if (this.autoCommit) {
|
||||
// reset the autoCommit status prior to returning to pool
|
||||
connection.setAutoCommit(true);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Error setting to readOnly?", e);
|
||||
}
|
||||
try {
|
||||
connection.close();
|
||||
} catch (Exception ex) {
|
||||
// the connection pool will automatically remove the
|
||||
// connection if it does not pass the test
|
||||
logger.log(Level.SEVERE, "Error closing connection", ex);
|
||||
}
|
||||
connection = null;
|
||||
active = false;
|
||||
}
|
||||
|
||||
public TransactionLogBuffer getLogBuffer() {
|
||||
return logBuffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the transaction manager.
|
||||
*/
|
||||
protected void notifyCommit() {
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
if (queryOnly) {
|
||||
manager.notifyOfQueryOnly(true, this, null);
|
||||
} else {
|
||||
manager.notifyOfCommit(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback, Commit or Close for query only transaction.
|
||||
* <p>
|
||||
* For a transaction that was used for queries only we can choose to either
|
||||
* rollback or just close the connection for performance.
|
||||
* </p>
|
||||
*/
|
||||
private void commitQueryOnly() {
|
||||
try {
|
||||
switch (onQueryOnly) {
|
||||
case ROLLBACK:
|
||||
connection.rollback();
|
||||
break;
|
||||
case COMMIT:
|
||||
connection.commit();
|
||||
break;
|
||||
case CLOSE_ON_READCOMMITTED:
|
||||
// Connection is closed via deactivate() which follows
|
||||
// This optimisation is only available at READ COMMITTED Isolation
|
||||
break;
|
||||
default:
|
||||
connection.rollback();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String m = "Error when ending a query only transaction via " + onQueryOnly;
|
||||
logger.log(Level.SEVERE, m, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the transaction.
|
||||
*/
|
||||
public void commit() throws RollbackException {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
try {
|
||||
if (queryOnly) {
|
||||
// can rollback or just close for performance
|
||||
commitQueryOnly();
|
||||
} else {
|
||||
// commit
|
||||
if (batchControl != null && !batchControl.isEmpty()) {
|
||||
batchControl.flush();
|
||||
}
|
||||
connection.commit();
|
||||
}
|
||||
// these will not throw an exception
|
||||
deactivate();
|
||||
notifyCommit();
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RollbackException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the transaction manager.
|
||||
*/
|
||||
protected void notifyRollback(Throwable cause) {
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
if (queryOnly) {
|
||||
manager.notifyOfQueryOnly(false, this, cause);
|
||||
} else {
|
||||
manager.notifyOfRollback(this, cause);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback the transaction.
|
||||
*/
|
||||
public void rollback() throws PersistenceException {
|
||||
rollback(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback the transaction. If there is a throwable it is logged as the cause
|
||||
* in the transaction log.
|
||||
*/
|
||||
public void rollback(Throwable cause) throws PersistenceException {
|
||||
if (!isActive()) {
|
||||
throw new IllegalStateException(illegalStateMessage);
|
||||
}
|
||||
try {
|
||||
connection.rollback();
|
||||
|
||||
// these will not throw an exception
|
||||
deactivate();
|
||||
notifyRollback(cause);
|
||||
|
||||
} catch (Exception ex) {
|
||||
throw new PersistenceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the transaction is active then perform rollback.
|
||||
*/
|
||||
public void end() throws PersistenceException {
|
||||
if (isActive()) {
|
||||
rollback();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the transaction is active.
|
||||
*/
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public boolean isPersistCascade() {
|
||||
return persistCascade;
|
||||
}
|
||||
|
||||
public void setPersistCascade(boolean persistCascade) {
|
||||
this.persistCascade = persistCascade;
|
||||
}
|
||||
|
||||
public void addModification(String tableName, boolean inserts, boolean updates, boolean deletes) {
|
||||
getEvent().add(tableName, inserts, updates, deletes);
|
||||
}
|
||||
|
||||
public void putUserObject(String name, Object value) {
|
||||
userObjects.put(name, value);
|
||||
}
|
||||
|
||||
public Object getUserObject(String name) {
|
||||
return userObjects.get(name);
|
||||
}
|
||||
|
||||
public final TransactionManager getTransactionManger() {
|
||||
return manager;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.sql.DataSource;
|
||||
import javax.transaction.Status;
|
||||
import javax.transaction.UserTransaction;
|
||||
|
||||
import com.avaje.ebean.LogLevel;
|
||||
|
||||
/**
|
||||
* Jta based transaction.
|
||||
*/
|
||||
public class JtaTransaction extends JdbcTransaction {
|
||||
|
||||
private UserTransaction userTransaction;
|
||||
|
||||
private DataSource dataSource;
|
||||
|
||||
private boolean commmitted = false;
|
||||
|
||||
private boolean newTransaction = false;
|
||||
|
||||
|
||||
/**
|
||||
* Create the JtaTransaction.
|
||||
*/
|
||||
public JtaTransaction(String id, boolean explicit, LogLevel logLevel, UserTransaction utx, DataSource ds, TransactionManager manager) {
|
||||
super(id, explicit, logLevel, null, manager);
|
||||
userTransaction = utx;
|
||||
dataSource = ds;
|
||||
|
||||
try {
|
||||
newTransaction = userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION;
|
||||
if (newTransaction) {
|
||||
userTransaction.begin();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
// Open JDBC Connection
|
||||
this.connection = dataSource.getConnection();
|
||||
if (connection == null) {
|
||||
throw new PersistenceException("The DataSource returned a null connection.");
|
||||
}
|
||||
if (connection.getAutoCommit()) {
|
||||
connection.setAutoCommit(false);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit the transaction.
|
||||
*/
|
||||
public void commit() {
|
||||
if (commmitted) {
|
||||
throw new PersistenceException("This transaction has already been committed.");
|
||||
}
|
||||
try {
|
||||
try {
|
||||
if (newTransaction) {
|
||||
userTransaction.commit();
|
||||
}
|
||||
notifyCommit();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
commmitted = true;
|
||||
}
|
||||
|
||||
public void rollback() {
|
||||
rollback(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback the transaction.
|
||||
*/
|
||||
public void rollback(Throwable e) {
|
||||
if (!commmitted) {
|
||||
try {
|
||||
try {
|
||||
if (userTransaction != null) {
|
||||
if (newTransaction) {
|
||||
userTransaction.rollback();
|
||||
} else {
|
||||
userTransaction.setRollbackOnly();
|
||||
}
|
||||
}
|
||||
notifyRollback(e);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new PersistenceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the underlying connection.
|
||||
*/
|
||||
private void close() throws SQLException {
|
||||
if (connection != null) {
|
||||
connection.close();
|
||||
connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.sql.DataSource;
|
||||
import javax.transaction.HeuristicMixedException;
|
||||
import javax.transaction.HeuristicRollbackException;
|
||||
import javax.transaction.NotSupportedException;
|
||||
import javax.transaction.RollbackException;
|
||||
import javax.transaction.Status;
|
||||
import javax.transaction.Synchronization;
|
||||
import javax.transaction.SystemException;
|
||||
import javax.transaction.TransactionSynchronizationRegistry;
|
||||
import javax.transaction.UserTransaction;
|
||||
|
||||
import com.avaje.ebean.LogLevel;
|
||||
import com.avaje.ebean.config.ExternalTransactionManager;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
|
||||
/**
|
||||
* Hook into external JTA transaction manager.
|
||||
*
|
||||
* @author rbygrave
|
||||
*/
|
||||
public class JtaTransactionManager implements ExternalTransactionManager {
|
||||
|
||||
private final static Logger logger = Logger.getLogger(JtaTransactionManager.class.getName());
|
||||
|
||||
private static final String EBEAN_TXN_RESOURCE = "EBEAN_TXN_RESOURCE";
|
||||
|
||||
/**
|
||||
* The data source.
|
||||
*/
|
||||
private DataSource dataSource;
|
||||
|
||||
/**
|
||||
* The Ebean transaction manager.
|
||||
*/
|
||||
private TransactionManager transactionManager;
|
||||
|
||||
/**
|
||||
* The EbeanServer name.
|
||||
*/
|
||||
private String serverName;
|
||||
|
||||
/**
|
||||
* Instantiates a new spring aware transaction scope manager.
|
||||
*/
|
||||
public JtaTransactionManager() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise this with the Ebean internal transaction manager.
|
||||
*/
|
||||
public void setTransactionManager(Object txnMgr) {
|
||||
|
||||
// RB: At this stage not exposing TransactionManager to
|
||||
// the public API and hence the Object type and casting here
|
||||
|
||||
this.transactionManager = (TransactionManager) txnMgr;
|
||||
this.dataSource = transactionManager.getDataSource();
|
||||
this.serverName = transactionManager.getServerName();
|
||||
}
|
||||
|
||||
private TransactionSynchronizationRegistry getSyncRegistry() {
|
||||
try {
|
||||
InitialContext ctx = new InitialContext();
|
||||
return (TransactionSynchronizationRegistry)ctx.lookup("java:comp/TransactionSynchronizationRegistry");
|
||||
} catch (NamingException e){
|
||||
throw new PersistenceException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private UserTransaction getUserTransaction() {
|
||||
try {
|
||||
InitialContext ctx = new InitialContext();
|
||||
return (UserTransaction) ctx.lookup("java:comp/UserTransaction");
|
||||
} catch (NamingException e){
|
||||
// assuming CMT
|
||||
return new DummyUserTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for a current Spring managed transaction and wraps/returns that as a Ebean transaction.
|
||||
* <p>
|
||||
* Returns null if there is no current spring transaction (lazy loading outside a spring txn etc).
|
||||
* </p>
|
||||
*/
|
||||
public Object getCurrentTransaction() {
|
||||
|
||||
TransactionSynchronizationRegistry syncRegistry = getSyncRegistry();
|
||||
|
||||
SpiTransaction t = (SpiTransaction)syncRegistry.getResource(EBEAN_TXN_RESOURCE);
|
||||
if (t != null){
|
||||
// we have already seen this transaction
|
||||
return t;
|
||||
}
|
||||
|
||||
// check current Ebean transaction
|
||||
SpiTransaction currentEbeanTransaction = DefaultTransactionThreadLocal.get(serverName);
|
||||
if (currentEbeanTransaction != null){
|
||||
// NOT expecting this so log WARNING
|
||||
String msg = "JTA Transaction - no current txn BUT using current Ebean one "+currentEbeanTransaction.getId();
|
||||
logger.log(Level.WARNING, msg);
|
||||
return currentEbeanTransaction;
|
||||
}
|
||||
|
||||
UserTransaction ut = getUserTransaction();
|
||||
if (ut == null){
|
||||
// no current JTA transaction
|
||||
if (logger.isLoggable(Level.FINE)){
|
||||
logger.fine("JTA Transaction - no current txn");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// This is a transaction that Ebean has not seen before.
|
||||
|
||||
// "wrap" it in a Ebean specific JtaTransaction
|
||||
String txnId = String.valueOf(System.currentTimeMillis());
|
||||
JtaTransaction newTrans = new JtaTransaction(txnId, true, LogLevel.NONE, ut, dataSource, transactionManager);
|
||||
|
||||
// create and register transaction listener
|
||||
JtaTxnListener txnListener = createJtaTxnListener(newTrans);
|
||||
|
||||
syncRegistry.putResource(EBEAN_TXN_RESOURCE, newTrans);
|
||||
syncRegistry.registerInterposedSynchronization(txnListener);
|
||||
|
||||
// also put in Ebean ThreadLocal
|
||||
DefaultTransactionThreadLocal.set(serverName, newTrans);
|
||||
return newTrans;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a listener to register with JTA to enable Ebean to be
|
||||
* notified when transactions commit and rollback.
|
||||
* <p>
|
||||
* This is used by Ebean to notify it's appropriate listeners and maintain it's server
|
||||
* cache etc.
|
||||
* </p>
|
||||
*/
|
||||
private JtaTxnListener createJtaTxnListener(SpiTransaction t) {
|
||||
return new JtaTxnListener(transactionManager, t);
|
||||
}
|
||||
|
||||
private static class DummyUserTransaction implements UserTransaction {
|
||||
|
||||
public void begin() throws NotSupportedException, SystemException {
|
||||
}
|
||||
|
||||
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
|
||||
SecurityException, IllegalStateException, SystemException {
|
||||
}
|
||||
|
||||
public int getStatus() throws SystemException {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public void rollback() throws IllegalStateException, SecurityException, SystemException {
|
||||
}
|
||||
|
||||
public void setRollbackOnly() throws IllegalStateException, SystemException {
|
||||
}
|
||||
|
||||
public void setTransactionTimeout(int seconds) throws SystemException {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A JTA Transaction Synchronization that we register to get notified when a
|
||||
* managed transaction has been committed or rolled back.
|
||||
* <p>
|
||||
* When Ebean is notified (of the commit/rollback) it can then manage its
|
||||
* cache, notify BeanPersistListeners etc.
|
||||
* </p>
|
||||
*/
|
||||
private static class JtaTxnListener implements Synchronization {
|
||||
|
||||
private final TransactionManager transactionManager;
|
||||
|
||||
private final SpiTransaction transaction;
|
||||
|
||||
private final String serverName;
|
||||
|
||||
private JtaTxnListener(TransactionManager transactionManager, SpiTransaction t){
|
||||
this.transactionManager = transactionManager;
|
||||
this.transaction = t;
|
||||
this.serverName = transactionManager.getServerName();
|
||||
}
|
||||
|
||||
public void beforeCompletion() {
|
||||
// Future note: for JPA2 locking we will
|
||||
// have beforeCommit events to fire
|
||||
}
|
||||
|
||||
public void afterCompletion(int status) {
|
||||
|
||||
switch (status) {
|
||||
case Status.STATUS_COMMITTED:
|
||||
if (logger.isLoggable(Level.FINE)){
|
||||
logger.fine("Jta Txn ["+transaction.getId()+"] committed");
|
||||
}
|
||||
transactionManager.notifyOfCommit(transaction);
|
||||
// Remove this transaction object as it is completed
|
||||
DefaultTransactionThreadLocal.replace(serverName, null);
|
||||
break;
|
||||
|
||||
case Status.STATUS_ROLLEDBACK:
|
||||
if (logger.isLoggable(Level.FINE)){
|
||||
logger.fine("Jta Txn ["+transaction.getId()+"] rollback");
|
||||
}
|
||||
transactionManager.notifyOfRollback(transaction, null);
|
||||
// Remove this transaction object as it is completed
|
||||
DefaultTransactionThreadLocal.replace(serverName, null);
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.fine("Jta Txn ["+transaction.getId()+"] status:"+status);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.api.TransactionEvent;
|
||||
import com.avaje.ebeaninternal.api.TransactionEventBeans;
|
||||
import com.avaje.ebeaninternal.api.TransactionEventTable;
|
||||
import com.avaje.ebeaninternal.api.TransactionEventTable.TableIUD;
|
||||
import com.avaje.ebeaninternal.server.cluster.ClusterManager;
|
||||
import com.avaje.ebeaninternal.server.core.PersistRequestBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager;
|
||||
|
||||
/**
|
||||
* Performs post commit processing using a background thread.
|
||||
* <p>
|
||||
* This includes Cluster notification, and BeanPersistListeners.
|
||||
* </p>
|
||||
*/
|
||||
public final class PostCommitProcessing {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PostCommitProcessing.class.getName());
|
||||
|
||||
private final ClusterManager clusterManager;
|
||||
|
||||
private final TransactionEvent event;
|
||||
|
||||
private final String serverName;
|
||||
|
||||
private final TransactionManager manager;
|
||||
|
||||
private final List<PersistRequestBean<?>> persistBeanRequests;
|
||||
|
||||
private final BeanPersistIdMap beanPersistIdMap;
|
||||
|
||||
// private final BeanDeltaMap beanDeltaMap;
|
||||
|
||||
private final RemoteTransactionEvent remoteTransactionEvent;
|
||||
|
||||
private final DeleteByIdMap deleteByIdMap;
|
||||
|
||||
/**
|
||||
* Create for a TransactionManager and event.
|
||||
*/
|
||||
public PostCommitProcessing(ClusterManager clusterManager, TransactionManager manager, SpiTransaction transaction, TransactionEvent event) {
|
||||
|
||||
this.clusterManager = clusterManager;
|
||||
this.manager = manager;
|
||||
this.serverName = manager.getServerName();
|
||||
this.event = event;
|
||||
this.deleteByIdMap = event.getDeleteByIdMap();
|
||||
this.persistBeanRequests = createPersistBeanRequests();
|
||||
|
||||
this.beanPersistIdMap = createBeanPersistIdMap();
|
||||
//this.beanDeltaMap = new BeanDeltaMap(event.getBeanDeltas());
|
||||
|
||||
this.remoteTransactionEvent = createRemoteTransactionEvent();
|
||||
}
|
||||
|
||||
public void notifyLocalCacheIndex() {
|
||||
|
||||
// notify cache with bulk insert/update/delete statements
|
||||
processTableEvents(event.getEventTables());
|
||||
|
||||
// notify cache with bean changes
|
||||
event.notifyCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Table events are where SQL or external tools are used. In this case the
|
||||
* cache is notified based on the table name (rather than bean type).
|
||||
*/
|
||||
private void processTableEvents(TransactionEventTable tableEvents) {
|
||||
|
||||
if (tableEvents != null && !tableEvents.isEmpty()) {
|
||||
// notify cache with table based changes
|
||||
BeanDescriptorManager dm = manager.getBeanDescriptorManager();
|
||||
for (TableIUD tableIUD : tableEvents.values()) {
|
||||
dm.cacheNotify(tableIUD);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void notifyCluster() {
|
||||
if (remoteTransactionEvent != null && !remoteTransactionEvent.isEmpty()) {
|
||||
// send the interesting events to the cluster
|
||||
if (manager.getClusterDebugLevel() > 0 || logger.isLoggable(Level.FINE)) {
|
||||
logger.info("Cluster Send: " + remoteTransactionEvent.toString());
|
||||
}
|
||||
|
||||
clusterManager.broadcast(remoteTransactionEvent);
|
||||
}
|
||||
}
|
||||
|
||||
public Runnable notifyPersistListeners() {
|
||||
return new Runnable() {
|
||||
public void run() {
|
||||
localPersistListenersNotify();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void localPersistListenersNotify() {
|
||||
if (persistBeanRequests != null) {
|
||||
for (int i = 0; i < persistBeanRequests.size(); i++) {
|
||||
persistBeanRequests.get(i).notifyLocalPersistListener();
|
||||
}
|
||||
}
|
||||
TransactionEventTable eventTables = event.getEventTables();
|
||||
if (eventTables != null && !eventTables.isEmpty()) {
|
||||
BulkEventListenerMap map = manager.getBulkEventListenerMap();
|
||||
for (TableIUD tableIUD : eventTables.values()) {
|
||||
map.process(tableIUD);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<PersistRequestBean<?>> createPersistBeanRequests() {
|
||||
TransactionEventBeans eventBeans = event.getEventBeans();
|
||||
if (eventBeans != null) {
|
||||
return eventBeans.getRequests();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private BeanPersistIdMap createBeanPersistIdMap() {
|
||||
|
||||
if (persistBeanRequests == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
BeanPersistIdMap m = new BeanPersistIdMap();
|
||||
for (int i = 0; i < persistBeanRequests.size(); i++) {
|
||||
persistBeanRequests.get(i).addToPersistMap(m);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
private RemoteTransactionEvent createRemoteTransactionEvent() {
|
||||
|
||||
if (!clusterManager.isClustering()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
RemoteTransactionEvent remoteTransactionEvent = new RemoteTransactionEvent(serverName);
|
||||
|
||||
// if (beanDeltaMap != null) {
|
||||
// for (BeanDeltaList deltaList : beanDeltaMap.deltaLists()) {
|
||||
// remoteTransactionEvent.addBeanDeltaList(deltaList);
|
||||
// }
|
||||
// }
|
||||
|
||||
if (beanPersistIdMap != null) {
|
||||
for (BeanPersistIds beanPersist : beanPersistIdMap.values()) {
|
||||
remoteTransactionEvent.addBeanPersistIds(beanPersist);
|
||||
}
|
||||
}
|
||||
|
||||
if (deleteByIdMap != null) {
|
||||
remoteTransactionEvent.setDeleteByIdMap(deleteByIdMap);
|
||||
}
|
||||
|
||||
TransactionEventTable eventTables = event.getEventTables();
|
||||
if (eventTables != null && !eventTables.isEmpty()) {
|
||||
for (TableIUD tableIUD : eventTables.values()) {
|
||||
remoteTransactionEvent.addTableIUD(tableIUD);
|
||||
}
|
||||
}
|
||||
|
||||
Set<IndexInvalidate> indexInvalidations = event.getIndexInvalidations();
|
||||
if (indexInvalidations != null) {
|
||||
for (IndexInvalidate indexInvalidate : indexInvalidations) {
|
||||
remoteTransactionEvent.addIndexInvalidate(indexInvalidate);
|
||||
}
|
||||
}
|
||||
|
||||
return remoteTransactionEvent;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
import com.avaje.ebeaninternal.api.TransactionEventTable.TableIUD;
|
||||
import com.avaje.ebeaninternal.server.cluster.BinaryMessageList;
|
||||
|
||||
public class RemoteTransactionEvent implements Runnable {
|
||||
|
||||
private List<BeanPersistIds> beanPersistList = new ArrayList<BeanPersistIds>();
|
||||
|
||||
private List<TableIUD> tableList;
|
||||
|
||||
private List<BeanDeltaList> beanDeltaLists;
|
||||
|
||||
private BeanDeltaMap beanDeltaMap;
|
||||
|
||||
private List<IndexEvent> indexEventList;
|
||||
|
||||
private Set<IndexInvalidate> indexInvalidations;
|
||||
|
||||
private DeleteByIdMap deleteByIdMap;
|
||||
|
||||
private String serverName;
|
||||
|
||||
private transient SpiEbeanServer server;
|
||||
|
||||
public RemoteTransactionEvent(String serverName) {
|
||||
this.serverName = serverName;
|
||||
}
|
||||
|
||||
public RemoteTransactionEvent(SpiEbeanServer server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
server.remoteTransactionEvent(this);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (beanDeltaMap != null){
|
||||
sb.append(beanDeltaMap);
|
||||
}
|
||||
sb.append(beanPersistList);
|
||||
if (tableList != null){
|
||||
sb.append(tableList);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void writeBinaryMessage(BinaryMessageList msgList) throws IOException {
|
||||
|
||||
if (indexInvalidations != null){
|
||||
for (IndexInvalidate indexInvalidate : indexInvalidations) {
|
||||
indexInvalidate.writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
|
||||
if (tableList != null){
|
||||
for (int i = 0; i < tableList.size(); i++) {
|
||||
tableList.get(i).writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
|
||||
if (deleteByIdMap != null){
|
||||
for (BeanPersistIds deleteIds : deleteByIdMap.values()) {
|
||||
deleteIds.writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
|
||||
if (beanPersistList != null){
|
||||
for (int i = 0; i < beanPersistList.size(); i++) {
|
||||
beanPersistList.get(i).writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
|
||||
if (beanDeltaLists != null){
|
||||
for (int i = 0; i < beanDeltaLists.size(); i++) {
|
||||
beanDeltaLists.get(i).writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
|
||||
if (indexEventList != null){
|
||||
for (int i = 0; i < indexEventList.size(); i++) {
|
||||
indexEventList.get(i).writeBinaryMessage(msgList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return beanPersistList.isEmpty() && (tableList == null || tableList.isEmpty());
|
||||
}
|
||||
|
||||
public void addBeanPersistIds(BeanPersistIds beanPersist){
|
||||
beanPersistList.add(beanPersist);
|
||||
}
|
||||
|
||||
public void addIndexInvalidate(IndexInvalidate indexInvalidate){
|
||||
if (indexInvalidations == null){
|
||||
indexInvalidations = new HashSet<IndexInvalidate>();
|
||||
}
|
||||
indexInvalidations.add(indexInvalidate);
|
||||
}
|
||||
|
||||
public void addTableIUD(TableIUD tableIud){
|
||||
if (tableList == null){
|
||||
tableList = new ArrayList<TableIUD>(4);
|
||||
}
|
||||
tableList.add(tableIud);
|
||||
}
|
||||
|
||||
public void addBeanDeltaList(BeanDeltaList deltaList){
|
||||
if (beanDeltaLists == null){
|
||||
beanDeltaLists = new ArrayList<BeanDeltaList>();
|
||||
}
|
||||
beanDeltaLists.add(deltaList);
|
||||
}
|
||||
|
||||
public void addBeanDelta(BeanDelta beanDelta){
|
||||
if (beanDeltaMap == null){
|
||||
beanDeltaMap = new BeanDeltaMap();
|
||||
}
|
||||
beanDeltaMap.addBeanDelta(beanDelta);
|
||||
}
|
||||
|
||||
public void addIndexEvent(IndexEvent indexEvent){
|
||||
if (indexEventList == null){
|
||||
indexEventList = new ArrayList<IndexEvent>(2);
|
||||
}
|
||||
indexEventList.add(indexEvent);
|
||||
}
|
||||
|
||||
public String getServerName() {
|
||||
return serverName;
|
||||
}
|
||||
|
||||
public SpiEbeanServer getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public void setServer(SpiEbeanServer server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public DeleteByIdMap getDeleteByIdMap() {
|
||||
return deleteByIdMap;
|
||||
}
|
||||
|
||||
public void setDeleteByIdMap(DeleteByIdMap deleteByIdMap) {
|
||||
this.deleteByIdMap = deleteByIdMap;
|
||||
}
|
||||
|
||||
public Set<IndexInvalidate> getIndexInvalidations() {
|
||||
return indexInvalidations;
|
||||
}
|
||||
|
||||
public List<IndexEvent> getIndexEventList() {
|
||||
return indexEventList;
|
||||
}
|
||||
|
||||
public List<TableIUD> getTableIUDList() {
|
||||
return tableList;
|
||||
}
|
||||
|
||||
public List<BeanPersistIds> getBeanPersistList() {
|
||||
return beanPersistList;
|
||||
}
|
||||
|
||||
public List<BeanDeltaList> getBeanDeltaLists() {
|
||||
if (beanDeltaMap != null){
|
||||
beanDeltaLists.addAll(beanDeltaMap.deltaLists());
|
||||
}
|
||||
return beanDeltaLists;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Buffer of transaction messages.
|
||||
* <p>
|
||||
* For performance reasons we add all the transaction messages to an instance of
|
||||
* TransactionLogBuffer and then when the buffer is full or the transaction ends
|
||||
* we send the buffer to the transaction manager to log.
|
||||
* </p>
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
*/
|
||||
public class TransactionLogBuffer {
|
||||
|
||||
private final String transactionId;
|
||||
|
||||
private final ArrayList<LogEntry> buffer;
|
||||
|
||||
private final int maxSize;
|
||||
|
||||
private int currentSize;
|
||||
|
||||
/**
|
||||
* Create the buffer with a maxSize and transaction id.
|
||||
*/
|
||||
public TransactionLogBuffer(int maxSize, String transactionId) {
|
||||
this.maxSize = maxSize;
|
||||
this.transactionId = transactionId;
|
||||
this.buffer = new ArrayList<LogEntry>(maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new buffer using the same configuration.
|
||||
*/
|
||||
public TransactionLogBuffer newBuffer() {
|
||||
return new TransactionLogBuffer(maxSize, transactionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the transaction id.
|
||||
*/
|
||||
public String getTransactionId() {
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a message to the buffer.
|
||||
*/
|
||||
public boolean add(String msg) {
|
||||
buffer.add(new LogEntry(msg));
|
||||
return ++currentSize >= maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the buffer is empty.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return buffer.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all the messages.
|
||||
*/
|
||||
public List<LogEntry> messages() {
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry in the buffer.
|
||||
*/
|
||||
public class LogEntry {
|
||||
|
||||
private final long timestamp;
|
||||
private final String msg;
|
||||
|
||||
/**
|
||||
* Construct an entry.
|
||||
*/
|
||||
public LogEntry(String msg) {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time the entry was put into the buffer.
|
||||
*/
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the text of the message.
|
||||
*/
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.transaction.log.FileTransactionLoggerWrapper;
|
||||
import com.avaje.ebeaninternal.server.transaction.log.JuliTransactionLogger;
|
||||
|
||||
/**
|
||||
* Manages the transaction logs.
|
||||
*/
|
||||
public class TransactionLogManager {
|
||||
|
||||
private final TransactionLogWriter logWriter;
|
||||
|
||||
/**
|
||||
* Create the TransactionLogger.
|
||||
* <p>
|
||||
* DevNote: This registers a shutdown hook to flush and close the
|
||||
* sharedLogger. Alternate option would be to flush() the log after each
|
||||
* write to the log.
|
||||
* </p>
|
||||
*/
|
||||
public TransactionLogManager(ServerConfig serverConfig) {
|
||||
|
||||
if (serverConfig.isLoggingToJavaLogger()){
|
||||
logWriter = new JuliTransactionLogger();
|
||||
} else {
|
||||
logWriter = new FileTransactionLoggerWrapper(serverConfig);
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
logWriter.shutdown();
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
logWriter.log(logBuffer);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
/**
|
||||
* Write transaction log events to a file or other destination.
|
||||
*/
|
||||
public interface TransactionLogWriter {
|
||||
|
||||
/**
|
||||
* Log all the messages in the buffer.
|
||||
*/
|
||||
public void log(TransactionLogBuffer logBuffer);
|
||||
|
||||
/**
|
||||
* Shutdown the writer.
|
||||
*/
|
||||
public void shutdown();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import com.avaje.ebean.BackgroundExecutor;
|
||||
import com.avaje.ebean.LogLevel;
|
||||
import com.avaje.ebean.TxIsolation;
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebean.event.TransactionEventListener;
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.api.TransactionEvent;
|
||||
import com.avaje.ebeaninternal.api.TransactionEventTable;
|
||||
import com.avaje.ebeaninternal.api.TransactionEventTable.TableIUD;
|
||||
import com.avaje.ebeaninternal.server.cluster.ClusterManager;
|
||||
import com.avaje.ebeaninternal.server.core.BootupClasses;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager;
|
||||
|
||||
/**
|
||||
* Manages transactions.
|
||||
* <p>
|
||||
* Keeps the Cache, Cluster and Lucene indexes in synch when transactions are
|
||||
* committed.
|
||||
* </p>
|
||||
*/
|
||||
public class TransactionManager {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(TransactionManager.class.getName());
|
||||
|
||||
/**
|
||||
* The behaviour desired when ending a query only transaction.
|
||||
*/
|
||||
public enum OnQueryOnly {
|
||||
|
||||
/**
|
||||
* Rollback the transaction.
|
||||
*/
|
||||
ROLLBACK,
|
||||
|
||||
/**
|
||||
* Just close the transaction.
|
||||
*/
|
||||
CLOSE_ON_READCOMMITTED,
|
||||
|
||||
/**
|
||||
* Commit the transaction
|
||||
*/
|
||||
COMMIT
|
||||
}
|
||||
|
||||
private final BeanDescriptorManager beanDescriptorManager;
|
||||
|
||||
private LogLevel logLevel;
|
||||
|
||||
/**
|
||||
* The logger.
|
||||
*/
|
||||
private final TransactionLogManager transLogger;
|
||||
|
||||
/**
|
||||
* Prefix for transaction id's (logging).
|
||||
*/
|
||||
private final String prefix;
|
||||
|
||||
private final String externalTransPrefix;
|
||||
|
||||
/**
|
||||
* The dataSource of connections.
|
||||
*/
|
||||
private final DataSource dataSource;
|
||||
|
||||
/**
|
||||
* Flag to indicate the default Isolation is READ COMMITTED. This enables us
|
||||
* to close queryOnly transactions rather than commit or rollback them.
|
||||
*/
|
||||
private final OnQueryOnly onQueryOnly;
|
||||
|
||||
/**
|
||||
* The default batchMode for transactions.
|
||||
*/
|
||||
private final boolean defaultBatchMode;
|
||||
|
||||
private final BackgroundExecutor backgroundExecutor;
|
||||
|
||||
private final ClusterManager clusterManager;
|
||||
|
||||
private final int commitDebugLevel;
|
||||
|
||||
private final String serverName;
|
||||
|
||||
/**
|
||||
* Id's for transaction logging.
|
||||
*/
|
||||
private AtomicLong transactionCounter = new AtomicLong(1000);
|
||||
|
||||
private int clusterDebugLevel;
|
||||
|
||||
private final BulkEventListenerMap bulkEventListenerMap;
|
||||
|
||||
private TransactionEventListener[] transactionEventListeners;
|
||||
|
||||
/**
|
||||
* Create the TransactionManager
|
||||
*/
|
||||
public TransactionManager(ClusterManager clusterManager, BackgroundExecutor backgroundExecutor, ServerConfig config,
|
||||
BeanDescriptorManager descMgr, BootupClasses bootupClasses) {
|
||||
|
||||
this.beanDescriptorManager = descMgr;
|
||||
this.clusterManager = clusterManager;
|
||||
this.serverName = config.getName();
|
||||
|
||||
this.logLevel = config.getLoggingLevel();
|
||||
this.transLogger = new TransactionLogManager(config);
|
||||
this.backgroundExecutor = backgroundExecutor;
|
||||
this.dataSource = config.getDataSource();
|
||||
this.bulkEventListenerMap = new BulkEventListenerMap(config.getBulkTableEventListeners());
|
||||
|
||||
List<TransactionEventListener> transactionEventListeners = bootupClasses.getTransactionEventListeners();
|
||||
this.transactionEventListeners = transactionEventListeners.toArray(new TransactionEventListener[transactionEventListeners.size()]);
|
||||
|
||||
// log some transaction events using a java util logger
|
||||
this.commitDebugLevel = GlobalProperties.getInt("ebean.commit.debuglevel", 0);
|
||||
this.clusterDebugLevel = GlobalProperties.getInt("ebean.cluster.debuglevel", 0);
|
||||
|
||||
this.defaultBatchMode = config.isPersistBatching();
|
||||
|
||||
this.prefix = GlobalProperties.get("transaction.prefix", "");
|
||||
this.externalTransPrefix = GlobalProperties.get("transaction.prefix", "e");
|
||||
|
||||
String value = GlobalProperties.get("transaction.onqueryonly", "ROLLBACK").toUpperCase().trim();
|
||||
this.onQueryOnly = getOnQueryOnly(value, dataSource);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
transLogger.shutdown();
|
||||
}
|
||||
|
||||
public BeanDescriptorManager getBeanDescriptorManager() {
|
||||
return beanDescriptorManager;
|
||||
}
|
||||
|
||||
public BulkEventListenerMap getBulkEventListenerMap() {
|
||||
return bulkEventListenerMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the logging level for transactions.
|
||||
*/
|
||||
public LogLevel getTransactionLogLevel(){
|
||||
return logLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the log level for transactions.
|
||||
*/
|
||||
public void setTransactionLogLevel(LogLevel logLevel){
|
||||
this.logLevel = logLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the behaviour to use when a query only transaction is committed.
|
||||
* <p>
|
||||
* There is a potential optimisation available when read committed is the default
|
||||
* isolation level. If it is, then Connections used only for queries do not require
|
||||
* commit or rollback but instead can just be put back into the pool via close().
|
||||
* </p>
|
||||
* <p>
|
||||
* If the Isolation level is higher (say SERIALIZABLE) then Connections used
|
||||
* just for queries do need to be committed or rollback after the query.
|
||||
* </p>
|
||||
*/
|
||||
private OnQueryOnly getOnQueryOnly(String onQueryOnly, DataSource ds) {
|
||||
|
||||
|
||||
if (onQueryOnly.equals("COMMIT")){
|
||||
return OnQueryOnly.COMMIT;
|
||||
}
|
||||
if (onQueryOnly.startsWith("CLOSE")){
|
||||
if (!isReadCommitedIsolation(ds)){
|
||||
String m = "transaction.queryonlyclose is true but the transaction Isolation Level is not READ_COMMITTED";
|
||||
throw new PersistenceException(m);
|
||||
} else {
|
||||
return OnQueryOnly.CLOSE_ON_READCOMMITTED;
|
||||
}
|
||||
}
|
||||
// default to rollback
|
||||
return OnQueryOnly.ROLLBACK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the isolation level is read committed.
|
||||
*/
|
||||
private boolean isReadCommitedIsolation(DataSource ds) {
|
||||
|
||||
Connection c = null;
|
||||
try {
|
||||
c = ds.getConnection();
|
||||
|
||||
int isolationLevel = c.getTransactionIsolation();
|
||||
return (isolationLevel == Connection.TRANSACTION_READ_COMMITTED);
|
||||
|
||||
} catch (SQLException ex) {
|
||||
String m = "Errored trying to determine the default Isolation Level";
|
||||
throw new PersistenceException(m, ex);
|
||||
|
||||
} finally {
|
||||
try {
|
||||
if (c != null) {
|
||||
c.close();
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.log(Level.SEVERE, "closing connection", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getServerName() {
|
||||
return serverName;
|
||||
}
|
||||
|
||||
public DataSource getDataSource() {
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the cluster debug level.
|
||||
*/
|
||||
public int getClusterDebugLevel() {
|
||||
return clusterDebugLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cluster debug level.
|
||||
*/
|
||||
public void setClusterDebugLevel(int clusterDebugLevel) {
|
||||
this.clusterDebugLevel = clusterDebugLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines the type of behaviour to use when closing a transaction that was used to query data only.
|
||||
*/
|
||||
public OnQueryOnly getOnQueryOnly() {
|
||||
return onQueryOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the TransactionLogger used by this TransactionManager.
|
||||
*/
|
||||
public TransactionLogManager getLogger() {
|
||||
return transLogger;
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer){
|
||||
if (!logBuffer.isEmpty()){
|
||||
transLogger.log(logBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the externally supplied Connection.
|
||||
*/
|
||||
public SpiTransaction wrapExternalConnection(Connection c) {
|
||||
|
||||
return wrapExternalConnection(externalTransPrefix + c.hashCode(), c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an externally supplied Connection with a known transaction id.
|
||||
*/
|
||||
public SpiTransaction wrapExternalConnection(String id, Connection c) {
|
||||
|
||||
ExternalJdbcTransaction t = new ExternalJdbcTransaction(id, true, logLevel, c, this);
|
||||
|
||||
// set the default batch mode. This can be on for
|
||||
// jdbc drivers that support getGeneratedKeys
|
||||
if (defaultBatchMode){
|
||||
t.setBatchMode(true);
|
||||
}
|
||||
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new Transaction.
|
||||
*/
|
||||
public SpiTransaction createTransaction(boolean explicit, int isolationLevel) {
|
||||
Connection c = null;
|
||||
try {
|
||||
c = dataSource.getConnection();
|
||||
long id = transactionCounter.incrementAndGet();
|
||||
|
||||
JdbcTransaction t = new JdbcTransaction(prefix + id, explicit, logLevel, c, this);
|
||||
|
||||
// set the default batch mode. This can be on for
|
||||
// jdbc drivers that support getGeneratedKeys
|
||||
if (defaultBatchMode){
|
||||
t.setBatchMode(true);
|
||||
}
|
||||
if (isolationLevel > -1) {
|
||||
c.setTransactionIsolation(isolationLevel);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 3){
|
||||
String msg = "Transaction ["+t.getId()+"] begin";
|
||||
if (isolationLevel > -1){
|
||||
TxIsolation txi = TxIsolation.fromLevel(isolationLevel);
|
||||
msg += " isolationLevel["+txi+"]";
|
||||
}
|
||||
logger.info(msg);
|
||||
}
|
||||
|
||||
return t;
|
||||
|
||||
} catch (SQLException ex) {
|
||||
// close connection on failed creation
|
||||
try {
|
||||
if (c != null){
|
||||
c.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE,"Error closing failed connection", e);
|
||||
}
|
||||
throw new PersistenceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public SpiTransaction createQueryTransaction() {
|
||||
Connection c = null;
|
||||
try {
|
||||
c = dataSource.getConnection();
|
||||
long id = transactionCounter.incrementAndGet();
|
||||
|
||||
JdbcTransaction t = new JdbcTransaction(prefix + id, false, logLevel, c, this);
|
||||
|
||||
// set the default batch mode. Can be true for
|
||||
// jdbc drivers that support getGeneratedKeys
|
||||
if (defaultBatchMode){
|
||||
t.setBatchMode(true);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 3){
|
||||
logger.info("Transaction ["+t.getId()+"] begin - queryOnly");
|
||||
}
|
||||
|
||||
return t;
|
||||
|
||||
} catch (PersistenceException ex) {
|
||||
// close the connection and re-throw the exception
|
||||
try {
|
||||
if (c != null) {
|
||||
c.close();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE,"Error closing failed connection", e);
|
||||
}
|
||||
throw ex;
|
||||
|
||||
} catch (SQLException ex) {
|
||||
// don't need to close connection in this case
|
||||
throw new PersistenceException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a local rolled back transaction.
|
||||
*/
|
||||
public void notifyOfRollback(SpiTransaction transaction, Throwable cause) {
|
||||
|
||||
try {
|
||||
for (TransactionEventListener listener : transactionEventListeners) {
|
||||
listener.postTransactionRollback(transaction, cause);
|
||||
}
|
||||
|
||||
if (transaction.isLogSummary() || commitDebugLevel >= 1) {
|
||||
String msg = "Rollback";
|
||||
if (cause != null){
|
||||
msg += " error: "+formatThrowable(cause);
|
||||
}
|
||||
if (transaction.isLogSummary()) {
|
||||
transaction.logInternal(msg);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 1){
|
||||
logger.info("Transaction ["+transaction.getId()+"] "+msg);
|
||||
}
|
||||
}
|
||||
|
||||
log(transaction.getLogBuffer());
|
||||
} catch (Exception ex) {
|
||||
String m = "Potentially Transaction Log incomplete due to error:";
|
||||
logger.log(Level.SEVERE, m, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query only transaction in read committed isolation.
|
||||
*/
|
||||
public void notifyOfQueryOnly(boolean onCommit, SpiTransaction transaction, Throwable cause) {
|
||||
|
||||
try {
|
||||
if (commitDebugLevel >= 2){
|
||||
String msg;
|
||||
if (onCommit){
|
||||
msg = "Commit queryOnly";
|
||||
|
||||
} else {
|
||||
msg = "Rollback queryOnly";
|
||||
if (cause != null){
|
||||
msg += " error: "+formatThrowable(cause);
|
||||
}
|
||||
}
|
||||
if (transaction.isLogSummary()) {
|
||||
transaction.logInternal(msg);
|
||||
}
|
||||
logger.info("Transaction ["+transaction.getId()+"] "+msg);
|
||||
}
|
||||
|
||||
log(transaction.getLogBuffer());
|
||||
|
||||
} catch (Exception ex) {
|
||||
String m = "Potentially Transaction Log incomplete due to error:";
|
||||
logger.log(Level.SEVERE, m, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private String formatThrowable(Throwable e){
|
||||
if (e == null){
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
formatThrowable(e, sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void formatThrowable(Throwable e, StringBuilder sb){
|
||||
|
||||
sb.append(e.toString());
|
||||
StackTraceElement[] stackTrace = e.getStackTrace();
|
||||
if (stackTrace.length > 0){
|
||||
sb.append(" stack0: ");
|
||||
sb.append(stackTrace[0]);
|
||||
}
|
||||
Throwable cause = e.getCause();
|
||||
if (cause != null){
|
||||
sb.append(" cause: ");
|
||||
formatThrowable(cause, sb);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a local committed transaction.
|
||||
*/
|
||||
public void notifyOfCommit(SpiTransaction transaction) {
|
||||
|
||||
try {
|
||||
|
||||
log(transaction.getLogBuffer());
|
||||
|
||||
PostCommitProcessing postCommit = new PostCommitProcessing(clusterManager, this, transaction,
|
||||
transaction.getEvent());
|
||||
|
||||
postCommit.notifyLocalCacheIndex();
|
||||
postCommit.notifyCluster();
|
||||
|
||||
// cluster and text indexing
|
||||
backgroundExecutor.execute(postCommit.notifyPersistListeners());
|
||||
|
||||
for (TransactionEventListener listener : transactionEventListeners) {
|
||||
listener.postTransactionCommit(transaction);
|
||||
}
|
||||
|
||||
if (commitDebugLevel >= 1) {
|
||||
logger.info("Transaction ["+transaction.getId()+"] commit");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
String m = "NotifyOfCommit failed. Cache/Lucene potentially not notified.";
|
||||
logger.log(Level.SEVERE, m, ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Process a Transaction that comes from another framework or local code.
|
||||
* <p>
|
||||
* For cases where raw SQL/JDBC or other frameworks are used this can
|
||||
* invalidate the appropriate parts of the cache.
|
||||
* </p>
|
||||
*/
|
||||
public void externalModification(TransactionEventTable tableEvents) {
|
||||
|
||||
TransactionEvent event = new TransactionEvent();
|
||||
event.add(tableEvents);
|
||||
|
||||
PostCommitProcessing postCommit = new PostCommitProcessing(clusterManager, this, null, event);
|
||||
|
||||
// invalidate parts of local cache and index
|
||||
postCommit.notifyLocalCacheIndex();
|
||||
|
||||
backgroundExecutor.execute(postCommit.notifyPersistListeners());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Notify local BeanPersistListeners etc of events from another server in the cluster.
|
||||
*/
|
||||
public void remoteTransactionEvent(RemoteTransactionEvent remoteEvent) {
|
||||
|
||||
if (clusterDebugLevel > 0 || logger.isLoggable(Level.FINE)){
|
||||
logger.info("Cluster Received: "+remoteEvent.toString());
|
||||
}
|
||||
|
||||
List<TableIUD> tableIUDList = remoteEvent.getTableIUDList();
|
||||
if (tableIUDList != null){
|
||||
for (int i = 0; i < tableIUDList.size(); i++) {
|
||||
TableIUD tableIUD = tableIUDList.get(i);
|
||||
beanDescriptorManager.cacheNotify(tableIUD);
|
||||
}
|
||||
}
|
||||
|
||||
List<BeanPersistIds> beanPersistList = remoteEvent.getBeanPersistList();
|
||||
if (beanPersistList != null){
|
||||
for (int i = 0; i < beanPersistList.size(); i++) {
|
||||
BeanPersistIds beanPersist = beanPersistList.get(i);
|
||||
beanPersist.notifyCacheAndListener();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
|
||||
|
||||
/**
|
||||
* Current transactions mapped by server name.
|
||||
*/
|
||||
public class TransactionMap {
|
||||
|
||||
/**
|
||||
* Map of State by serverName.
|
||||
*/
|
||||
private HashMap<String,State> map = new HashMap<String, State>();
|
||||
|
||||
public String toString() {
|
||||
return map.toString();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return map.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the State for a given serverName.
|
||||
*/
|
||||
public State getState(String serverName) {
|
||||
|
||||
return map.get(serverName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the State for a given serverName.
|
||||
*/
|
||||
public State getStateWithCreate(String serverName) {
|
||||
|
||||
State state = map.get(serverName);
|
||||
if (state == null){
|
||||
state = new State();
|
||||
map.put(serverName, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove and return the State for a given serverName.
|
||||
*/
|
||||
public State removeState(String serverName) {
|
||||
return map.remove(serverName);
|
||||
}
|
||||
|
||||
/**
|
||||
* The transaction and whether it is active.
|
||||
*/
|
||||
public static class State {
|
||||
|
||||
SpiTransaction transaction;
|
||||
|
||||
public String toString() {
|
||||
return "txn["+transaction+"]";
|
||||
}
|
||||
|
||||
public SpiTransaction get() {
|
||||
return transaction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the transaction. This will now be the current transaction.
|
||||
*/
|
||||
public void set(SpiTransaction trans) {
|
||||
|
||||
if (transaction != null && transaction.isActive()){
|
||||
String m = "The existing transaction is still active?";
|
||||
throw new PersistenceException(m);
|
||||
}
|
||||
transaction = trans;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Commit the transaction.
|
||||
*/
|
||||
public void commit() {
|
||||
transaction.commit();
|
||||
transaction = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback the transaction.
|
||||
*/
|
||||
public void rollback() {
|
||||
transaction.rollback();
|
||||
transaction = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* End the transaction.
|
||||
*/
|
||||
public void end() {
|
||||
if (transaction != null){
|
||||
transaction.end();
|
||||
transaction = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to replace transaction with a proxy.
|
||||
*/
|
||||
public void replace(SpiTransaction trans) {
|
||||
transaction = trans;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import com.avaje.ebeaninternal.api.SpiTransaction;
|
||||
import com.avaje.ebeaninternal.api.SpiTransactionScopeManager;
|
||||
|
||||
/**
|
||||
* Manages the Transactions typically held in a ThreadLocal.
|
||||
*/
|
||||
public abstract class TransactionScopeManager implements SpiTransactionScopeManager {
|
||||
|
||||
protected final TransactionManager transactionManager;
|
||||
|
||||
protected final String serverName;
|
||||
|
||||
public TransactionScopeManager(TransactionManager transactionManager){
|
||||
this.transactionManager = transactionManager;
|
||||
this.serverName = transactionManager.getServerName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current Transaction for this serverName and Thread.
|
||||
*/
|
||||
public abstract SpiTransaction get();
|
||||
|
||||
/**
|
||||
* Set a new Transaction for this serverName and Thread.
|
||||
*/
|
||||
public abstract void set(SpiTransaction trans);
|
||||
|
||||
/**
|
||||
* Commit the current transaction.
|
||||
*/
|
||||
public abstract void commit();
|
||||
|
||||
/**
|
||||
* Rollback the current transaction.
|
||||
*/
|
||||
public abstract void rollback();
|
||||
|
||||
|
||||
/**
|
||||
* Rollback if required.
|
||||
*/
|
||||
public abstract void end();
|
||||
|
||||
/**
|
||||
* Replace the current transaction with this one.
|
||||
* <p>
|
||||
* Used for Background fetching and Nested transaction scopes.
|
||||
* </p>
|
||||
* <p>
|
||||
* Used for background fetching. Replaces the current transaction with a
|
||||
* 'dummy' transaction. The current transaction is given to the background
|
||||
* thread so it can continue the fetch.
|
||||
* </p>
|
||||
*/
|
||||
public abstract void replace(SpiTransaction trans);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction;
|
||||
|
||||
import java.lang.ref.Reference;
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A Weak value map designed for use with DefaultPersistenceContext.
|
||||
* <p>
|
||||
* This provides the mechanism where entries in the persistence context will be
|
||||
* automatically removed when they are not referenced externally.
|
||||
* </p>
|
||||
*
|
||||
* @author mario, rbygrave
|
||||
*/
|
||||
public class WeakValueMap<K, V> {
|
||||
|
||||
protected final ReferenceQueue<V> refQueue = new ReferenceQueue<V>();
|
||||
|
||||
/**
|
||||
* Backing map.
|
||||
*/
|
||||
private final Map<K, WeakReferenceWithKey<K, V>> backing;
|
||||
|
||||
/**
|
||||
* Hold the key with the value for expunge purposes.
|
||||
*/
|
||||
private static class WeakReferenceWithKey<K, V> extends WeakReference<V> {
|
||||
|
||||
private final K key;
|
||||
|
||||
public WeakReferenceWithKey(K key, V referent, ReferenceQueue<? super V> q) {
|
||||
super(referent, q);
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public K getKey() {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
public WeakValueMap() {
|
||||
this.backing = new HashMap<K, WeakReferenceWithKey<K, V>>();
|
||||
}
|
||||
|
||||
private WeakReferenceWithKey<K, V> createReference(K key, V value) {
|
||||
return new WeakReferenceWithKey<K, V>(key, value, refQueue);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes" })
|
||||
private void expunge() {
|
||||
|
||||
Reference ref;
|
||||
|
||||
while ((ref = refQueue.poll()) != null) {
|
||||
backing.remove(((WeakReferenceWithKey) ref).getKey());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the key value pair if there is not already a matching entry. If there
|
||||
* is an existing entry then return that instead.
|
||||
*/
|
||||
public Object putIfAbsent(K key, V value) {
|
||||
expunge();
|
||||
|
||||
Reference<V> ref = backing.get(key);
|
||||
if (ref != null) {
|
||||
V existingValue = ref.get();
|
||||
if (existingValue != null) {
|
||||
// it is not absent
|
||||
return existingValue;
|
||||
}
|
||||
}
|
||||
// put the new value and return null
|
||||
// indicating the put was successful
|
||||
backing.put(key, createReference(key, value));
|
||||
return null;
|
||||
}
|
||||
|
||||
public void put(K key, V value) {
|
||||
expunge();
|
||||
|
||||
backing.put(key, createReference(key, value));
|
||||
}
|
||||
|
||||
public V get(K key) {
|
||||
expunge();
|
||||
|
||||
Reference<V> v = backing.get(key);
|
||||
return v == null ? null : v.get();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
expunge();
|
||||
|
||||
return backing.size();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
expunge();
|
||||
|
||||
return backing.isEmpty();
|
||||
}
|
||||
|
||||
public boolean containsKey(Object key) {
|
||||
expunge();
|
||||
|
||||
return backing.containsKey(key);
|
||||
}
|
||||
|
||||
public V remove(K key) {
|
||||
expunge();
|
||||
|
||||
Reference<V> v = backing.remove(key);
|
||||
return v == null ? null : v.get();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
expunge();
|
||||
backing.clear();
|
||||
expunge();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
expunge();
|
||||
|
||||
return backing.toString();
|
||||
}
|
||||
|
||||
}
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
/**
|
||||
* Copyright (C) 2010 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer.LogEntry;
|
||||
|
||||
/**
|
||||
* Default transaction logger implementation.
|
||||
* <p>
|
||||
* File based logger that can switch daily. It will include the date in the
|
||||
* files name.
|
||||
* </p>
|
||||
* <p>
|
||||
* Administration Note: If log file switching fails it will send the error to
|
||||
* standard out and standard err print streams. This is assumed to be rather
|
||||
* unlikely but possible.
|
||||
* </p>
|
||||
*/
|
||||
public class FileTransactionLogger implements Runnable, TransactionLogWriter {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(FileTransactionLogger.class.getName());
|
||||
|
||||
/**
|
||||
* Used to print stack trace.
|
||||
*/
|
||||
private static final String atString = " at ";
|
||||
|
||||
/**
|
||||
* The newLineChar used instead of NL or CRNL for printing stack traces.
|
||||
*/
|
||||
private final String newLinePlaceholder = "\\r\\n";
|
||||
|
||||
/**
|
||||
* The maximum number of stack lines to output. This is just for transaction
|
||||
* logging so 5 is fine.
|
||||
*/
|
||||
private final int maxStackTraceLines = 5;
|
||||
|
||||
/**
|
||||
* Queue that transactions put their LogBuffers onto and this LogBufferWriter
|
||||
* pulls LogBuffers from.
|
||||
*/
|
||||
private final ConcurrentLinkedQueue<TransactionLogBuffer> logBufferQueue = new ConcurrentLinkedQueue<TransactionLogBuffer>();
|
||||
|
||||
private final Object queueMonitor = new Object();
|
||||
|
||||
/**
|
||||
* Thread that is the sole writer of logBuffer entries to the file.
|
||||
*/
|
||||
private final Thread logWriterThread;
|
||||
|
||||
private final String threadName;
|
||||
|
||||
/**
|
||||
* The path of the log file.
|
||||
*/
|
||||
private final String filepath;
|
||||
|
||||
/**
|
||||
* The delimiter to use.
|
||||
*/
|
||||
private final String deliminator = ", ";
|
||||
|
||||
/**
|
||||
* The prefix of the log file name.
|
||||
*/
|
||||
private final String logFileName;
|
||||
|
||||
/**
|
||||
* The file suffix for the logs.
|
||||
*/
|
||||
private final String logFileSuffix;
|
||||
|
||||
/**
|
||||
* Shutdown flag.
|
||||
*/
|
||||
private volatile boolean shutdown;
|
||||
private volatile boolean shutdownComplete;
|
||||
|
||||
/**
|
||||
* The output stream.
|
||||
*/
|
||||
private PrintStream out;
|
||||
|
||||
/**
|
||||
* The current file path.
|
||||
*/
|
||||
private String currentPath;
|
||||
|
||||
/**
|
||||
* Counter thats incremented when maxBytesPerFile is hit.
|
||||
*/
|
||||
private int fileCounter;
|
||||
|
||||
/**
|
||||
* Roughly the max bytes written to a file before we switch. Switch Daily and
|
||||
* on hitting max bytes.
|
||||
*/
|
||||
private long maxBytesPerFile;
|
||||
|
||||
/**
|
||||
* Roughly the bytes written to a file.
|
||||
*/
|
||||
private long bytesWritten;
|
||||
|
||||
public FileTransactionLogger(String threadName, String dir, String logFileName, int maxBytesPerFile) {
|
||||
this(threadName, dir, logFileName, "log", maxBytesPerFile);
|
||||
}
|
||||
|
||||
public FileTransactionLogger(String threadName, String dir, String logFileName, String suffix, int maxBytesPerFile) {
|
||||
this.threadName = threadName;
|
||||
this.logFileName = logFileName;
|
||||
this.logFileSuffix = "." + suffix;
|
||||
this.maxBytesPerFile = maxBytesPerFile;
|
||||
|
||||
try {
|
||||
// get the directory where the log files are going to go
|
||||
filepath = makeDirIfRequired(dir);
|
||||
|
||||
switchFile(LogTime.nextDay());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
System.err.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
logWriterThread = new Thread(this, threadName);
|
||||
logWriterThread.setDaemon(true);
|
||||
}
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
close();
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
public void start() {
|
||||
logWriterThread.start();
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
|
||||
shutdown = true;
|
||||
|
||||
synchronized (logWriterThread) {
|
||||
try {
|
||||
// wait max 20 seconds
|
||||
logWriterThread.wait(20000);
|
||||
logger.fine("Shutdown LogBufferWriter " + threadName + " shutdownComplete:" + shutdownComplete);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
logger.fine("InterruptedException:" + e);
|
||||
}
|
||||
}
|
||||
|
||||
if (!shutdownComplete) {
|
||||
String m = "WARNING: Shutdown of LogBufferWriter " + threadName + " not completed.";
|
||||
System.err.println(m);
|
||||
logger.warning(m);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void run() {
|
||||
|
||||
int missCount = 0;
|
||||
|
||||
while (!shutdown || missCount < 10) {
|
||||
if (missCount > 50) {
|
||||
|
||||
if (out != null) {
|
||||
out.flush();
|
||||
}
|
||||
try {
|
||||
Thread.sleep(20);
|
||||
} catch (InterruptedException e) {
|
||||
logger.log(Level.INFO, "Interrupted TxnLogBufferWriter", e);
|
||||
}
|
||||
}
|
||||
synchronized (queueMonitor) {
|
||||
if (logBufferQueue.isEmpty()) {
|
||||
++missCount;
|
||||
} else {
|
||||
TransactionLogBuffer buffer = logBufferQueue.remove();
|
||||
write(buffer);
|
||||
missCount = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close();
|
||||
shutdownComplete = true;
|
||||
|
||||
synchronized (logWriterThread) {
|
||||
logWriterThread.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
logBufferQueue.add(logBuffer);
|
||||
}
|
||||
|
||||
private void write(TransactionLogBuffer logBuffer) {
|
||||
|
||||
// check to see if we need to switch file?
|
||||
LogTime logTime = LogTime.get();
|
||||
if (logTime.isNextDay()) {
|
||||
logTime = LogTime.nextDay();
|
||||
switchFile(logTime);
|
||||
}
|
||||
|
||||
if (bytesWritten > maxBytesPerFile) {
|
||||
++fileCounter;
|
||||
switchFile(logTime);
|
||||
}
|
||||
|
||||
String txnId = logBuffer.getTransactionId();
|
||||
|
||||
List<LogEntry> messages = logBuffer.messages();
|
||||
for (int i = 0; i < messages.size(); i++) {
|
||||
LogEntry msg = messages.get(i);
|
||||
printMessage(logTime, txnId, msg);
|
||||
}
|
||||
}
|
||||
|
||||
private void printMessage(LogTime logTime, String txnId, LogEntry logEntry) {
|
||||
|
||||
String msg = logEntry.getMsg();
|
||||
int len = msg.length();
|
||||
if (len == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// add overhead + content
|
||||
bytesWritten += 16;
|
||||
bytesWritten += len;
|
||||
|
||||
if (txnId != null) {
|
||||
bytesWritten += 7;
|
||||
bytesWritten += txnId.length();
|
||||
out.append("txn[");
|
||||
out.append(txnId);
|
||||
out.append("]");
|
||||
out.append(deliminator);
|
||||
}
|
||||
|
||||
out.append(logTime.getTimestamp(logEntry.getTimestamp()));
|
||||
out.append(deliminator);
|
||||
out.append(msg).append(" ");
|
||||
out.append("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively output the Throwable stack trace to the log.
|
||||
*
|
||||
* @param sb
|
||||
* the buffer to write the stack trace to
|
||||
* @param e
|
||||
* the source throwable
|
||||
* @param isCause
|
||||
* flag to indicate if this is the top level throwable or a cause
|
||||
*/
|
||||
protected void printThrowable(StringBuilder sb, Throwable e, boolean isCause) {
|
||||
if (e != null) {
|
||||
if (isCause) {
|
||||
sb.append("Caused by: ");
|
||||
}
|
||||
sb.append(e.getClass().getName());
|
||||
sb.append(":");
|
||||
sb.append(e.getMessage()).append(newLinePlaceholder);
|
||||
|
||||
StackTraceElement[] ste = e.getStackTrace();
|
||||
int outputStackLines = ste.length;
|
||||
int notShownCount = 0;
|
||||
if (ste.length > maxStackTraceLines) {
|
||||
outputStackLines = maxStackTraceLines;
|
||||
notShownCount = ste.length - outputStackLines;
|
||||
}
|
||||
for (int i = 0; i < outputStackLines; i++) {
|
||||
sb.append(atString);
|
||||
sb.append(ste[i].toString()).append(newLinePlaceholder);
|
||||
}
|
||||
if (notShownCount > 0) {
|
||||
sb.append(" ... ");
|
||||
sb.append(notShownCount);
|
||||
sb.append(" more").append(newLinePlaceholder);
|
||||
}
|
||||
Throwable cause = e.getCause();
|
||||
if (cause != null) {
|
||||
printThrowable(sb, cause, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String newFileName(LogTime logTime) {
|
||||
return filepath + File.separator + logFileName + logTime.getYMD() + "-" + fileCounter + logFileSuffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the file to log to.
|
||||
*/
|
||||
protected void switchFile(LogTime logTime) {
|
||||
|
||||
try {
|
||||
long currentFileLength = 0;
|
||||
String newFilePath = null;
|
||||
|
||||
// skip a file if it already has max bytes
|
||||
do {
|
||||
newFilePath = newFileName(logTime);
|
||||
File f = new File(newFilePath);
|
||||
if (!f.exists()) {
|
||||
currentFileLength = 0;
|
||||
} else {
|
||||
if (f.length() < maxBytesPerFile * 0.8) {
|
||||
currentFileLength = f.length();
|
||||
} else {
|
||||
++fileCounter;
|
||||
newFilePath = null;
|
||||
}
|
||||
}
|
||||
} while (newFilePath == null);
|
||||
|
||||
if (!newFilePath.equals(currentPath)) {
|
||||
PrintStream newOut = new PrintStream(new BufferedOutputStream(new FileOutputStream(newFilePath, true)));
|
||||
|
||||
close();
|
||||
|
||||
bytesWritten = currentFileLength;
|
||||
currentPath = newFilePath;
|
||||
out = newOut;
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
logger.log(Level.SEVERE, "Error switch log file", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the file output stream being used for logging.
|
||||
*/
|
||||
private void close() {
|
||||
if (out != null) {
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory path of the log file.
|
||||
*/
|
||||
protected String makeDirIfRequired(String dir) {
|
||||
|
||||
File f = new File(dir);
|
||||
if (f.exists()) {
|
||||
if (!f.isDirectory()) {
|
||||
String msg = "Transaction logs directory is a file? " + dir;
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
} else {
|
||||
if (!f.mkdirs()) {
|
||||
String msg = "Failed to create transaction logs directory " + dir;
|
||||
logger.log(Level.SEVERE, msg);
|
||||
}
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.config.GlobalProperties;
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
|
||||
|
||||
/**
|
||||
* Wraps a FileTransactionLogger to provide delayed initialisation.
|
||||
* <p>
|
||||
* This means that it should only create the log file WHEN there is something
|
||||
* actually logged. This means the logLevel can start at NONE and then change at
|
||||
* runtime (and the log file will then be initialised). NOTE that a volatile
|
||||
* with double checked locking is used to make this transition thread safe.
|
||||
* </p>
|
||||
*
|
||||
* @author rbygrave
|
||||
*
|
||||
*/
|
||||
public class FileTransactionLoggerWrapper implements TransactionLogWriter {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(FileTransactionLoggerWrapper.class.getName());
|
||||
|
||||
private final String serverName;
|
||||
private final String dir;
|
||||
private final int maxFileSize;
|
||||
|
||||
private volatile FileTransactionLogger logWriter;
|
||||
|
||||
public FileTransactionLoggerWrapper(ServerConfig serverConfig) {
|
||||
|
||||
String evalDir = serverConfig.getLoggingDirectoryWithEval();
|
||||
this.dir = evalDir != null ? evalDir : "logs";
|
||||
this.maxFileSize = GlobalProperties.getInt("ebean.logging.maxFileSize", 100 * 1024 * 1024);
|
||||
this.serverName = serverConfig.getName();
|
||||
}
|
||||
|
||||
private FileTransactionLogger initialiseLogger() {
|
||||
|
||||
synchronized (this) {
|
||||
// double check locking here so logWriter NEEDS to be volatile!!
|
||||
FileTransactionLogger writer = this.logWriter;
|
||||
if (writer != null) {
|
||||
return writer;
|
||||
}
|
||||
|
||||
String middleName = GlobalProperties.get("ebean.logging.filename", "_txn_");
|
||||
String logPrefix = serverName + middleName;
|
||||
String threadName = "Ebean-" + serverName + "-TxnLogWriter";
|
||||
|
||||
// create the real logger and start it
|
||||
FileTransactionLogger newLogWriter = new FileTransactionLogger(threadName, dir, logPrefix, maxFileSize);
|
||||
|
||||
// assignment of volatile field
|
||||
this.logWriter = newLogWriter;
|
||||
|
||||
// start background thread for the writer
|
||||
newLogWriter.start();
|
||||
logger.info("Transaction logs in: " + dir);
|
||||
return newLogWriter;
|
||||
}
|
||||
}
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
// volatile read
|
||||
FileTransactionLogger writer = this.logWriter;
|
||||
if (writer == null) {
|
||||
writer = initialiseLogger();
|
||||
}
|
||||
writer.log(logBuffer);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
if (logWriter != null) {
|
||||
logWriter.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Copyright (C) 2009 Authors
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogWriter;
|
||||
import com.avaje.ebeaninternal.server.transaction.TransactionLogBuffer.LogEntry;
|
||||
|
||||
/**
|
||||
* A transactionLogger that uses a java.util.logging.Logger.
|
||||
* <p>
|
||||
* See {@link ServerConfig#setUseJuliTransactionLogger(boolean)}
|
||||
* </p>
|
||||
* @author rbygrave
|
||||
*/
|
||||
public class JuliTransactionLogger implements TransactionLogWriter {
|
||||
|
||||
private static Logger logger = Logger.getLogger(JuliTransactionLogger.class.getName());
|
||||
|
||||
public void log(TransactionLogBuffer logBuffer) {
|
||||
|
||||
String txnId = logBuffer.getTransactionId();
|
||||
|
||||
List<LogEntry> messages = logBuffer.messages();
|
||||
for (int i = 0; i < messages.size(); i++) {
|
||||
LogEntry logEntry = messages.get(i);
|
||||
log(txnId, logEntry);
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
}
|
||||
|
||||
private void log(String txnId, LogEntry entry) {
|
||||
|
||||
String message = entry.getMsg();
|
||||
if (txnId != null && message != null && !message.startsWith("Trans[")){
|
||||
message = "Trans["+txnId+"] "+message;
|
||||
}
|
||||
|
||||
logger.log(Level.INFO, message);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
/**
|
||||
* Utility object used to in logging time.
|
||||
* <p>
|
||||
* Used in place of SimpleDateFormat which requires synchronization. Determines
|
||||
* if the day has changed and returns a format of the current time and day.
|
||||
* </p>
|
||||
*/
|
||||
public class LogTime {
|
||||
|
||||
private static final String[] sep = { ":", "." };
|
||||
|
||||
private static LogTime day;
|
||||
static {
|
||||
day = new LogTime();
|
||||
}
|
||||
|
||||
public static LogTime get() {
|
||||
return day;
|
||||
}
|
||||
|
||||
public static LogTime nextDay() {
|
||||
LogTime d = new LogTime();
|
||||
day = d;
|
||||
return d;
|
||||
}
|
||||
|
||||
public static LogTime getWithCheck() {
|
||||
LogTime d = day;
|
||||
if (d.isNextDay()) {
|
||||
return nextDay();
|
||||
} else {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
private final String ymd;
|
||||
|
||||
private final long startMidnight;
|
||||
|
||||
private final long startTomorrow;
|
||||
|
||||
/**
|
||||
* Because every variable is private final the constructor should be thread
|
||||
* safe (In JDK5+).
|
||||
*/
|
||||
private LogTime() {
|
||||
|
||||
GregorianCalendar now = new GregorianCalendar();
|
||||
|
||||
now.set(Calendar.HOUR_OF_DAY, 0);
|
||||
now.set(Calendar.MINUTE, 0);
|
||||
now.set(Calendar.SECOND, 0);
|
||||
now.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
this.startMidnight = now.getTime().getTime();
|
||||
this.ymd = getDayDerived(now);
|
||||
|
||||
now.add(Calendar.DATE, 1);
|
||||
this.startTomorrow = now.getTime().getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if we have moved into tomorrow. This is used to trigger log
|
||||
* switching if required.
|
||||
*/
|
||||
public boolean isNextDay() {
|
||||
return (System.currentTimeMillis() >= startTomorrow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Year Month Day for today.
|
||||
*/
|
||||
public String getYMD() {
|
||||
return ymd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current time specify the separators.
|
||||
* <p>
|
||||
* The separators is a String[2] with the first string separating hours
|
||||
* minutes and seconds and the second separating seconds from millis.
|
||||
* </p>
|
||||
* <p>
|
||||
* The default is {":","."}
|
||||
* </p>
|
||||
*/
|
||||
public String getNow(String[] separators) {
|
||||
|
||||
return getTimestamp(System.currentTimeMillis(), separators);
|
||||
|
||||
}
|
||||
|
||||
public String getTimestamp(long systime) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
getTime(sb, systime, startMidnight, sep);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String getTimestamp(long systime, String[] separators) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
getTime(sb, systime, startMidnight, separators);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current time.
|
||||
* <p>
|
||||
* Format used is hours:minutes:seconds.millis
|
||||
* </p>
|
||||
*/
|
||||
public String getNow() {
|
||||
return getNow(sep);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the derived day information.
|
||||
*/
|
||||
private String getDayDerived(Calendar now) {
|
||||
|
||||
int nowyear = now.get(Calendar.YEAR);
|
||||
int nowmonth = now.get(Calendar.MONTH);
|
||||
int nowday = now.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
nowmonth++;
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
format(sb, nowyear, 4);
|
||||
format(sb, nowmonth, 2);
|
||||
format(sb, nowday, 2);
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void getTime(StringBuilder sb, long time, long midnight, String[] separator) {
|
||||
|
||||
long rem = time - midnight;// startMidnight;
|
||||
|
||||
long millis = rem % 1000;
|
||||
rem = rem / 1000;
|
||||
long secs = rem % 60;
|
||||
rem = rem / 60;
|
||||
long mins = rem % 60;
|
||||
rem = rem / 60;
|
||||
long hrs = rem;
|
||||
|
||||
format(sb, hrs, 2);
|
||||
sb.append(separator[0]);
|
||||
format(sb, mins, 2);
|
||||
sb.append(separator[0]);
|
||||
format(sb, secs, 2);
|
||||
sb.append(separator[1]);
|
||||
format(sb, millis, 3);
|
||||
}
|
||||
|
||||
private void format(StringBuilder sb, long value, int places) {
|
||||
String format = Long.toString(value);
|
||||
|
||||
int pad = places - format.length();
|
||||
for (int i = 0; i < pad; i++) {
|
||||
sb.append("0");
|
||||
}
|
||||
sb.append(format);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* Copyright (C) 2006 Robin Bygrave
|
||||
*
|
||||
* This file is part of Ebean.
|
||||
*
|
||||
* Ebean is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Ebean is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Ebean; if not, write to the Free Software Foundation, Inc.,
|
||||
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.avaje.ebeaninternal.server.transaction.log;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
|
||||
/**
|
||||
* File based logger that can switch daily. It will include the date in the
|
||||
* files name.
|
||||
* <p>
|
||||
* Administration Note: If log file switching fails it will send the error to
|
||||
* standard out and standard err print streams. This is assumed to be rather
|
||||
* unlikely but possible.
|
||||
* </p>
|
||||
*/
|
||||
public class SimpleLogger {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(SimpleLogger.class.getName());
|
||||
|
||||
/**
|
||||
* Used to print stack trace.
|
||||
*/
|
||||
private static final String atString = " at ";
|
||||
|
||||
/**
|
||||
* The output stream.
|
||||
*/
|
||||
private PrintStream out;
|
||||
|
||||
/**
|
||||
* Whether to append or replace.
|
||||
*/
|
||||
private boolean doAppend = true;
|
||||
|
||||
/**
|
||||
* Flag to indicate the logger if the logger has been closed.
|
||||
*/
|
||||
private boolean open = true;
|
||||
|
||||
/**
|
||||
* The current file path.
|
||||
*/
|
||||
private String currentPath;
|
||||
|
||||
/**
|
||||
* The path of the log file.
|
||||
*/
|
||||
private final String filepath;
|
||||
|
||||
/**
|
||||
* Set to true if using daily file switching.
|
||||
*/
|
||||
private final boolean useFileSwitching;
|
||||
|
||||
/**
|
||||
* The maximum number of stack lines to output.
|
||||
* This is just for transaction logging so 5 is fine.
|
||||
*/
|
||||
private final int maxStackTraceLines = 5;
|
||||
|
||||
/**
|
||||
* The delimiter to use.
|
||||
*/
|
||||
private final String deliminator;
|
||||
|
||||
/**
|
||||
* Object used to synch the file switching.
|
||||
*/
|
||||
private final Object fileMonitor = new Object();
|
||||
|
||||
/**
|
||||
* The prefix of the log file name.
|
||||
*/
|
||||
private final String logFileName;
|
||||
|
||||
/**
|
||||
* The file suffix for the logs.
|
||||
*/
|
||||
private final String logFileSuffix;
|
||||
|
||||
/**
|
||||
* The newLineChar used instead of NL or CRNL.
|
||||
*/
|
||||
private final String newLineChar = "\\r\\n";
|
||||
|
||||
private final boolean csv;
|
||||
|
||||
/**
|
||||
* Create a logger with a logFileName and useFileSwitching flag.
|
||||
*
|
||||
* @param dir
|
||||
* the sub directory to put the log. Can be null.
|
||||
* @param logFileName
|
||||
* the prefix log file name.
|
||||
* @param useFileSwitching
|
||||
* if true then use daily file switching.
|
||||
*/
|
||||
public SimpleLogger(String dir, String logFileName, boolean useFileSwitching, String suffix) {
|
||||
this.logFileName = logFileName;
|
||||
this.useFileSwitching = useFileSwitching;
|
||||
this.logFileSuffix = "."+suffix;
|
||||
csv = "csv".equalsIgnoreCase(suffix);
|
||||
deliminator = csv ? "," : ", ";
|
||||
try {
|
||||
|
||||
// get the directory where the log files are going to go
|
||||
filepath = makeDirIfRequired(dir);
|
||||
|
||||
switchFile(LogTime.nextDay());
|
||||
|
||||
} catch (Exception e) {
|
||||
// Not going to use logger to show logger exceptions...
|
||||
// Using standard out and standard err instead.
|
||||
System.out.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
System.err.println("FATAL ERROR: init of FileLogger: " + e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public SimpleLogger(String dir, String logFileName, boolean useFileSwitching) {
|
||||
this(dir, logFileName, useFileSwitching, "log");
|
||||
}
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
close();
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the file output stream being used for logging.
|
||||
*/
|
||||
public void close() {
|
||||
if (open) {
|
||||
out.flush();
|
||||
out.close();
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void log(String msg) {
|
||||
log(null, msg, null);
|
||||
}
|
||||
|
||||
public void log(String msg, Throwable e) {
|
||||
log(null, msg, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the event to the file.
|
||||
*/
|
||||
public void log(String transId, String msg, Throwable e) {
|
||||
|
||||
// check to see if we need to switch file?
|
||||
LogTime logTime = LogTime.get();
|
||||
if (logTime.isNextDay()) {
|
||||
logTime = LogTime.nextDay();
|
||||
try {
|
||||
switchFile(logTime);
|
||||
} catch (Exception ex) {
|
||||
// This is a pretty serious error... not logging it though as
|
||||
// this could be recursive so just going to send to std err
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// prefix of transID and timestamp ~ 40 chars
|
||||
int roughSize = 40;
|
||||
if (msg != null) {
|
||||
roughSize += msg.length();
|
||||
}
|
||||
if (e != null) {
|
||||
roughSize += 200;
|
||||
}
|
||||
|
||||
StringBuilder line = new StringBuilder(roughSize);
|
||||
if (transId != null){
|
||||
line.append("trans[").append(transId).append("]").append(deliminator);
|
||||
}
|
||||
|
||||
if (csv){
|
||||
line.append("\"'");
|
||||
}
|
||||
line.append(logTime.getNow());
|
||||
if (csv){
|
||||
line.append("'\"");
|
||||
}
|
||||
line.append(deliminator);
|
||||
|
||||
if (msg != null) {
|
||||
line.append(msg).append(" ");
|
||||
}
|
||||
|
||||
printThrowable(line, e, false);
|
||||
|
||||
String lineString = line.toString();
|
||||
|
||||
synchronized (fileMonitor) {
|
||||
out.println(lineString);
|
||||
// without flush automatic close() *MUST* be called
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively output the Throwable stack trace to the log.
|
||||
*
|
||||
* @param sb
|
||||
* the buffer to write the stack trace to
|
||||
* @param e
|
||||
* the source throwable
|
||||
* @param isCause
|
||||
* flag to indicate if this is the top level throwable or a cause
|
||||
*/
|
||||
protected void printThrowable(StringBuilder sb, Throwable e, boolean isCause) {
|
||||
if (e != null) {
|
||||
if (isCause) {
|
||||
sb.append("Caused by: ");
|
||||
}
|
||||
sb.append(e.getClass().getName());
|
||||
sb.append(":");
|
||||
sb.append(e.getMessage()).append(newLineChar);
|
||||
|
||||
StackTraceElement[] ste = e.getStackTrace();
|
||||
int outputStackLines = ste.length;
|
||||
int notShownCount = 0;
|
||||
if (ste.length > maxStackTraceLines) {
|
||||
outputStackLines = maxStackTraceLines;
|
||||
notShownCount = ste.length - outputStackLines;
|
||||
}
|
||||
for (int i = 0; i < outputStackLines; i++) {
|
||||
sb.append(atString);
|
||||
sb.append(ste[i].toString()).append(newLineChar);
|
||||
}
|
||||
if (notShownCount > 0) {
|
||||
sb.append(" ... ");
|
||||
sb.append(notShownCount);
|
||||
sb.append(" more").append(newLineChar);
|
||||
}
|
||||
Throwable cause = e.getCause();
|
||||
if (cause != null) {
|
||||
printThrowable(sb, cause, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new file and sets the file logging output to be directed to the
|
||||
* new file.
|
||||
*
|
||||
* @exception Exception
|
||||
* indicates a problem writing to the new log file.
|
||||
*/
|
||||
protected void switchFile(LogTime logTime) throws Exception {
|
||||
|
||||
String newFilePath = filepath + File.separator + logFileName;
|
||||
|
||||
if (useFileSwitching) {
|
||||
// For file switching include the date in the file name
|
||||
newFilePath = newFilePath + logTime.getYMD() + logFileSuffix;
|
||||
|
||||
} else {
|
||||
newFilePath = newFilePath + logFileSuffix;
|
||||
}
|
||||
|
||||
// Try to open an output stream to the file
|
||||
synchronized (fileMonitor) {
|
||||
|
||||
if (!newFilePath.equals(currentPath)) {
|
||||
currentPath = newFilePath;
|
||||
|
||||
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(newFilePath,
|
||||
doAppend)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory path of the log file.
|
||||
*/
|
||||
protected String makeDirIfRequired(String dir) {
|
||||
|
||||
File f = new File(dir);
|
||||
if (f.exists()){
|
||||
if (!f.isDirectory()){
|
||||
String msg = "Transaction logs directory is a file? "+dir;
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
} else {
|
||||
if (!f.mkdirs()) {
|
||||
String msg = "Failed to create transaction logs directory "+dir;
|
||||
logger.log(Level.SEVERE, msg);
|
||||
}
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Transaction Logging</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Transaction logging
|
||||
|
||||
</Body>
|
||||
</HTML>
|
||||
@@ -0,0 +1,14 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Transaction implementation</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Transaction implementation
|
||||
|
||||
<p>
|
||||
Implementation of the transaction functions.
|
||||
</p>
|
||||
|
||||
</Body>
|
||||
</HTML>
|
||||
Reference in new issue
Block a user