Change license to Apache2 and reformat

This commit is contained in:
rbygrave committed 2012-09-15 00:00:08 +12:00
1 parent 96ce4c0ddf
commit 7aae897def
560 files changed
+73292 -85907

No files matched your search

@@ -1,121 +1,102 @@
/**
* 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);
}
}
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);
}
}
@@ -1,61 +1,42 @@
/**
* 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);
}
}
}
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);
}
}
}
@@ -1,67 +1,48 @@
/**
* 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;
}
}
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;
}
}
@@ -1,54 +1,35 @@
/**
* 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);
}
}
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);
}
}
@@ -1,43 +1,24 @@
/**
* 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);
}
}
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);
}
}
@@ -1,163 +1,144 @@
/**
* 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;
}
}
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;
}
}
@@ -1,69 +1,50 @@
/**
* 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;
}
}
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;
}
}
@@ -1,307 +1,288 @@
/**
* 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);
}
}
}
}
}
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);
}
}
}
}
}
@@ -1,183 +1,164 @@
/**
* 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);
}
}
}
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);
}
}
}
@@ -1,147 +1,128 @@
/**
* 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();
}
}
}
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();
}
}
}
@@ -1,95 +1,76 @@
/**
* 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;
}
}
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;
}
}
@@ -1,67 +1,48 @@
/**
* 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);
}
}
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);
}
}
@@ -1,68 +1,49 @@
/**
* 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);
}
}
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);
}
}
@@ -1,73 +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.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);
}
}
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);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,138 +1,119 @@
/**
* 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;
}
}
}
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;
}
}
}
@@ -1,249 +1,230 @@
/**
* 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);
}
}
}
}
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);
}
}
}
}
@@ -1,202 +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.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;
}
}
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;
}
}
@@ -1,200 +1,181 @@
/**
* 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;
}
}
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;
}
}
@@ -1,121 +1,102 @@
/**
* 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;
}
}
}
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;
}
}
}
@@ -1,58 +1,39 @@
/**
* 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);
}
}
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);
}
}
@@ -1,37 +1,18 @@
/**
* 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();
}
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();
}
File diff suppressed because it is too large. Load diff
@@ -1,137 +1,118 @@
/**
* 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;
}
}
}
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;
}
}
}
@@ -1,152 +1,133 @@
/**
* 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();
}
}
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();
}
}
@@ -1,401 +1,382 @@
/**
* 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;
}
}
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;
}
}
@@ -1,101 +1,82 @@
/**
* 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();
}
}
}
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();
}
}
}
@@ -1,67 +1,48 @@
/**
* 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);
}
}
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);
}
}
@@ -1,192 +1,173 @@
/**
* 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);
}
}
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);
}
}
@@ -1,322 +1,303 @@
/**
* 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;
}
}
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;
}
}