id
stringlengths
33
40
content
stringlengths
662
61.5k
max_stars_repo_path
stringlengths
85
97
bugs-dot-jar_data_OAK-238_24ce6788
--- BugID: OAK-238 Summary: 'ValueFactory: Missing identifier validation when creating (weak)reference value from String' Description: "the JCR specification mandates validation of the identifier during\nvalue conversion from STRING to REFERENCE or WEAK_REFERENCE:\n\n<quote from 3.6.4.1 From STRING To)>\nREFERENCE or WEAKREFERENCE: If the string is a syntactically valid \nidentifier, according to the implementation, it is converted directly, otherwise a \nValueFormatException is thrown. The identifier is not required to be that of an \nexisting node in the current workspace. \n<end_quote>\n\nthe current ValueFactory implementation in oak-jcr lacks that validation:\ncreating a REFERENCE or WEAKREFERENCE value using\nValueFactory#createValue(String, int) succeeds even if the specified string\nisn't a valid referenceable node identifier.\n\n" diff --git a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/value/ValueFactoryImpl.java b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/value/ValueFactoryImpl.java index eb45232..a722509 100644 --- a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/value/ValueFactoryImpl.java +++ b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/value/ValueFactoryImpl.java @@ -37,6 +37,7 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.util.Calendar; +import java.util.UUID; /** * Implementation of {@link ValueFactory} interface based on the @@ -185,6 +186,17 @@ public class ValueFactoryImpl implements ValueFactory { cv = factory.createValue(value, type); break; + case PropertyType.REFERENCE: + case PropertyType.WEAKREFERENCE: + // TODO: move to identifier/uuid management utility instead of relying on impl specific uuid-format here. + try { + UUID.fromString(value); + } catch (IllegalArgumentException e) { + throw new ValueFormatException(e); + } + cv = factory.createValue(value, type); + break; + case PropertyType.BINARY: cv = factory.createValue(new ByteArrayInputStream(value.getBytes("UTF-8"))); break;
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-238_24ce6788.diff
bugs-dot-jar_data_OAK-1076_9238264d
--- BugID: OAK-1076 Summary: XPath failures for typed properties Description: It looks like there are some failures in xpath queries that expect a match only on properties of a certain type (which is to be inferred from the query) diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/ast/SelectorImpl.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/ast/SelectorImpl.java index 7421870..8434fb2 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/ast/SelectorImpl.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/ast/SelectorImpl.java @@ -42,6 +42,7 @@ import org.apache.jackrabbit.oak.api.PropertyValue; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.commons.PathUtils; +import org.apache.jackrabbit.oak.plugins.memory.PropertyBuilder; import org.apache.jackrabbit.oak.query.QueryImpl; import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression; import org.apache.jackrabbit.oak.query.index.FilterImpl; @@ -533,12 +534,33 @@ public class SelectorImpl extends SourceImpl { readOakProperties(list, t, oakPropertyName, propertyType); if (list.size() == 0) { return null; + } else if (list.size() == 1) { + return list.get(0); } - ArrayList<String> strings = new ArrayList<String>(); - for (PropertyValue p : list) { - Iterables.addAll(strings, p.getValue(Type.STRINGS)); + Type<?> type = list.get(0).getType(); + for (int i = 1; i < list.size(); i++) { + Type<?> t2 = list.get(i).getType(); + if (t2 != type) { + // types don't match + type = Type.STRING; + break; + } + } + if (type == Type.STRING) { + ArrayList<String> strings = new ArrayList<String>(); + for (PropertyValue p : list) { + Iterables.addAll(strings, p.getValue(Type.STRINGS)); + } + return PropertyValues.newString(strings); + } + @SuppressWarnings("unchecked") + PropertyBuilder<Object> builder = (PropertyBuilder<Object>) PropertyBuilder.array(type); + builder.setName(""); + for (PropertyValue v : list) { + builder.addValue(v.getValue(type)); } - return PropertyValues.newString(strings); + PropertyState s = builder.getPropertyState(); + return PropertyValues.create(s); } boolean relative = oakPropertyName.indexOf('/') >= 0; Tree t = currentTree(); @@ -590,6 +612,7 @@ public class SelectorImpl extends SourceImpl { } private void readOakProperties(ArrayList<PropertyValue> target, Tree t, String oakPropertyName, Integer propertyType) { + boolean skipCurrentNode = false; while (true) { if (t == null || !t.exists()) { return; @@ -608,10 +631,14 @@ public class SelectorImpl extends SourceImpl { for (Tree child : t.getChildren()) { readOakProperties(target, child, oakPropertyName, propertyType); } + skipCurrentNode = true; } else { t = t.getChild(parent); } } + if (skipCurrentNode) { + return; + } if (!"*".equals(oakPropertyName)) { PropertyValue value = currentOakProperty(t, oakPropertyName, propertyType); if (value != null) { @@ -619,12 +646,12 @@ public class SelectorImpl extends SourceImpl { } return; } - for (PropertyState p : t.getProperties()) { - if (propertyType == null || p.getType().tag() == propertyType) { - PropertyValue v = PropertyValues.create(p); - target.add(v); - } - } + for (PropertyState p : t.getProperties()) { + if (propertyType == null || p.getType().tag() == propertyType) { + PropertyValue v = PropertyValues.create(p); + target.add(v); + } + } } @Override
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1076_9238264d.diff
bugs-dot-jar_data_OAK-2047_ca63fdf3
--- BugID: OAK-2047 Summary: Missing privileges after repository upgrade Description: "After upgrading from Jackrabbit classic all Oak specific privileges are missing (rep:userManagement, rep:readNodes, rep:readProperties, rep:addProperties,\nrep:alterProperties, rep:removeProperties, rep:indexDefinitionManagement).\n\nThe reason seems to be that the {{PrivilegeInitializer}} is not run during upgrade. " diff --git a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java index 6db5152..27e82ab 100644 --- a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java +++ b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java @@ -257,6 +257,9 @@ public class RepositoryUpgrade { initializer.initialize(builder); } for (SecurityConfiguration sc : security.getConfigurations()) { + sc.getRepositoryInitializer().initialize(builder); + } + for (SecurityConfiguration sc : security.getConfigurations()) { sc.getWorkspaceInitializer().initialize(builder, workspaceName); }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-2047_ca63fdf3.diff
bugs-dot-jar_data_OAK-1364_b481a14c
--- BugID: OAK-1364 Summary: CacheLIRS concurrency issue Description: "Some of the methods of the cache can throw a NullPointerException when the cache is used concurrently. Example stack trace:\n\n{code}\njava.lang.NullPointerException: null\norg.apache.jackrabbit.oak.cache.CacheLIRS.values(CacheLIRS.java:470) \norg.apache.jackrabbit.oak.cache.CacheLIRS$1.values(CacheLIRS.java:1432)\norg.apache.jackrabbit.oak.plugins.segment.file.FileStore.flush(FileStore.java:205)\n{code}\n" diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/cache/CacheLIRS.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/cache/CacheLIRS.java index 8392b7f..34ca662 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/cache/CacheLIRS.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/cache/CacheLIRS.java @@ -619,7 +619,9 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { int queue2Size; /** - * The map array. The size is always a power of 2. + * The map array. The size is always a power of 2. The bit mask that is + * applied to the key hash code to get the index in the map array. The + * mask is the length of the array minus one. */ Entry<K, V>[] entries; @@ -657,12 +659,6 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { private int averageMemory; /** - * The bit mask that is applied to the key hash code to get the index in the - * map array. The mask is the length of the array minus one. - */ - private int mask; - - /** * The LIRS stack size. */ private int stackSize; @@ -722,8 +718,6 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { } // the array size is at most 2^31 elements int len = (int) Math.min(1L << 31, l); - // the bit mask has all bits set - mask = len - 1; // initialize the stack and queue heads stack = new Entry<K, V>(); @@ -733,8 +727,10 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { queue2 = new Entry<K, V>(); queue2.queuePrev = queue2.queueNext = queue2; - // first set to null - avoiding out of memory - entries = null; + // first set to a small array, to avoiding out of memory + @SuppressWarnings("unchecked") + Entry<K, V>[] small = new Entry[1]; + entries = small; @SuppressWarnings("unchecked") Entry<K, V>[] e = new Entry[len]; entries = e; @@ -920,6 +916,10 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { } synchronized void refresh(K key, int hash, CacheLoader<K, V> loader) throws ExecutionException { + if (loader == null) { + // no loader - no refresh + return; + } V value; V old = get(key, hash); long start = System.nanoTime(); @@ -968,9 +968,11 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { e.key = key; e.value = value; e.memory = memory; + Entry<K, V>[] array = entries; + int mask = array.length - 1; int index = hash & mask; - e.mapNext = entries[index]; - entries[index] = e; + e.mapNext = array[index]; + array[index] = e; usedMemory += memory; if (usedMemory > maxMemory && mapSize > 0) { // an old entry needs to be removed @@ -990,13 +992,15 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { * @param hash the hash */ synchronized void invalidate(Object key, int hash) { + Entry<K, V>[] array = entries; + int mask = array.length - 1; int index = hash & mask; - Entry<K, V> e = entries[index]; + Entry<K, V> e = array[index]; if (e == null) { return; } if (e.key.equals(key)) { - entries[index] = e.mapNext; + array[index] = e.mapNext; } else { Entry<K, V> last; do { @@ -1107,8 +1111,10 @@ public class CacheLIRS<K, V> implements LoadingCache<K, V> { * @return the entry (might be a non-resident) */ Entry<K, V> find(Object key, int hash) { + Entry<K, V>[] array = entries; + int mask = array.length - 1; int index = hash & mask; - Entry<K, V> e = entries[index]; + Entry<K, V> e = array[index]; while (e != null && !e.key.equals(key)) { e = e.mapNext; }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1364_b481a14c.diff
bugs-dot-jar_data_OAK-4351_59a83d23
--- BugID: OAK-4351 Summary: Non-root lucene index throws exception if query constraints match root of sub-tree Description: |- LucenePropetyIndexProvider returns incorrect (normalized) path for root of sub-tree if index is defined on the sub-tree. e.g. {{/jcr:root/test//element(*, nt:base)\[@foo='bar']}} would fail with following defn {noformat} + /test - foo="bar" + test1 - foo="bar" + oak:index - indexRules/nt:base/properties/foo/propertyIndex="true" {noformat} diff --git a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java index 42a7804..5079088 100644 --- a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java +++ b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java @@ -1528,6 +1528,8 @@ public class LucenePropertyIndex implements AdvancedQueryIndex, QueryIndex, Nati String sub = pathRow.getPath(); if (isVirtualRow()) { return sub; + } else if (!"".equals(pathPrefix) && PathUtils.denotesRoot(sub)) { + return pathPrefix; } else if (PathUtils.isAbsolute(sub)) { return pathPrefix + sub; } else {
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4351_59a83d23.diff
bugs-dot-jar_data_OAK-3433_b76b31f7
--- BugID: OAK-3433 Summary: Background update may create journal entry with incorrect id Description: The conflict check does not consider changes that are made visible between the rebase and the background read. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java index b4aae75..2c72ff4 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/DocumentNodeStore.java @@ -2084,9 +2084,9 @@ public final class DocumentNodeStore BackgroundWriteStats backgroundWrite() { return unsavedLastRevisions.persist(this, new UnsavedModifications.Snapshot() { @Override - public void acquiring() { + public void acquiring(Revision mostRecent) { if (store.create(JOURNAL, - singletonList(changes.asUpdateOp(getHeadRevision())))) { + singletonList(changes.asUpdateOp(mostRecent)))) { changes = JOURNAL.newDocument(getDocumentStore()); } } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/LastRevRecoveryAgent.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/LastRevRecoveryAgent.java index 69e8fe7..25f0390 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/LastRevRecoveryAgent.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/LastRevRecoveryAgent.java @@ -235,7 +235,7 @@ public class LastRevRecoveryAgent { unsaved.persist(nodeStore, new UnsavedModifications.Snapshot() { @Override - public void acquiring() { + public void acquiring(Revision mostRecent) { if (lastRootRev == null) { // this should never happen - when unsaved has no changes // that is reflected in the 'map' to be empty - in that diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UnsavedModifications.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UnsavedModifications.java index d5f6c1e..1d06fa7 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UnsavedModifications.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UnsavedModifications.java @@ -159,7 +159,7 @@ class UnsavedModifications { time = clock.getTime(); Map<String, Revision> pending; try { - snapshot.acquiring(); + snapshot.acquiring(getMostRecentRevision()); pending = Maps.newTreeMap(PathComparator.INSTANCE); pending.putAll(map); } finally { @@ -234,14 +234,26 @@ class UnsavedModifications { return map.toString(); } + private Revision getMostRecentRevision() { + // use revision of root document + Revision rev = map.get("/"); + // otherwise find most recent + if (rev == null) { + for (Revision r : map.values()) { + rev = Utils.max(rev, r); + } + } + return rev; + } + public interface Snapshot { Snapshot IGNORE = new Snapshot() { @Override - public void acquiring() { + public void acquiring(Revision mostRecent) { } }; - void acquiring(); + void acquiring(Revision mostRecent); } }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-3433_b76b31f7.diff
bugs-dot-jar_data_OAK-2336_d0f6715d
--- BugID: OAK-2336 Summary: NodeDocument.getNodeAtRevision() may read too many revisions Description: |- This is a regression introduced by OAK-1972. The revision returned with the value may be different from the revision of the change when the change was first committed to a branch and later merged. In this case the value will return the merge revision. The check in getNodeAtRevision() introduced with OAK-1972 then assumes there may be more recent changes in a previous document and starts to scan the revision history. This scan depends on the number of changes that have been applied on the document since the most recent change on the property in question. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java index e617e17..1134673 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java @@ -775,7 +775,7 @@ public final class NodeDocument extends Document implements CachedNodeDocument{ // check if there may be more recent values in a previous document if (value != null && !getPreviousRanges().isEmpty()) { Revision newest = getLocalMap(key).firstKey(); - if (!value.revision.equals(newest)) { + if (isRevisionNewer(nodeStore, newest, value.revision)) { // not reading the most recent value, we may need to // consider previous documents as well Revision newestPrev = getPreviousRanges().firstKey();
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-2336_d0f6715d.diff
bugs-dot-jar_data_OAK-2246_dcadb0e1
--- BugID: OAK-2246 Summary: UUID collision check is not does not work in transient space Description: |- I think OAK-1037 broke the system view import. test case: 1. create a new node with a uuid (referenceable, or new user) 2. import systemview with IMPORT_UUID_COLLISION_REPLACE_EXISTING 3. save() result: {noformat} javax.jcr.nodetype.ConstraintViolationException: OakConstraint0030: Uniqueness constraint violated at path [/] for one of the property in [jcr:uuid] having value e358efa4-89f5-3062-b10d-d7316b65649e {noformat} expected: * imported content should replace the existing node - even in transient space. note: * if you perform a save() after step 1, everything works. diff --git a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java index 176dffe..8e7e72f 100644 --- a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java +++ b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/xml/ImporterImpl.java @@ -47,6 +47,7 @@ import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.jackrabbit.JcrConstants; +import org.apache.jackrabbit.oak.api.ContentSession; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.Tree; @@ -82,26 +83,10 @@ public class ImporterImpl implements Importer { private final String userID; private final AccessManager accessManager; - /** - * There are two IdentifierManagers used. - * - * 1) currentStateIdManager - Associated with current root on which all import - * operations are being performed - * - * 2) baseStateIdManager - Associated with the initial root on which - * no modifications are performed - */ - private final IdentifierManager currentStateIdManager; - private final IdentifierManager baseStateIdManager; - private final EffectiveNodeTypeProvider effectiveNodeTypeProvider; private final DefinitionProvider definitionProvider; - /** - * Set of newly created uuid from nodes which are - * created in this import - */ - private final Set<String> uuids = new HashSet<String>(); + private final IdResolver idLookup; private final Stack<Tree> parents; @@ -171,8 +156,7 @@ public class ImporterImpl implements Importer { accessManager = sessionContext.getAccessManager(); - currentStateIdManager = new IdentifierManager(root); - baseStateIdManager = new IdentifierManager(sd.getContentSession().getLatestRoot()); + idLookup = new IdResolver(root, sd.getContentSession()); refTracker = new ReferenceChangeTracker(); @@ -465,24 +449,7 @@ public class ImporterImpl implements Importer { } } else { - //1. First check from base state that tree corresponding to - //this id exist - Tree conflicting = baseStateIdManager.getTree(id); - - if (conflicting == null) { - //1.a. Check if id is found in newly created nodes - if (uuids.contains(id)) { - conflicting = currentStateIdManager.getTree(id); - } - } else { - //1.b Re obtain the conflicting tree from Id Manager - //associated with current root. Such that any operation - //on it gets reflected in later operations - //In case a tree with same id was removed earlier then it - //would return null - conflicting = currentStateIdManager.getTree(id); - } - + Tree conflicting = idLookup.getConflictingTree(id); if (conflicting != null && conflicting.exists()) { // resolve uuid conflict tree = resolveUUIDConflict(parent, conflicting, id, nodeInfo); @@ -522,22 +489,7 @@ public class ImporterImpl implements Importer { } } - collectUUIDs(parent); - } - - private void collectUUIDs(Tree tree) { - if (tree == null) { - return; - } - - String uuid = TreeUtil.getString(tree, JcrConstants.JCR_UUID); - if (uuid != null) { - uuids.add(uuid); - } - - for (Tree child : tree.getChildren()) { - collectUUIDs(child); - } + idLookup.rememberImportedUUIDs(parent); } @Override @@ -621,4 +573,78 @@ public class ImporterImpl implements Importer { tree.setProperty(prop); } } + + /** + * Resolves 'uuid' property values to {@code Tree} objects and optionally + * keeps track of newly imported UUIDs. + */ + private static final class IdResolver { + /** + * There are two IdentifierManagers used. + * + * 1) currentStateIdManager - Associated with current root on which all import + * operations are being performed + * + * 2) baseStateIdManager - Associated with the initial root on which + * no modifications are performed + */ + private final IdentifierManager currentStateIdManager; + private final IdentifierManager baseStateIdManager; + + /** + * Set of newly created uuid from nodes which are + * created in this import, which are only remembered if the editing + * session doesn't have any pending transient changes preventing this + * performance optimisation from working properly (see OAK-2246). + */ + private final Set<String> importedUUIDs; + + private IdResolver(@Nonnull Root root, @Nonnull ContentSession contentSession) { + currentStateIdManager = new IdentifierManager(root); + baseStateIdManager = new IdentifierManager(contentSession.getLatestRoot()); + + if (!root.hasPendingChanges()) { + importedUUIDs = new HashSet<String>(); + } else { + importedUUIDs = null; + } + } + + + @CheckForNull + private Tree getConflictingTree(@Nonnull String id) { + //1. First check from base state that tree corresponding to + //this id exist + Tree conflicting = baseStateIdManager.getTree(id); + if (conflicting == null && importedUUIDs != null) { + //1.a. Check if id is found in newly created nodes + if (importedUUIDs.contains(id)) { + conflicting = currentStateIdManager.getTree(id); + } + } else { + //1.b Re obtain the conflicting tree from Id Manager + //associated with current root. Such that any operation + //on it gets reflected in later operations + //In case a tree with same id was removed earlier then it + //would return null + conflicting = currentStateIdManager.getTree(id); + } + return conflicting; + } + + private void rememberImportedUUIDs(@CheckForNull Tree tree) { + if (tree == null || importedUUIDs == null) { + return; + } + + String uuid = TreeUtil.getString(tree, JcrConstants.JCR_UUID); + if (uuid != null) { + importedUUIDs.add(uuid); + } + + for (Tree child : tree.getChildren()) { + rememberImportedUUIDs(child); + } + } + } }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-2246_dcadb0e1.diff
bugs-dot-jar_data_OAK-4066_9a109aa3
--- BugID: OAK-4066 Summary: Suggestion dictionary don't update after suggestUpdateFrequencyMinutes unless something else causes index update Description: |- Currently, suggestions building is tied at the end of indexing cycle. Along with that we check if diff between currTime and lastSugguestionBuildTime is more than {{suggestUpdateFrequencyMinutes}} before deciding to build suggestions or not. This allows for suggestions not getting updated if: * At T1 suggestions are built * At T2 an index update takes place but suggestions aren't rebuilt because not enough time has passed since T1 * Now at T3 (after sufficient time), changes at T2 won't show up for suggestions until some other index change happens. We should probably see track about last changes in index (at T2) and use that too while running indexing cycle at T3. diff --git a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorContext.java b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorContext.java index c49902c..fb79cc7 100644 --- a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorContext.java +++ b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorContext.java @@ -245,6 +245,12 @@ public class LuceneIndexEditorContext { getWriter(); } + boolean updateSuggestions = shouldUpdateSuggestions(); + if (writer == null && updateSuggestions) { + log.debug("Would update suggester dictionary although no index changes were detected in current cycle"); + getWriter(); + } + if (writer != null) { if (log.isTraceEnabled()) { trackIndexSizeInfo(writer, definition, directory); @@ -252,8 +258,14 @@ public class LuceneIndexEditorContext { final long start = PERF_LOGGER.start(); - updateSuggester(writer.getAnalyzer()); - PERF_LOGGER.end(start, -1, "Completed suggester for directory {}", definition); + Calendar lastUpdated = null; + if (updateSuggestions) { + lastUpdated = updateSuggester(writer.getAnalyzer()); + PERF_LOGGER.end(start, -1, "Completed suggester for directory {}", definition); + } + if (lastUpdated == null) { + lastUpdated = getCalendar(); + } writer.close(); PERF_LOGGER.end(start, -1, "Closed writer for directory {}", definition); @@ -265,8 +277,9 @@ public class LuceneIndexEditorContext { //as to make IndexTracker detect changes when index //is stored in file system NodeBuilder status = definitionBuilder.child(":status"); - status.setProperty("lastUpdated", ISO8601.format(getCalendar()), Type.DATE); - status.setProperty("indexedNodes",indexedNodes); + status.setProperty("lastUpdated", ISO8601.format(lastUpdated), Type.DATE); + status.setProperty("indexedNodes", indexedNodes); + PERF_LOGGER.end(start, -1, "Overall Closed IndexWriter for directory {}", definition); textExtractionStats.log(reindex); @@ -278,38 +291,69 @@ public class LuceneIndexEditorContext { * eventually update suggest dictionary * @throws IOException if suggest dictionary update fails * @param analyzer the analyzer used to update the suggester + * @return {@link Calendar} object representing the lastUpdated value written by suggestions */ - private void updateSuggester(Analyzer analyzer) throws IOException { + private Calendar updateSuggester(Analyzer analyzer) throws IOException { + Calendar ret = null; + NodeBuilder suggesterStatus = definitionBuilder.child(":suggesterStatus"); + DirectoryReader reader = DirectoryReader.open(writer, false); + final OakDirectory suggestDirectory = new OakDirectory(definitionBuilder, ":suggest-data", definition, false); + try { + SuggestHelper.updateSuggester(suggestDirectory, analyzer, reader); + ret = getCalendar(); + suggesterStatus.setProperty("lastUpdated", ISO8601.format(ret), Type.DATE); + } catch (Throwable e) { + log.warn("could not update suggester", e); + } finally { + suggestDirectory.close(); + reader.close(); + } - if (definition.isSuggestEnabled()) { + return ret; + } + + /** + * Checks if last suggestion build time was done sufficiently in the past AND that there were non-zero indexedNodes + * stored in the last run. Note, if index is updated only to rebuild suggestions, even then we update indexedNodes, + * which would be zero in case it was a forced update of suggestions. + * @return is suggest dict should be updated + */ + private boolean shouldUpdateSuggestions() { + boolean updateSuggestions = false; - boolean updateSuggester = false; + if (definition.isSuggestEnabled()) { NodeBuilder suggesterStatus = definitionBuilder.child(":suggesterStatus"); - if (suggesterStatus.hasProperty("lastUpdated")) { - PropertyState suggesterLastUpdatedValue = suggesterStatus.getProperty("lastUpdated"); + + PropertyState suggesterLastUpdatedValue = suggesterStatus.getProperty("lastUpdated"); + + if (suggesterLastUpdatedValue != null) { Calendar suggesterLastUpdatedTime = ISO8601.parse(suggesterLastUpdatedValue.getValue(Type.DATE)); + int updateFrequency = definition.getSuggesterUpdateFrequencyMinutes(); - suggesterLastUpdatedTime.add(Calendar.MINUTE, updateFrequency); - if (getCalendar().after(suggesterLastUpdatedTime)) { - updateSuggester = true; + Calendar nextSuggestUpdateTime = (Calendar)suggesterLastUpdatedTime.clone(); + nextSuggestUpdateTime.add(Calendar.MINUTE, updateFrequency); + if (getCalendar().after(nextSuggestUpdateTime)) { + updateSuggestions = (writer != null || isIndexUpdatedAfter(suggesterLastUpdatedTime)); } } else { - updateSuggester = true; + updateSuggestions = true; } + } - if (updateSuggester) { - DirectoryReader reader = DirectoryReader.open(writer, false); - final OakDirectory suggestDirectory = new OakDirectory(definitionBuilder, ":suggest-data", definition, false); - try { - SuggestHelper.updateSuggester(suggestDirectory, analyzer, reader); - suggesterStatus.setProperty("lastUpdated", ISO8601.format(getCalendar()), Type.DATE); - } catch (Throwable e) { - log.warn("could not update suggester", e); - } finally { - suggestDirectory.close(); - reader.close(); - } - } + return updateSuggestions; + } + + /** + * @return {@code false} if persisted lastUpdated time for index is after {@code calendar}. {@code true} otherwise + */ + private boolean isIndexUpdatedAfter(Calendar calendar) { + NodeBuilder indexStats = definitionBuilder.child(":status"); + PropertyState indexLastUpdatedValue = indexStats.getProperty("lastUpdated"); + if (indexLastUpdatedValue != null) { + Calendar indexLastUpdatedTime = ISO8601.parse(indexLastUpdatedValue.getValue(Type.DATE)); + return indexLastUpdatedTime.after(calendar); + } else { + return true; } }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4066_9a109aa3.diff
bugs-dot-jar_data_OAK-3920_99996c25
--- BugID: OAK-3920 Summary: OakDirectory not usable in readOnly mode with a readOnly builder Description: |- When using {{OakDirectory}} with a read only builder say in LuceneCommand in oak-console following error is seen {noformat} lc info /oak:index/users ERROR java.lang.UnsupportedOperationException: This builder is read-only. at org.apache.jackrabbit.oak.spi.state.ReadOnlyBuilder.unsupported (ReadOnlyBuilder.java:45) at org.apache.jackrabbit.oak.spi.state.ReadOnlyBuilder.child (ReadOnlyBuilder.java:190) at org.apache.jackrabbit.oak.spi.state.ReadOnlyBuilder.child (ReadOnlyBuilder.java:35) at org.apache.jackrabbit.oak.plugins.index.lucene.OakDirectory.<init> (OakDirectory.java:93) at org.apache.jackrabbit.oak.plugins.index.lucene.OakDirectory.<init> (OakDirectory.java:87) at org.apache.jackrabbit.oak.console.commands.LuceneCommand.getDirectory (LuceneCommand.groovy:128) at org.apache.jackrabbit.oak.console.commands.LuceneCommand.this$4$getDirectory (LuceneCommand.groovy) at org.apache.jackrabbit.oak.console.commands.LuceneCommand$_closure1.doCall (LuceneCommand.groovy:55) {noformat} diff --git a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/OakDirectory.java b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/OakDirectory.java index 50c7f9e..2e137d5 100644 --- a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/OakDirectory.java +++ b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/OakDirectory.java @@ -91,7 +91,7 @@ class OakDirectory extends Directory { public OakDirectory(NodeBuilder builder, String dataNodeName, IndexDefinition definition, boolean readOnly) { this.lockFactory = NoLockFactory.getNoLockFactory(); this.builder = builder; - this.directoryBuilder = builder.child(dataNodeName); + this.directoryBuilder = readOnly ? builder.getChildNode(dataNodeName) : builder.child(dataNodeName); this.definition = definition; this.readOnly = readOnly; this.fileNames.addAll(getListing());
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-3920_99996c25.diff
bugs-dot-jar_data_OAK-1822_3e83a4c1
--- BugID: OAK-1822 Summary: NodeDocument _modified may go back in time Description: In a cluster with multiple DocumentMK instances the _modified field of a NodeDocument may go back in time. This will result in incorrect diff calculations when the DocumentNodeStore uses the _modified field to find changed nodes for a given revision range. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java index e0eb865..e63e2d8 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java @@ -1205,7 +1205,7 @@ public final class NodeDocument extends Document implements CachedNodeDocument{ public static void setModified(@Nonnull UpdateOp op, @Nonnull Revision revision) { - checkNotNull(op).set(MODIFIED_IN_SECS, getModifiedInSecs(checkNotNull(revision).getTimestamp())); + checkNotNull(op).max(MODIFIED_IN_SECS, getModifiedInSecs(checkNotNull(revision).getTimestamp())); } public static void setRevision(@Nonnull UpdateOp op, diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateOp.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateOp.java index f00df7a..b957c37 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateOp.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateOp.java @@ -131,9 +131,7 @@ public final class UpdateOp { * @param value the value */ void setMapEntry(@Nonnull String property, @Nonnull Revision revision, String value) { - Operation op = new Operation(); - op.type = Operation.Type.SET_MAP_ENTRY; - op.value = value; + Operation op = new Operation(Operation.Type.SET_MAP_ENTRY, value); changes.put(new Key(property, checkNotNull(revision)), op); } @@ -145,8 +143,7 @@ public final class UpdateOp { * @param revision the revision */ public void removeMapEntry(@Nonnull String property, @Nonnull Revision revision) { - Operation op = new Operation(); - op.type = Operation.Type.REMOVE_MAP_ENTRY; + Operation op = new Operation(Operation.Type.REMOVE_MAP_ENTRY, null); changes.put(new Key(property, checkNotNull(revision)), op); } @@ -157,9 +154,23 @@ public final class UpdateOp { * @param value the value */ void set(String property, Object value) { - Operation op = new Operation(); - op.type = Operation.Type.SET; - op.value = value; + Operation op = new Operation(Operation.Type.SET, value); + changes.put(new Key(property, null), op); + } + + /** + * Set the property to the given value if the new value is higher than the + * existing value. The property is also set to the given value if the + * property does not yet exist. + * <p> + * The result of a max operation with different types of values is + * undefined. + * + * @param property the name of the property to set. + * @param value the new value for the property. + */ + <T> void max(String property, Comparable<T> value) { + Operation op = new Operation(Operation.Type.MAX, value); changes.put(new Key(property, null), op); } @@ -187,9 +198,7 @@ public final class UpdateOp { if (isNew) { throw new IllegalStateException("Cannot use containsMapEntry() on new document"); } - Operation op = new Operation(); - op.type = Operation.Type.CONTAINS_MAP_ENTRY; - op.value = exists; + Operation op = new Operation(Operation.Type.CONTAINS_MAP_ENTRY, exists); changes.put(new Key(property, checkNotNull(revision)), op); } @@ -200,9 +209,7 @@ public final class UpdateOp { * @param value the increment */ public void increment(@Nonnull String property, long value) { - Operation op = new Operation(); - op.type = Operation.Type.INCREMENT; - op.value = value; + Operation op = new Operation(Operation.Type.INCREMENT, value); changes.put(new Key(property, null), op); } @@ -239,6 +246,14 @@ public final class UpdateOp { SET, /** + * Set the value if the new value is higher than the existing value. + * The new value is also considered higher, when there is no + * existing value. + * The sub-key is not used. + */ + MAX, + + /** * Increment the Long value with the provided Long value. * The sub-key is not used. */ @@ -267,12 +282,17 @@ public final class UpdateOp { /** * The operation type. */ - public Type type; + public final Type type; /** * The value, if any. */ - public Object value; + public final Object value; + + Operation(Type type, Object value) { + this.type = checkNotNull(type); + this.value = value; + } @Override public String toString() { @@ -283,18 +303,16 @@ public final class UpdateOp { Operation reverse = null; switch (type) { case INCREMENT: - reverse = new Operation(); - reverse.type = Type.INCREMENT; - reverse.value = -(Long) value; + reverse = new Operation(Type.INCREMENT, -(Long) value); break; case SET: + case MAX: case REMOVE_MAP_ENTRY: case CONTAINS_MAP_ENTRY: // nothing to do break; case SET_MAP_ENTRY: - reverse = new Operation(); - reverse.type = Type.REMOVE_MAP_ENTRY; + reverse = new Operation(Type.REMOVE_MAP_ENTRY, null); break; } return reverse; diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateUtils.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateUtils.java index b8015ff..240665d 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateUtils.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/UpdateUtils.java @@ -44,7 +44,9 @@ public class UpdateUtils { * @param comparator * the revision comparator. */ - public static void applyChanges(@Nonnull Document doc, @Nonnull UpdateOp update, @Nonnull Comparator<Revision> comparator) { + public static void applyChanges(@Nonnull Document doc, + @Nonnull UpdateOp update, + @Nonnull Comparator<Revision> comparator) { for (Entry<Key, Operation> e : checkNotNull(update).getChanges().entrySet()) { Key k = e.getKey(); Operation op = e.getValue(); @@ -53,6 +55,15 @@ public class UpdateUtils { doc.put(k.toString(), op.value); break; } + case MAX: { + Comparable newValue = (Comparable) op.value; + Object old = doc.get(k.toString()); + //noinspection unchecked + if (old == null || newValue.compareTo(old) > 0) { + doc.put(k.toString(), op.value); + } + break; + } case INCREMENT: { Object old = doc.get(k.toString()); Long x = (Long) op.value; diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java index 0266e38..684f39f 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/mongo/MongoDocumentStore.java @@ -29,6 +29,8 @@ import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.Lock; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; @@ -127,6 +129,7 @@ public class MongoDocumentStore implements CachingDocumentStore { private String lastReadWriteMode; public MongoDocumentStore(DB db, DocumentMK.Builder builder) { + checkVersion(db); nodes = db.getCollection( Collection.NODES.toString()); clusterNodes = db.getCollection( @@ -179,6 +182,24 @@ public class MongoDocumentStore implements CachingDocumentStore { builder.getDocumentCacheSize()); } + private static void checkVersion(DB db) { + String version = db.command("buildInfo").getString("version"); + Matcher m = Pattern.compile("^(\\d+)\\.(\\d+)\\..*").matcher(version); + if (!m.matches()) { + throw new IllegalArgumentException("Malformed MongoDB version: " + version); + } + int major = Integer.parseInt(m.group(1)); + int minor = Integer.parseInt(m.group(2)); + if (major > 2) { + return; + } + if (minor < 6) { + String msg = "MongoDB version 2.6.0 or higher required. " + + "Currently connected to a MongoDB with version: " + version; + throw new RuntimeException(msg); + } + } + private Cache<CacheValue, NodeDocument> createOffHeapCache( DocumentMK.Builder builder) { ForwardingListener<CacheValue, NodeDocument> listener = ForwardingListener.newInstance(); @@ -570,6 +591,7 @@ public class MongoDocumentStore implements CachingDocumentStore { Operation op = entry.getValue(); switch (op.type) { case SET: + case MAX: case INCREMENT: { inserts[i].put(k.toString(), op.value); break; @@ -965,6 +987,7 @@ public class MongoDocumentStore implements CachingDocumentStore { @Nonnull private static DBObject createUpdate(UpdateOp updateOp) { BasicDBObject setUpdates = new BasicDBObject(); + BasicDBObject maxUpdates = new BasicDBObject(); BasicDBObject incUpdates = new BasicDBObject(); BasicDBObject unsetUpdates = new BasicDBObject(); @@ -980,16 +1003,17 @@ public class MongoDocumentStore implements CachingDocumentStore { } Operation op = entry.getValue(); switch (op.type) { - case SET: { + case SET: + case SET_MAP_ENTRY: { setUpdates.append(k.toString(), op.value); break; } - case INCREMENT: { - incUpdates.append(k.toString(), op.value); + case MAX: { + maxUpdates.append(k.toString(), op.value); break; } - case SET_MAP_ENTRY: { - setUpdates.append(k.toString(), op.value); + case INCREMENT: { + incUpdates.append(k.toString(), op.value); break; } case REMOVE_MAP_ENTRY: { @@ -1003,6 +1027,9 @@ public class MongoDocumentStore implements CachingDocumentStore { if (!setUpdates.isEmpty()) { update.append("$set", setUpdates); } + if (!maxUpdates.isEmpty()) { + update.append("$max", maxUpdates); + } if (!incUpdates.isEmpty()) { update.append("$inc", incUpdates); }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1822_3e83a4c1.diff
bugs-dot-jar_data_OAK-4038_557eec4f
--- BugID: OAK-4038 Summary: o.a.j.o.spi.query.Filter exposes unexported class o.a.j.o.query.ast.SelectorImpl Description: The interface {{o.a.j.o.spi.query.Filter}} uses in its public API the class {{o.a.j.o.query.ast.SelectorImpl}}, but while the former is contained in an exported package, the latter is not. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndex.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndex.java index 40eca04..3ec211f 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndex.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndex.java @@ -192,7 +192,7 @@ class PropertyIndex implements QueryIndex { // not an appropriate index for native search return Double.POSITIVE_INFINITY; } - if (filter.getPropertyRestrictions().isEmpty() && filter.getSelector().getSelectorConstraints().isEmpty()) { + if (filter.getPropertyRestrictions().isEmpty()) { // not an appropriate index for no property restrictions & selector constraints return Double.POSITIVE_INFINITY; } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java index b1123a0..d15c273 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java @@ -35,14 +35,6 @@ import org.apache.jackrabbit.oak.plugins.index.property.strategy.ContentMirrorSt import org.apache.jackrabbit.oak.plugins.index.property.strategy.IndexStoreStrategy; import org.apache.jackrabbit.oak.plugins.index.property.strategy.UniqueEntryStoreStrategy; import org.apache.jackrabbit.oak.query.QueryEngineSettings; -import org.apache.jackrabbit.oak.query.ast.ComparisonImpl; -import org.apache.jackrabbit.oak.query.ast.ConstraintImpl; -import org.apache.jackrabbit.oak.query.ast.DynamicOperandImpl; -import org.apache.jackrabbit.oak.query.ast.InImpl; -import org.apache.jackrabbit.oak.query.ast.Operator; -import org.apache.jackrabbit.oak.query.ast.OrImpl; -import org.apache.jackrabbit.oak.query.ast.PropertyValueImpl; -import org.apache.jackrabbit.oak.query.ast.StaticOperandImpl; import org.apache.jackrabbit.oak.spi.query.Cursor; import org.apache.jackrabbit.oak.spi.query.Cursors; import org.apache.jackrabbit.oak.spi.query.Filter; @@ -72,8 +64,6 @@ public class PropertyIndexPlan { private static final IndexStoreStrategy UNIQUE = new UniqueEntryStoreStrategy(); - private final NodeState root; - private final NodeState definition; private final String name; @@ -98,7 +88,6 @@ public class PropertyIndexPlan { PropertyIndexPlan(String name, NodeState root, NodeState definition, Filter filter) { this.name = name; - this.root = root; this.definition = definition; this.properties = newHashSet(definition.getNames(PROPERTY_NAMES)); pathFilter = PathFilter.from(definition.builder()); @@ -162,24 +151,6 @@ public class PropertyIndexPlan { } } } - - // OAK-1965: let's see if we can find a (x='...' OR y='...') - // constraint where both x and y are covered by this index - // TODO: avoid repeated scans through the constraints - for (ConstraintImpl constraint - : filter.getSelector().getSelectorConstraints()) { - if (constraint instanceof OrImpl) { - Set<String> values = findMultiProperty((OrImpl) constraint); - if (values != null) { - double cost = strategy.count(filter, root, definition, values, MAX_COST); - if (cost < bestCost) { - bestDepth = 1; - bestValues = values; - bestCost = cost; - } - } - } - } } this.depth = bestDepth; @@ -187,46 +158,6 @@ public class PropertyIndexPlan { this.cost = COST_OVERHEAD + bestCost; } - private Set<String> findMultiProperty(OrImpl or) { - Set<String> values = newLinkedHashSet(); - for (ConstraintImpl constraint : or.getConstraints()) { - if (constraint instanceof ComparisonImpl) { - ComparisonImpl comparison = (ComparisonImpl) constraint; - if (isIndexed(comparison.getOperand1()) - && comparison.getOperator() == Operator.EQUAL) { - values.addAll(encode(comparison.getOperand2().currentValue())); - } else { - return null; - } - } else if (constraint instanceof InImpl) { - InImpl in = (InImpl) constraint; - if (isIndexed(in.getOperand1())) { - for (StaticOperandImpl operand : in.getOperand2()) { - values.addAll(encode(operand.currentValue())); - } - } else { - return null; - } - } else { - return null; - } - } - return values; - } - - /** - * Checks whether the given dynamic operand is a property - * covered by this index. - */ - private boolean isIndexed(DynamicOperandImpl operand) { - if (operand instanceof PropertyValueImpl) { - PropertyValueImpl property = (PropertyValueImpl) operand; - return properties.contains(property.getPropertyName()); - } else { - return false; - } - } - private static Set<String> getValues(PropertyRestriction restriction) { if (restriction.firstIncluding && restriction.lastIncluding diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/index/FilterImpl.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/index/FilterImpl.java index 6908950..0f851b1 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/index/FilterImpl.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/index/FilterImpl.java @@ -218,7 +218,6 @@ public class FilterImpl implements Filter { return alwaysFalse; } - @Override public SelectorImpl getSelector() { return selector; } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Filter.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Filter.java index f2e55fd..9aabf1a 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Filter.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Filter.java @@ -28,7 +28,6 @@ import javax.jcr.PropertyType; import org.apache.jackrabbit.oak.api.PropertyValue; import org.apache.jackrabbit.oak.query.QueryEngineSettings; -import org.apache.jackrabbit.oak.query.ast.SelectorImpl; import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression; /** @@ -45,13 +44,6 @@ import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression; public interface Filter { /** - * Get the selector associated with this filter. - * - * @return selector - */ - SelectorImpl getSelector(); - - /** * Get the list of property restrictions, if any. Each property may contain * multiple restrictions, for example x=1 and x=2. For this case, only * multi-valued properties match that contain both 1 and 2.
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4038_557eec4f.diff
bugs-dot-jar_data_OAK-1817_78c37386
--- BugID: OAK-1817 Summary: NPE in MarkSweepGarbageCollector.saveBatchToFile during Datastore GC with FileDataStore Description: "During running a datastore garbage collection on a Jackrabbit 2 FileDataStore (org.apache.jackrabbit.oak.plugins.blob.datastore.FileDataStore, see http://jackrabbit.apache.org/oak/docs/osgi_config.html) an NPE is thrown\n{code}\n13.05.2014 17:50:16.944 *ERROR* [qtp1416657193-147] org.apache.jackrabbit.oak.management.ManagementOperation Blob garbage collection failed\njava.lang.RuntimeException: Error in retrieving references\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector$1.addReference(MarkSweepGarbageCollector.java:395)\n\tat org.apache.jackrabbit.oak.plugins.segment.Segment.collectBlobReferences(Segment.java:248)\n\tat org.apache.jackrabbit.oak.plugins.segment.SegmentTracker.collectBlobReferences(SegmentTracker.java:178)\n\tat org.apache.jackrabbit.oak.plugins.segment.SegmentBlobReferenceRetriever.collectReferences(SegmentBlobReferenceRetriever.java:38)\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.iterateNodeTree(MarkSweepGarbageCollector.java:361)\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.mark(MarkSweepGarbageCollector.java:201)\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.markAndSweep(MarkSweepGarbageCollector.java:173)\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.collectGarbage(MarkSweepGarbageCollector.java:149)\n\tat org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStoreService$2.collectGarbage(SegmentNodeStoreService.java:185)\n\tat org.apache.jackrabbit.oak.plugins.blob.BlobGC$1.call(BlobGC.java:68)\n\tat org.apache.jackrabbit.oak.plugins.blob.BlobGC$1.call(BlobGC.java:64)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:262)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\n\tat java.lang.Thread.run(Thread.java:745)\nCaused by: java.lang.NullPointerException: null\n\tat com.google.common.base.Preconditions.checkNotNull(Preconditions.java:192)\n\tat com.google.common.base.Joiner.toString(Joiner.java:436)\n\tat com.google.common.base.Joiner.appendTo(Joiner.java:108)\n\tat com.google.common.base.Joiner.appendTo(Joiner.java:152)\n\tat com.google.common.base.Joiner.join(Joiner.java:193)\n\tat com.google.common.base.Joiner.join(Joiner.java:183)\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.saveBatchToFile(MarkSweepGarbageCollector.java:317)\n\tat org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector$1.addReference(MarkSweepGarbageCollector.java:391)\n\t... 14 common frames omitted\n{code}\n\nAttached you find the OSGi config for both the nodestore and the datastore." diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/SegmentWriter.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/SegmentWriter.java index 0552b33..16c3f83 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/SegmentWriter.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/SegmentWriter.java @@ -219,7 +219,7 @@ public class SegmentWriter { data.put(buffer, buffer.length - length, length); data.rewind(); } else { - data = ByteBuffer.wrap(buffer); + data = ByteBuffer.wrap(buffer, buffer.length - length, length); } tracker.setSegment(id, new Segment(tracker, id, data));
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1817_78c37386.diff
bugs-dot-jar_data_OAK-313_e115fd90
--- BugID: OAK-313 Summary: Trailing slash not removed for simple path in JCR to Oak path conversion Description: | While converting from JCR path to Oak path the trailing slashes are not removed for simple paths. They are removed for complex path {code} assertEquals("/oak-foo:bar/oak-quu:qux",npMapper.getOakPath("/foo:bar/quu:qux/")); assertEquals("/a/b/c",npMapper.getOakPath("/a/b/c/")); } {code} Of the two cases above the first one passes while the second one fails diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java index 7bce77d..65639f1 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/NamePathMapperImpl.java @@ -151,9 +151,6 @@ public class NamePathMapperImpl implements NamePathMapper { } private String getOakPath(String jcrPath, final boolean keepIndex) { - final List<String> elements = new ArrayList<String>(); - final StringBuilder parseErrors = new StringBuilder(); - if ("/".equals(jcrPath)) { // avoid the need to special case the root path later on return "/"; @@ -180,6 +177,7 @@ public class NamePathMapperImpl implements NamePathMapper { boolean hasIndexBrackets = false; boolean hasColon = false; boolean hasNameStartingWithDot = false; + boolean hasTrailingSlash = false; char prev = 0; for (int i = 0; i < length; i++) { @@ -193,6 +191,8 @@ public class NamePathMapperImpl implements NamePathMapper { hasColon = true; } else if (c == '.' && (prev == 0 || prev == '/')) { hasNameStartingWithDot = true; + } else if(c == '/' && i == (length - 1)){ + hasTrailingSlash = true; } prev = c; @@ -202,6 +202,9 @@ public class NamePathMapperImpl implements NamePathMapper { if (!hasNameStartingWithDot && !hasClarkBrackets && !hasIndexBrackets) { if (!hasColon || !hasSessionLocalMappings()) { if (JcrPathParser.validate(jcrPath)) { + if(hasTrailingSlash){ + return jcrPath.substring(0, length - 1); + } return jcrPath; } else { @@ -211,6 +214,9 @@ public class NamePathMapperImpl implements NamePathMapper { } } + final List<String> elements = new ArrayList<String>(); + final StringBuilder parseErrors = new StringBuilder(); + JcrPathParser.Listener listener = new JcrPathParser.Listener() { @Override
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-313_e115fd90.diff
bugs-dot-jar_data_OAK-3412_2f85bd78
--- BugID: OAK-3412 Summary: Node name having non space whitspace chars should not be allowed Description: |- Due to the changes done in OAK-1174 node with non space whitespace chars like '\n', '\r' etc can be created. This is not desirable and also JR2 does not allow such node to be created so check must be added to prevent such a name from getting created. As discussed in [1] this is regression due to usage of incorrect utility method as part of [2] the fix can be simply using a {{Character#isWhitespace}} instead of {{Character#isSpaceChar}} [1] http://mail-archives.apache.org/mod_mbox/jackrabbit-oak-dev/201509.mbox/%3CCAHCW-mkkGtxkn%2B9xfXuvMTfgykewjMPsLwrVH%2B00%2BXaBQjA0sg%40mail.gmail.com%3E [2] https://github.com/apache/jackrabbit-oak/commit/342809f7f04221782ca6bbfbde9392ec4ff441c2 diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/Namespaces.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/Namespaces.java index d0d1e26..a0a2367 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/Namespaces.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/name/Namespaces.java @@ -58,6 +58,13 @@ public class Namespaces implements NamespaceConstants { */ private static final Map<String, String> ENCODED_URIS = newConcurrentMap(); + /** + * By default node names with non space whitespace chars are not allowed. + * However initial Oak release did allowed that and this flag is provided + * to revert back to old behaviour if required for some case temporarily + */ + private static final boolean allowOtherWhitespaceChars = Boolean.getBoolean("oak.allowOtherWhitespaceChars"); + private Namespaces() { } @@ -244,7 +251,8 @@ public class Namespaces implements NamespaceConstants { for (int i = 0; i < local.length(); i++) { char ch = local.charAt(i); - if (Character.isSpaceChar(ch)) { + boolean spaceChar = allowOtherWhitespaceChars ? Character.isSpaceChar(ch) : Character.isWhitespace(ch); + if (spaceChar) { if (i == 0) { return false; // leading whitespace } else if (i == local.length() - 1) {
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-3412_2f85bd78.diff
bugs-dot-jar_data_OAK-539_ffa818f3
--- BugID: OAK-539 Summary: Wrong compareTo in micro-kernel Id class Description: "CompareTo method in Id class fails in some cases.\n\n{code} \n// this works\nfinal Id id1 = Id.fromString( \"0000000000000007\" );\nfinal Id id2 = Id.fromString( \"000000000000000c\" );\n\nassertTrue( id1 + \" should be less than \" + id2, id1.compareTo( id2 ) < 0 );\n\n// but this doesn't\nfinal Id id1 = Id.fromString( \"0000000000000070\" );\nfinal Id id2 = Id.fromString( \"00000000000000c0\" );\n\nassertTrue( id1 + \" should be less than \" + id2, id1.compareTo( id2 ) < 0 );\n{code} " diff --git a/oak-mk/src/main/java/org/apache/jackrabbit/mk/model/Id.java b/oak-mk/src/main/java/org/apache/jackrabbit/mk/model/Id.java index a263ddb..021b5ef 100644 --- a/oak-mk/src/main/java/org/apache/jackrabbit/mk/model/Id.java +++ b/oak-mk/src/main/java/org/apache/jackrabbit/mk/model/Id.java @@ -113,7 +113,9 @@ public class Id implements Comparable<Id> { for (int i = 0; i < len; i++) { if (raw[i] != other[i]) { - return raw[i] - other[i]; + final int rawValue = raw[i] & 0xFF; // unsigned value + final int otherValue = other[i] & 0xFF; // unsigned value + return rawValue - otherValue; } } return raw.length - other.length;
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-539_ffa818f3.diff
bugs-dot-jar_data_OAK-1178_f2bb1a17
--- BugID: OAK-1178 Summary: 'MutableTree#isNew: replace implementation by NodeBuilder#isNew ' Description: |- Similar to the issue described in OAK-1177 we may consider replacing the implementation of MutableTree#isNew by the corresponding call on the NodeBuilder. See also OAK-947. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/core/MutableTree.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/core/MutableTree.java index a1aa87d..1b02d0a 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/core/MutableTree.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/core/MutableTree.java @@ -18,8 +18,22 @@ */ package org.apache.jackrabbit.oak.core; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.indexOf; +import static org.apache.jackrabbit.oak.api.Tree.Status.EXISTING; +import static org.apache.jackrabbit.oak.api.Tree.Status.MODIFIED; +import static org.apache.jackrabbit.oak.api.Tree.Status.NEW; +import static org.apache.jackrabbit.oak.api.Type.STRING; +import static org.apache.jackrabbit.oak.commons.PathUtils.elements; +import static org.apache.jackrabbit.oak.commons.PathUtils.isAbsolute; +import static org.apache.jackrabbit.oak.spi.state.NodeStateUtils.isHidden; + import java.util.Collections; import java.util.Set; + import javax.annotation.CheckForNull; import javax.annotation.Nonnull; @@ -36,19 +50,6 @@ import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.PropertyBuilder; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.indexOf; -import static org.apache.jackrabbit.oak.api.Tree.Status.EXISTING; -import static org.apache.jackrabbit.oak.api.Tree.Status.MODIFIED; -import static org.apache.jackrabbit.oak.api.Tree.Status.NEW; -import static org.apache.jackrabbit.oak.api.Type.STRING; -import static org.apache.jackrabbit.oak.commons.PathUtils.elements; -import static org.apache.jackrabbit.oak.commons.PathUtils.isAbsolute; -import static org.apache.jackrabbit.oak.spi.state.NodeStateUtils.isHidden; - public class MutableTree extends AbstractTree { /** @@ -86,7 +87,7 @@ public class MutableTree extends AbstractTree { @Override protected boolean isNew() { - return !getBase().exists(); + return nodeBuilder.isNew(); } @Override @@ -335,15 +336,6 @@ public class MutableTree extends AbstractTree { } //---------------------------------------------------------< internal >--- - - private NodeState getBase() { - if (parent == null) { - return root.getBaseState(); - } else { - return parent.getBase().getChildNode(name); - } - } - /** * Set the parent and name of this tree. * @param parent parent of this tree @@ -480,7 +472,7 @@ public class MutableTree extends AbstractTree { * Internal method for checking whether this node exists and is visible * (i.e. not hidden). * - * @return {@true} if the node is visible, {@code false} if not + * @return {@code true} if the node is visible, {@code false} if not */ private boolean isVisible() { return !isHidden(name) && nodeBuilder.exists(); diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeBuilder.java index aa9d7d8..5058a8b 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeBuilder.java @@ -34,7 +34,7 @@ public class KernelNodeBuilder extends MemoryNodeBuilder implements FastCopyMove private NodeState base = null; - protected NodeState rootBase = null; + private NodeState rootBase = null; KernelNodeBuilder(MemoryNodeBuilder parent, String name, KernelRootBuilder root) { super(parent, name); diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelRootBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelRootBuilder.java index dfe7596..87b2a0d 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelRootBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelRootBuilder.java @@ -117,7 +117,8 @@ class KernelRootBuilder extends MemoryNodeBuilder implements FastCopyMove { purge(); branch.rebase(); NodeState head = branch.getHead(); - reset(head); + reset(branch.getBase()); + super.reset(head); return head; } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java index 00136aa..a83ca87 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java @@ -260,7 +260,7 @@ public class MemoryNodeBuilder implements NodeBuilder { @Override public boolean isNew() { - return exists() && !base.exists(); + return exists() && !getBaseState().exists(); } @Override diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeBuilder.java index 4b10bd0..3837974 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeBuilder.java @@ -18,11 +18,13 @@ package org.apache.jackrabbit.oak.plugins.mongomk; import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; +import org.apache.jackrabbit.oak.spi.state.NodeState; /** * A node builder implementation for MongoMK. */ class MongoNodeBuilder extends MemoryNodeBuilder { + private NodeState base; protected MongoNodeBuilder(MongoNodeState base) { super(base); @@ -33,6 +35,14 @@ class MongoNodeBuilder extends MemoryNodeBuilder { } @Override + public NodeState getBaseState() { + if (base == null) { + base = getParent().getBaseState().getChildNode(getName()); + } + return base; + } + + @Override protected MongoNodeBuilder createChildBuilder(String name) { return new MongoNodeBuilder(this, name); } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoRootBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoRootBuilder.java index 7a1d815..aa6460e 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoRootBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoRootBuilder.java @@ -98,7 +98,8 @@ class MongoRootBuilder extends MongoNodeBuilder { purge(); branch.rebase(); NodeState head = branch.getHead(); - reset(head); + reset(branch.getBase()); + super.reset(head); return head; }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1178_f2bb1a17.diff
bugs-dot-jar_data_OAK-2219_f2740ce1
--- BugID: OAK-2219 Summary: Ordered index does not return relative properties for un-restricted indexes Description: Even if we specify an index without any restriction to node type; the ordered index does not return any result for relative properties diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java index 0574916..b675324 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java @@ -191,7 +191,7 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { PropertyRestriction pr = plan.getPropertyRestriction(); if (pr != null) { String propertyName = PathUtils.getName(pr.propertyName); - depth = PathUtils.getDepth(propertyName); + depth = PathUtils.getDepth(pr.propertyName); paths = strategy.query(plan.getFilter(), propertyName, plan.getDefinition(), pr, pathPrefix); }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-2219_f2740ce1.diff
bugs-dot-jar_data_OAK-4359_002c5845
--- BugID: OAK-4359 Summary: 'Lucene index / compatVersion 2: search for ''a=b=c'' does not work' Description: |- Similar to OAK-3879, we need to escape '=' (althoug lucene [escape()|https://github.com/apache/lucene-solr/blob/releases/lucene-solr/4.7.1/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java#L988] apparently doesn't escape it). Due to this searching for {{a=b=c}} throws parse exception from lucene query parser. Also, searching for {{a=b}} gives incorrect result. diff --git a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java index 749756a..42a7804 100644 --- a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java +++ b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java @@ -1371,7 +1371,7 @@ public class LucenePropertyIndex implements AdvancedQueryIndex, QueryIndex, Nati /** * Following chars are used as operators in Lucene Query and should be escaped */ - private static final char[] LUCENE_QUERY_OPERATORS = {':' , '/', '!', '&', '|'}; + private static final char[] LUCENE_QUERY_OPERATORS = {':' , '/', '!', '&', '|', '='}; /** * Following logic is taken from org.apache.jackrabbit.core.query.lucene.JackrabbitQueryParser#parse(java.lang.String)
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4359_002c5845.diff
bugs-dot-jar_data_OAK-1977_4bfbfcdd
--- BugID: OAK-1977 Summary: ContentMirrorStoreStrategy should utilize path restriction when available Description: |- Currently {{ContentStoreMirrorStrategy}} has a mirror of content path under {{:index}}. Yet, while {{query}} (and {{count}}) methods doesn't jump directly into restricted path. This would be very useful for {{PropertyIndex}} where the queries can be optimized by supplying a path restriction along with an indexed property restriction (I don't know if queries with references would use paths so much though) diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java index 74cfd81..0574916 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndex.java @@ -44,6 +44,7 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { private static final Logger LOG = LoggerFactory.getLogger(OrderedPropertyIndex.class); + @Override public String getIndexName() { return TYPE; } @@ -57,6 +58,7 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { * * !!! for now we want to skip the use-case of NON range-queries !!! */ + @Override public double getCost(Filter filter, NodeState root) { throw new UnsupportedOperationException("Not supported as implementing AdvancedQueryIndex"); } @@ -181,6 +183,7 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { Filter filter = plan.getFilter(); List<OrderEntry> sortOrder = plan.getSortOrder(); + String pathPrefix = plan.getPathPrefix(); Iterable<String> paths = null; OrderedContentMirrorStoreStrategy strategy = OrderedPropertyIndexLookup.getStrategy(plan.getDefinition()); @@ -190,7 +193,7 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { String propertyName = PathUtils.getName(pr.propertyName); depth = PathUtils.getDepth(propertyName); paths = strategy.query(plan.getFilter(), propertyName, - plan.getDefinition(), pr); + plan.getDefinition(), pr, pathPrefix); } if (paths == null && sortOrder != null && !sortOrder.isEmpty()) { // we could be here if we have a query where the ORDER BY makes us play it. @@ -198,7 +201,7 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { String propertyName = PathUtils.getName(oe.getPropertyName()); depth = PathUtils.getDepth(oe.getPropertyName()); paths = strategy.query(plan.getFilter(), propertyName, - plan.getDefinition(), new PropertyRestriction()); + plan.getDefinition(), new PropertyRestriction(), pathPrefix); } } @@ -209,7 +212,6 @@ public class OrderedPropertyIndex implements QueryIndex, AdvancedQueryIndex { + filter); } Cursor cursor = Cursors.newPathCursor(paths, filter.getQueryEngineSettings()); - cursor = Cursors.newPrefixCursor(cursor, plan.getPathPrefix()); if (depth > 1) { cursor = Cursors.newAncestorCursor(cursor, depth - 1, filter.getQueryEngineSettings()); } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndexLookup.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndexLookup.java index df94011..dc35da4 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndexLookup.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/OrderedPropertyIndexLookup.java @@ -203,7 +203,8 @@ public class OrderedPropertyIndexLookup { if (indexMeta == null) { throw new IllegalArgumentException("No index for " + propertyName); } - return getStrategy(indexMeta).query(filter, propertyName, indexMeta, pr); + return getStrategy(indexMeta).query( + filter, propertyName, indexMeta, pr, ""); } /** diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexLookup.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexLookup.java index ae18d9b..cfd96e2 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexLookup.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexLookup.java @@ -129,7 +129,7 @@ public class PropertyIndexLookup { return Double.POSITIVE_INFINITY; } return COST_OVERHEAD + - getStrategy(indexMeta).count(indexMeta, encode(value), MAX_COST); + getStrategy(indexMeta).count(filter, indexMeta, encode(value), MAX_COST); } /** diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java index 5cc398d..8ace776 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndexPlan.java @@ -135,7 +135,7 @@ public class PropertyIndexPlan { if (restriction != null) { Set<String> values = getValues(restriction); - double cost = strategy.count(definition, values, MAX_COST); + double cost = strategy.count(filter, definition, values, MAX_COST); if (cost < bestCost) { bestDepth = depth; bestValues = values; @@ -152,7 +152,7 @@ public class PropertyIndexPlan { if (constraint instanceof OrImpl) { Set<String> values = findMultiProperty((OrImpl) constraint); if (values != null) { - double cost = strategy.count(definition, values, MAX_COST); + double cost = strategy.count(filter, definition, values, MAX_COST); if (cost < bestCost) { bestDepth = 1; bestValues = values; @@ -208,7 +208,7 @@ public class PropertyIndexPlan { } } - private Set<String> getValues(PropertyRestriction restriction) { + private static Set<String> getValues(PropertyRestriction restriction) { if (restriction.firstIncluding && restriction.lastIncluding && restriction.first != null @@ -249,6 +249,7 @@ public class PropertyIndexPlan { //------------------------------------------------------------< Object >-- + @Override public String toString() { StringBuilder buffer = new StringBuilder("property "); buffer.append(name); diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/ContentMirrorStoreStrategy.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/ContentMirrorStoreStrategy.java index be32205..26eed1e 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/ContentMirrorStoreStrategy.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/ContentMirrorStoreStrategy.java @@ -121,7 +121,7 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { return new Iterable<String>() { @Override public Iterator<String> iterator() { - PathIterator it = new PathIterator(filter, indexName); + PathIterator it = new PathIterator(filter, indexName, ""); if (values == null) { it.setPathContainsValue(true); it.enqueue(getChildNodeEntries(index).iterator()); @@ -157,8 +157,18 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { return count(indexMeta, INDEX_CONTENT_NODE_NAME, values, max); } + @Override + public long count(final Filter filter, NodeState indexMeta, Set<String> values, int max) { + return count(filter, indexMeta, INDEX_CONTENT_NODE_NAME, values, max); + } + public long count(NodeState indexMeta, final String indexStorageNodeName, Set<String> values, int max) { + return count(null, indexMeta, indexStorageNodeName, values, max); + } + + public long count(Filter filter, NodeState indexMeta, final String indexStorageNodeName, + Set<String> values, int max) { NodeState index = indexMeta.getChildNode(indexStorageNodeName); int count = 0; if (values == null) { @@ -196,6 +206,11 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { } max = Math.max(10, max / size); int i = 0; + String filterRootPath = null; + if (filter != null && + filter.getPathRestriction().equals(Filter.PathRestriction.ALL_CHILDREN)) { + filterRootPath = filter.getPath(); + } for (String p : values) { if (count > max && i > 3) { // the total count is extrapolated from the the number @@ -204,6 +219,16 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { break; } NodeState s = index.getChildNode(p); + if (filterRootPath != null && s.exists()) { + // Descend directly to path restriction inside index tree + for (String pathFragment : PathUtils + .elements(filterRootPath)) { + s = s.getChildNode(pathFragment); + if (!s.exists()) { + break; + } + } + } if (s.exists()) { CountingNodeVisitor v = new CountingNodeVisitor(max); v.visit(s); @@ -227,6 +252,8 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { private int readCount; private boolean init; private boolean closed; + private String filterPath; + private String pathPrefix; private String parentPath; private String currentPath; private boolean pathContainsValue; @@ -237,9 +264,19 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { private final Set<String> knownPaths = Sets.newHashSet(); private final long maxMemoryEntries; - PathIterator(Filter filter, String indexName) { + PathIterator(Filter filter, String indexName, String pathPrefix) { this.filter = filter; + this.pathPrefix = pathPrefix; this.indexName = indexName; + boolean shouldDescendDirectly = filter.getPathRestriction().equals(Filter.PathRestriction.ALL_CHILDREN); + if (shouldDescendDirectly) { + filterPath = filter.getPath(); + if (PathUtils.denotesRoot(filterPath)) { + filterPath = ""; + } + } else { + filterPath = ""; + } parentPath = ""; currentPath = "/"; this.maxMemoryEntries = filter.getQueryEngineSettings().getLimitInMemory(); @@ -305,6 +342,25 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { } currentPath = PathUtils.concat(parentPath, name); + if (!"".equals(filterPath)) { + String p = currentPath; + if (pathContainsValue) { + String value = PathUtils.elements(p).iterator().next(); + p = PathUtils.relativize(value, p); + } + if ("".equals(pathPrefix)) { + p = PathUtils.concat("/", p); + } else { + p = PathUtils.concat(pathPrefix, p); + } + if (!"".equals(p) && + !p.equals(filterPath) && + !PathUtils.isAncestor(p, filterPath) && + !PathUtils.isAncestor(filterPath, p)) { + continue; + } + } + nodeIterators.addLast(node.getChildNodeEntries().iterator()); parentPath = currentPath; @@ -330,7 +386,7 @@ public class ContentMirrorStoreStrategy implements IndexStoreStrategy { fetchNext(); init = true; } - String result = currentPath; + String result = PathUtils.concat(pathPrefix, currentPath); fetchNext(); return result; } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/IndexStoreStrategy.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/IndexStoreStrategy.java index 5864eef..6438fc0 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/IndexStoreStrategy.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/IndexStoreStrategy.java @@ -43,7 +43,7 @@ public interface IndexStoreStrategy { /** * Search for a given set of values. * - * @param filter the filter (used for logging) + * @param filter the filter (can optionally be used for optimized query execution) * @param indexName the name of the index (for logging) * @param indexMeta the index metadata node (may not be null) * @param values values to look for (null to check for property existence) @@ -62,4 +62,16 @@ public interface IndexStoreStrategy { */ long count(NodeState indexMeta, Set<String> values, int max); + /** + * Count the occurrence of a given set of values. Used in calculating the + * cost of an index. + * + * @param filter the filter which can be used to estimate better cost + * @param indexMeta the index metadata node (may not be null) + * @param values values to look for (null to check for property existence) + * @param max the maximum value to return + * @return the aggregated count of occurrences for each provided value + */ + long count(Filter filter, NodeState indexMeta, Set<String> values, int max); + } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/OrderedContentMirrorStoreStrategy.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/OrderedContentMirrorStoreStrategy.java index 2445869..411f734 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/OrderedContentMirrorStoreStrategy.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/OrderedContentMirrorStoreStrategy.java @@ -264,6 +264,11 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg } return cne; } + + public Iterable<String> query(final Filter filter, final String indexName, + final NodeState indexMeta, final PropertyRestriction pr) { + return query(filter, indexName, indexMeta, pr, ""); + } /** * search the index for the provided PropertyRestriction @@ -275,8 +280,9 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg * @return the iterable */ public Iterable<String> query(final Filter filter, final String indexName, - final NodeState indexMeta, final PropertyRestriction pr) { - return query(filter, indexName, indexMeta, INDEX_CONTENT_NODE_NAME, pr); + final NodeState indexMeta, final PropertyRestriction pr, + String pathPrefix) { + return query(filter, indexName, indexMeta, INDEX_CONTENT_NODE_NAME, pr, pathPrefix); } /** @@ -292,7 +298,7 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg */ public Iterable<String> query(final Filter filter, final String indexName, final NodeState indexMeta, final String indexStorageNodeName, - final PropertyRestriction pr) { + final PropertyRestriction pr, String pathPrefix) { if (LOG.isDebugEnabled()) { LOG.debug("query() - filter: {}", filter); LOG.debug("query() - indexName: {}", indexName); @@ -325,11 +331,14 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg indexState.getChildNode(firstValuableItemKey)); if (direction.isAscending()) { childrenIterable = new SeekedIterable(indexState, firstValueableItem); - it = new QueryResultsWrapper(filter, indexName, childrenIterable); + it = new QueryResultsWrapper(filter, indexName, + childrenIterable, pathPrefix); } else { - it = new QueryResultsWrapper(filter, indexName, new BetweenIterable( - indexState, firstValueableItem, firstEncoded, - pr.firstIncluding, direction)); + it = new QueryResultsWrapper(filter, indexName, + new BetweenIterable( + indexState, firstValueableItem, firstEncoded, + pr.firstIncluding, direction), + pathPrefix); } } } else { @@ -362,7 +371,8 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg indexState.getChildNode(firstValuableItemKey)); childrenIterable = new BetweenIterable(indexState, firstValueableItem, last, includeLast, direction); - it = new QueryResultsWrapper(filter, indexName, childrenIterable); + it = new QueryResultsWrapper(filter, indexName, + childrenIterable, pathPrefix); } } @@ -387,18 +397,21 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg firstValueableItem = new OrderedChildNodeEntry(firstValueableItemKey, indexState.getChildNode(firstValueableItemKey)); if (direction.isAscending()) { - it = new QueryResultsWrapper(filter, indexName, new BetweenIterable(indexState, - firstValueableItem, searchfor, include, direction)); + it = new QueryResultsWrapper(filter, indexName, + new BetweenIterable(indexState, firstValueableItem, searchfor, include, direction), + pathPrefix); } else { - it = new QueryResultsWrapper(filter, indexName, new SeekedIterable(indexState, - firstValueableItem)); + it = new QueryResultsWrapper(filter, indexName, + new SeekedIterable(indexState, firstValueableItem), + pathPrefix); } } return it; } else { // property is not null. AKA "open query" LOG.debug("property is not null. AKA 'open query'. FullIterable"); - return new QueryResultsWrapper(filter, indexName, new FullIterable(indexState, false)); + return new QueryResultsWrapper(filter, indexName, + new FullIterable(indexState, false), pathPrefix); } } @@ -602,17 +615,20 @@ public class OrderedContentMirrorStoreStrategy extends ContentMirrorStoreStrateg private Iterable<ChildNodeEntry> children; private String indexName; private Filter filter; + private String pathPrefix; public QueryResultsWrapper(Filter filter, String indexName, - Iterable<ChildNodeEntry> children) { + Iterable<ChildNodeEntry> children, + String pathPrefix) { this.children = children; this.indexName = indexName; this.filter = filter; + this.pathPrefix = pathPrefix; } @Override public Iterator<String> iterator() { - PathIterator pi = new PathIterator(filter, indexName); + PathIterator pi = new PathIterator(filter, indexName, pathPrefix); pi.setPathContainsValue(true); pi.enqueue(children.iterator()); return pi; diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/UniqueEntryStoreStrategy.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/UniqueEntryStoreStrategy.java index 15111ec..ca80c7e 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/UniqueEntryStoreStrategy.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/strategy/UniqueEntryStoreStrategy.java @@ -166,4 +166,8 @@ public class UniqueEntryStoreStrategy implements IndexStoreStrategy { return count; } + @Override + public long count(final Filter filter, NodeState indexMeta, Set<String> values, int max) { + return count(indexMeta, values, max); + } } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Cursors.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Cursors.java index 4d85191..ff4a1ab 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Cursors.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/query/Cursors.java @@ -24,7 +24,6 @@ import java.util.List; import javax.annotation.Nullable; -import org.apache.jackrabbit.oak.api.PropertyValue; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.plugins.memory.MemoryChildNodeEntry; import org.apache.jackrabbit.oak.query.FilterIterators; @@ -74,23 +73,6 @@ public class Cursors { } /** - * Creates a cursor which wraps another cursor and adds a path prefix to - * each of row of the wrapped cursor. This method will return the passed - * cursor as is if {@code path} is the empty string or the root path ("/"). - * - * @param c the cursor to wrap. - * @param path the path prefix. - * @return the cursor. - */ - public static Cursor newPrefixCursor(Cursor c, String path) { - if (path.isEmpty() || PathUtils.denotesRoot(path)) { - // no need to wrap - return c; - } - return new PrefixCursor(c, path); - } - - /** * Creates a {@link Cursor} over paths, and make the result distinct. * The iterator might return duplicate paths * @@ -220,48 +202,6 @@ public class Cursors { } /** - * A cursor which wraps another cursor and adds a path prefix to each of - * row of the wrapped cursor. - */ - private static final class PrefixCursor extends AbstractCursor { - - private final Cursor c; - private final String path; - - PrefixCursor(Cursor c, String prefix) { - this.c = c; - this.path = prefix; - } - - @Override - public IndexRow next() { - final IndexRow r = c.next(); - return new IndexRow() { - - @Override - public String getPath() { - String sub = r.getPath(); - if (PathUtils.isAbsolute(sub)) { - return path + sub; - } else { - return PathUtils.concat(path, r.getPath()); - } - } - - @Override - public PropertyValue getValue(String columnName) { - return r.getValue(columnName); - } - }; - } - - @Override - public boolean hasNext() { - return c.hasNext(); - } - } - - /** * A cursor that reads all nodes in a given subtree. */ private static class TraversingCursor extends AbstractCursor {
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1977_4bfbfcdd.diff
bugs-dot-jar_data_OAK-1235_1beb2a50
--- BugID: OAK-1235 Summary: Upgrade should not overwrite new oak specific builtin nodetypes Description: diff --git a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java index 2734f3b..d29b8f5 100644 --- a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java +++ b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java @@ -22,6 +22,7 @@ import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.Set; import javax.jcr.NamespaceException; import javax.jcr.NamespaceRegistry; @@ -38,8 +39,10 @@ import org.apache.jackrabbit.core.persistence.PersistenceManager; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.plugins.index.reference.ReferenceEditorProvider; +import org.apache.jackrabbit.oak.plugins.name.NamespaceConstants; import org.apache.jackrabbit.oak.plugins.name.Namespaces; import org.apache.jackrabbit.oak.plugins.nodetype.RegistrationEditorProvider; +import org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent; import org.apache.jackrabbit.oak.spi.commit.CommitHook; import org.apache.jackrabbit.oak.spi.commit.CompositeHook; import org.apache.jackrabbit.oak.spi.commit.EditorHook; @@ -58,6 +61,8 @@ import org.apache.jackrabbit.spi.QValueConstraint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.collect.ImmutableSet; + import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static com.google.common.collect.Maps.newHashMap; @@ -119,6 +124,85 @@ public class RepositoryUpgrade { private final NodeStore target; /** + * the set of oak built-in nodetypes + * todo: load from file or from repo + */ + private static final Set<String> BUILT_IN_NODE_TYPES = ImmutableSet.of( + "mix:created", + "mix:etag", + "mix:language", + "mix:lastModified", + "mix:lifecycle", + "mix:lockable", + "mix:mimeType", + "mix:referenceable", + "mix:shareable", + "mix:simpleVersionable", + "mix:title", + "mix:versionable", + "nt:activity", + "nt:address", + "nt:base", + "nt:childNodeDefinition", + "nt:configuration", + "nt:file", + "nt:folder", + "nt:frozenNode", + "nt:hierarchyNode", + "nt:linkedFile", + "nt:nodeType", + "nt:propertyDefinition", + "nt:query", + "nt:resource", + "nt:unstructured", + "nt:version", + "nt:versionHistory", + "nt:versionLabels", + "nt:versionedChild", + "oak:childNodeDefinition", + "oak:childNodeDefinitions", + "oak:namedChildNodeDefinitions", + "oak:namedPropertyDefinitions", + "oak:nodeType", + "oak:propertyDefinition", + "oak:propertyDefinitions", + "oak:queryIndexDefinition", + "oak:unstructured", + "rep:ACE", + "rep:ACL", + "rep:AccessControl", + "rep:AccessControllable", + "rep:Activities", + "rep:Authorizable", + "rep:AuthorizableFolder", + "rep:Configurations", + "rep:DenyACE", + "rep:GrantACE", + "rep:Group", + "rep:Impersonatable", + "rep:MemberReferences", + "rep:MemberReferencesList", + "rep:Members", + "rep:MergeConflict", + "rep:PermissionStore", + "rep:Permissions", + "rep:Policy", + "rep:PrincipalAccessControl", + "rep:Privilege", + "rep:Privileges", + "rep:RepoAccessControllable", + "rep:Restrictions", + "rep:RetentionManageable", + "rep:Token", + "rep:User", + "rep:VersionReference", + "rep:nodeTypes", + "rep:root", + "rep:system", + "rep:versionStorage" + ); + + /** * Copies the contents of the repository in the given source directory * to the given target node store. * @@ -183,6 +267,9 @@ public class RepositoryUpgrade { try { NodeBuilder builder = target.getRoot().builder(); + // init target repository first + new InitialContent().initialize(builder); + Map<Integer, String> idxToPrefix = copyNamespaces(builder); copyNodeTypes(builder); copyVersionStore(builder, idxToPrefix); @@ -223,7 +310,7 @@ public class RepositoryUpgrade { Map<Integer, String> idxToPrefix = newHashMap(); NodeBuilder system = root.child(JCR_SYSTEM); - NodeBuilder namespaces = Namespaces.createStandardMappings(system); + NodeBuilder namespaces = system.child(NamespaceConstants.REP_NAMESPACES); Properties registry = loadProperties("/namespaces/ns_reg.properties"); Properties indexes = loadProperties("/namespaces/ns_idx.properties"); @@ -292,8 +379,14 @@ public class RepositoryUpgrade { logger.info("Copying registered node types"); for (Name name : sourceRegistry.getRegisteredNodeTypes()) { + // skip built-in nodetypes (OAK-1235) + String oakName = getOakName(name); + if (BUILT_IN_NODE_TYPES.contains(oakName)) { + logger.info("skipping built-on nodetype: {}", name); + continue; + } QNodeTypeDefinition def = sourceRegistry.getNodeTypeDef(name); - NodeBuilder type = types.child(getOakName(name)); + NodeBuilder type = types.child(oakName); copyNodeType(def, type); } }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1235_1beb2a50.diff
bugs-dot-jar_data_OAK-3367_06812d25
--- BugID: OAK-3367 Summary: Boosting fields not working as expected Description: "When the boost support was added the intention was to support a usecase like \n\n{quote}\nFor the fulltext search on a node where the fulltext content is derived from multiple field it should be possible to boost specific text contributed by individual field. Meaning that if a title field is boosted more than description, the title (part) in the fulltext field will mean more than the description (part) in the fulltext field.\n{quote}\n\nThis would enable a user to perform a search like _/jcr:root/content/geometrixx-outdoors/en//element(*, cq:Page)\\[jcr:contains(., 'Keyword')\\]_ and get a result where pages having 'Keyword' in title come above in search result compared to those where Keyword is found in description.\n\nCurrent implementation just sets the boost while add the field value to fulltext field with the intention that Lucene would use the boost as explained above. However it does not work like that and boost value gets multiplies with other field and hence boosting does not work as expected" diff --git a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexDefinition.java b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexDefinition.java index cd4a119..843fc82 100644 --- a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexDefinition.java +++ b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexDefinition.java @@ -865,7 +865,6 @@ class IndexDefinition implements Aggregate.AggregateMapper{ //Include props with name, boosted and nodeScopeIndex if (pd.nodeScopeIndex - && pd.boost != PropertyDefinition.DEFAULT_BOOST && pd.analyzed && !pd.isRegexp){ boostedProps.add(pd);
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-3367_06812d25.diff
bugs-dot-jar_data_OAK-2288_57bd2dc5
--- BugID: OAK-2288 Summary: DocumentNS may expose branch commit on earlier revision Description: The DocumentNodeStore may expose the changes of a branch on a revision earlier than it's commit revision. This only happens when the read revision equals the revision of the not yet merged changes on the branch. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java index 077d4b3..388cca2 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java @@ -1330,9 +1330,6 @@ public final class NodeDocument extends Document implements CachedNodeDocument{ @Nonnull Revision revision, @Nullable String commitValue, @Nonnull Revision readRevision) { - if (revision.equalsIgnoreBranch(readRevision)) { - return true; - } if (commitValue == null) { commitValue = getCommitValue(revision); }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-2288_57bd2dc5.diff
bugs-dot-jar_data_OAK-499_61381ea2
--- BugID: OAK-499 Summary: SQL-2 query parser doesn't detect some illegal statements Description: |- The SQL-2 query parser doesn't detect some illegal statements, for example {code} select * from [nt:base] where name =+ 'Hello' select * from [nt:base] where name => 'Hello' {code} Both are currently interpreted as "name = 'Hello'", which is wrong. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/SQL2Parser.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/SQL2Parser.java index a31fd0a..4f70f1e 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/SQL2Parser.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/SQL2Parser.java @@ -525,6 +525,23 @@ public class SQL2Parser { private StaticOperandImpl parseStaticOperand() throws ParseException { if (currentTokenType == PLUS) { read(); + if (currentTokenType != VALUE) { + throw getSyntaxError("number"); + } + int valueType = currentValue.getType().tag(); + switch (valueType) { + case PropertyType.LONG: + currentValue = PropertyValues.newLong(currentValue.getValue(Type.LONG)); + break; + case PropertyType.DOUBLE: + currentValue = PropertyValues.newDouble(currentValue.getValue(Type.DOUBLE)); + break; + case PropertyType.DECIMAL: + currentValue = PropertyValues.newDecimal(currentValue.getValue(Type.DECIMAL).negate()); + break; + default: + throw getSyntaxError("Illegal operation: + " + currentValue); + } } else if (currentTokenType == MINUS) { read(); if (currentTokenType != VALUE) { @@ -923,7 +940,10 @@ public class SQL2Parser { if (types[i] == CHAR_SPECIAL_2) { i++; } - // fall through + currentToken = statement.substring(start, i); + currentTokenType = KEYWORD; + parseIndex = i; + return; case CHAR_SPECIAL_1: currentToken = statement.substring(start, i); switch (c) {
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-499_61381ea2.diff
bugs-dot-jar_data_OAK-4307_f303c916
--- BugID: OAK-4307 Summary: SegmentWriter saves references to external blobs Description: |- The new {{SegmentWriteOperation#internalWriteStream}} method checks whether the input stream to write is a {{SegmentStream}}. If it's, writer will reuse existing block ids, rather than storing the whole stream. It should also check whether the blocks in {{SegmentStream}} comes from the same tracker / segment store. Otherwise this will create invalid references if someone invokes the {{internalWriteStream()}} method with a {{SegmentStream}} created externally. diff --git a/oak-segment-next/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java b/oak-segment-next/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java index b2f44f2..ee320ed 100644 --- a/oak-segment-next/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java +++ b/oak-segment-next/src/main/java/org/apache/jackrabbit/oak/segment/SegmentWriter.java @@ -608,8 +608,20 @@ public class SegmentWriter { boolean threw = true; try { RecordId id = SegmentStream.getRecordIdIfAvailable(stream, store); - if (id == null || isOldGen(id)) { + if (id == null) { + // This is either not a segment stream or a one from another store: + // fully serialise the stream. id = internalWriteStream(stream); + } else if (isOldGen(id)) { + // This is a segment stream from this store but from an old generation: + // try to link to the blocks if there are any. + SegmentStream segmentStream = (SegmentStream) stream; + List<RecordId> blockIds = segmentStream.getBlockIds(); + if (blockIds == null) { + return internalWriteStream(stream); + } else { + return writeValueRecord(segmentStream.getLength(), writeList(blockIds)); + } } threw = false; return id; @@ -619,14 +631,6 @@ public class SegmentWriter { } private RecordId internalWriteStream(InputStream stream) throws IOException { - if (stream instanceof SegmentStream) { - SegmentStream segmentStream = (SegmentStream) stream; - List<RecordId> blockIds = segmentStream.getBlockIds(); - if (blockIds != null) { - return writeValueRecord(segmentStream.getLength(), writeList(blockIds)); - } - } - // Special case for short binaries (up to about 16kB): // store them directly as small- or medium-sized value records byte[] data = new byte[Segment.MEDIUM_LIMIT];
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4307_f303c916.diff
bugs-dot-jar_data_OAK-208_daf9a4ef
--- BugID: OAK-208 Summary: RootImplFuzzIT test failures Description: |- As seen in the CI build, {{RootImplFuzzIT}} fails every now and then. This might be because of OAK-174, but there's been quite a bit of other work on the same area, so this could be caused also by something else. The troublesome seeds as seen in failing CI builds are 1437930918, 206057576, 1638075186, 1705736349, -1856261793 and 569172885. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/core/RootImpl.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/core/RootImpl.java index abda5d2..a868959 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/core/RootImpl.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/core/RootImpl.java @@ -225,9 +225,7 @@ public class RootImpl implements Root { * All registered {@link PurgeListener}s are notified. */ private void purgePendingChanges() { - if (hasPendingChanges()) { - branch.setRoot(rootTree.getNodeState()); - } + branch.setRoot(rootTree.getNodeState()); notifyListeners(); } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStoreBranch.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStoreBranch.java index 79ffaff..63b1ec5 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStoreBranch.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStoreBranch.java @@ -80,8 +80,10 @@ class KernelNodeStoreBranch implements NodeStoreBranch { @Override public void setRoot(NodeState newRoot) { - currentRoot = newRoot; - commit(buildJsop()); + if (!currentRoot.equals(newRoot)) { + currentRoot = newRoot; + commit(buildJsop()); + } } @Override
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-208_daf9a4ef.diff
bugs-dot-jar_data_OAK-1369_ce0b0955
--- BugID: OAK-1369 Summary: 'XPath queries: compatibility for missing @ in front of property names' Description: |- XPath queries with conditions of the form {noformat}[id='test']{noformat} are not problematic. Jackrabbit 2.x interpreted such conditions as {noformat}[@id='test']{noformat}, and Oak currently interprets them as {noformat}[@id/* = 'test']{noformat}, as this is the expected behavior for conditions of the form {noformat}[jcr:contains(id, 'test')]{noformat}. I believe the condition {noformat}[id='test']{noformat} is illegal, and it would be better to throw an exception instead, saying a @ is missing. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/Expression.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/Expression.java index f6ad95a..5c37162 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/Expression.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/Expression.java @@ -180,10 +180,6 @@ abstract class Expression { if (right == null) { rightExpr = ""; } else { - if (left != null && left instanceof Property && ((Property) left).implicitAsterisk) { - throw new IllegalArgumentException( - "Missing @ in front of the property name: " + left); - } if (leftExprIsName && !"like".equals(operator)) { // need to de-escape _x0020_ and so on if (!(right instanceof Literal)) { @@ -275,8 +271,16 @@ abstract class Expression { @Override public String toString() { - StringBuilder buff = new StringBuilder("contains"). - append('(').append(left).append(", ").append(right).append(')'); + StringBuilder buff = new StringBuilder("contains("); + Expression l = left; + if (l instanceof Property) { + Property p = (Property) l; + if (p.thereWasNoAt) { + l = new Property(p.selector, p.name + "/*", true); + } + } + buff.append(l); + buff.append(", ").append(right).append(')'); return buff.toString(); } @@ -386,12 +390,18 @@ abstract class Expression { final Selector selector; final String name; - final boolean implicitAsterisk; + + /** + * If there was no "@" character in front of the property name. If that + * was the case, then it is still considered a property, except for + * "contains(x, 'y')", where "x" is considered to be a node. + */ + final boolean thereWasNoAt; - Property(Selector selector, String name, boolean implicitAsterisk) { + Property(Selector selector, String name, boolean thereWasNoAt) { this.selector = selector; this.name = name; - this.implicitAsterisk = implicitAsterisk; + this.thereWasNoAt = thereWasNoAt; } @Override diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/XPathToSQL2Converter.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/XPathToSQL2Converter.java index 5ac0529..76955a0 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/XPathToSQL2Converter.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/xpath/XPathToSQL2Converter.java @@ -552,9 +552,7 @@ public class XPathToSQL2Converter { // path without all attributes, as in: // jcr:contains(jcr:content, 'x') if (buff.toString().equals(".")) { - buff = new StringBuilder("*"); - } else { - buff.append("/*"); + return new Expression.Property(currentSelector, "*", false); } return new Expression.Property(currentSelector, buff.toString(), true); }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1369_ce0b0955.diff
bugs-dot-jar_data_OAK-4397_e33516d5
--- BugID: OAK-4397 Summary: DefaultSyncContext.syncMembership may sync group of a foreign IDP Description: |- With the following scenario the {{DefaultSyncContext.syncMembership}} may end up synchronizing (i.e. updating) a group defined by an foreign IDP and even add the user to be synchronized as a new member: - configuration with different IDPs - foreign IDP synchronizes a given external group 'groupA' => rep:externalID points to foreign-IDP (e.g. rep:externalId = 'groupA;foreignIDP') - my-IDP contains a group with the same ID (but obviously with a different rep:externalID) and user that has declared group membership pointing to 'groupA' from my IDP if synchronizing my user first the groupA will be created with a rep:externalId = 'groupA;myIDP'. however, if the group has been synced before by the foreignIDP the code fails to verify that an existing group 'groupA' really belongs to the same IDP and thus may end up synchronizing the group and updating it's members. IMHO that's a critical issue as it violates the IDP boundaries. the fix is pretty trivial as it only requires testing for the IDP of the existing group as we do it in other places (even in the same method). diff --git a/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/basic/DefaultSyncContext.java b/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/basic/DefaultSyncContext.java index 7d78159..1218fb7 100644 --- a/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/basic/DefaultSyncContext.java +++ b/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/basic/DefaultSyncContext.java @@ -531,10 +531,10 @@ public class DefaultSyncContext implements SyncContext { if (a == null) { grp = createGroup(extGroup); log.debug("- created new group"); - } else if (a.isGroup()) { + } else if (a.isGroup() && isSameIDP(a)) { grp = (Group) a; } else { - log.warn("Authorizable '{}' is not a group, but should be one.", extGroup.getId()); + log.warn("Existing authorizable '{}' is not a group from this IDP '{}'.", extGroup.getId(), idp.getName()); continue; } log.debug("- user manager returned '{}'", grp); @@ -557,6 +557,7 @@ public class DefaultSyncContext implements SyncContext { } } timer.mark("adding"); + // remove us from the lost membership groups for (Group grp : declaredExternalGroups.values()) { grp.removeMember(auth);
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4397_e33516d5.diff
bugs-dot-jar_data_OAK-1789_07646fba
--- BugID: OAK-1789 Summary: Upgraded version history has UUIDs as jcr:frozenUuid of non-referenceable nodes Description: |- In Jackrabbit Classic each node, even non-referenceable ones, has a UUID as its identifier, and thus the {{jcr:frozenUuid}} properties of frozen nodes are always UUIDs. In contrast Oak uses path identifiers for non-referenceable frozen nodes (see OAK-1009), which presents a problem when dealing with version histories migrated from Jackrabbit Classic. To avoid this mismatch, the upgrade code should check each frozen node for referenceability and replace the frozen UUID with a path identifier if needed. diff --git a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/JackrabbitNodeState.java b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/JackrabbitNodeState.java index 3752b91..fded86c 100644 --- a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/JackrabbitNodeState.java +++ b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/JackrabbitNodeState.java @@ -332,10 +332,12 @@ class JackrabbitNodeState extends AbstractNodeState { } if (!isReferenceable.apply(frozenPrimary, frozenMixins)) { - frozenUuid = PropertyStates.createProperty( - JCR_FROZENUUID, - parent.getString(JCR_FROZENUUID) + "/" + name); - properties.put(JCR_FROZENUUID, frozenUuid); + String parentFrozenUuid = parent.getString(JCR_FROZENUUID); + if (parentFrozenUuid != null) { + frozenUuid = PropertyStates.createProperty( + JCR_FROZENUUID, parentFrozenUuid + "/" + name); + properties.put(JCR_FROZENUUID, frozenUuid); + } } } } diff --git a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java index 5dff050..ce8b019 100644 --- a/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java +++ b/oak-upgrade/src/main/java/org/apache/jackrabbit/oak/upgrade/RepositoryUpgrade.java @@ -238,7 +238,8 @@ public class RepositoryUpgrade { logger.info( "Copying repository content from {} to Oak", config.getHomeDir()); try { - NodeBuilder builder = target.getRoot().builder(); + NodeState base = target.getRoot(); + NodeBuilder builder = base.builder(); String workspace = source.getRepositoryConfig().getDefaultWorkspaceName(); @@ -260,6 +261,11 @@ public class RepositoryUpgrade { copyNodeTypes(builder, uriToPrefix.inverse()); copyPrivileges(builder); + // Triggers compilation of type information, which we need for + // the type predicates used by the bulk copy operations below. + new TypeEditorProvider(false).getRootEditor( + base, builder.getNodeState(), builder, null); + NodeState root = builder.getNodeState(); copyVersionStore(builder, root, uriToPrefix, idxToPrefix); copyWorkspace(builder, root, workspace, uriToPrefix, idxToPrefix);
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1789_07646fba.diff
bugs-dot-jar_data_OAK-4358_74cbba24
--- BugID: OAK-4358 Summary: Stale cluster ids can potentially lead to lots of previous docs traversal in NodeDocument.getNewestRevision Description: |- When some (actual test case and conditions still being investigated) of the following conditions are met: * There are property value changes from different cluster id * There are very old and stale cluster id (probably older incarnations of current node itself) * A parallel background split removes all _commitRoot, _revision entries such that the latest one (which is less that baseRev) is very old , finding newest revision traverses a lot of previous docs. Since root document gets split a lot and is a very common commitRoot (thus participating during checkConflicts in lot of commits), the issue can slow down commits by a lot diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java index cdff3e1..e36d1ad 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/NodeDocument.java @@ -19,6 +19,7 @@ package org.apache.jackrabbit.oak.plugins.document; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; @@ -39,6 +40,7 @@ import com.google.common.base.Predicate; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; import com.google.common.collect.Queues; import org.apache.jackrabbit.oak.cache.CacheValue; import org.apache.jackrabbit.oak.commons.PathUtils; @@ -54,7 +56,6 @@ import org.slf4j.LoggerFactory; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import com.google.common.primitives.Longs; import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkArgument; @@ -65,6 +66,7 @@ import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES; import static org.apache.jackrabbit.oak.plugins.document.StableRevisionComparator.REVERSE; import static org.apache.jackrabbit.oak.plugins.document.UpdateOp.Key; import static org.apache.jackrabbit.oak.plugins.document.UpdateOp.Operation; +import static org.apache.jackrabbit.oak.plugins.document.util.Utils.abortingIterable; import static org.apache.jackrabbit.oak.plugins.document.util.Utils.resolveCommitRevision; /** @@ -759,18 +761,24 @@ public final class NodeDocument extends Document implements CachedNodeDocument{ } // if we don't have clusterIds, we can use the local changes only boolean fullScan = true; - Iterable<Revision> changes; - if (clusterIds.isEmpty()) { - // baseRev is newer than all previous documents - changes = Iterables.mergeSorted( - ImmutableList.of( - getLocalRevisions().keySet(), - getLocalCommitRoot().keySet()), - getLocalRevisions().comparator()); - } else { + Iterable<Revision> changes = Iterables.mergeSorted( + ImmutableList.of( + getLocalRevisions().keySet(), + getLocalCommitRoot().keySet()), + getLocalRevisions().comparator() + ); + if (!clusterIds.isEmpty()) { + // there are some previous documents that potentially + // contain changes after 'lower' revision vector // include previous documents as well (only needed in rare cases) fullScan = false; - changes = getAllChanges(); + changes = Iterables.mergeSorted( + ImmutableList.of( + changes, + getChanges(REVISIONS, lower), + getChanges(COMMIT_ROOT, lower) + ), getLocalRevisions().comparator() + ); if (LOG.isDebugEnabled()) { LOG.debug("getNewestRevision() with changeRev {} on {}, " + "_revisions {}, _commitRoot {}", @@ -1453,90 +1461,18 @@ public final class NodeDocument extends Document implements CachedNodeDocument{ * @return revisions of all changes performed on this document. */ Iterable<Revision> getAllChanges() { - final SortedSet<Revision> stack = Sets.newTreeSet(REVERSE); - // initialize with local revisions and commitRoot entries - stack.addAll(getLocalCommitRoot().keySet()); - stack.addAll(getLocalRevisions().keySet()); - if (getPreviousRanges().isEmpty()) { - return stack; - } - return new Iterable<Revision>() { - @Override - public Iterator<Revision> iterator() { - final Iterator<NodeDocument> previousDocs = getPreviousDocLeaves(); - return new AbstractIterator<Revision>() { - private NodeDocument nextDoc; - private Revision nextRevision; - @Override - protected Revision computeNext() { - if (stack.isEmpty()) { - return endOfData(); - } - Revision next = stack.first(); - stack.remove(next); - fillStackIfNeeded(); - return next; - } - - private void fillStackIfNeeded() { - for (;;) { - fetchNextDoc(); - - // no more changes to compare with - if (nextDoc == null) { - return; - } - - // check if current top revision is still newer than - // most recent revision of next document - if (!stack.isEmpty()) { - Revision top = stack.first(); - if (top.compareRevisionTimeThenClusterId(nextRevision) > 0) { - return; - } - } - - // if we get here, we need to pull in changes - // from nextDoc - Iterables.addAll(stack, nextDoc.getAllChanges()); - nextDoc = null; - nextRevision = null; - } - } - - /** - * Fetch the next document if {@code nextDoc} is - * {@code null} and there are more documents. - */ - private void fetchNextDoc() { - for (;;) { - if (nextDoc != null) { - break; - } - if (!previousDocs.hasNext()) { - // no more previous docs - break; - } - nextDoc = previousDocs.next(); - Iterator<Revision> changes = nextDoc.getAllChanges().iterator(); - if (changes.hasNext()) { - nextRevision = changes.next(); - break; - } else { - // empty document, try next - nextDoc = null; - } - } - } - }; - } - }; + RevisionVector empty = new RevisionVector(); + return Iterables.mergeSorted(ImmutableList.of( + getChanges(REVISIONS, empty), + getChanges(COMMIT_ROOT, empty) + ), StableRevisionComparator.REVERSE); } /** * Returns all changes for the given property back to {@code min} revision * (exclusive). The revisions include committed as well as uncommitted - * changes. + * changes. The returned revisions are sorted in reverse order (newest + * first). * * @param property the name of the property. * @param min the lower bound revision (exclusive). @@ -1545,43 +1481,27 @@ public final class NodeDocument extends Document implements CachedNodeDocument{ @Nonnull Iterable<Revision> getChanges(@Nonnull final String property, @Nonnull final RevisionVector min) { - return new Iterable<Revision>() { + Predicate<Revision> p = new Predicate<Revision>() { @Override - public Iterator<Revision> iterator() { - final Set<Revision> changes = getValueMap(property).keySet(); - final Set<Integer> clusterIds = Sets.newHashSet(); - for (Revision r : getLocalMap(property).keySet()) { - clusterIds.add(r.getClusterId()); - } - for (Range r : getPreviousRanges().values()) { - if (min.isRevisionNewer(r.high)) { - clusterIds.add(r.high.getClusterId()); - } - } - final Iterator<Revision> unfiltered = changes.iterator(); - return new AbstractIterator<Revision>() { - @Override - protected Revision computeNext() { - while (unfiltered.hasNext()) { - Revision next = unfiltered.next(); - if (min.isRevisionNewer(next)) { - return next; - } else { - // further revisions with this clusterId - // are older than min revision - clusterIds.remove(next.getClusterId()); - // no more revisions to check - if (clusterIds.isEmpty()) { - return endOfData(); - } - } - } - return endOfData(); - } - }; + public boolean apply(Revision input) { + return min.isRevisionNewer(input); } }; - + List<Iterable<Revision>> changes = Lists.newArrayList(); + changes.add(abortingIterable(getLocalMap(property).keySet(), p)); + for (Map.Entry<Revision, Range> e : getPreviousRanges().entrySet()) { + if (min.isRevisionNewer(e.getKey())) { + final NodeDocument prev = getPreviousDoc(e.getKey(), e.getValue()); + if (prev != null) { + changes.add(abortingIterable(prev.getValueMap(property).keySet(), p)); + } + } + } + if (changes.size() == 1) { + return changes.get(0); + } else { + return Iterables.mergeSorted(changes, StableRevisionComparator.REVERSE); + } } /** diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java index c7a4253..40ad9bb 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java @@ -758,4 +758,36 @@ public class Utils { } return min; } + + /** + * Wraps the given iterable and aborts iteration over elements when the + * predicate on an element evaluates to {@code false}. + * + * @param iterable the iterable to wrap. + * @param p the predicate. + * @return the aborting iterable. + */ + public static <T> Iterable<T> abortingIterable(final Iterable<T> iterable, + final Predicate<T> p) { + checkNotNull(iterable); + checkNotNull(p); + return new Iterable<T>() { + @Override + public Iterator<T> iterator() { + final Iterator<T> it = iterable.iterator(); + return new AbstractIterator<T>() { + @Override + protected T computeNext() { + if (it.hasNext()) { + T next = it.next(); + if (p.apply(next)) { + return next; + } + } + return endOfData(); + } + }; + } + }; + } }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-4358_74cbba24.diff
bugs-dot-jar_data_OAK-3442_17032c50
--- BugID: OAK-3442 Summary: Intermittent IllegalMonitorStateException seen while releaseing IndexNode Description: "At times following exception seen. On this system the index got corrupted because backing index files got deleted from the system and hence index is not accessible. \n\n{noformat}\n21.09.2015 09:26:36.764 *ERROR* [FelixStartLevel] com.adobe.granite.repository.impl.SlingRepositoryManager start: Uncaught Throwable trying to access Repository, calling stopRepository()\njava.lang.IllegalMonitorStateException: attempt to unlock read lock, not locked by current thread\n at java.util.concurrent.locks.ReentrantReadWriteLock$Sync.unmatchedUnlockException(ReentrantReadWriteLock.java:444)\n \ at java.util.concurrent.locks.ReentrantReadWriteLock$Sync.tryReleaseShared(ReentrantReadWriteLock.java:428)\n \ at java.util.concurrent.locks.AbstractQueuedSynchronizer.releaseShared(AbstractQueuedSynchronizer.java:1341)\n \ at java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock.unlock(ReentrantReadWriteLock.java:881)\n \ at org.apache.jackrabbit.oak.plugins.index.lucene.IndexNode.release(IndexNode.java:121)\n \ at org.apache.jackrabbit.oak.plugins.index.lucene.LucenePropertyIndex.getPlans(LucenePropertyIndex.java:212)\n \ at org.apache.jackrabbit.oak.query.QueryImpl.getBestSelectorExecutionPlan(QueryImpl.java:847)\n \ at org.apache.jackrabbit.oak.query.QueryImpl.getBestSelectorExecutionPlan(QueryImpl.java:793)\n \ at org.apache.jackrabbit.oak.query.ast.SelectorImpl.prepare(SelectorImpl.java:283)\n \ at org.apache.jackrabbit.oak.query.QueryImpl.prepare(QueryImpl.java:568)\n \ at org.apache.jackrabbit.oak.query.QueryEngineImpl.executeQuery(QueryEngineImpl.java:183)\n \ at org.apache.jackrabbit.oak.security.user.UserProvider.getAuthorizableByPrincipal(UserProvider.java:234)\n \ at org.apache.jackrabbit.oak.security.user.UserManagerImpl.getAuthorizable(UserManagerImpl.java:116)\n \ at org.apache.jackrabbit.oak.security.principal.PrincipalProviderImpl.getAuthorizable(PrincipalProviderImpl.java:140)\n \ at org.apache.jackrabbit.oak.security.principal.PrincipalProviderImpl.getPrincipal(PrincipalProviderImpl.java:69)\n \ at org.apache.jackrabbit.oak.spi.security.principal.CompositePrincipalProvider.getPrincipal(CompositePrincipalProvider.java:50)\n \ at org.apache.jackrabbit.oak.spi.security.principal.PrincipalManagerImpl.getPrincipal(PrincipalManagerImpl.java:47)\n \ at com.adobe.granite.repository.impl.SlingRepositoryManager.setupPermissions(SlingRepositoryManager.java:997)\n \ at com.adobe.granite.repository.impl.SlingRepositoryManager.createRepository(SlingRepositoryManager.java:420)\n \ at com.adobe.granite.repository.impl.SlingRepositoryManager.acquireRepository(SlingRepositoryManager.java:290)\n \ at org.apache.sling.jcr.base.AbstractSlingRepositoryManager.start(AbstractSlingRepositoryManager.java:304)\n \ at com.adobe.granite.repository.impl.SlingRepositoryManager.activate(SlingRepositoryManager.java:267)\n \ at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n \ at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n \ at java.lang.reflect.Method.invoke(Method.java:483)\n at org.apache.felix.scr.impl.helper.BaseMethod.invokeMethod(BaseMethod.java:222)\n \ at org.apache.felix.scr.impl.helper.BaseMethod.access$500(BaseMethod.java:37)\n \ at org.apache.felix.scr.impl.helper.BaseMethod$Resolved.invoke(BaseMethod.java:615)\n \ at org.apache.felix.scr.impl.helper.BaseMethod.invoke(BaseMethod.java:499)\n \ at org.apache.felix.scr.impl.helper.ActivateMethod.invoke(ActivateMethod.java:295)\n \ at org.apache.felix.scr.impl.manager.SingleComponentManager.createImplementationObject(SingleComponentManager.java:302)\n \ at org.apache.felix.scr.impl.manager.SingleComponentManager.createComponent(SingleComponentManager.java:113)\n \ at org.apache.felix.scr.impl.manager.SingleComponentManager.getService(SingleComponentManager.java:832)\n \ at org.apache.felix.scr.impl.manager.SingleComponentManager.getServiceInternal(SingleComponentManager.java:799)\n \ at org.apache.felix.scr.impl.manager.AbstractComponentManager.activateInternal(AbstractComponentManager.java:724)\n \ at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:927)\n \ at org.apache.felix.scr.impl.manager.DependencyManager$SingleStaticCustomizer.addedService(DependencyManager.java:891)\n \ at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1492)\n \ at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.customizerAdded(ServiceTracker.java:1413)\n \ at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.trackAdding(ServiceTracker.java:1222)\n \ at org.apache.felix.scr.impl.manager.ServiceTracker$AbstractTracked.track(ServiceTracker.java:1158)\n \ at org.apache.felix.scr.impl.manager.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:1444)\n \ at org.apache.felix.framework.util.EventDispatcher.invokeServiceListenerCallback(EventDispatcher.java:987)\n \ at org.apache.felix.framework.util.EventDispatcher.fireEventImmediately(EventDispatcher.java:838)\n \ at org.apache.felix.framework.util.EventDispatcher.fireServiceEvent(EventDispatcher.java:545)\n \ at org.apache.felix.framework.Felix.fireServiceEvent(Felix.java:4547)\n \ at org.apache.felix.framework.Felix.registerService(Felix.java:3521)\n at org.apache.felix.framework.BundleContextImpl.registerService(BundleContextImpl.java:348)\n \ at org.apache.sling.commons.threads.impl.Activator.start(Activator.java:55)\n \ at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:697)\n \ at org.apache.felix.framework.Felix.activateBundle(Felix.java:2223)\n at org.apache.felix.framework.Felix.startBundle(Felix.java:2141)\n at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1368)\n \ at org.apache.felix.framework.FrameworkStartLevelImpl.run(FrameworkStartLevelImpl.java:308)\n \ at java.lang.Thread.run(Thread.java:745)\n{noformat}\n\nAbove exception happens at\n\n{code}\nfor (String path : indexPaths) {\n try {\n indexNode = tracker.acquireIndexNode(path);\n\n if (indexNode != null) {\n \ IndexPlan plan = new IndexPlanner(indexNode, path, filter, sortOrder).getPlan();\n \ if (plan != null) {\n plans.add(plan);\n \ }\n }\n } finally {\n if (indexNode != null) {\n indexNode.release();\n }\n \ }\n }\n{code}\n\nIt has been ensured that if indexNode is initialized then it has been acquired. So only way for such an exception to happen is that in a loop of say 2 paths {{indexNode}} got initialized for Loop 1 and then while acquiring in Loop 2 the indexNode still refers to old released value and that would cause the exception. The fix should be simply to null the variable once released" diff --git a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java index b01ff99..1c84164 100644 --- a/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java +++ b/oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/LucenePropertyIndex.java @@ -206,8 +206,8 @@ public class LucenePropertyIndex implements AdvancedQueryIndex, QueryIndex, Nati public List<IndexPlan> getPlans(Filter filter, List<OrderEntry> sortOrder, NodeState rootState) { Collection<String> indexPaths = new LuceneIndexLookup(rootState).collectIndexNodePaths(filter); List<IndexPlan> plans = Lists.newArrayListWithCapacity(indexPaths.size()); - IndexNode indexNode = null; for (String path : indexPaths) { + IndexNode indexNode = null; try { indexNode = tracker.acquireIndexNode(path);
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-3442_17032c50.diff
bugs-dot-jar_data_OAK-1877_716e1237
--- BugID: OAK-1877 Summary: Hourly async reindexing on an idle instance Description: |- OAK-1292 introduced the following interesting but not very nice behavior: On an idle system with no changes for an extended amount of time, the OAK-1292 change blocks the async indexer from updating the reference to the last indexed checkpoint. After one hour (the default checkpoint lifetime), the referenced checkpoint will expire, and the indexer will fall back to full reindexing. The result of this behavior is that once every hour, the size of an idle instance will grow with dozens or hundreds of megabytes of new index data generated by reindexing. Older index data becomes garbage, but the compaction code from OAK-1804 is needed to make it collectable. A better solution would be to prevent the reindexing from happening in the first place. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdate.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdate.java index d52c430..74755fe 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdate.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/AsyncIndexUpdate.java @@ -21,11 +21,9 @@ package org.apache.jackrabbit.oak.plugins.index; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.MISSING_NODE; import static org.apache.jackrabbit.oak.api.jmx.IndexStatsMBean.STATUS_DONE; -import static org.apache.jackrabbit.oak.api.jmx.IndexStatsMBean.STATUS_RUNNING; import static org.apache.jackrabbit.oak.commons.PathUtils.elements; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.REINDEX_PROPERTY_NAME; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.ASYNC_PROPERTY_NAME; -import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME; import java.util.Calendar; import java.util.HashSet; @@ -36,18 +34,15 @@ import javax.annotation.Nonnull; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.api.PropertyState; -import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.api.jmx.IndexStatsMBean; import org.apache.jackrabbit.oak.plugins.commit.AnnotatingConflictHandler; import org.apache.jackrabbit.oak.plugins.commit.ConflictHook; import org.apache.jackrabbit.oak.plugins.commit.ConflictValidatorProvider; -import org.apache.jackrabbit.oak.plugins.value.Conversions; import org.apache.jackrabbit.oak.spi.commit.CommitHook; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.CompositeHook; import org.apache.jackrabbit.oak.spi.commit.EditorDiff; import org.apache.jackrabbit.oak.spi.commit.EditorHook; -import org.apache.jackrabbit.oak.spi.commit.EmptyHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStateDiff; @@ -75,8 +70,9 @@ public class AsyncIndexUpdate implements Runnable { "Async", 1, "Concurrent update detected"); /** - * Timeout in minutes after which an async job would be considered as timed out. Another - * node in cluster would wait for timeout before taking over a running job + * Timeout in minutes after which an async job would be considered as + * timed out. Another node in cluster would wait for timeout before + * taking over a running job */ private static final int ASYNC_TIMEOUT = 15; @@ -125,13 +121,55 @@ public class AsyncIndexUpdate implements Runnable { */ private class AsyncUpdateCallback implements IndexUpdateCallback { - private boolean dirty = false; + /** The base checkpoint */ + private final String checkpoint; + + /** Expiration time of the last lease we committed */ + private long lease; + + private long updates = 0; + + public AsyncUpdateCallback(String checkpoint) + throws CommitFailedException { + long now = System.currentTimeMillis(); + this.checkpoint = checkpoint; + this.lease = now + 2 * ASYNC_TIMEOUT; + + String leaseName = name + "-lease"; + NodeState root = store.getRoot(); + long beforeLease = root.getChildNode(ASYNC).getLong(leaseName); + if (beforeLease > now) { + throw CONCURRENT_UPDATE; + } + + NodeBuilder builder = root.builder(); + builder.child(ASYNC).setProperty(leaseName, lease); + mergeWithConcurrencyCheck(builder, checkpoint, beforeLease); + } + + boolean isDirty() { + return updates > 0; + } + + void close() throws CommitFailedException { + NodeBuilder builder = store.getRoot().builder(); + NodeBuilder async = builder.child(ASYNC); + async.removeProperty(name + "-lease"); + mergeWithConcurrencyCheck(builder, async.getString(name), lease); + } @Override public void indexUpdate() throws CommitFailedException { - if (!dirty) { - dirty = true; - preAsyncRun(store, name); + updates++; + if (updates % 100 == 0) { + long now = System.currentTimeMillis(); + if (now + ASYNC_TIMEOUT > lease) { + long newLease = now + 2 * ASYNC_TIMEOUT; + NodeBuilder builder = store.getRoot().builder(); + builder.child(ASYNC).setProperty(name + "-lease", newLease); + mergeWithConcurrencyCheck(builder, checkpoint, lease); + lease = newLease; + } } } @@ -141,20 +179,26 @@ public class AsyncIndexUpdate implements Runnable { public synchronized void run() { log.debug("Running background index task {}", name); - if (isAlreadyRunning(store, name)) { - log.debug("The {} indexer is already running; skipping this update", name); + NodeState root = store.getRoot(); + + // check for concurrent updates + NodeState async = root.getChildNode(ASYNC); + if (async.getLong(name + "-lease") > System.currentTimeMillis()) { + log.debug("Another copy of the {} index update is already running;" + + " skipping this update", name); return; } + // find the last indexed state, and check if there are recent changes NodeState before; - NodeState root = store.getRoot(); - String refCheckpoint = root.getChildNode(ASYNC).getString(name); - if (refCheckpoint != null) { - NodeState state = store.retrieve(refCheckpoint); + String beforeCheckpoint = async.getString(name); + if (beforeCheckpoint != null) { + NodeState state = store.retrieve(beforeCheckpoint); if (state == null) { log.warn("Failed to retrieve previously indexed checkpoint {};" - + " rerunning the initial {} index update", - refCheckpoint, name); + + " re-running the initial {} index update", + beforeCheckpoint, name); + beforeCheckpoint = null; before = MISSING_NODE; } else if (noVisibleChanges(state, root)) { log.debug("No changes since last checkpoint;" @@ -168,43 +212,84 @@ public class AsyncIndexUpdate implements Runnable { before = MISSING_NODE; } - String checkpoint = store.checkpoint(lifetime); - NodeState after = store.retrieve(checkpoint); + // there are some recent changes, so let's create a new checkpoint + String afterCheckpoint = store.checkpoint(lifetime); + NodeState after = store.retrieve(afterCheckpoint); if (after == null) { log.warn("Unable to retrieve newly created checkpoint {}," - + " skipping the {} index update", checkpoint, name); + + " skipping the {} index update", afterCheckpoint, name); return; } - NodeBuilder builder = store.getRoot().builder(); - NodeBuilder async = builder.child(ASYNC); + String checkpointToRelease = afterCheckpoint; + try { + updateIndex(before, beforeCheckpoint, after, afterCheckpoint); + + // the update succeeded, i.e. it no longer fails + if (failing) { + log.info("Index update {} no longer fails", name); + failing = false; + } + + // the update succeeded, so we can release the earlier checkpoint + // otherwise the new checkpoint associated with the failed update + // will get released in the finally block + checkpointToRelease = beforeCheckpoint; - AsyncUpdateCallback callback = new AsyncUpdateCallback(); + } catch (CommitFailedException e) { + if (e == CONCURRENT_UPDATE) { + log.debug("Concurrent update detected in the {} index update", name); + } else if (failing) { + log.debug("The {} index update is still failing", name, e); + } else { + log.warn("The {} index update failed", name, e); + failing = true; + } + + } finally { + if (checkpointToRelease != null) { // null during initial indexing + store.release(checkpointToRelease); + } + } + } + + private void updateIndex( + NodeState before, String beforeCheckpoint, + NodeState after, String afterCheckpoint) + throws CommitFailedException { + // start collecting runtime statistics preAsyncRunStatsStats(indexStats); - IndexUpdate indexUpdate = new IndexUpdate( - provider, name, after, builder, callback); - - CommitFailedException exception = EditorDiff.process( - indexUpdate, before, after); - if (exception == null) { - if (callback.dirty) { - async.setProperty(name, checkpoint); - try { - store.merge(builder, newCommitHook(name, refCheckpoint), - CommitInfo.EMPTY); - } catch (CommitFailedException e) { - if (e != CONCURRENT_UPDATE) { - exception = e; - } - } + + // create an update callback for tracking index updates + // and maintaining the update lease + AsyncUpdateCallback callback = + new AsyncUpdateCallback(beforeCheckpoint); + try { + NodeBuilder builder = store.getRoot().builder(); + + IndexUpdate indexUpdate = + new IndexUpdate(provider, name, after, builder, callback); + CommitFailedException exception = + EditorDiff.process(indexUpdate, before, after); + if (exception != null) { + throw exception; + } + + if (callback.isDirty() || before == MISSING_NODE) { + builder.child(ASYNC).setProperty(name, afterCheckpoint); + mergeWithConcurrencyCheck( + builder, beforeCheckpoint, callback.lease); + if (switchOnSync) { reindexedDefinitions.addAll( indexUpdate.getReindexedDefinitions()); + } else { + postAsyncRunStatsStatus(indexStats); } } else if (switchOnSync) { - log.debug("No changes detected after diff, will try to switch to synchronous updates on " - + reindexedDefinitions); - async.setProperty(name, checkpoint); + log.debug("No changes detected after diff; will try to" + + " switch to synchronous updates on {}", + reindexedDefinitions); // no changes after diff, switch to sync on the async defs for (String path : reindexedDefinitions) { @@ -217,126 +302,49 @@ public class AsyncIndexUpdate implements Runnable { } } - try { - store.merge(builder, newCommitHook(name, refCheckpoint), - CommitInfo.EMPTY); - reindexedDefinitions.clear(); - } catch (CommitFailedException e) { - if (e != CONCURRENT_UPDATE) { - exception = e; - } - } + mergeWithConcurrencyCheck( + builder, beforeCheckpoint, callback.lease); + reindexedDefinitions.clear(); } + } finally { + callback.close(); } - postAsyncRunStatsStatus(indexStats); - // checkpoints cleanup - if (exception != null || (exception == null && !callback.dirty)) { - log.debug("The {} index update failed; releasing the related checkpoint {}", - name, checkpoint); - store.release(checkpoint); - } else { - if (refCheckpoint != null) { - log.debug( - "The {} index update succeeded; releasing the previous checkpoint {}", - name, refCheckpoint); - store.release(refCheckpoint); - } - } - - if (exception != null) { - if (!failing) { - log.warn("Index update {} failed", name, exception); - } - failing = true; - } else { - if (failing) { - log.info("Index update {} no longer fails", name); - } - failing = false; - } + postAsyncRunStatsStatus(indexStats); } - private static CommitHook newCommitHook( - final String name, final String checkpoint) { - return new CompositeHook( - new ConflictHook(new AnnotatingConflictHandler()), - new EditorHook(new ConflictValidatorProvider()), - new CommitHook() { + private void mergeWithConcurrencyCheck( + NodeBuilder builder, final String checkpoint, final long lease) + throws CommitFailedException { + CommitHook concurrentUpdateCheck = new CommitHook() { @Override @Nonnull public NodeState processCommit( NodeState before, NodeState after, CommitInfo info) throws CommitFailedException { // check for concurrent updates by this async task - String checkpointAfterRebase = - before.getChildNode(ASYNC).getString(name); - if (Objects.equal(checkpoint, checkpointAfterRebase)) { - return postAsyncRunNodeStatus(after.builder(), name) - .getNodeState(); + NodeState async = before.getChildNode(ASYNC); + if (Objects.equal(checkpoint, async.getString(name)) + && lease == async.getLong(name + "-lease")) { + return after; } else { + new Exception(checkpoint + " - " + async.getString(name) + + " / " + lease + " - " + async.getLong(name + "-lease")).printStackTrace(); throw CONCURRENT_UPDATE; } } - }); - } - - private static void preAsyncRun(NodeStore store, String name) throws CommitFailedException { - NodeBuilder builder = store.getRoot().builder(); - preAsyncRunNodeStatus(builder, name); - store.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY); - } - - private static boolean isAlreadyRunning(NodeStore store, String name) { - NodeState indexState = store.getRoot().getChildNode(INDEX_DEFINITIONS_NAME); - - //Probably the first run - if (!indexState.exists()) { - return false; - } - - //Check if already running or timed out - if (STATUS_RUNNING.equals(indexState.getString(name + "-status"))) { - PropertyState startTime = indexState.getProperty(name + "-start"); - Calendar start = Conversions.convert(startTime.getValue(Type.DATE)).toCalendar(); - Calendar now = Calendar.getInstance(); - long delta = now.getTimeInMillis() - start.getTimeInMillis(); - - //Check if the job has timed out and we need to take over - if (TimeUnit.MILLISECONDS.toMinutes(delta) > ASYNC_TIMEOUT) { - log.info("Async job found which stated on {} has timed out in {} minutes. " + - "This node would take over the job.", - startTime.getValue(Type.DATE), ASYNC_TIMEOUT); - return false; - } - return true; - } - - return false; - } - - private static void preAsyncRunNodeStatus(NodeBuilder builder, String name) { - String now = now(); - builder.getChildNode(INDEX_DEFINITIONS_NAME) - .setProperty(name + "-status", STATUS_RUNNING) - .setProperty(name + "-start", now, Type.DATE) - .removeProperty(name + "-done"); + }; + CompositeHook hooks = new CompositeHook( + new ConflictHook(new AnnotatingConflictHandler()), + new EditorHook(new ConflictValidatorProvider()), + concurrentUpdateCheck); + store.merge(builder, hooks, CommitInfo.EMPTY); } private static void preAsyncRunStatsStats(AsyncIndexStats stats) { stats.start(now()); } - private static NodeBuilder postAsyncRunNodeStatus( - NodeBuilder builder, String name) { - String now = now(); - builder.getChildNode(INDEX_DEFINITIONS_NAME) - .setProperty(name + "-status", STATUS_DONE) - .setProperty(name + "-done", now, Type.DATE) - .removeProperty(name + "-start"); - return builder; - } - - private static void postAsyncRunStatsStatus(AsyncIndexStats stats) { + private static void postAsyncRunStatsStatus(AsyncIndexStats stats) { stats.done(now()); } diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/IndexUpdate.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/IndexUpdate.java index 75f0f31..914f23f 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/IndexUpdate.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/IndexUpdate.java @@ -102,7 +102,7 @@ public class IndexUpdate implements Editor { this.provider = parent.provider; this.async = parent.async; this.root = parent.root; - this.builder = parent.builder.child(checkNotNull(name)); + this.builder = parent.builder.getChildNode(checkNotNull(name)); this.updateCallback = parent.updateCallback; }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1877_716e1237.diff
bugs-dot-jar_data_OAK-93_0be7e8f0
--- BugID: OAK-93 Summary: Tree has wrong parent after move Description: |- After a move operation Tree.getParent() still returns the old parent. {code} Tree x = r.getChild("x"); Tree y = r.getChild("y"); root.move("x", "y/x"); assertEquals("y", x.getParent().getName()); // Fails {code} diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/core/TreeImpl.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/core/TreeImpl.java index 9631cbe..d20d820 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/core/TreeImpl.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/core/TreeImpl.java @@ -21,6 +21,7 @@ package org.apache.jackrabbit.oak.core; import org.apache.jackrabbit.oak.api.CoreValue; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.Tree; +import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.oak.spi.state.NodeStateBuilder; @@ -29,8 +30,10 @@ import org.apache.jackrabbit.oak.spi.state.NodeStore; import org.apache.jackrabbit.oak.util.Function1; import org.apache.jackrabbit.oak.util.Iterators; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; /** * Implementation of tree based on {@link NodeStateBuilder}s. Each subtree @@ -42,43 +45,46 @@ public class TreeImpl implements Tree { /** Underlying store */ private final NodeStore store; + private final NodeStateBuilder rootBuilder; + /** * Underlying persistent state or {@code null} if this instance represents an * added tree */ private final NodeState baseState; - private final NodeStateBuilder builder; - /** Listener for changes on this tree */ private final Listener listener; + /** Parent of this tree */ + private TreeImpl parent; + /** Name of this tree */ private String name; - /** Parent of this tree */ - private TreeImpl parent; + // FIXME: should be synchronized, and weak refs + private final Map<String, TreeImpl> children = new HashMap<String, TreeImpl>(); - private TreeImpl(NodeStore store, NodeState baseState, NodeStateBuilder builder, + private TreeImpl(NodeStore store, NodeState baseState, NodeStateBuilder rootBuilder, TreeImpl parent, String name, Listener listener) { this.store = store; - this.builder = builder; + this.rootBuilder = rootBuilder; this.baseState = baseState; this.listener = listener; - this.name = name; this.parent = parent; + this.name = name; } /** * Create a new instance which represents the root of a tree. * @param store underlying store to the tree - * @param nodeStateBuilder builder for the root + * @param rootBuilder builder for the root * @param listener change listener for the tree. May be {@code null} if * listening to changes is not needed. */ - TreeImpl(NodeStore store, NodeStateBuilder nodeStateBuilder, Listener listener) { - this(store, nodeStateBuilder.getNodeState(), nodeStateBuilder, null, "", listener); + TreeImpl(NodeStore store, NodeStateBuilder rootBuilder, Listener listener) { + this(store, rootBuilder.getNodeState(), rootBuilder, null, "", listener); } /** @@ -147,15 +153,14 @@ public class TreeImpl implements Tree { @Override public String getPath() { + // Shortcut for root if (parent == null) { - return name; - } - else { - String path = parent.getPath(); - return path.isEmpty() - ? name - : path + '/' + name; + return ""; } + + StringBuilder sb = new StringBuilder(); + buildPath(sb); + return sb.toString(); } @Override @@ -233,17 +238,22 @@ public class TreeImpl implements Tree { @Override public TreeImpl getChild(String name) { - NodeStateBuilder childBuilder = builder.getChildBuilder(name); - if (childBuilder == null) { - return null; + TreeImpl child = children.get(name); + if (child != null) { + return child; } - else { - NodeState childBaseState = baseState == null - ? null - : baseState.getChildNode(name); - return new TreeImpl(store, childBaseState, childBuilder, this, name, listener); + if (!hasChild(name)) { + return null; } + + NodeState childBaseState = baseState == null + ? null + : baseState.getChildNode(name); + + child = new TreeImpl(store, childBaseState, rootBuilder, this, name, listener); + children.put(name, child); + return child; } @Override @@ -307,14 +317,24 @@ public class TreeImpl implements Tree { return new Iterable<Tree>() { @Override public Iterator<Tree> iterator() { + final NodeState nodeState = getNodeState(); + Iterator<? extends ChildNodeEntry> childEntries = - getNodeState().getChildNodeEntries().iterator(); + nodeState.getChildNodeEntries().iterator(); return Iterators.map(childEntries, new Function1<ChildNodeEntry, Tree>() { @Override public Tree apply(ChildNodeEntry entry) { - NodeStateBuilder childBuilder = builder.getChildBuilder(entry.getName()); - return new TreeImpl(store, childBuilder.getNodeState(), childBuilder, TreeImpl.this, entry.getName(), listener); + String childName = entry.getName(); + TreeImpl child = children.get(entry.getName()); + if (child != null) { + return child; + } + + NodeState childNodeState = nodeState.getChildNode(childName); + child = new TreeImpl(store, childNodeState, rootBuilder, TreeImpl.this, childName, listener); + children.put(childName, child); + return child; } }); } @@ -323,24 +343,27 @@ public class TreeImpl implements Tree { @Override public Tree addChild(String name) { - if (builder.addNode(name) != null) { + if (getBuilder().addNode(name) != null) { listener.addChild(this, name); } - return getChild(name); + TreeImpl child = getChild(name); + children.put(name, child); + return child; } @Override public boolean removeChild(String name) { - boolean result = builder.removeNode(name); + boolean result = getBuilder().removeNode(name); if (result) { listener.removeChild(this, name); + children.remove(name); } return result; } @Override public PropertyState setProperty(String name, CoreValue value) { - PropertyState property = builder.setProperty(name, value); + PropertyState property = getBuilder().setProperty(name, value); if (listener != null) { listener.setProperty(this, name, value); } @@ -349,7 +372,7 @@ public class TreeImpl implements Tree { @Override public PropertyState setProperty(String name, List<CoreValue> values) { - PropertyState property = builder.setProperty(name, values); + PropertyState property = getBuilder().setProperty(name, values); if (listener != null) { listener.setProperty(this, name, values); } @@ -358,7 +381,7 @@ public class TreeImpl implements Tree { @Override public void removeProperty(String name) { - builder.removeProperty(name); + getBuilder().removeProperty(name); if (listener != null) { listener.removeProperty(this, name); } @@ -374,8 +397,13 @@ public class TreeImpl implements Tree { * when {@code destName} already exists at {@code destParent} */ public boolean move(TreeImpl destParent, String destName) { - boolean result = builder.moveTo(destParent.builder, destName); + NodeStateBuilder builder = getBuilder(); + NodeStateBuilder destParentBuilder = destParent.getBuilder(); + boolean result = builder.moveTo(destParentBuilder, destName); if (result) { + parent.children.remove(name); + destParent.children.put(destName, this); + TreeImpl oldParent = parent; String oldName = name; @@ -398,7 +426,7 @@ public class TreeImpl implements Tree { * when {@code destName} already exists at {@code destParent} */ public boolean copy(TreeImpl destParent, String destName) { - boolean result = builder.copyTo(destParent.builder, destName); + boolean result = getBuilder().copyTo(destParent.getBuilder(), destName); if (result) { if (listener != null) { listener.copy(parent, name, destParent.getChild(destName)); @@ -410,8 +438,30 @@ public class TreeImpl implements Tree { //------------------------------------------------------------< private >--- + private void buildPath(StringBuilder sb) { + if (parent != null) { + parent.buildPath(sb); + if (sb.length() > 0) { + sb.append('/'); + } + sb.append(name); + } + } + + private NodeStateBuilder getBuilder() { + NodeStateBuilder builder = rootBuilder; + for (String name : PathUtils.elements(getPath())) { + builder = builder.getChildBuilder(name); + if (builder == null) { + throw new IllegalStateException("Stale NodeStateBuilder for " + getPath()); + } + } + + return builder; + } + private NodeState getNodeState() { - return builder.getNodeState(); + return getBuilder().getNodeState(); } private boolean isSame(NodeState state1, NodeState state2) { diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateBuilder.java index d35d82e..5c477f8 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/kernel/KernelNodeStateBuilder.java @@ -28,27 +28,28 @@ import java.util.List; public class KernelNodeStateBuilder implements NodeStateBuilder { private final NodeStateBuilderContext context; - private String path; + private KernelNodeStateBuilder parent; + private String name; - private KernelNodeStateBuilder(NodeStateBuilderContext context, String path) { + private KernelNodeStateBuilder(NodeStateBuilderContext context, KernelNodeStateBuilder parent, String name) { this.context = context; - this.path = path; + this.parent = parent; + this.name = name; } public static NodeStateBuilder create(NodeStateBuilderContext context) { - return new KernelNodeStateBuilder(context, ""); + return new KernelNodeStateBuilder(context, null, ""); } - @Override public NodeState getNodeState() { - return context.getNodeState(path); + return context.getNodeState(getPath()); } @Override public NodeStateBuilder getChildBuilder(String name) { return hasChild(name) - ? new KernelNodeStateBuilder(context, PathUtils.concat(path, name)) + ? new KernelNodeStateBuilder(context, this, name) : null; } @@ -58,9 +59,9 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { return null; } else { - String targetPath = PathUtils.concat(path, name); + String targetPath = PathUtils.concat(getPath(), name); context.addNode(nodeState, targetPath); - return new KernelNodeStateBuilder(context, targetPath); + return new KernelNodeStateBuilder(context, this, name); } } @@ -70,16 +71,16 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { return null; } else { - String targetPath = PathUtils.concat(path, name); + String targetPath = PathUtils.concat(getPath(), name); context.addNode(targetPath); - return new KernelNodeStateBuilder(context, targetPath); + return new KernelNodeStateBuilder(context, this, name); } } @Override public boolean removeNode(String name) { if (hasChild(name)) { - context.removeNode(PathUtils.concat(path, name)); + context.removeNode(PathUtils.concat(getPath(), name)); return true; } else { @@ -91,10 +92,10 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { public PropertyState setProperty(String name, CoreValue value) { PropertyState property = new PropertyStateImpl(name, value); if (hasProperty(name)) { - context.setProperty(property, path); + context.setProperty(property, getPath()); } else { - context.addProperty(property, path); + context.addProperty(property, getPath()); } return property; } @@ -103,10 +104,10 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { public PropertyState setProperty(String name, List<CoreValue> values) { PropertyState property = new PropertyStateImpl(name, values); if (hasProperty(name)) { - context.setProperty(property, path); + context.setProperty(property, getPath()); } else { - context.addProperty(property, path); + context.addProperty(property, getPath()); } return property; } @@ -114,7 +115,7 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { @Override public void removeProperty(String name) { if (hasProperty(name)) { - context.removeProperty(PathUtils.concat(path, name)); + context.removeProperty(PathUtils.concat(getPath(), name)); } } @@ -129,10 +130,13 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { } KernelNodeStateBuilder destParentBuilder = (KernelNodeStateBuilder) destParent; - String destPath = PathUtils.concat(destParentBuilder.path, destName); + String destPath = PathUtils.concat(destParentBuilder.getPath(), destName); + + context.moveNode(getPath(), destPath); + + name = destName; + parent = destParentBuilder; - context.moveNode(path, destPath); - path = destPath; return true; } @@ -147,9 +151,9 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { } KernelNodeStateBuilder destParentBuilder = (KernelNodeStateBuilder) destParent; - String destPath = PathUtils.concat(destParentBuilder.path, destName); + String destPath = PathUtils.concat(destParentBuilder.getPath(), destName); - context.copyNode(path, destPath); + context.copyNode(getPath(), destPath); return true; } @@ -161,6 +165,27 @@ public class KernelNodeStateBuilder implements NodeStateBuilder { //------------------------------------------------------------< private >--- + private String getPath() { + // Shortcut for root + if (parent == null) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + buildPath(sb); + return sb.toString(); + } + + private void buildPath(StringBuilder sb) { + if (parent != null) { + parent.buildPath(sb); + if (sb.length() > 0) { + sb.append('/'); + } + sb.append(name); + } + } + private boolean hasChild(String name) { return getNodeState().getChildNode(name) != null; }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-93_0be7e8f0.diff
bugs-dot-jar_data_OAK-888_6d82cb64
--- BugID: OAK-888 Summary: PathUtils#getDepth returns 1 for empty path Description: |- PathUtils#getDepths that the root path / has depth 0. however, passing in a empty string is accepted and returns 1. according to the API contract getDepth is counting the number of elements in the path which for "" should IMO be zero. diff --git a/oak-commons/src/main/java/org/apache/jackrabbit/oak/commons/PathUtils.java b/oak-commons/src/main/java/org/apache/jackrabbit/oak/commons/PathUtils.java index 6e68cb0..f82ec93 100644 --- a/oak-commons/src/main/java/org/apache/jackrabbit/oak/commons/PathUtils.java +++ b/oak-commons/src/main/java/org/apache/jackrabbit/oak/commons/PathUtils.java @@ -185,6 +185,9 @@ public final class PathUtils { public static int getDepth(String path) { assert isValid(path); + if (path.isEmpty()) { + return 0; + } int count = 1, i = 0; if (isAbsolutePath(path)) { if (denotesRootPath(path)) {
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-888_6d82cb64.diff
bugs-dot-jar_data_OAK-537_a8493efc
--- BugID: OAK-537 Summary: The Property2Index eagerly and unnecessarily fetches all data Description: | Currently, the Property2Index (as well as the PropertyIndex and the NodeTypeIndex) loads all paths into a hash set. This is even the case for the getCost operation, which should be fast and therefore not load too much data. This strategy can cause ouf-of-memory if the result is too big. Also, loading all data is not necessary unless the user reads all rows. Instead, the index should only load data on demand. Also, the getCost operation should only estimate the number of read nodes, and not actually read the data. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/p2/Property2IndexLookup.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/p2/Property2IndexLookup.java index bbf71e3..7a31ae6 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/p2/Property2IndexLookup.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/p2/Property2IndexLookup.java @@ -18,6 +18,7 @@ package org.apache.jackrabbit.oak.plugins.index.p2; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME; +import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; @@ -25,6 +26,7 @@ import javax.annotation.Nullable; import org.apache.jackrabbit.oak.api.PropertyState; import org.apache.jackrabbit.oak.api.PropertyValue; import org.apache.jackrabbit.oak.api.Type; +import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.plugins.index.IndexConstants; import org.apache.jackrabbit.oak.plugins.index.p2.strategy.ContentMirrorStoreStrategy; import org.apache.jackrabbit.oak.plugins.index.p2.strategy.IndexStoreStrategy; @@ -72,24 +74,24 @@ public class Property2IndexLookup { * @return true if the property is indexed */ public boolean isIndexed(String name, String path) { - if (getIndexDefinitionNode(name) != null) { - return true; - } - - // TODO use PathUtils - if (path.startsWith("/")) { - path = path.substring(1); - } - int slash = path.indexOf('/'); - if (slash == -1) { - return false; + return isIndexed(root, name, path); + } + + private static boolean isIndexed(NodeState root, String name, String path) { + NodeState node = root; + Iterator<String> it = PathUtils.elements(path).iterator(); + while (true) { + if (getIndexDefinitionNode(node, name) != null) { + return true; + } + if (!it.hasNext()) { + break; + } + node = node.getChildNode(it.next()); } - - NodeState child = root.getChildNode(path.substring(0, slash)); - return new Property2IndexLookup(child).isIndexed( - name, path.substring(slash)); + return false; } - + /** * Searches for a given <code>String<code> value within this index. * @@ -112,69 +114,33 @@ public class Property2IndexLookup { * @return the set of matched paths */ public Set<String> find(String name, PropertyValue value) { + NodeState state = getIndexDefinitionNode(root, name); + if (state == null || state.getChildNode(":index") == null) { + throw new IllegalArgumentException("No index for " + name); + } Set<String> paths = Sets.newHashSet(); - - NodeState state = getIndexDefinitionNode(name); - if (state != null && state.getChildNode(":index") != null) { - state = state.getChildNode(":index"); - if (value == null) { - paths.addAll(store.find(state, null)); - } else { - paths.addAll(store.find(state, Property2Index.encode(value))); - } + state = state.getChildNode(":index"); + if (value == null) { + paths.addAll(store.find(state, null)); } else { - // No index available, so first check this node for a match - PropertyState property = root.getProperty(name); - if (property != null) { - if (value == null || value.isArray()) { - // let query engine handle property existence and - // multi-valued look ups; - // simply return all nodes that have this property - paths.add(""); - } else { - // does it match any of the values of this property? - for (int i = 0; i < property.count(); i++) { - if (property.getValue(value.getType(), i).equals(value.getValue(value.getType()))) { - paths.add(""); - // no need to check for more matches in this property - break; - } - } - } - } - - // ... and then recursively look up from the rest of the tree - for (ChildNodeEntry entry : root.getChildNodeEntries()) { - String base = entry.getName(); - Property2IndexLookup lookup = - new Property2IndexLookup(entry.getNodeState()); - for (String path : lookup.find(name, value)) { - if (path.isEmpty()) { - paths.add(base); - } else { - paths.add(base + "/" + path); - } - } - } + paths.addAll(store.find(state, Property2Index.encode(value))); } - return paths; } public double getCost(String name, PropertyValue value) { - double cost = 0.0; // TODO the cost method is currently reading all the data - // is not supposed to do that, it is only supposed to estimate - NodeState state = getIndexDefinitionNode(name); - if (state != null && state.getChildNode(":index") != null) { - state = state.getChildNode(":index"); - if (value == null) { - cost += store.count(state, null); - } else { - cost += store.count(state, Property2Index.encode(value)); - } + NodeState state = getIndexDefinitionNode(root, name); + if (state == null || state.getChildNode(":index") == null) { + return Double.POSITIVE_INFINITY; + } + state = state.getChildNode(":index"); + double cost; + if (value == null) { + cost = store.count(state, null); } else { - cost = Double.POSITIVE_INFINITY; + cost = store.count(state, Property2Index.encode(value)); } return cost; } @@ -187,8 +153,8 @@ public class Property2IndexLookup { * index definition node was found */ @Nullable - private NodeState getIndexDefinitionNode(String name) { - NodeState state = root.getChildNode(INDEX_DEFINITIONS_NAME); + private static NodeState getIndexDefinitionNode(NodeState node, String name) { + NodeState state = node.getChildNode(INDEX_DEFINITIONS_NAME); if (state != null) { for (ChildNodeEntry entry : state.getChildNodeEntries()) { PropertyState type = entry.getNodeState().getProperty(IndexConstants.TYPE_PROPERTY_NAME);
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-537_a8493efc.diff
bugs-dot-jar_data_OAK-3377_00b9bc52
--- BugID: OAK-3377 Summary: Two spaces in SQL2 fulltext search -> error Description: "Execute the following SQL2 query (eg, in crx/de's query tool)\nSELECT * FROM [nt:unstructured] AS c WHERE (CONTAINS(c.[jcr:title], 'a b') AND ISDESCENDANTNODE(c, '/content'))\n(note there are 2 spaces between \"a\" and \"b\")\nResult: java.lang.IllegalArgumentException: Invalid expression: 'a b'\n\nIf there is only 1 space between a and b, there is no error. \n\nPer jsr-283, fulltext expressions should be able to have strings of whitespace." diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/fulltext/FullTextParser.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/fulltext/FullTextParser.java index 8217960..1827d72 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/query/fulltext/FullTextParser.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/query/fulltext/FullTextParser.java @@ -163,7 +163,14 @@ public class FullTextParser { } else if (c == '^') { boost = ""; break; - } else if (c == ' ') { + } else if (c <= ' ') { + while (parseIndex < text.length()) { + c = text.charAt(parseIndex); + if (c > ' ') { + break; + } + parseIndex++; + } break; } else { buff.append(c);
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-3377_00b9bc52.diff
bugs-dot-jar_data_OAK-1297_73cc2442
--- BugID: OAK-1297 Summary: MoveDetector does not detect moved nodes that have been moved in an earlier commit already Description: diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java index 75d6c45..31f6236 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryNodeBuilder.java @@ -374,9 +374,7 @@ public class MemoryNodeBuilder implements NodeBuilder { PropertyState base = builder.getBaseState().getProperty(MoveDetector.SOURCE_PATH); PropertyState head = builder.getNodeState().getProperty(MoveDetector.SOURCE_PATH); if (Objects.equal(base, head)) { - if (!builder.hasProperty(MoveDetector.SOURCE_PATH)) { - builder.setProperty(MoveDetector.SOURCE_PATH, path); - } + builder.setProperty(MoveDetector.SOURCE_PATH, path); } }
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1297_73cc2442.diff
bugs-dot-jar_data_OAK-509_b896c926
--- BugID: OAK-509 Summary: Item names starting with '{X}' cause RepositoryException Description: |- The exception is RepositoryException: Invalid name or path: {0} foo E.g. for an item named '{0} foo'. I guess oak-jcr tries to interpret it as a name in expanded form but does not find a namespace uri for '0'. IIRC these names are valid in Jackrabbit 2.x. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/LocalNameMapper.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/LocalNameMapper.java index f17a69b..eb558c5 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/LocalNameMapper.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/namepath/LocalNameMapper.java @@ -40,8 +40,8 @@ public abstract class LocalNameMapper extends GlobalNameMapper { @Override @CheckForNull public String getJcrName(String oakName) { checkNotNull(oakName); - checkArgument(!oakName.startsWith(":")); // hidden name - checkArgument(isExpandedName(oakName)); // expanded name + checkArgument(!oakName.startsWith(":"), oakName); // hidden name + checkArgument(!isExpandedName(oakName), oakName); // expanded name if (hasSessionLocalMappings()) { int colon = oakName.indexOf(':');
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-509_b896c926.diff
bugs-dot-jar_data_OAK-738_8ed779dc
--- BugID: OAK-738 Summary: Assertion error when adding node with expanded name Description: |- {code} node.addNode("{http://foo}new"); {code} results in an assertion error diff --git a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/NodeImpl.java b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/NodeImpl.java index f93c214..752a3e8 100644 --- a/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/NodeImpl.java +++ b/oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/NodeImpl.java @@ -240,8 +240,7 @@ public class NodeImpl<T extends NodeDelegate> extends ItemImpl<T> implements Nod String ntName = primaryNodeTypeName; if (ntName == null) { DefinitionProvider dp = getDefinitionProvider(); - String childName = getOakName(PathUtils.getName(relPath)); - NodeDefinition def = dp.getDefinition(parent.getTree(), childName); + NodeDefinition def = dp.getDefinition(parent.getTree(), oakName); ntName = def.getDefaultPrimaryTypeName(); if (ntName == null) { throw new ConstraintViolationException(
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-738_8ed779dc.diff
bugs-dot-jar_data_OAK-1129_2f95b81f
--- BugID: OAK-1129 Summary: Repeated MongoMK.rebase() always adds new revision Description: MongoMK always adds a new revision to the branch on rebase, even when the branch is already up-to-date. diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeStore.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeStore.java index c92d4f5..4047727 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeStore.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/mongomk/MongoNodeStore.java @@ -747,7 +747,7 @@ public final class MongoNodeStore // empty branch return base.asBranchRevision(); } - if (b.getBase().equals(base)) { + if (b.getBase(branchHead).equals(base)) { return branchHead; } // add a pseudo commit to make sure current head of branch
bugs-dot-jar/jackrabbit-oak_extracted_diff/developer-patch_bugs-dot-jar_OAK-1129_2f95b81f.diff
bugs-dot-jar_data_LOG4J2-177_f91ce934
--- BugID: LOG4J2-177 Summary: ERROR StatusLogger An exception occurred processing Appender udpsocket java.lang.NullPointerException Description: "This seems to be a race condition of some kind. Two threads are exiting at almost exactly the same time, and both print a message as they exit. This exception happens every 3 or 4 times the code is run, so it's easily reproducible.\n\nERROR StatusLogger An exception occurred processing Appender udpsocket java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.net.DatagramOutputStream.flush(DatagramOutputStream.java:93)\n\tat org.apache.logging.log4j.core.appender.OutputStreamManager.flush(OutputStreamManager.java:146)\n\tat org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:117)\n\tat org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:102)\n\tat org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:335)\n\tat org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:316)\n\tat org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:281)\n\tat org.apache.logging.log4j.core.Logger.log(Logger.java:108)\n\tat org.apache.logging.log4j.spi.AbstractLogger.trace(AbstractLogger.java:250)\n\tat com.galmont.automation.framework.gui.handlers.RunCycleHandler$2.run(RunCycleHandler.java:128)\n\tat java.lang.Thread.run(Unknown Source)\n\nMy configuration file:\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration status=\"OFF\">\n\t\n\t<appenders>\n\t\t<Console name=\"console\" target=\"SYSTEM_OUT\">\n\t\t\t<PatternLayout pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n\" />\n\t\t</Console>\n\t\t<Socket name=\"udpsocket\" host=\"localhost\" port=\"90\" protocol=\"UDP\">\n\t\t\t<PatternLayout pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n\" />\n\t\t</Socket>\n\t\t<RollingFile name=\"RollingFile\" fileName=\"logs/app.log\" filePattern=\"logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz\">\n\t\t\t<PatternLayout pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n\" />\n\t\t\t<Policies>\n\t\t\t\t<SizeBasedTriggeringPolicy size=\"20 MB\" />\n\t\t\t</Policies>\n\t\t</RollingFile>\n\t</appenders>\n\t\n\t<loggers>\n\t\t<root level=\"trace\">\n\t\t\t<appender-ref ref=\"console\" />\n\t\t\t<appender-ref ref=\"udpsocket\" />\n\t\t\t<appender-ref ref=\"RollingFile\" />\n\t\t</root>\n\t</loggers>\n\t\n</configuration>" diff --git a/core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java b/core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java index 8d6b3a3..54fde20 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java +++ b/core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java @@ -28,6 +28,7 @@ public class OutputStreamManager extends AbstractManager { private OutputStream os; private byte[] footer = null; + private byte[] header = null; protected OutputStreamManager(final OutputStream os, final String streamName) { super(streamName); @@ -54,6 +55,7 @@ public class OutputStreamManager extends AbstractManager { */ public synchronized void setHeader(final byte[] header) { if (header != null) { + this.header = header; try { this.os.write(header, 0, header.length); } catch (final IOException ioe) { @@ -97,6 +99,13 @@ public class OutputStreamManager extends AbstractManager { protected void setOutputStream(final OutputStream os) { this.os = os; + if (header != null) { + try { + this.os.write(header, 0, header.length); + } catch (final IOException ioe) { + LOGGER.error("Unable to write header", ioe); + } + } } /** diff --git a/core/src/main/java/org/apache/logging/log4j/core/net/DatagramOutputStream.java b/core/src/main/java/org/apache/logging/log4j/core/net/DatagramOutputStream.java index bf2a2e6..2fe3d9a 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/net/DatagramOutputStream.java +++ b/core/src/main/java/org/apache/logging/log4j/core/net/DatagramOutputStream.java @@ -89,7 +89,7 @@ public class DatagramOutputStream extends OutputStream { @Override public synchronized void flush() throws IOException { - if (this.ds != null && this.address != null) { + if (this.data != null && this.ds != null && this.address != null) { final DatagramPacket packet = new DatagramPacket(data, data.length, address, port); ds.send(packet); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-177_f91ce934.diff
bugs-dot-jar_data_LOG4J2-114_afcf92eb
--- BugID: LOG4J2-114 Summary: StructuredDataMessage is incorrectly validating value length instead of key length Description: |- During execution of method SLF4JLogger.log, the following exception is thrown during creation of the StructuredMessage with a key longer than 32 characters. java.lang.IllegalArgumentException: Structured data values are limited to 32 characters. key: memo value: This is a very long test memo to demonstrate the issue The validation should be on key length and not the value length. diff --git a/api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java b/api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java index d3dee6d..b4e6401 100644 --- a/api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java +++ b/api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java @@ -188,8 +188,8 @@ public class StructuredDataMessage extends MapMessage implements MultiformatMess @Override protected void validate(String key, String value) { - if (value.length() > MAX_LENGTH) { - throw new IllegalArgumentException("Structured data values are limited to 32 characters. key: " + key + + if (key.length() > MAX_LENGTH) { + throw new IllegalArgumentException("Structured data keys are limited to 32 characters. key: " + key + " value: " + value); } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-114_afcf92eb.diff
bugs-dot-jar_data_LOG4J2-892_f9b0bbee
--- BugID: LOG4J2-892 Summary: JUL adapter does not map Log4j's FATAL level to a JUL level Description: |- JUL module does not map Log4j's FATAL level. See {{org.apache.logging.log4j.jul.DefaultLevelConverter}}. diff --git a/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java b/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java index 01d5aa3..b79478b 100644 --- a/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java +++ b/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java @@ -32,7 +32,7 @@ public class DefaultLevelConverter implements LevelConverter { private final Map<java.util.logging.Level, Level> JDK_TO_LOG4J = new IdentityHashMap<java.util.logging.Level, Level>(9); private final Map<Level, java.util.logging.Level> LOG4J_TO_JDK = - new IdentityHashMap<Level, java.util.logging.Level>(9); + new IdentityHashMap<Level, java.util.logging.Level>(10); public DefaultLevelConverter() { JDK_TO_LOG4J.put(java.util.logging.Level.OFF, Level.OFF); @@ -52,6 +52,7 @@ public class DefaultLevelConverter implements LevelConverter { LOG4J_TO_JDK.put(Level.INFO, java.util.logging.Level.INFO); LOG4J_TO_JDK.put(Level.WARN, java.util.logging.Level.WARNING); LOG4J_TO_JDK.put(Level.ERROR, java.util.logging.Level.SEVERE); + LOG4J_TO_JDK.put(Level.FATAL, java.util.logging.Level.SEVERE); LOG4J_TO_JDK.put(Level.ALL, java.util.logging.Level.ALL); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-892_f9b0bbee.diff
bugs-dot-jar_data_LOG4J2-1372_ffedf33f
--- BugID: LOG4J2-1372 Summary: XMLLayout indents, but not the first child tag (<Event>) Description: "I am using log4j 2.5 to print the logs via XMLLayout. I have set compact=\"true\", hence the new line and indents of sub tags work correctly. However I have noticed that the first child tag is not indented correctly. \n\nFollowing is such a sample where <Events> and <Event> are at the same indent level (0 indent). \n\n{code:xml}\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">\n<Event xmlns=\"http://logging.apache.org/log4j/2.0/events\" timeMillis=\"1460974404123\" thread=\"main\" level=\"INFO\" loggerName=\"com.foo.Bar\" endOfBatch=\"true\" loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLogger\" threadId=\"11\" threadPriority=\"5\">\n <Message>First Msg tag must be in level 2 after correct indentation</Message>\n</Event>\n\n<Event xmlns=\"http://logging.apache.org/log4j/2.0/events\" timeMillis=\"1460974404133\" thread=\"main\" level=\"INFO\" loggerName=\"com.foo.Bar\" endOfBatch=\"true\" loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLogger\" threadId=\"11\" threadPriority=\"5\">\n <Message>Second Msg tag must also be in level 2 after correct indentation</Message>\n</Event>\n\n</Events>\n{code}\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java index 763f42a..3b34957 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java @@ -19,12 +19,15 @@ package org.apache.logging.log4j.core.layout; import java.util.HashSet; import java.util.Set; +import javax.xml.stream.XMLStreamException; + import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.jackson.JsonConstants; import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jYamlObjectMapper; import org.apache.logging.log4j.core.jackson.XmlConstants; +import org.codehaus.stax2.XMLStreamWriter2; import com.fasterxml.jackson.core.PrettyPrinter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; @@ -72,6 +75,8 @@ abstract class JacksonFactory { static class XML extends JacksonFactory { + static final int DEFAULT_INDENT = 1; + @Override protected String getPropertNameForContextMap() { return XmlConstants.ELT_CONTEXT_MAP; @@ -100,7 +105,7 @@ abstract class JacksonFactory { @Override protected PrettyPrinter newPrettyPrinter() { - return new DefaultXmlPrettyPrinter(); + return new Log4jXmlPrettyPrinter(DEFAULT_INDENT); } } @@ -137,6 +142,38 @@ abstract class JacksonFactory { } } + /** + * When &lt;Event&gt;s are written into a XML file; the "Event" object is not the root element, but an element named + * &lt;Events&gt; created using {@link #getHeader()} and {@link #getFooter()} methods.<br/> + * {@link com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter} is used to print the Event object into + * XML; hence it assumes &lt;Event&gt; tag as the root element, so it prints the &lt;Event&gt; tag without any + * indentation. To add an indentation to the &lt;Event&gt; tag; hence an additional indentation for any + * sub-elements, this class is written. As an additional task, to avoid the blank line printed after the ending + * &lt;/Event&gt; tag, {@link #writePrologLinefeed(XMLStreamWriter2)} method is also overridden. + */ + static class Log4jXmlPrettyPrinter extends DefaultXmlPrettyPrinter { + + private static final long serialVersionUID = 1L; + + Log4jXmlPrettyPrinter(int nesting) { + _nesting = nesting; + } + + @Override + public void writePrologLinefeed(XMLStreamWriter2 sw) throws XMLStreamException { + // nothing + } + + /** + * Sets the nesting level to 1 rather than 0, so the "Event" tag will get indentation of next level below root. + */ + @Override + public DefaultXmlPrettyPrinter createInstance() { + return new Log4jXmlPrettyPrinter(XML.DEFAULT_INDENT); + } + + } + abstract protected String getPropertNameForContextMap(); abstract protected String getPropertNameForSource();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1372_ffedf33f.diff
bugs-dot-jar_data_LOG4J2-378_ef8517e4
--- BugID: LOG4J2-378 Summary: Logging generates file named ${sys on some systems Description: "In a webapp I'm setting a system property in my apps ServletContextListener, and using that system property in my log4j2.xml file, like so:\n{code}\n<appender type=\"FastFile\" name=\"File\" fileName=\"${sys:catalina.home}/logs/${sys:application-name}.log\">\n{code}\nOn my Windows machine, a log file named \"${sys.\" (always 0 bytes) is being created instead of a log file with the application-name. The same war deployed on one of our linux servers does not create a ${sys.\" file and instead creates a log file with the intended application-name. \n\nI should note that the files DO appear in the directory that sys:catalina.home should resolve to. They appear elsewhere when I don't use sys:catalina.home so I'm quite sure that this variable is resolving correctly and it is the sys:application-name which is the problem.\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java index a768f4e..f50293f 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java @@ -71,6 +71,8 @@ public class Interpolator implements StrLookup { lookups.put("sys", new SystemPropertiesLookup()); lookups.put("env", new EnvironmentLookup()); lookups.put("jndi", new JndiLookup()); + lookups.put("date", new DateLookup()); + lookups.put("ctx", new ContextMapLookup()); try { if (Class.forName("javax.servlet.ServletContext") != null) { lookups.put("web", new WebLookup());
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-378_ef8517e4.diff
bugs-dot-jar_data_LOG4J2-1067_4786a739
--- BugID: LOG4J2-1067 Summary: ThrowableProxy getExtendedStackTraceAsString throws NPE on deserialized nested exceptions Description: "In a similar vein to LOG4J2-914, I also am attempting to use log4j as a daemon log server. The fix for LOG4J2-914 only solved the NPE problem for one dimensional exceptions. Nested exceptions also cause an NPE in the current implementation. \ Here is a test/patch diff for the bug:\n\n{code}\n---\n .../org/apache/logging/log4j/core/impl/ThrowableProxy.java \ | 2 +-\n .../org/apache/logging/log4j/core/impl/ThrowableProxyTest.java | 10 ++++++++++\n 2 files changed, 11 insertions(+), 1 deletion(-)\n\ndiff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java\nindex 67d55ec..307de58 100644\n--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java\n+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java\n@@ -207,7 +207,7 @@ public class ThrowableProxy implements Serializable {\n return;\n \ }\n sb.append(\"Caused by: \").append(cause).append(EOL);\n- this.formatElements(sb, cause.commonElementCount, cause.getThrowable().getStackTrace(),\n+ this.formatElements(sb, cause.commonElementCount, cause.getStackTrace(),\n cause.extendedStackTrace, ignorePackages);\n this.formatCause(sb, cause.causeProxy, ignorePackages);\n \ }\ndiff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java\nindex 7019aa2..6eb5dbc 100644\n--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java\n+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java\n@@ -146,6 +146,16 @@ public class ThrowableProxyTest {\n \n assertEquals(proxy.getExtendedStackTraceAsString(), proxy2.getExtendedStackTraceAsString());\n }\n+ \n+ @Test\n+ public void testSerialization_getExtendedStackTraceAsStringWithNestedThrowable() throws Exception {\n+ final Throwable throwable = new RuntimeException(new IllegalArgumentException(\"This is a test\"));\n+ final ThrowableProxy proxy = new ThrowableProxy(throwable);\n+ \ final byte[] binary = serialize(proxy);\n+ final ThrowableProxy proxy2 = deserialize(binary);\n+\n+ assertEquals(proxy.getExtendedStackTraceAsString(), proxy2.getExtendedStackTraceAsString());\n+ }\n \n @Test\n public void testSerializationWithUnknownThrowable() throws Exception {\n-- \n{code}" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java index 67d55ec..d0800cc 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java @@ -202,15 +202,15 @@ public class ThrowableProxy implements Serializable { } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") - private void formatCause(final StringBuilder sb, final ThrowableProxy cause, final List<String> ignorePackages) { - if (cause == null) { - return; - } - sb.append("Caused by: ").append(cause).append(EOL); - this.formatElements(sb, cause.commonElementCount, cause.getThrowable().getStackTrace(), - cause.extendedStackTrace, ignorePackages); - this.formatCause(sb, cause.causeProxy, ignorePackages); - } + private void formatCause(final StringBuilder sb, final ThrowableProxy cause, final List<String> ignorePackages) { + if (cause == null) { + return; + } + sb.append("Caused by: ").append(cause).append(EOL); + this.formatElements(sb, cause.commonElementCount, cause.getStackTrace(), cause.extendedStackTrace, + ignorePackages); + this.formatCause(sb, cause.causeProxy, ignorePackages); + } private void formatElements(final StringBuilder sb, final int commonCount, final StackTraceElement[] causedTrace, final ExtendedStackTraceElement[] extStackTrace, final List<String> ignorePackages) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1067_4786a739.diff
bugs-dot-jar_data_LOG4J2-464_484c865f
--- BugID: LOG4J2-464 Summary: 'JSON Syntax: LoggerConfig - multiple AppenderRef entries' Description: "How does one assign multiple AppenderRef entries to a logger when using JSON syntax? I've tried numerous formats but none of them appear to work. Exampe below.\n\n\"loggers\": {\n \"logger\": [\n {\n \"name\": \"helloWorld\",\n \"level\": \"info\",\n \"additivity\": \"true\",\n \"AppenderRef\": [\n {\n \"ref\": \"File Routing Appender\"\n },\n {\n \"ref\": \"Database Routing Appender\"\n }\n ]\n }\n \ ],\n \"root\": {\n \"level\": \"info\",\n \"AppenderRef\": {\n \"ref\": \"Console Appender\"\n }\n }\n }\n\n2013-12-11 08:32:07,012 DEBUG Calling createLogger on class org.apache.logging.log4j.core.config.LoggerConfig for element logger with params(additivity=\"true\", level=\"info\", name=\"helloWorld\", includeLocation=\"null\", AppenderRef={}, Properties={}, Configuration(Hello World Config), null)\n\nThe only way I've been able to hack this (up to a maximum of two AppenderRefs) is to use the appender-ref alias in conjunction with AppenderRef e.g.:\n\"loggers\": {\n \"logger\": [\n \n {\n \"name\": \"helloWorld\",\n \"level\": \"info\",\n \"additivity\": \"true\",\n \"AppenderRef\": {\n \t\"ref\":\"File Routing Appender\"\n },\n \"appender-ref\": {\n \t\"ref\":\"Database Routing Appender\"\n }\n \ }\n ],\n \"root\": {\n \"level\": \"info\",\n \"AppenderRef\": {\n \"ref\": \"Console Appender\"\n }\n }\n \t\t}\n2013-12-11 08:51:54,977 DEBUG Calling createLogger on class org.apache.logging.log4j.core.config.LoggerConfig for element logger with params(additivity=\"true\", level=\"info\", name=\"helloWorld\", includeLocation=\"null\", AppenderRef={File Routing Appender, Database Routing Appender}, Properties={}, Configuration(Hello World Config), null)" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/JSONConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/JSONConfiguration.java index be62509..892c45b 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/JSONConfiguration.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/JSONConfiguration.java @@ -232,7 +232,16 @@ public class JSONConfiguration extends BaseConfiguration implements Reconfigurab if (itemEntry.getValue().isObject()) { LOGGER.debug("Processing node for object " + itemEntry.getKey()); itemChildren.add(constructNode(itemEntry.getKey(), item, itemEntry.getValue())); + } else if (itemEntry.getValue().isArray()) { + JsonNode array = itemEntry.getValue(); + String entryName = itemEntry.getKey(); + LOGGER.debug("Processing array for object " + entryName); + final PluginType<?> itemEntryType = pluginManager.getPluginType(entryName); + for (int j = 0; j < array.size(); ++j) { + itemChildren.add(constructNode(entryName, item, array.get(j))); + } } + } children.add(item); } @@ -240,6 +249,8 @@ public class JSONConfiguration extends BaseConfiguration implements Reconfigurab LOGGER.debug("Processing node for object " + entry.getKey()); children.add(constructNode(entry.getKey(), node, n)); } + } else { + LOGGER.debug("Node {} is of type {}", entry.getKey(), n.getNodeType()); } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-464_484c865f.diff
bugs-dot-jar_data_LOG4J2-385_7c2ce5cf
--- BugID: LOG4J2-385 Summary: Unable to roll log files monthly Description: Attempting to use FastRollingFile appender and configure log file rollover to occur monthly. When {{filePattern="logs/app-%d\{yyyy-MM}.log.gz"}} is used, at application startup an archive file is created immediately (app-2013-01.log.gz) even if no log previously existed. A log file is created, but only a single entry is made into the log. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessor.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessor.java index 5a10f1a..82fc0ca 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessor.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessor.java @@ -102,6 +102,7 @@ public class PatternProcessor { nextFileTime = cal.getTimeInMillis(); return nextTime; } + cal.set(Calendar.MONTH, currentCal.get(Calendar.MONTH)); if (frequency == RolloverFrequency.MONTHLY) { increment(cal, Calendar.MONTH, increment, modulus); nextTime = cal.getTimeInMillis(); @@ -110,7 +111,9 @@ public class PatternProcessor { return nextTime; } if (frequency == RolloverFrequency.WEEKLY) { + cal.set(Calendar.WEEK_OF_YEAR, currentCal.get(Calendar.WEEK_OF_YEAR)); increment(cal, Calendar.WEEK_OF_YEAR, increment, modulus); + cal.set(Calendar.DAY_OF_WEEK, currentCal.getFirstDayOfWeek()); nextTime = cal.getTimeInMillis(); cal.add(Calendar.WEEK_OF_YEAR, -1); nextFileTime = cal.getTimeInMillis(); @@ -124,11 +127,11 @@ public class PatternProcessor { nextFileTime = cal.getTimeInMillis(); return nextTime; } - cal.set(Calendar.HOUR, currentCal.get(Calendar.HOUR)); + cal.set(Calendar.HOUR_OF_DAY, currentCal.get(Calendar.HOUR_OF_DAY)); if (frequency == RolloverFrequency.HOURLY) { - increment(cal, Calendar.HOUR, increment, modulus); + increment(cal, Calendar.HOUR_OF_DAY, increment, modulus); nextTime = cal.getTimeInMillis(); - cal.add(Calendar.HOUR, -1); + cal.add(Calendar.HOUR_OF_DAY, -1); nextFileTime = cal.getTimeInMillis(); return nextTime; } @@ -148,6 +151,7 @@ public class PatternProcessor { nextFileTime = cal.getTimeInMillis(); return nextTime; } + cal.set(Calendar.MILLISECOND, currentCal.get(Calendar.MILLISECOND)); increment(cal, Calendar.MILLISECOND, increment, modulus); nextTime = cal.getTimeInMillis(); cal.add(Calendar.MILLISECOND, -1);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-385_7c2ce5cf.diff
bugs-dot-jar_data_LOG4J2-1099_3f41ff48
--- BugID: LOG4J2-1099 Summary: AbstractStringLayout implements Serializable, but is not Serializable Description: "{{org.apache.logging.log4j.core.layout.AbstractLayout}} line 34 :\n{code}\n \ // TODO: Charset is not serializable. Implement read/writeObject() ?\n private final Charset charset;\n{code}\n\nThe developer has recognised that this class claims to be serializable, but is not actually serializable.\n\nThis actually has wide impact due to the fact that the Logger is holding onto the Layout via the {{org.apache.logging.log4j.core.Logger.PrivateConfig#config}} (XML in my case). Many projects, including Spring, do not use static Loggers and prefer getClass type approaches off of their abstract classes, i.e.:\n{code}\nprotected final Log logger = LogFactory.getLog(getClass());\n{code} \nThis actually can lead to use of spring session beans, which are serialized with the session, trying to serialize the logger also and failing due to this bug." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/AbstractStringLayout.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/AbstractStringLayout.java index c928d62..255c73b 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/AbstractStringLayout.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/AbstractStringLayout.java @@ -16,6 +16,9 @@ */ package org.apache.logging.log4j.core.layout; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -46,8 +49,8 @@ public abstract class AbstractStringLayout extends AbstractLayout<String> { /** * The charset for the formatted message. */ - // TODO: Charset is not serializable. Implement read/writeObject() ? - private final Charset charset; + // LOG4J2-1099: charset cannot be final due to serialization needs, so we serialize as charset name instead + private transient Charset charset; private final String charsetName; private final boolean useCustomEncoding; @@ -97,6 +100,17 @@ public abstract class AbstractStringLayout extends AbstractLayout<String> { return null; } + private void writeObject(final ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.writeUTF(charset.name()); + } + + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + final String charsetName = in.readUTF(); + charset = Charset.forName(charsetName); + } + /** * Returns a {@code StringBuilder} that this Layout implementation can use to write the formatted log event to. *
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1099_3f41ff48.diff
bugs-dot-jar_data_LOG4J2-832_411dad65
--- BugID: LOG4J2-832 Summary: ThrowableProxy fails if a class in logged stack trace throws java.lang.Error from initializer Description: "When the Logger attempts to log a message with an exception stack trace, it uses the ThrowableProxy class to introspect classes in the stack trace frames.\n\nIf the class sun.reflect.misc.Trampoline is in the stack trace, the introspection performed by ThrowableProxy will fail causing a java.lang.Error to be thrown by the Logger call.\n\nThe sun.reflect.misc.Trampoline class is used by the sun.reflect.misc.MethodUtil class to perform reflection-based method invocations. MethodUtil is widely used by libraries to perform method invocations. I've encountered this problem when invoking methods over JMX and inside Jetty.\n\nI am classifying this as a blocker because it means that any logging statement that is logging a Throwable message containing a MethodUtil-based reflection stack trace can cause a java.lang.Error to be thrown by Log4j2. \n\nI will attach a unit test for this failure." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java index 2320ad7..51a924e 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java @@ -500,7 +500,7 @@ public class ThrowableProxy implements Serializable { if (clazz != null) { return clazz; } - } catch (final Exception ignore) { + } catch (final Throwable ignore) { // Ignore exception. } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-832_411dad65.diff
bugs-dot-jar_data_LOG4J2-398_2c966ad9
--- BugID: LOG4J2-398 Summary: DateLookup not parsed for FastRollingFile appender Description: "I'm trying to create a Log4j2 configuration file that will create a log file using DateLookup so that the current date and time are in the filename (so it matches the logging used in our other products). This is what the appender configuration looks like:\n\n{code:borderStyle=solid|language=XML}\n<FastRollingFile name=\"Rolling\" fileName=\"log/$${date:yyyyMMdd-HHmmss} - myApp.log\" filePattern=\"log/$${date:yyyyMMdd-HHmmss} - myApp-%i.log\">\n\t<immediateFlush>true</immediateFlush>\n\t<suppressExceptions>false</suppressExceptions>\n\t<PatternLayout>\n\t\t<pattern>%d %p %c{1.} [%t] $${env:USER} %m%n</pattern>\n\t</PatternLayout>\n\t<Policies>\n\t\t<OnStartupTriggeringPolicy />\n\t\t<SizeBasedTriggeringPolicy size=\"100 MB\"/>\n\t</Policies>\n</FastRollingFile>\n{code}\n\nHowever when the log file is generated the filename is \"${date\". I've tried different variations and haven't been able to get this lookup to work at all." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java index 986d2b9..b203fb3 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java @@ -243,22 +243,28 @@ public class BaseConfiguration extends AbstractFilterable implements Configurati protected void doConfigure() { boolean setRoot = false; boolean setLoggers = false; - for (final Node child : rootNode.getChildren()) { - createConfiguration(child, null); - if (child.getObject() == null) { - continue; + if (rootNode.hasChildren() && rootNode.getChildren().get(0).getName().equalsIgnoreCase("Properties")) { + Node first = rootNode.getChildren().get(0); + createConfiguration(first, null); + if (first.getObject() != null) { + subst.setVariableResolver((StrLookup) first.getObject()); } + } else { + final Map<String, String> map = (Map<String, String>) componentMap.get(CONTEXT_PROPERTIES); + final StrLookup lookup = map == null ? null : new MapLookup(map); + subst.setVariableResolver(new Interpolator(lookup)); + } + + for (final Node child : rootNode.getChildren()) { if (child.getName().equalsIgnoreCase("Properties")) { if (tempLookup == subst.getVariableResolver()) { - subst.setVariableResolver((StrLookup) child.getObject()); - } else { LOGGER.error("Properties declaration must be the first element in the configuration"); } continue; - } else if (tempLookup == subst.getVariableResolver()) { - final Map<String, String> map = (Map<String, String>) componentMap.get(CONTEXT_PROPERTIES); - final StrLookup lookup = map == null ? null : new MapLookup(map); - subst.setVariableResolver(new Interpolator(lookup)); + } + createConfiguration(child, null); + if (child.getObject() == null) { + continue; } if (child.getName().equalsIgnoreCase("Appenders")) { appenders = (ConcurrentMap<String, Appender>) child.getObject();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-398_2c966ad9.diff
bugs-dot-jar_data_LOG4J2-478_11763dee
--- BugID: LOG4J2-478 Summary: The message and ndc fields are not JavaScript escaped in JSONLayout Description: The output of the JSONLayout includes the "message" field as is. If there are any embedded newlines, quote, etc, this renders the JSON output as invalid. To correct this, the "message" field should be properly JavaScript escaped. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/Transform.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/Transform.java index 6c68e4d..a502245 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/Transform.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/Transform.java @@ -139,7 +139,7 @@ public final class Transform { final int len = input.length(); for (int i = 0; i < len; i++) { final char ch = input.charAt(i); - final String escBs = "\\\\"; + final String escBs = "\\"; switch (ch) { case '"': buf.append(escBs); diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JSONLayout.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JSONLayout.java index a6a8af0..a9005d1 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JSONLayout.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JSONLayout.java @@ -189,7 +189,7 @@ public class JSONLayout extends AbstractStringLayout { if (jsonSupported) { buf.append(((MultiformatMessage) msg).getFormattedMessage(FORMATS)); } else { - Transform.appendEscapingCDATA(buf, event.getMessage().getFormattedMessage()); + buf.append(Transform.escapeJsonControlCharacters(event.getMessage().getFormattedMessage())); } buf.append('\"'); } @@ -198,7 +198,7 @@ public class JSONLayout extends AbstractStringLayout { buf.append(","); buf.append(this.eol); buf.append("\"ndc\":"); - Transform.appendEscapingCDATA(buf, event.getContextStack().toString()); + buf.append(Transform.escapeJsonControlCharacters(event.getContextStack().toString())); buf.append("\""); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-478_11763dee.diff
bugs-dot-jar_data_LOG4J2-523_837dcd89
--- BugID: LOG4J2-523 Summary: LocalizedMessage serialization is broken Description: |- You can serialize a LocalizedMessage but you get an exception when it is deserialized, an EOF exception. See the tests in https://svn.apache.org/repos/asf/logging/log4j/log4j2/trunk/log4j-api/src/test/java/org/apache/logging/log4j/message/LocalizedMessageTest.java diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java index 8889d5f..40e3324 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java @@ -265,6 +265,7 @@ public class LocalizedMessage implements Message, LoggerNameAwareMessage { stringArgs[i] = obj.toString(); ++i; } + out.writeObject(stringArgs); } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { @@ -273,10 +274,7 @@ public class LocalizedMessage implements Message, LoggerNameAwareMessage { messagePattern = in.readUTF(); baseName = in.readUTF(); final int length = in.readInt(); - stringArgs = new String[length]; - for (int i = 0; i < length; ++i) { - stringArgs[i] = in.readUTF(); - } + stringArgs = (String[]) in.readObject(); logger = StatusLogger.getLogger(); resourceBundle = null; argArray = null;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-523_837dcd89.diff
bugs-dot-jar_data_LOG4J2-470_50340d0c
--- BugID: LOG4J2-470 Summary: Resolution of ${hostName} in log4j2.xml file only works after first reference Description: "I am using $\\{hostName} to include the hostname in the log file. When I use it it resolves to \"$\\{hostName}\" the first time it is referred to in the log and then the proper hostname after that.\n\nExample configuration (comment out the \"Properties\" section to duplicate):\n{code}\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Configuration monitorInterval=\"60\"\tname=\"SMSLog4JConfiguration\"> <!-- add this to spit out debug about configuration: 'status=\"debug\"' -->\n\n\t<!-- This seems to be a bug, but the $hostName seems to need to be referenced\n\t once before it can be used. Maybe it gets correct in a future log4j2 release --> \n\t<Properties>\n\t\t<Property name=\"theHostName\">${hostName}</Property>\n\t</Properties>\n\n\n\t<Appenders>\n\t\t<RollingFile name=\"RollingFileAppender\" fileName=\"/applicationlogs/CTMSApplicationService-${hostName}.log\"\n\t\t\tfilePattern=\"/applicationlogs/${hostName}-%d{MM-dd-yyyy}-%i.log\">\n\t\t\t<Policies>\n\t\t\t\t<OnStartupTriggeringPolicy />\n\t\t\t\t<TimeBasedTriggeringPolicy interval=\"24\" modulate=\"true\" />\n\t\t\t</Policies>\n\t\t\t<PatternLayout pattern=\"[%d{ISO8601}] [%t] %-5level %logger{6} - %msg%n\" />\n\t\t</RollingFile>\n\t</Appenders>\n\t<Loggers>\n\t\t<!-- default for \"includeLocation\" is false, but I want to be clear -->\n\t\t<Root level=\"debug\" includeLocation=\"false\">\n\t\t\t<AppenderRef ref=\"RollingFileAppender\" />\n\t\t</Root>\n\t</Loggers>\n</Configuration>\n{code}" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java index 0759bc4..a8af6ae 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java @@ -334,10 +334,9 @@ public class LoggerContext implements org.apache.logging.log4j.spi.LoggerContext } final Configuration prev = this.config; config.addListener(this); - final Map<String, String> map = new HashMap<String, String>(); - map.put("hostName", NetUtils.getLocalHostname()); - map.put("contextName", name); - config.addComponent(Configuration.CONTEXT_PROPERTIES, map); + final ConcurrentMap<String, String> map = config.getComponent(Configuration.CONTEXT_PROPERTIES); + map.putIfAbsent("hostName", NetUtils.getLocalHostname()); + map.putIfAbsent("contextName", name); config.start(); this.config = config; updateLoggers(); diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java index 2b5c41f..986d2b9 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/BaseConfiguration.java @@ -104,7 +104,9 @@ public class BaseConfiguration extends AbstractFilterable implements Configurati private ConcurrentMap<String, LoggerConfig> loggers = new ConcurrentHashMap<String, LoggerConfig>(); - private final StrLookup tempLookup = new Interpolator(); + private ConcurrentMap<String, String> properties = new ConcurrentHashMap<String, String>(); + + private final StrLookup tempLookup = new Interpolator(properties); private final StrSubstitutor subst = new StrSubstitutor(tempLookup); @@ -120,6 +122,7 @@ public class BaseConfiguration extends AbstractFilterable implements Configurati * Constructor. */ protected BaseConfiguration() { + componentMap.put(Configuration.CONTEXT_PROPERTIES, properties); pluginManager = new PluginManager("Core"); rootNode = new Node(); } @@ -127,7 +130,7 @@ public class BaseConfiguration extends AbstractFilterable implements Configurati @Override @SuppressWarnings("unchecked") public Map<String, String> getProperties() { - return (Map<String, String>) componentMap.get(CONTEXT_PROPERTIES); + return properties; } /** diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PropertiesPlugin.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PropertiesPlugin.java index b804d45..6c5c3f3 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PropertiesPlugin.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/PropertiesPlugin.java @@ -44,7 +44,7 @@ public final class PropertiesPlugin { public static StrLookup configureSubstitutor(@PluginElement("Properties") final Property[] properties, @PluginConfiguration final Configuration config) { if (properties == null) { - return new Interpolator(null); + return new Interpolator(config.getProperties()); } final Map<String, String> map = new HashMap<String, String>(config.getProperties()); diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java index bf463de..a768f4e 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/Interpolator.java @@ -60,7 +60,14 @@ public class Interpolator implements StrLookup { * Create the default Interpolator using only Lookups that work without an event. */ public Interpolator() { - this.defaultLookup = new MapLookup(new HashMap<String, String>()); + this((Map<String, String>) null); + } + + /** + * Create the dInterpolator using only Lookups that work without an event and initial properties. + */ + public Interpolator(Map<String, String> properties) { + this.defaultLookup = new MapLookup(properties == null ? new HashMap<String, String>() : properties); lookups.put("sys", new SystemPropertiesLookup()); lookups.put("env", new EnvironmentLookup()); lookups.put("jndi", new JndiLookup()); diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jWebInitializerImpl.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jWebInitializerImpl.java index 7d14a14..78708dc 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jWebInitializerImpl.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jWebInitializerImpl.java @@ -17,12 +17,15 @@ package org.apache.logging.log4j.core.web; import java.net.URI; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContext; import javax.servlet.UnavailableException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configurator; +import org.apache.logging.log4j.core.helpers.NetUtils; import org.apache.logging.log4j.core.impl.ContextAnchor; import org.apache.logging.log4j.core.impl.Log4jContextFactory; import org.apache.logging.log4j.core.lookup.Interpolator; @@ -48,7 +51,8 @@ final class Log4jWebInitializerImpl implements Log4jWebInitializer { } } - private final StrSubstitutor substitutor = new StrSubstitutor(new Interpolator()); + private final Map<String, String> map = new ConcurrentHashMap<String, String>(); + private final StrSubstitutor substitutor = new StrSubstitutor(new Interpolator(map)); private final ServletContext servletContext; private String name; @@ -60,6 +64,7 @@ final class Log4jWebInitializerImpl implements Log4jWebInitializer { private Log4jWebInitializerImpl(final ServletContext servletContext) { this.servletContext = servletContext; + map.put("hostName", NetUtils.getLocalHostname()); } @Override
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-470_50340d0c.diff
bugs-dot-jar_data_LOG4J2-1008_0c20bfd8
--- BugID: LOG4J2-1008 Summary: org.apache.logging.log4j.core.config.plugins.util.ResolverUtil.extractPath(URL) incorrectly converts '+' characters to spaces Description: org.apache.logging.log4j.core.config.plugins.util.ResolverUtil.extractPath(URL) incorrectly converts '+' characters to spaces. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java index 475ef9c..65da5bc 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java @@ -22,6 +22,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Arrays; @@ -41,36 +42,40 @@ import org.osgi.framework.FrameworkUtil; import org.osgi.framework.wiring.BundleWiring; /** - * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet - * arbitrary conditions. The two most common conditions are that a class implements/extends - * another class, or that is it annotated with a specific annotation. However, through the use - * of the {@link Test} class it is possible to search using arbitrary conditions.</p> + * <p> + * ResolverUtil is used to locate classes that are available in the/a class path and meet arbitrary conditions. The two + * most common conditions are that a class implements/extends another class, or that is it annotated with a specific + * annotation. However, through the use of the {@link Test} class it is possible to search using arbitrary conditions. + * </p> * - * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class - * path that contain classes within certain packages, and then to load those classes and - * check them. By default the ClassLoader returned by - * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden - * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()} - * methods.</p> + * <p> + * A ClassLoader is used to locate all locations (directories and jar files) in the class path that contain classes + * within certain packages, and then to load those classes and check them. By default the ClassLoader returned by + * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden by calling + * {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()} methods. + * </p> * - * <p>General searches are initiated by calling the - * {@link #find(ResolverUtil.Test, String...)} method and supplying - * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b> - * to be scanned for classes that meet the test. There are also utility methods for the common - * use cases of scanning multiple packages for extensions of particular classes, or classes - * annotated with a specific annotation.</p> + * <p> + * General searches are initiated by calling the {@link #find(ResolverUtil.Test, String...)} method and supplying a + * package name and a Test instance. This will cause the named package <b>and all sub-packages</b> to be scanned for + * classes that meet the test. There are also utility methods for the common use cases of scanning multiple packages for + * extensions of particular classes, or classes annotated with a specific annotation. + * </p> * - * <p>The standard usage pattern for the ResolverUtil class is as follows:</p> + * <p> + * The standard usage pattern for the ResolverUtil class is as follows: + * </p> * - *<pre> - *ResolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;(); - *resolver.findImplementation(ActionBean.class, pkg1, pkg2); - *resolver.find(new CustomTest(), pkg1); - *resolver.find(new CustomTest(), pkg2); - *Collection&lt;ActionBean&gt; beans = resolver.getClasses(); - *</pre> + * <pre> + * ResolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;(); + * resolver.findImplementation(ActionBean.class, pkg1, pkg2); + * resolver.find(new CustomTest(), pkg1); + * resolver.find(new CustomTest(), pkg2); + * Collection&lt;ActionBean&gt; beans = resolver.getClasses(); + * </pre> * - * <p>This class was copied and modified from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home + * <p> + * This class was copied and modified from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home * </p> */ public class ResolverUtil { @@ -88,14 +93,14 @@ public class ResolverUtil { private final Set<URI> resourceMatches = new HashSet<URI>(); /** - * The ClassLoader to use when looking for classes. If null then the ClassLoader returned - * by Thread.currentThread().getContextClassLoader() will be used. + * The ClassLoader to use when looking for classes. If null then the ClassLoader returned by + * Thread.currentThread().getContextClassLoader() will be used. */ private ClassLoader classloader; /** - * Provides access to the classes discovered so far. If no calls have been made to - * any of the {@code find()} methods, this set will be empty. + * Provides access to the classes discovered so far. If no calls have been made to any of the {@code find()} + * methods, this set will be empty. * * @return the set of classes that have been discovered. */ @@ -105,16 +110,16 @@ public class ResolverUtil { /** * Returns the matching resources. + * * @return A Set of URIs that match the criteria. */ public Set<URI> getResources() { return resourceMatches; } - /** - * Returns the classloader that will be used for scanning for classes. If no explicit - * ClassLoader has been set by the calling, the context class loader will be used. + * Returns the classloader that will be used for scanning for classes. If no explicit ClassLoader has been set by + * the calling, the context class loader will be used. * * @return the ClassLoader that will be used to scan for classes */ @@ -123,19 +128,24 @@ public class ResolverUtil { } /** - * Sets an explicit ClassLoader that should be used when scanning for classes. If none - * is set then the context classloader will be used. + * Sets an explicit ClassLoader that should be used when scanning for classes. If none is set then the context + * classloader will be used. * - * @param classloader a ClassLoader to use when scanning for classes + * @param classloader + * a ClassLoader to use when scanning for classes */ - public void setClassLoader(final ClassLoader classloader) { this.classloader = classloader; } + public void setClassLoader(final ClassLoader classloader) { + this.classloader = classloader; + } /** - * Attempts to discover classes that pass the test. Accumulated - * classes can be accessed by calling {@link #getClasses()}. + * Attempts to discover classes that pass the test. Accumulated classes can be accessed by calling + * {@link #getClasses()}. * - * @param test the test to determine matching classes - * @param packageNames one or more package names to scan (including subpackages) for classes + * @param test + * the test to determine matching classes + * @param packageNames + * one or more package names to scan (including subpackages) for classes */ public void find(final Test test, final String... packageNames) { if (packageNames == null) { @@ -148,14 +158,14 @@ public class ResolverUtil { } /** - * Scans for classes starting at the package provided and descending into subpackages. - * Each class is offered up to the Test as it is discovered, and if the Test returns - * true the class is retained. Accumulated classes can be fetched by calling - * {@link #getClasses()}. + * Scans for classes starting at the package provided and descending into subpackages. Each class is offered up to + * the Test as it is discovered, and if the Test returns true the class is retained. Accumulated classes can be + * fetched by calling {@link #getClasses()}. * - * @param test an instance of {@link Test} that will be used to filter classes - * @param packageName the name of the package from which to start scanning for - * classes, e.g. {@code net.sourceforge.stripes} + * @param test + * an instance of {@link Test} that will be used to filter classes + * @param packageName + * the name of the package from which to start scanning for classes, e.g. {@code net.sourceforge.stripes} */ public void findInPackage(final Test test, String packageName) { packageName = packageName.replace('.', '/'); @@ -198,13 +208,15 @@ public class ResolverUtil { } } catch (final IOException ioe) { LOGGER.warn("could not read entries", ioe); + } catch (URISyntaxException e) { + LOGGER.warn("could not read entries", e); } } } - String extractPath(final URL url) throws UnsupportedEncodingException { + String extractPath(final URL url) throws UnsupportedEncodingException, URISyntaxException { String urlPath = url.getPath(); // same as getFile but without the Query portion - //System.out.println(url.getProtocol() + "->" + urlPath); + // System.out.println(url.getProtocol() + "->" + urlPath); // I would be surprised if URL.getPath() ever starts with "jar:" but no harm in checking if (urlPath.startsWith("jar:")) { @@ -226,39 +238,42 @@ public class ResolverUtil { if (neverDecode.contains(protocol)) { return urlPath; } - if (new File(urlPath).exists()) { + final String cleanPath = new URI(urlPath).getPath(); + if (new File(cleanPath).exists()) { // if URL-encoded file exists, don't decode it - return urlPath; + return cleanPath; } urlPath = URLDecoder.decode(urlPath, Constants.UTF_8.name()); return urlPath; } private void loadImplementationsInBundle(final Test test, final String packageName) { - //Do not remove the cast on the next line as removing it will cause a compile error on Java 7. + // Do not remove the cast on the next line as removing it will cause a compile error on Java 7. @SuppressWarnings("RedundantCast") - final BundleWiring wiring = (BundleWiring) FrameworkUtil.getBundle( - ResolverUtil.class).adapt(BundleWiring.class); + final BundleWiring wiring = (BundleWiring) FrameworkUtil.getBundle(ResolverUtil.class) + .adapt(BundleWiring.class); @SuppressWarnings("unchecked") final Collection<String> list = (Collection<String>) wiring.listResources(packageName, "*.class", - BundleWiring.LISTRESOURCES_RECURSE); + BundleWiring.LISTRESOURCES_RECURSE); for (final String name : list) { addIfMatching(test, name); } } - /** - * Finds matches in a physical directory on a filesystem. Examines all - * files within a directory - if the File object is not a directory, and ends with <i>.class</i> - * the file is loaded and tested to see if it is acceptable according to the Test. Operates - * recursively to find classes within a folder structure matching the package structure. + * Finds matches in a physical directory on a filesystem. Examines all files within a directory - if the File object + * is not a directory, and ends with <i>.class</i> the file is loaded and tested to see if it is acceptable + * according to the Test. Operates recursively to find classes within a folder structure matching the package + * structure. * - * @param test a Test used to filter the classes that are discovered - * @param parent the package name up to this directory in the package hierarchy. E.g. if - * /classes is in the classpath and we wish to examine files in /classes/org/apache then - * the values of <i>parent</i> would be <i>org/apache</i> - * @param location a File object representing a directory + * @param test + * a Test used to filter the classes that are discovered + * @param parent + * the package name up to this directory in the package hierarchy. E.g. if /classes is in the classpath and + * we wish to examine files in /classes/org/apache then the values of <i>parent</i> would be + * <i>org/apache</i> + * @param location + * a File object representing a directory */ private void loadImplementationsInDirectory(final Test test, final String parent, final File location) { final File[] files = location.listFiles(); @@ -285,13 +300,15 @@ public class ResolverUtil { } /** - * Finds matching classes within a jar files that contains a folder structure - * matching the package structure. If the File is not a JarFile or does not exist a warning - * will be logged, but no error will be raised. + * Finds matching classes within a jar files that contains a folder structure matching the package structure. If the + * File is not a JarFile or does not exist a warning will be logged, but no error will be raised. * - * @param test a Test used to filter the classes that are discovered - * @param parent the parent package under which classes must be in order to be considered - * @param jarFile the jar file to be examined for classes + * @param test + * a Test used to filter the classes that are discovered + * @param parent + * the parent package under which classes must be in order to be considered + * @param jarFile + * the jar file to be examined for classes */ private void loadImplementationsInJar(final Test test, final String parent, final File jarFile) { @SuppressWarnings("resource") @@ -325,16 +342,18 @@ public class ResolverUtil { } /** - * Finds matching classes within a jar files that contains a folder structure - * matching the package structure. If the File is not a JarFile or does not exist a warning - * will be logged, but no error will be raised. + * Finds matching classes within a jar files that contains a folder structure matching the package structure. If the + * File is not a JarFile or does not exist a warning will be logged, but no error will be raised. * - * @param test a Test used to filter the classes that are discovered - * @param parent the parent package under which classes must be in order to be considered - * @param stream The jar InputStream + * @param test + * a Test used to filter the classes that are discovered + * @param parent + * the parent package under which classes must be in order to be considered + * @param stream + * The jar InputStream */ private void loadImplementationsInJar(final Test test, final String parent, final String path, - final JarInputStream stream) { + final JarInputStream stream) { try { JarEntry entry; @@ -346,17 +365,19 @@ public class ResolverUtil { } } } catch (final IOException ioe) { - LOGGER.error("Could not search jar file '" + path + "' for classes matching criteria: " + - test + " due to an IOException", ioe); + LOGGER.error("Could not search jar file '" + path + "' for classes matching criteria: " + test + + " due to an IOException", ioe); } } /** - * Add the class designated by the fully qualified class name provided to the set of - * resolved classes if and only if it is approved by the Test supplied. + * Add the class designated by the fully qualified class name provided to the set of resolved classes if and only if + * it is approved by the Test supplied. * - * @param test the test used to determine if the class matches - * @param fqn the fully qualified name of a class + * @param test + * the test used to determine if the class matches + * @param fqn + * the fully qualified name of a class */ protected void addIfMatching(final Test test, final String fqn) { try { @@ -387,21 +408,25 @@ public class ResolverUtil { } /** - * A simple interface that specifies how to test classes to determine if they - * are to be included in the results produced by the ResolverUtil. + * A simple interface that specifies how to test classes to determine if they are to be included in the results + * produced by the ResolverUtil. */ public interface Test { /** - * Will be called repeatedly with candidate classes. Must return True if a class - * is to be included in the results, false otherwise. - * @param type The Class to match against. + * Will be called repeatedly with candidate classes. Must return True if a class is to be included in the + * results, false otherwise. + * + * @param type + * The Class to match against. * @return true if the Class matches. */ boolean matches(Class<?> type); /** * Test for a resource. - * @param resource The URI to the resource. + * + * @param resource + * The URI to the resource. * @return true if the resource matches. */ boolean matches(URI resource);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1008_0c20bfd8.diff
bugs-dot-jar_data_LOG4J2-359_1df1db27
--- BugID: LOG4J2-359 Summary: Log4jServletContextListener does not work on Weblogic 12.1.1 (12c) with web-app version "2.5" Description: "I have Weblogic 12c running. My web-app is version \"2.5\".\n\nFollowing is a snippet from my web.xml \n\n{code:xml}\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txmlns=\"http://java.sun.com/xml/ns/javaee\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n\tid=\"WebApp_ID\" version=\"2.5\">\n\t<display-name>pec-service</display-name>\n\t<context-param>\n\t\t<param-name>log4jConfiguration</param-name>\n\t\t<param-value>file:/C:/log4j/dev.log4j.xml</param-value>\n\t</context-param>\n\n\t<listener> \n\t\t<listener-class>org.apache.logging.log4j.core.web.Log4jServletContextListener</listener-class> \n\t</listener>\t\n\n\t<filter>\n\t\t<filter-name>log4jServletFilter</filter-name>\n\t\t<filter-class>org.apache.logging.log4j.core.web.Log4jServletFilter</filter-class> \n\t</filter>\n\t<filter-mapping>\n\t\t<filter-name>log4jServletFilter</filter-name> \n\t\t<url-pattern>/*</url-pattern>\n\t\t<dispatcher>REQUEST</dispatcher>\n\t\t<dispatcher>FORWARD</dispatcher> \n\t\t<dispatcher>INCLUDE</dispatcher>\n\t\t<dispatcher>ERROR</dispatcher>\n\t</filter-mapping>\n\t\n</web-app>\n{code}\n\nHowever, on my server startup I am getting the following error - \n{code}\n<Aug 16, 2013 3:12:32 PM PDT> <Warning> <HTTP> <BEA-101162> <User defined listener org.apache.logging.log4j.core.web.Log4jServletContextListener failed: java.lang.IllegalStateException: Context destroyed before it was initialized..\njava.lang.IllegalStateException: Context destroyed before it was initialized.\n\tat org.apache.logging.log4j.core.web.Log4jServletContextListener.contextDestroyed(Log4jServletContextListener.java:51)\n\tat weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:583)\n\tat weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)\n\tat weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)\n\tat weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)\n\tTruncated. see log file for complete stacktrace\n> \n<Aug 16, 2013 3:12:32 PM PDT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID \"1376691143681\" for task \"2\". Error is: \"weblogic.application.ModuleException\"\nweblogic.application.ModuleException\n\tat weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1708)\n\tat weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:781)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)\n\tat weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)\n\tTruncated. see log file for complete stacktrace\nCaused By: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:44)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializer(WebAppServletContext.java:1271)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializers(WebAppServletContext.java:1229)\n\tat weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1726)\n\tat weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2740)\n\tTruncated. see log file for complete stacktrace\n> \n<Aug 16, 2013 3:12:32 PM PDT> <Error> <Deployer> <BEA-149202> <Encountered an exception while attempting to commit the 7 task for the application \"_auto_generated_ear_\".> \n<Aug 16, 2013 3:12:32 PM PDT> <Warning> <Deployer> <BEA-149004> <Failures were detected while initiating start task for application \"_auto_generated_ear_\".> \n<Aug 16, 2013 3:12:32 PM PDT> <Warning> <Deployer> <BEA-149078> <Stack trace for message 149004\nweblogic.application.ModuleException\n\tat weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1708)\n\tat weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:781)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)\n\tat weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)\n\tat weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)\n\tTruncated. see log file for complete stacktrace\nCaused By: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:44)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializer(WebAppServletContext.java:1271)\n\tat weblogic.servlet.internal.WebAppServletContext.initContainerInitializers(WebAppServletContext.java:1229)\n\tat weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1726)\n\tat weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2740)\n\tTruncated. see log file for complete stacktrace\n{code}\n\nIf I remove the listener & the filter, it works fine.\n\n{color:red}\nI did some research and found that even though the web-app is version \"2.5\", the {code}Log4jServletContainerInitializer{code} is getting invoked. \n{color}" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java index 6add448..50b0820 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java @@ -23,24 +23,33 @@ import javax.servlet.FilterRegistration; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; +import javax.servlet.UnavailableException; /** * In a Servlet 3.0 or newer environment, this initializer is responsible for starting up Log4j logging before anything - * else happens in application initialization. + * else happens in application initialization. For consistency across all containers, if the effective Servlet major + * version of the application is less than 3.0, this initializer does nothing. */ public class Log4jServletContainerInitializer implements ServletContainerInitializer { @Override public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException { - servletContext.log("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment."); + if (servletContext.getMajorVersion() > 2) { + servletContext.log("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment."); - final Log4jWebInitializer initializer = Log4jWebInitializerImpl.getLog4jWebInitializer(servletContext); - initializer.initialize(); - initializer.setLoggerContext(); // the application is just now starting to start up + final Log4jWebInitializer initializer = Log4jWebInitializerImpl.getLog4jWebInitializer(servletContext); + initializer.initialize(); + initializer.setLoggerContext(); // the application is just now starting to start up - servletContext.addListener(new Log4jServletContextListener()); + servletContext.addListener(new Log4jServletContextListener()); - final FilterRegistration.Dynamic filter = servletContext.addFilter("log4jServletFilter", new Log4jServletFilter()); - filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); + final FilterRegistration.Dynamic filter = + servletContext.addFilter("log4jServletFilter", new Log4jServletFilter()); + if (filter == null) { + throw new UnavailableException("In a Servlet 3.0+ application, you must not define a " + + "log4jServletFilter in web.xml. Log4j 2 defines this for you automatically."); + } + filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); + } } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-359_1df1db27.diff
bugs-dot-jar_data_LOG4J2-368_a8a24357
--- BugID: LOG4J2-368 Summary: PatternLayout in 1.2 bridge missing constructor Description: "java.lang.NoSuchMethodError: org.apache.log4j.PatternLayout.<init>(Ljava/lang/String;)V\n\tat org.apache.velocity.runtime.log.Log4JLogChute.initAppender(Log4JLogChute.java:117) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.log.Log4JLogChute.init(Log4JLogChute.java:85) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:269) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:871) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:262) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.RuntimeInstance.requireInitialization(RuntimeInstance.java:302) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1531) ~[velocity-1.7-dep.jar:1.7]\n\tat org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:343) ~[velocity-1.7-dep.jar:1.7]" diff --git a/log4j-1.2-api/src/main/java/org/apache/log4j/PatternLayout.java b/log4j-1.2-api/src/main/java/org/apache/log4j/PatternLayout.java index 7595f75..a1d77c7 100644 --- a/log4j-1.2-api/src/main/java/org/apache/log4j/PatternLayout.java +++ b/log4j-1.2-api/src/main/java/org/apache/log4j/PatternLayout.java @@ -23,6 +23,10 @@ import org.apache.log4j.spi.LoggingEvent; */ public class PatternLayout extends Layout { + public PatternLayout(String pattern) { + + } + @Override public String format(final LoggingEvent event) { return "";
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-368_a8a24357.diff
bugs-dot-jar_data_LOG4J2-492_24a3bed4
--- BugID: LOG4J2-492 Summary: 'MalformedObjectNameException: Invalid escape sequence... under Jetty' Description: |- Although it is not stopping my webapp from running, I am encountering the following exception when running jetty (via Maven) for a webapp using a trunk build of log4j2. My debug line is also included: {noformat} loggerContext.getName()= WebAppClassLoader=1320771902@4eb9613e 2014-01-09 13:28:52,904 ERROR Could not register mbeans java.lang.IllegalStateException: javax.management.MalformedObjectNameException: Invalid escape sequence '\=' in quoted value at org.apache.logging.log4j.core.jmx.LoggerContextAdmin.<init>(LoggerContextAdmin.java:81) at org.apache.logging.log4j.core.jmx.Server.registerContexts(Server.java:266) at org.apache.logging.log4j.core.jmx.Server.reregisterMBeansAfterReconfigure(Server.java:185) at org.apache.logging.log4j.core.jmx.Server.reregisterMBeansAfterReconfigure(Server.java:150) at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:387) at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:151) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:105) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:33) at org.apache.logging.log4j.LogManager.getContext(LogManager.java:222) at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:103) at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:63) at org.apache.logging.log4j.core.web.Log4jWebInitializerImpl.initializeNonJndi(Log4jWebInitializerImpl.java:136) at org.apache.logging.log4j.core.web.Log4jWebInitializerImpl.initialize(Log4jWebInitializerImpl.java:82) at org.apache.logging.log4j.core.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:41) at org.eclipse.jetty.plus.annotation.ContainerInitializer.callStartup(ContainerInitializer.java:106) at org.eclipse.jetty.annotations.ServletContainerInitializerListener.doStart(ServletContainerInitializerListener.java:107) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.util.component.AggregateLifeCycle.doStart(AggregateLifeCycle.java:81) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:58) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:96) at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:115) at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:763) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:249) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494) at org.mortbay.jetty.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:298) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229) at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:172) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95) at org.eclipse.jetty.server.Server.doStart(Server.java:282) at org.mortbay.jetty.plugin.JettyServer.doStart(JettyServer.java:65) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64) at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:520) at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:365) at org.mortbay.jetty.plugin.JettyRunMojo.execute(JettyRunMojo.java:523) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by: javax.management.MalformedObjectNameException: Invalid escape sequence '\=' in quoted value at javax.management.ObjectName.construct(ObjectName.java:582) at javax.management.ObjectName.<init>(ObjectName.java:1382) at org.apache.logging.log4j.core.jmx.LoggerContextAdmin.<init>(LoggerContextAdmin.java:79) ... 60 more 2014-01-09 13:28:52.989:INFO:/wallboard:Initializing Spring root WebApplicationContext 2014-01-09 13:29:04.645:INFO:/wallboard:Log4jServletContextListener ensuring that Log4j starts up properly. 2014-01-09 13:29:04.651:INFO:/wallboard:Log4jServletFilter initialized. 2014-01-09 13:29:04.778:WARN:oejsh.RequestLogHandler:!RequestLog 2014-01-09 13:29:04.872:INFO:oejs.AbstractConnector:Started [email protected]:8080 [INFO] Started Jetty Server [INFO] Starting scanner at interval of 10 seconds. {noformat} diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java index 537b029..898e5e1 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java @@ -87,6 +87,14 @@ public final class Server { // no need to escape these, but value must be quoted needsQuotes = true; break; + case '\r': + // replace by \\r, no need to quote + sb.append("\\r"); + continue; + case '\n': + // replace by \\n, no need to quote + sb.append("\\n"); + continue; } sb.append(c); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-492_24a3bed4.diff
bugs-dot-jar_data_LOG4J2-991_3cee912e
--- BugID: LOG4J2-991 Summary: Async root logger config is defaulting includeLocation to true without use of Log4jContextSelector system property Description: I'm using the approach detailed here - https://logging.apache.org/log4j/2.x/manual/async.html - under "Mixing Synchronous and Asynchronous Loggers" where we have the <asyncRoot> logger defined. I noticed this was slow so looked into it and noticed the location was being captured but I thought this should default to false for async loggers. Looking into this, the line here - https://github.com/apache/logging-log4j2/blob/master/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfig.java#L239 - the call to includeLocation() is actually calling LoggerConfig.includeLocation() which checks for the existence of the system property (which we don't have set), therefore include location defaults to true. I think instead it should be calling the includeLocation() static method inside of AsyncLoggerConfig here - https://github.com/apache/logging-log4j2/blob/master/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfig.java#L204 - which would end up defaulting this to false correctly as the includeLocation value is actually null since I didn't explicitly configured it. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfig.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfig.java index 9e1cd9a..f87d4e3 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfig.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLoggerConfig.java @@ -236,7 +236,7 @@ public class AsyncLoggerConfig extends LoggerConfig { return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, level, additive, properties, config, - includeLocation(includeLocation)); + AsyncLoggerConfig.includeLocation(includeLocation)); } } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-991_3cee912e.diff
bugs-dot-jar_data_LOG4J2-293_ca59ece6
--- BugID: LOG4J2-293 Summary: classloader URI scheme broken or insufficient when using Log4jContextListener Description: |- I'm trying to migrate to Log4j2, and things looked promising when I spotted Log4jContextListener. However, there are too many holes. Firstly, I tried using classpath: as a scheme, and nothing blew up, so I assumed I'd got it right. Then I *looked at the code* (which shouldn't be how we find out) and eventually discovered some code relating to a 'classloader' scheme. Still silent failure. It seems that the classpath is not being searched, perhaps just the WAR classloader, not the JARs in WEB-INF/lib. Next I tried omitting the / (i.e. using classloader:log4j2.xml) and got a NullPointerException. Can you please document what schemes are supported and what you expect them to do, and *not fail silently* when a configuration file is specified, but nothing happens. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java index 058b630..13ba4ba 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelector.java @@ -28,6 +28,7 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.helpers.Loader; import org.apache.logging.log4j.core.impl.ContextAnchor; import org.apache.logging.log4j.core.impl.ReflectiveCallerClassUtility; @@ -224,6 +225,13 @@ public class ClassLoaderContextSelector implements ContextSelector { final WeakReference<LoggerContext> r = ref.get(); LoggerContext ctx = r.get(); if (ctx != null) { + if (ctx.getConfigLocation() == null && configLocation != null) { + LOGGER.debug("Setting configuration to {}", configLocation); + ctx.setConfigLocation(configLocation); + } else if (ctx.getConfigLocation() != null && !ctx.getConfigLocation().equals(configLocation)) { + LOGGER.warn("locateContext called with URI {}. Existing LoggerContext has URI {}", configLocation, + ctx.getConfigLocation()); + } return ctx; } ctx = new LoggerContext(name, null, configLocation);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-293_ca59ece6.diff
bugs-dot-jar_data_LOG4J2-1406_a523dcd5
--- BugID: LOG4J2-1406 Summary: 2.6 is re-logging prior throwable instead of logging the throwable that is currently passed in by application code Description: | Hi, I just want to make sure you saw the issue I submitted PR for a couple days ago. It seems a very serious issue in 2.6: https://github.com/apache/logging-log4j2/pull/31 Thanks, Trask diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/ReusableParameterizedMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/ReusableParameterizedMessage.java index abfd620..1f4e8b9 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/ReusableParameterizedMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/ReusableParameterizedMessage.java @@ -121,8 +121,10 @@ public class ReusableParameterizedMessage implements ReusableMessage { } private void initThrowable(final Object[] params, final int argCount, final int usedParams) { - if (usedParams < argCount && this.throwable == null && params[argCount - 1] instanceof Throwable) { + if (usedParams < argCount && params[argCount - 1] instanceof Throwable) { this.throwable = (Throwable) params[argCount - 1]; + } else { + this.throwable = null; } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1406_a523dcd5.diff
bugs-dot-jar_data_LOG4J2-763_97203de8
--- BugID: LOG4J2-763 Summary: Async loggers convert message parameters toString at log record writing not at log statement execution Description: "http://javaadventure.blogspot.com/2014/07/log4j-20-async-loggers-and-immutability.html\n\nWhen using parameterized messages, the toString() method of the log messages is not called when the log message is enqueued, rather after the log message has been dequeued for writing. If any of the message parameters are mutable, they can thus have changed state before the log message is written, thus resulting in the logged message content being incorrect.\n\nFrom the blog post, code that demonstrates the problem:\n{code}\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.util.concurrent.atomic.AtomicLong;\n\npublic class App {\n private static final AtomicLong value = new AtomicLong();\n public String toString() {\n return Long.toString(value.get());\n }\n public long next() {\n return value.incrementAndGet();\n \ }\n\n public static void main(String[] args) {\n for (int i = 0; i < 32; i++) {\n new Thread() {\n final Logger logger = LogManager.getLogger(App.class);\n final App instance = new App();\n \ @Override\n public void run() {\n for (int i = 0; i < 100000; i++) {\n logger.warn(\"{} == {}\", instance.next(), instance);\n }\n }\n }.start();\n \ }\n }\n}\n{code}\n\nHere is the first few lines of logging output\n{code}\n2014-07-28 15:59:45,729 WARN t.App [Thread-13] 13 == 13 \n2014-07-28 15:59:45,730 WARN t.App [Thread-29] 29 == 29 \n2014-07-28 15:59:45,729 WARN t.App [Thread-15] 15 == 15 \n2014-07-28 15:59:45,729 WARN t.App [Thread-6] 6 == 6 \n2014-07-28 15:59:45,730 WARN t.App [Thread-30] 30 == 30 \n2014-07-28 15:59:45,729 WARN t.App [Thread-20] 20 == 20 \n2014-07-28 15:59:45,729 WARN t.App [Thread-8] 8 == 8 \n2014-07-28 15:59:45,730 WARN t.App [Thread-28] 28 == 28 \n2014-07-28 15:59:45,729 WARN t.App [Thread-19] 19 == 19 \n2014-07-28 15:59:45,729 WARN t.App [Thread-18] 18 == 18 \n2014-07-28 15:59:45,729 WARN t.App [Thread-5] 5 == 6 \n2014-07-28 15:59:45,731 WARN t.App [Thread-13] 33 == 37 \n2014-07-28 15:59:45,731 WARN t.App [Thread-8] 39 == 39 \n2014-07-28 15:59:45,731 WARN t.App [Thread-28] 40 == 41 \n2014-07-28 15:59:45,731 WARN t.App [Thread-18] 42 == 43 \n2014-07-28 15:59:45,731 WARN t.App [Thread-5] 43 == 43\n{code}\n\nTo make my previous code work with Asynchronous loggers (other than by fixing the mutable state) I would need to log like this:\n\n{code}\nif (logger.isWarnEnabled()) {\n logger.warn(\"{} == {}\", instance.next(), instance.toString());\n}\n{code}\n\n" diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/FormattedMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/FormattedMessage.java index 1c540dd..3ca4b82 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/FormattedMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/FormattedMessage.java @@ -46,12 +46,11 @@ public class FormattedMessage implements Message { this.messagePattern = messagePattern; this.argArray = arguments; this.throwable = throwable; + getFormattedMessage(); // LOG4J2-763 take snapshot of parameters at message construction time } public FormattedMessage(final String messagePattern, final Object[] arguments) { - this.messagePattern = messagePattern; - this.argArray = arguments; - this.throwable = null; + this(messagePattern, arguments, null); } /** @@ -60,9 +59,7 @@ public class FormattedMessage implements Message { * @param arg The parameter. */ public FormattedMessage(final String messagePattern, final Object arg) { - this.messagePattern = messagePattern; - this.argArray = new Object[] {arg}; - this.throwable = null; + this(messagePattern, new Object[] {arg}, null); } /** diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java index c6839b8..2a2246b 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/LocalizedMessage.java @@ -78,6 +78,7 @@ public class LocalizedMessage implements Message, LoggerNameAwareMessage { this.baseName = baseName; this.resourceBundle = null; this.locale = locale; + getFormattedMessage(); // LOG4J2-763 take snapshot of parameters at message construction time } public LocalizedMessage(final ResourceBundle bundle, final Locale locale, final String key, @@ -88,6 +89,7 @@ public class LocalizedMessage implements Message, LoggerNameAwareMessage { this.baseName = null; this.resourceBundle = bundle; this.locale = locale; + getFormattedMessage(); // LOG4J2-763 take snapshot of parameters at message construction time } public LocalizedMessage(final Locale locale, final String key, final Object[] arguments) { diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/MapMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/MapMessage.java index db6826a..4cbef35 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/MapMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/MapMessage.java @@ -26,6 +26,11 @@ import org.apache.logging.log4j.util.Strings; /** * Represents a Message that consists of a Map. + * <p> + * Thread-safety note: the contents of this message can be modified after construction. + * When using asynchronous loggers and appenders it is not recommended to modify this message after the message is + * logged, because it is undefined whether the logged message string will contain the old values or the modified + * values. */ public class MapMessage implements MultiformatMessage { /** diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/MessageFormatMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/MessageFormatMessage.java index 0493b0f..f728324 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/MessageFormatMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/MessageFormatMessage.java @@ -49,6 +49,7 @@ public class MessageFormatMessage implements Message { if (arguments != null && arguments.length > 0 && arguments[arguments.length - 1] instanceof Throwable) { this.throwable = (Throwable) arguments[arguments.length - 1]; } + getFormattedMessage(); // LOG4J2-763 take snapshot of parameters at message construction time } /** diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java index 27f288e..dcccf46 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java @@ -29,6 +29,7 @@ public class ObjectMessage implements Message { private static final long serialVersionUID = -5903272448334166185L; private transient Object obj; + private final String objectString; /** * Create the ObjectMessage. @@ -39,6 +40,9 @@ public class ObjectMessage implements Message { obj = "null"; } this.obj = obj; + + // LOG4J2-763: take snapshot of parameters at message construction time + objectString = String.valueOf(obj); } /** @@ -47,7 +51,7 @@ public class ObjectMessage implements Message { */ @Override public String getFormattedMessage() { - return obj.toString(); + return objectString; } /** @@ -56,7 +60,7 @@ public class ObjectMessage implements Message { */ @Override public String getFormat() { - return obj.toString(); + return objectString; } /** @@ -89,7 +93,7 @@ public class ObjectMessage implements Message { @Override public String toString() { - return "ObjectMessage[obj=" + obj.toString() + ']'; + return "ObjectMessage[obj=" + objectString + ']'; } private void writeObject(final ObjectOutputStream out) throws IOException { diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java index f6007e4..91df370 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java @@ -48,6 +48,7 @@ public class StringFormattedMessage implements Message { if (arguments != null && arguments.length > 0 && arguments[arguments.length - 1] instanceof Throwable) { this.throwable = (Throwable) arguments[arguments.length - 1]; } + getFormattedMessage(); // LOG4J2-763 take snapshot of parameters at message construction time } /** diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java index 246e11b..f6300ee 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java @@ -22,6 +22,11 @@ import org.apache.logging.log4j.util.EnglishEnums; /** * Represents a Message that conforms to an RFC 5424 StructuredData element along with the syslog message. + * <p> + * Thread-safety note: the contents of this message can be modified after construction. + * When using asynchronous loggers and appenders it is not recommended to modify this message after the message is + * logged, because it is undefined whether the logged message string will contain the old values or the modified + * values. * * @see <a href="https://tools.ietf.org/html/rfc5424">RFC 5424</a> */
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-763_97203de8.diff
bugs-dot-jar_data_LOG4J2-395_a19ecc9e
--- BugID: LOG4J2-395 Summary: log4j.configurationFile via classpath URI Description: |- Can't specify log4j.configurationFile as a classpath URI. For eg: -Dlog4j.configurationFile=classpath:log4j/log4j.xml diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java index 8490196..c935512 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java @@ -37,6 +37,8 @@ import org.apache.logging.log4j.core.config.plugins.PluginManager; import org.apache.logging.log4j.core.config.plugins.PluginType; import org.apache.logging.log4j.core.helpers.FileUtils; import org.apache.logging.log4j.core.helpers.Loader; +import org.apache.logging.log4j.core.lookup.Interpolator; +import org.apache.logging.log4j.core.lookup.StrSubstitutor; import org.apache.logging.log4j.status.StatusLogger; import org.apache.logging.log4j.util.PropertiesUtil; @@ -104,6 +106,8 @@ public abstract class ConfigurationFactory { private static ConfigurationFactory configFactory = new Factory(); + protected final StrSubstitutor substitutor = new StrSubstitutor(new Interpolator()); + /** * Returns the ConfigurationFactory. * @return the ConfigurationFactory. @@ -362,10 +366,19 @@ public abstract class ConfigurationFactory { public Configuration getConfiguration(final String name, final URI configLocation) { if (configLocation == null) { - final String config = PropertiesUtil.getProperties().getStringProperty(CONFIGURATION_FILE_PROPERTY); + final String config = this.substitutor.replace( + PropertiesUtil.getProperties().getStringProperty(CONFIGURATION_FILE_PROPERTY)); if (config != null) { - final ClassLoader loader = this.getClass().getClassLoader(); - final ConfigurationSource source = getInputFromString(config, loader); + ConfigurationSource source = null; + try { + source = getInputFromURI(new URI(config)); + } catch (Exception ex) { + // Ignore the error and try as a String. + } + if (source == null) { + final ClassLoader loader = this.getClass().getClassLoader(); + source = getInputFromString(config, loader); + } if (source != null) { for (final ConfigurationFactory factory : factories) { final String[] types = factory.getSupportedTypes();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-395_a19ecc9e.diff
bugs-dot-jar_data_LOG4J2-293_25cb587a
--- BugID: LOG4J2-293 Summary: classloader URI scheme broken or insufficient when using Log4jContextListener Description: |- I'm trying to migrate to Log4j2, and things looked promising when I spotted Log4jContextListener. However, there are too many holes. Firstly, I tried using classpath: as a scheme, and nothing blew up, so I assumed I'd got it right. Then I *looked at the code* (which shouldn't be how we find out) and eventually discovered some code relating to a 'classloader' scheme. Still silent failure. It seems that the classpath is not being searched, perhaps just the WAR classloader, not the JARs in WEB-INF/lib. Next I tried omitting the / (i.e. using classloader:log4j2.xml) and got a NullPointerException. Can you please document what schemes are supported and what you expect them to do, and *not fail silently* when a configuration file is specified, but nothing happens. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java index 7873c79..8490196 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java @@ -88,6 +88,18 @@ public abstract class ConfigurationFactory { */ protected static final String DEFAULT_PREFIX = "log4j2"; + /** + * The name of the classloader URI scheme. + */ + private static final String CLASS_LOADER_SCHEME = "classloader"; + private static final int CLASS_LOADER_SCHEME_LENGTH = CLASS_LOADER_SCHEME.length() + 1; + + /** + * The name of the classpath URI scheme, synonymous with the classloader URI scheme. + */ + private static final String CLASS_PATH_SCHEME = "classpath"; + private static final int CLASS_PATH_SCHEME_LENGTH = CLASS_PATH_SCHEME.length() + 1; + private static volatile List<ConfigurationFactory> factories = null; private static ConfigurationFactory configFactory = new Factory(); @@ -221,9 +233,19 @@ public abstract class ConfigurationFactory { } } final String scheme = configLocation.getScheme(); - if (scheme == null || scheme.equals("classloader")) { + final boolean isClassLoaderScheme = scheme != null && scheme.equals(CLASS_LOADER_SCHEME); + final boolean isClassPathScheme = scheme != null && !isClassLoaderScheme && scheme.equals(CLASS_PATH_SCHEME); + if (scheme == null || isClassLoaderScheme || isClassPathScheme) { final ClassLoader loader = this.getClass().getClassLoader(); - final ConfigurationSource source = getInputFromResource(configLocation.getPath(), loader); + String path; + if (isClassLoaderScheme) { + path = configLocation.toString().substring(CLASS_LOADER_SCHEME_LENGTH); + } else if (isClassPathScheme) { + path = configLocation.toString().substring(CLASS_PATH_SCHEME_LENGTH); + } else { + path = configLocation.getPath(); + } + final ConfigurationSource source = getInputFromResource(path, loader); if (source != null) { return source; } @@ -365,7 +387,7 @@ public abstract class ConfigurationFactory { final String[] types = factory.getSupportedTypes(); if (types != null) { for (final String type : types) { - if (type.equals("*") || configLocation.getPath().endsWith(type)) { + if (type.equals("*") || configLocation.toString().endsWith(type)) { final Configuration config = factory.getConfiguration(name, configLocation); if (config != null) { return config;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-293_25cb587a.diff
bugs-dot-jar_data_LOG4J2-811_7bb1ad47
--- BugID: LOG4J2-811 Summary: SimpleLogger throws ArrayIndexOutOfBoundsException for an empty array Description: "There seems to be an issue with SimpleLogger implementation provided by log4j2. The issue seems to be in the new improved API supporting placeholders and var args when called with an Object Array of size 0.\n\nfor e.g logger.error(\"Hello World {} in {} \" , new Object[0]);\n\nA statement above results in an error as shown below\n\nERROR StatusLogger Unable to locate a logging implementation, using SimpleLogger\nException in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: -1\n at org.apache.logging.log4j.simple.SimpleLogger.logMessage(SimpleLogger.java:157)\n \ at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:1347)\n \ at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:1312)\n \ at org.apache.logging.log4j.spi.AbstractLogger.error(AbstractLogger.java:539)\n \ at TestError.main(TestError.java:21)\n\n\nSolution to place a check in SimpleLogger for checking the size of the array . " diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/simple/SimpleLogger.java b/log4j-api/src/main/java/org/apache/logging/log4j/simple/SimpleLogger.java index a474940..90fc598 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/simple/SimpleLogger.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/simple/SimpleLogger.java @@ -154,7 +154,7 @@ public class SimpleLogger extends AbstractLogger { } final Object[] params = msg.getParameters(); Throwable t; - if (throwable == null && params != null && params[params.length - 1] instanceof Throwable) { + if (throwable == null && params != null && params.length > 0 && params[params.length - 1] instanceof Throwable) { t = (Throwable) params[params.length - 1]; } else { t = throwable;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-811_7bb1ad47.diff
bugs-dot-jar_data_LOG4J2-430_238ce8aa
--- BugID: LOG4J2-430 Summary: RFC5424Layout not working with parametrized messages Description: "Syslog (i.e RFC5424Layout) does not work with parametrized messages. If I do something like this:\n{code}\nlogger.info(\"Hello {}\", \"World\");\n{code}\n\nI get this at the syslog server: \n{code}\nOct 16 18:24:33 10.0.0.3 myApp Hello {}\n{code}\n\nThis is the config file I'm using:\n{code:xml:title=log4j2.xml}\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Configuration>\n <Appenders>\n <Console name=\"STDOUT\" target=\"SYSTEM_OUT\">\n <PatternLayout pattern=\"%d{ISO8601}: %-5p [%t-%c{2}] - %m%n\"/>\n </Console>\n <Syslog name=\"syslog\" format=\"RFC5424\" host=\"10.0.0.1\" port=\"514\" protocol=\"TCP\" appName=\"myApp\" facility=\"LOCAL0\" newLine=\"true\" includeMDC=\"true\" id=\"App\" reconnectionDelay=\"1000\"/>\n </Appenders>\n <Loggers>\n \ <Root level=\"debug\">\n <AppenderRef ref=\"STDOUT\"/>\n <AppenderRef ref=\"syslog\"/>\n </Root>\n </Loggers>\n</Configuration>\n{code}\n\nThe log to stdout is ok though.\n\nAttached you find my patch for this bug." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/RFC5424Layout.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/RFC5424Layout.java index e7aff72..e26fa4d 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/RFC5424Layout.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/RFC5424Layout.java @@ -324,7 +324,8 @@ public class RFC5424Layout extends AbstractStringLayout { private void appendMessage(final StringBuilder buffer, final LogEvent event) { final Message message = event.getMessage(); - final String text = message.getFormat(); + // This layout formats StructuredDataMessages instead of delegating to the Message itself. + final String text = (message instanceof StructuredDataMessage) ? message.getFormat() : message.getFormattedMessage(); if (text != null && text.length() > 0) { buffer.append(" ").append(escapeNewlines(text, escapeNewLine));
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-430_238ce8aa.diff
bugs-dot-jar_data_LOG4J2-676_3b2e880e
--- BugID: LOG4J2-676 Summary: 'Failed to write log event to CouchDB due to error: Connection pool shut down' Description: "I'm trying to setup a NoSQL logger using Apache CouchDB. After logging a single message, the logger fails with the following exception:\n\n{color: blue}\n \ 2014-06-22 10:22:18,590 ERROR An exception occurred processing Appender databaseAppender org.apache.logging.log4j.core.appender.AppenderLoggingException: Failed to write log event to CouchDB due to error: Connection pool shut down\n\tat org.apache.logging.log4j.core.appender.db.nosql.couchdb.CouchDBConnection.insertObject(CouchDBConnection.java:57)\n\tat org.apache.logging.log4j.core.appender.db.nosql.NoSQLDatabaseManager.writeInternal(NoSQLDatabaseManager.java:148)\n\tat org.apache.logging.log4j.core.appender.db.AbstractDatabaseManager.write(AbstractDatabaseManager.java:159)\n\tat org.apache.logging.log4j.core.appender.db.AbstractDatabaseAppender.append(AbstractDatabaseAppender.java:103)\n\tat org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:97)\n\tat org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:425)\n\tat org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:406)\n\tat org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:367)\n\tat org.apache.logging.log4j.core.Logger.log(Logger.java:112)\n\tat org.apache.logging.log4j.spi.AbstractLogger.error(AbstractLogger.java:577)\n\tat be.pw999.kbomap.controller.KboMapController.getJson(KboMapController.java:65)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:601)\n\tat org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:125)\n\tat org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:195)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:91)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:346)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:341)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:101)\n\tat org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:224)\n\tat org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)\n\tat org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:315)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:297)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:267)\n\tat org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)\n\tat org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)\n\tat org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)\n\tat org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)\n\tat org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)\n\tat org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)\n\tat org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)\n\tat org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)\n\tat com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)\n\tat org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)\n\tat com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)\n\tat org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)\n\tat org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)\n\tat org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)\n\tat org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)\n\tat org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)\n\tat org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)\n\tat org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)\n\tat org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)\n\tat org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)\n\tat org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)\n\tat org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)\n\tat org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)\n\tat org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)\n\tat org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)\n\tat org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)\n\tat org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)\n\tat java.lang.Thread.run(Thread.java:722)\nCaused by: java.lang.IllegalStateException: Connection pool shut down\n\tat org.apache.http.util.Asserts.check(Asserts.java:34)\n\tat org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:169)\n\tat org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:217)\n\tat org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:158)\n\tat org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)\n\tat org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)\n\tat org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)\n\tat org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)\n\tat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)\n\tat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)\n\tat org.lightcouch.CouchDbClientBase.executeRequest(CouchDbClientBase.java:409)\n\tat org.lightcouch.CouchDbClientBase.put(CouchDbClientBase.java:517)\n\tat org.lightcouch.CouchDbClientBase.save(CouchDbClientBase.java:273)\n\tat org.apache.logging.log4j.core.appender.db.nosql.couchdb.CouchDBConnection.insertObject(CouchDBConnection.java:51)\n\t... 66 more]]\n{color}\n\n\nThe log4j2.xml file is:\n{code:xml}\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Configuration status=\"info\">\n <Appenders>\n <NoSql name=\"databaseAppender\">\n <CouchDb databaseName=\"kbomaplog\" protocol=\"http\" server=\"127.0.0.1\" port=\"5984\"\n username=\"loguser\" password=\"meh\" />\n </NoSql>\n </Appenders>\n <Loggers>\n <Root level=\"info\">\n <AppenderRef ref=\"databaseAppender\"/>\n </Root>\n </Loggers>\n</Configuration>\n{code}\n\n\nAnd the piece of code I'm using to test is:\n{code}\n\tprivate Logger logger = LogManager.getLogger(KboMapController.class);\n\t\n\t/**\n\t * Does nothing special. Returns a simple JSON object with a count of the code table for testing purposes.\n\t * \n\t * @param id unused\n\t * @param test unused\n\t * @return a JSON representation of the filled in {@link Enterprise} object.\n\t */\n\t@GET\n\t@Produces(MediaType.APPLICATION_JSON)\n\t@Path(\"{id}/{test}\")\n\tpublic Enterprise getJson(@PathParam(\"id\") String id, @PathParam(\"test\") String test) {\n\t\ttry {\n\t\t\tlogger.error(\"whoaaaaaah\");\n\t\t\treturn new Enterprise(\"SUCCESS\", \"COUNT=\" + dao.count());\n\t\t} catch (SQLException e) {\n\t\t\treturn new Enterprise(\"ERROR\", e.getMessage());\n\t\t}\n\n\t}\n{code}\n\nThe same issue occurs when the logger is {{static final}}" diff --git a/log4j-nosql/src/main/java/org/apache/logging/log4j/nosql/appender/NoSQLDatabaseManager.java b/log4j-nosql/src/main/java/org/apache/logging/log4j/nosql/appender/NoSQLDatabaseManager.java index 6f2ea26..d3c5b37 100644 --- a/log4j-nosql/src/main/java/org/apache/logging/log4j/nosql/appender/NoSQLDatabaseManager.java +++ b/log4j-nosql/src/main/java/org/apache/logging/log4j/nosql/appender/NoSQLDatabaseManager.java @@ -51,6 +51,7 @@ public final class NoSQLDatabaseManager<W> extends AbstractDatabaseManager { @Override protected void shutdownInternal() { + // NoSQL doesn't use transactions, so all we need to do here is simply close the client Closer.closeSilent(this.connection); } @@ -155,13 +156,10 @@ public final class NoSQLDatabaseManager<W> extends AbstractDatabaseManager { @Override protected void commitAndClose() { - try { - if (this.connection != null && !this.connection.isClosed()) { - this.connection.close(); - } - } catch (Exception e) { - throw new AppenderLoggingException("Failed to commit and close NoSQL connection in manager.", e); - } + // all NoSQL drivers auto-commit (since NoSQL doesn't generally use the concept of transactions). + // also, all our NoSQL drivers use internal connection pooling and provide clients, not connections. + // thus, we should not be closing the client until shutdown as NoSQL is very different from SQL. + // see LOG4J2-591 and LOG4J2-676 } private NoSQLObject<W>[] convertStackTrace(final StackTraceElement[] stackTrace) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-676_3b2e880e.diff
bugs-dot-jar_data_LOG4J2-1153_8acedb4e
--- BugID: LOG4J2-1153 Summary: Unable to define only rootLogger in a properties file. Description: "I've changed the version of log4j2 from *2.3* to *2.4* in order to load the configuration via properties file. So i have converted the xml file, that defines only {{<Root>}} in {{<Loggers>}} element, into a properties file. \nThis is a preview of the xml file :\n{code:xml}\n <Loggers>\n <Root level=\"info\">\n <AppenderRef ref=\"ConsoleAppender\"/>\n </Root>\n </Loggers>\n{code}\nAnd this is a preview of the properties file :\n\n{code}\nrootLogger.level = info\nrootLogger.appenderRefs = console\nrootLogger.appenderRef.console.ref = ConsoleAppender\n{code}\n\nThis configuration throw a null pointer exception :\n{noformat}Exception in thread \"main\" java.lang.ExceptionInInitializerError\nCaused by: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:132)\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:44)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:491)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:461)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:257)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:493)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:510)\n\tat org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:199)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:146)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:41)\n\tat org.apache.logging.log4j.LogManager.getContext(LogManager.java:264)\n\tat org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:59)\n\tat org.apache.log4j.Logger.getLogger(Logger.java:41)\n{noformat}\n\nIn order to make this configuration work, i had to add the {{loggers}} component and fill the identifiers. My question is why in xml file we can define only a root logger and it works fine, and in a properties file it does not work ? \n " diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java index 58094f0..6be8683 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java @@ -151,7 +151,7 @@ public class PropertiesConfigurationFactory extends ConfigurationFactory { } } String loggerProp = properties.getProperty("loggers"); - if (appenderProp != null) { + if (loggerProp != null) { String[] loggerNames = loggerProp.split(","); for (String loggerName : loggerNames) { String name = loggerName.trim(); @@ -400,7 +400,6 @@ public class PropertiesConfigurationFactory extends ConfigurationFactory { return componentBuilder; } - @SuppressWarnings({"unchecked", "rawtypes"}) private void processRemainingProperties(ComponentBuilder<?> builder, String name, Properties properties) { while (properties.size() > 0) { String propertyName = properties.stringPropertyNames().iterator().next();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1153_8acedb4e.diff
bugs-dot-jar_data_LOG4J2-668_60f64cc1
--- BugID: LOG4J2-668 Summary: AsyncAppender ignores RingBufferLogEvents from AsyncLoggers (when all loggers async by setting context selector) Description: |- AsyncAppender's #append method currently has this code: {code} if (!(logEvent instanceof Log4jLogEvent)) { return; // only know how to Serialize Log4jLogEvents } {code} When all loggers are made asynchronous by setting Log4jContextSelector to {{org.apache.logging.log4j.core.async.AsyncLoggerContextSelector}}, they produce {{RingBufferLogEvent}} instances, not {{Log4jLogEvent}}. These log events will be dropped by AsyncAppender. diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/AsyncAppender.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/AsyncAppender.java index 8178fe2..e470757 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/AsyncAppender.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/AsyncAppender.java @@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicLong; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.async.RingBufferLogEvent; import org.apache.logging.log4j.core.config.AppenderControl; import org.apache.logging.log4j.core.config.AppenderRef; import org.apache.logging.log4j.core.config.Configuration; @@ -127,12 +128,15 @@ public final class AsyncAppender extends AbstractAppender { * @param logEvent The LogEvent. */ @Override - public void append(final LogEvent logEvent) { + public void append(LogEvent logEvent) { if (!isStarted()) { throw new IllegalStateException("AsyncAppender " + getName() + " is not active"); } if (!(logEvent instanceof Log4jLogEvent)) { - return; // only know how to Serialize Log4jLogEvents + if (!(logEvent instanceof RingBufferLogEvent)) { + return; // only know how to Serialize Log4jLogEvents and RingBufferLogEvents + } + logEvent = ((RingBufferLogEvent) logEvent).createMemento(); } Log4jLogEvent coreEvent = (Log4jLogEvent) logEvent; boolean appendSuccessful = false;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-668_60f64cc1.diff
bugs-dot-jar_data_LOG4J2-392_731c84b5
--- BugID: LOG4J2-392 Summary: Intermittent errors with appenders Description: "I intermittently receive following errors after upgrading to beta 8. EVERYTHING was working well with beta 6:\n* 1st error (happens most frequently)\n2013-09-05 10:48:37,722 ERROR Attempted to append to non-started appender LogFile\n\n* 2nd error:\n2013-09-05 10:49:38,268 ERROR Attempted to append to non-started appender LogFile\n2013-09-05 10:49:38,268 ERROR Unable to write to stream log/ui-selenium-tests.log for appender LogFile\n2013-09-05 10:49:38,269 ERROR An exception occurred processing Appender LogFile org.apache.logging.log4j.core.appender.AppenderRuntimeException: Error writing to RandomAccessFile log/ui-selenium-tests.log\n\tat org.apache.logging.log4j.core.appender.rolling.FastRollingFileManager.flush(FastRollingFileManager.java:108)\n\tat org.apache.logging.log4j.core.appender.rolling.FastRollingFileManager.write(FastRollingFileManager.java:89)\n\tat org.apache.logging.log4j.core.appender.OutputStreamManager.write(OutputStreamManager.java:129)\n\tat org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:115)\n\tat org.apache.logging.log4j.core.appender.FastRollingFileAppender.append(FastRollingFileAppender.java:97)\n\tat org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:102)\n\tat org.apache.logging.log4j.core.appender.AsyncAppender$AsyncThread.run(AsyncAppender.java:228)\nCaused by: java.io.IOException: Write error\n\tat java.io.RandomAccessFile.writeBytes(Native Method)\n\tat java.io.RandomAccessFile.write(Unknown Source)\n\tat org.apache.logging.log4j.core.appender.rolling.FastRollingFileManager.flush(FastRollingFileManager.java:105)\n\t... 6 more\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java index 7e577bb..509f6c7 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/AbstractConfiguration.java @@ -151,13 +151,17 @@ public abstract class AbstractConfiguration extends AbstractFilterable implement setup(); setupAdvertisement(); doConfigure(); + final Set<LoggerConfig> alreadyStarted = new HashSet<LoggerConfig>(); for (final LoggerConfig logger : loggers.values()) { logger.start(); + alreadyStarted.add(logger); } for (final Appender appender : appenders.values()) { appender.start(); } - root.start(); // LOG4J2-336 + if (!alreadyStarted.contains(root)) { // LOG4J2-392 + root.start(); // LOG4J2-336 + } super.start(); LOGGER.debug("Started configuration {} OK.", this); } @@ -185,7 +189,7 @@ public abstract class AbstractConfiguration extends AbstractFilterable implement } } // similarly, first stop AsyncLoggerConfig Disruptor thread(s) - Set<LoggerConfig> alreadyStopped = new HashSet<LoggerConfig>(); + final Set<LoggerConfig> alreadyStopped = new HashSet<LoggerConfig>(); int asyncLoggerConfigCount = 0; for (final LoggerConfig logger : loggers.values()) { if (logger instanceof AsyncLoggerConfig) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-392_731c84b5.diff
bugs-dot-jar_data_LOG4J2-344_8dead3bb
--- BugID: LOG4J2-344 Summary: Log4j2 doesnt work with Weblogic 12c Description: I get a "Context destroyed before it was initialized" exception, the problem seems to be that the servlet filters init method is not being called by WebLogic, not sure why... diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java index 7d3ce05..84dbdb3 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/web/Log4jServletContainerInitializer.java @@ -41,7 +41,7 @@ public class Log4jServletContainerInitializer implements ServletContainerInitial servletContext.log("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment."); final FilterRegistration.Dynamic filter = - servletContext.addFilter("log4jServletFilter", new Log4jServletFilter()); + servletContext.addFilter("log4jServletFilter", Log4jServletFilter.class); if (filter == null) { servletContext.log("WARNING: In a Servlet 3.0+ application, you should not define a " + "log4jServletFilter in web.xml. Log4j 2 normally does this for you automatically. Log4j 2 " +
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-344_8dead3bb.diff
bugs-dot-jar_data_LOG4J2-1025_a96b455c
--- BugID: LOG4J2-1025 Summary: Custom java.util.logging.Level gives null Log4j Level and causes NPE Description: "I use a 3rd party library which uses custom non-standard java.util.logging.Level.\n\nThe Log4j JUL adapter will emit log event with level set to null in that case, which causes NullPointerException in a Log4j filter further on.\n\nThis is not acceptable. When encountering an unrecognised JUL Level, the JUL adapter should either: \n- emit some default Log4j Level\n- throw an Exception with a clear error message immediately\n- silently discard the log event\n- discard the log event and log a warning to the StatusLogger\n\n{code}\n java.lang.NullPointerException\n at org.apache.logging.log4j.Level.isMoreSpecificThan(Level.java:163)\n \ at org.apache.logging.log4j.core.filter.BurstFilter.filter(BurstFilter.java:129)\n \ at org.apache.logging.log4j.core.filter.BurstFilter.filter(BurstFilter.java:101)\n \ at org.apache.logging.log4j.core.Logger$PrivateConfig.filter(Logger.java:295)\n \ at org.apache.logging.log4j.core.Logger.isEnabled(Logger.java:122)\n at org.apache.logging.log4j.spi.ExtendedLoggerWrapper.isEnabled(ExtendedLoggerWrapper.java:87)\n \ at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:699)\n \ at org.apache.logging.log4j.jul.WrappedLogger.log(WrappedLogger.java:50)\n \ at org.apache.logging.log4j.jul.ApiLogger.log(ApiLogger.java:106)\n{code}" diff --git a/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java b/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java index 5d84de4..c2d8eb3 100644 --- a/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java +++ b/log4j-jul/src/main/java/org/apache/logging/log4j/jul/DefaultLevelConverter.java @@ -17,24 +17,38 @@ package org.apache.logging.log4j.jul; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.IdentityHashMap; +import java.util.List; import java.util.Map; import org.apache.logging.log4j.Level; /** * Default implementation of LevelConverter strategy. - * + * <p> + * Supports custom JUL levels by mapping them to their closest mapped neighbour. + * </p> * @since 2.1 */ public class DefaultLevelConverter implements LevelConverter { + static final class JulLevelComparator implements Comparator<java.util.logging.Level> { + @Override + public int compare(java.util.logging.Level level1, java.util.logging.Level level2) { + return Integer.compare(level1.intValue(), level2.intValue()); + } + } + private final Map<java.util.logging.Level, Level> julToLog4j = new IdentityHashMap<>(9); private final Map<Level, java.util.logging.Level> log4jToJul = new IdentityHashMap<>(10); + private final List<java.util.logging.Level> sortedJulLevels = new ArrayList<>(9); public DefaultLevelConverter() { // Map JUL to Log4j - mapJulToLog4j(java.util.logging.Level.OFF, Level.OFF); + mapJulToLog4j(java.util.logging.Level.ALL, Level.ALL); mapJulToLog4j(java.util.logging.Level.FINEST, LevelTranslator.FINEST); mapJulToLog4j(java.util.logging.Level.FINER, Level.TRACE); mapJulToLog4j(java.util.logging.Level.FINE, Level.DEBUG); @@ -42,9 +56,9 @@ public class DefaultLevelConverter implements LevelConverter { mapJulToLog4j(java.util.logging.Level.INFO, Level.INFO); mapJulToLog4j(java.util.logging.Level.WARNING, Level.WARN); mapJulToLog4j(java.util.logging.Level.SEVERE, Level.ERROR); - mapJulToLog4j(java.util.logging.Level.ALL, Level.ALL); + mapJulToLog4j(java.util.logging.Level.OFF, Level.OFF); // Map Log4j to JUL - mapLog4jToJul(Level.OFF, java.util.logging.Level.OFF); + mapLog4jToJul(Level.ALL, java.util.logging.Level.ALL); mapLog4jToJul(LevelTranslator.FINEST, java.util.logging.Level.FINEST); mapLog4jToJul(Level.TRACE, java.util.logging.Level.FINER); mapLog4jToJul(Level.DEBUG, java.util.logging.Level.FINE); @@ -53,18 +67,46 @@ public class DefaultLevelConverter implements LevelConverter { mapLog4jToJul(Level.WARN, java.util.logging.Level.WARNING); mapLog4jToJul(Level.ERROR, java.util.logging.Level.SEVERE); mapLog4jToJul(Level.FATAL, java.util.logging.Level.SEVERE); - mapLog4jToJul(Level.ALL, java.util.logging.Level.ALL); + mapLog4jToJul(Level.OFF, java.util.logging.Level.OFF); + // Sorted Java levels + sortedJulLevels.addAll(julToLog4j.keySet()); + Collections.sort(sortedJulLevels, new JulLevelComparator()); + + } + + private Level addCustomJulLevel(java.util.logging.Level customJavaLevel) { + long prevDist = Long.MAX_VALUE; + java.util.logging.Level prevLevel = null; + for (java.util.logging.Level mappedJavaLevel : sortedJulLevels) { + long distance = distance(customJavaLevel, mappedJavaLevel); + if (distance > prevDist) { + return mapCustomJulLevel(customJavaLevel, prevLevel); + } + prevDist = distance; + prevLevel = mappedJavaLevel; + } + return mapCustomJulLevel(customJavaLevel, prevLevel); + } + + private long distance(java.util.logging.Level javaLevel, java.util.logging.Level customJavaLevel) { + return Math.abs((long) customJavaLevel.intValue() - (long) javaLevel.intValue()); + } + + private Level mapCustomJulLevel(java.util.logging.Level customJavaLevel, java.util.logging.Level stdJavaLevel) { + final Level level = julToLog4j.get(stdJavaLevel); + julToLog4j.put(customJavaLevel, level); + return level; } - + /* - * TODO consider making public. + * TODO consider making public for advanced configuration. */ private void mapJulToLog4j(java.util.logging.Level julLevel, Level level) { julToLog4j.put(julLevel, level); } - + /* - * TODO consider making public. + * TODO consider making public for advanced configuration. */ private void mapLog4jToJul(Level level, java.util.logging.Level julLevel) { log4jToJul.put(level, julLevel); @@ -77,6 +119,7 @@ public class DefaultLevelConverter implements LevelConverter { @Override public Level toLevel(final java.util.logging.Level javaLevel) { - return julToLog4j.get(javaLevel); + final Level level = julToLog4j.get(javaLevel); + return level != null ? level : addCustomJulLevel(javaLevel); } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1025_a96b455c.diff
bugs-dot-jar_data_LOG4J2-914_f8a42197
--- BugID: LOG4J2-914 Summary: 'ThrowableProxy.getExtendedStackTraceAsString causes NullPointerException ' Description: "I'm trying to write a poc with Log4j 2.1, where distributed processes are logging to a remote server. The server is currently running the bundled TcpSocketServer.createSerializedSocketServer with a custom layout plugin. \n\nA process is logging an exception. I can then see in the custom layout plugin at the log server that the LogEvent doesn't contain a thrown, but that it contains a thrownProxy. So far so good. I'm then trying to get hold of a String representation of the message + stacktrace. I thought that I would be able to e.g invoke ThrowableProxy.getExtendedStackTraceAsString(), but that causes a NullPointerException since the throwable in the ThrowableProxy also is null after deserialization. Looks like ThrowableProxy assumes that throwable isn't null in a few methods. \n\nThe exception that is logged by the client process is a simple new Exception(\"A message\");\n\nThe pom.xml that I'm using:\n{code:xml}\n<dependency>\n\t<groupId>org.apache.logging.log4j</groupId>\n\t<artifactId>log4j-api</artifactId>\n\t<version>2.1</version>\n</dependency>\n<dependency>\n\t<groupId>org.apache.logging.log4j</groupId>\n\t<artifactId>log4j-core</artifactId>\n\t<version>2.1</version>\n</dependency>\n<dependency>\n\t<groupId>com.lmax</groupId>\n\t<artifactId>disruptor</artifactId>\n\t<version>3.3.0</version>\n</dependency>\n{code}\nThe stacktrace that I get in the server:\n{code}\n2014-12-05 14:30:44,601 ERROR An exception occurred processing Appender XXXXX java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.getExtendedStackTraceAsString(ThrowableProxy.java:340)\n\tat org.apache.logging.log4j.core.impl.ThrowableProxy.getExtendedStackTraceAsString(ThrowableProxy.java:323)\n{code}\nWorkaround:\nTo invoke ThrowableProxy. getExtendedStackTrace() and format the stacktrace + message with my own format methods.\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java index 2d0941f..1d3af2a 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java @@ -342,7 +342,8 @@ public class ThrowableProxy implements Serializable { sb.append(": ").append(msg); } sb.append(EOL); - this.formatElements(sb, 0, this.throwable.getStackTrace(), this.extendedStackTrace, ignorePackages); + StackTraceElement[] causedTrace = this.throwable != null ? this.throwable.getStackTrace() : null; + this.formatElements(sb, 0, causedTrace, this.extendedStackTrace, ignorePackages); this.formatCause(sb, this.causeProxy, ignorePackages); return sb.toString(); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-914_f8a42197.diff
bugs-dot-jar_data_LOG4J2-1062_4cf831b6
--- BugID: LOG4J2-1062 Summary: Log4jMarker#add(Marker) does not respect org.slf4j.Marker contract Description: Passing {{null}} to {{Log4jMarker#add(Marker)}} throws a {{NullPointerException}} instead of an {{IllegalArgumentException}}. diff --git a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java index d57cf19..aee8dcf 100644 --- a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java +++ b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java @@ -50,6 +50,9 @@ public class Log4jMarker implements Marker { @Override public void add(final Marker marker) { + if (marker == null) { + throw new IllegalArgumentException(); + } final Marker m = factory.getMarker(marker.getName()); this.marker.addParents(((Log4jMarker)m).getLog4jMarker()); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1062_4cf831b6.diff
bugs-dot-jar_data_LOG4J2-210_aeb6fc9d
--- BugID: LOG4J2-210 Summary: MapMessage does not enclose key in quotes when generating XML Description: MapMessage does not enclose key in quotes when generating XML diff --git a/api/src/main/java/org/apache/logging/log4j/message/MapMessage.java b/api/src/main/java/org/apache/logging/log4j/message/MapMessage.java index de1bb98..cbcd2ca 100644 --- a/api/src/main/java/org/apache/logging/log4j/message/MapMessage.java +++ b/api/src/main/java/org/apache/logging/log4j/message/MapMessage.java @@ -193,7 +193,7 @@ public class MapMessage implements MultiformatMessage { public void asXML(final StringBuilder sb) { sb.append("<Map>\n"); for (final Map.Entry<String, String> entry : data.entrySet()) { - sb.append(" <Entry key=").append(entry.getKey()).append(">").append(entry.getValue()).append("</Entry>\n"); + sb.append(" <Entry key=\"").append(entry.getKey()).append("\">").append(entry.getValue()).append("</Entry>\n"); } sb.append("</Map>"); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-210_aeb6fc9d.diff
bugs-dot-jar_data_LOG4J2-107_88641f49
--- BugID: LOG4J2-107 Summary: Nesting pattern layout options is broken Description: |- This pattern: {code:xml} <PatternLayout pattern="%highlight{%d{dd MMM yyyy HH:mm:ss,SSS}{GMT+0} [%t] %-5level: %msg%n%throwable}" /> {code} Incorrectly outputs: {noformat} 02 Nov 2012 16:51:14,907{GMT+0 [main] FATAL: Fatal message. }02 Nov 2012 16:51:14,910{GMT+0 [main] ERROR: Error message. }02 Nov 2012 16:51:14,914{GMT+0 [main] WARN : Warning message. }02 Nov 2012 16:51:14,917{GMT+0 [main] INFO : Information message. }02 Nov 2012 16:51:14,920{GMT+0 [main] DEBUG: Debug message. }02 Nov 2012 16:51:14,924{GMT+0 [main] TRACE: Trace message. }02 Nov 2012 16:51:14,929{GMT+0 [main] ERROR: Error message. {noformat} diff --git a/core/src/main/java/org/apache/logging/log4j/core/pattern/PatternParser.java b/core/src/main/java/org/apache/logging/log4j/core/pattern/PatternParser.java index 99fd17d..fd53a00 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/pattern/PatternParser.java +++ b/core/src/main/java/org/apache/logging/log4j/core/pattern/PatternParser.java @@ -210,13 +210,13 @@ public final class PatternParser { */ private static int extractOptions(String pattern, int i, List<String> options) { while ((i < pattern.length()) && (pattern.charAt(i) == '{')) { - int begin = i; + int begin = i++; int end; int depth = 0; do { end = pattern.indexOf('}', i); if (end != -1) { - int next = pattern.indexOf("{", i + 1); + int next = pattern.indexOf("{", i); if (next != -1 && next < end) { i = end + 1; ++depth;
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-107_88641f49.diff
bugs-dot-jar_data_LOG4J2-113_fc3e9d2d
--- BugID: LOG4J2-113 Summary: StructuredDataFilter defines "pairs" as attribute instead of element Description: | org.apache.logging.log4j.core.filter.StructuredDataFilter method createFilter defines parameter "pairs" as follows: @PluginAttr("pairs") KeyValuePair[] pairs It should have been: @PluginElement("pairs") KeyValuePair[] pairs diff --git a/core/src/main/java/org/apache/logging/log4j/core/filter/StructuredDataFilter.java b/core/src/main/java/org/apache/logging/log4j/core/filter/StructuredDataFilter.java index 26e12a6..6c9a862 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/filter/StructuredDataFilter.java +++ b/core/src/main/java/org/apache/logging/log4j/core/filter/StructuredDataFilter.java @@ -22,6 +22,7 @@ import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttr; +import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.helpers.KeyValuePair; import org.apache.logging.log4j.message.Message; @@ -98,7 +99,7 @@ public final class StructuredDataFilter extends MapFilter { * @return The StructuredDataFilter. */ @PluginFactory - public static StructuredDataFilter createFilter(@PluginAttr("pairs") KeyValuePair[] pairs, + public static StructuredDataFilter createFilter(@PluginElement("pairs") KeyValuePair[] pairs, @PluginAttr("operator") String oper, @PluginAttr("onmatch") String match, @PluginAttr("onmismatch") String mismatch) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-113_fc3e9d2d.diff
bugs-dot-jar_data_LOG4J2-742_4b77622b
--- BugID: LOG4J2-742 Summary: XInclude not working with relative path Description: "When using XInclude in a log4j2 configuration, it uses the CWD of the running application instead of the location of the log4j configuration as base.\nI.e. running the application from within eclipse, the CWD of eclipse is used as base for finding the document to be included.\n\nIMO, the problem is in XmlConfiguration:\n{code}\n \ final InputStream configStream = configSource.getInputStream();\n try {\n buffer = toByteArray(configStream);\n } finally {\n \ configStream.close();\n }\n final InputSource source = new InputSource(new ByteArrayInputStream(buffer));\n final Document document = newDocumentBuilder().parse(source);\n{code}\nThere is no way the DOMParser can know, where the base should be, because it is just parsing an InputStream and has no file location. \n\nThe fix would be to add source.setSystemId(configSource.getLocation()) before parsing the document." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java index eadcbbc..ca72c09 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java @@ -131,6 +131,7 @@ public class XmlConfiguration extends AbstractConfiguration implements Reconfigu configStream.close(); } final InputSource source = new InputSource(new ByteArrayInputStream(buffer)); + source.setSystemId(configSource.getLocation()); final Document document = newDocumentBuilder().parse(source); rootElement = document.getDocumentElement(); final Map<String, String> attrs = processAttributes(rootNode, rootElement);
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-742_4b77622b.diff
bugs-dot-jar_data_LOG4J2-143_1461f1f6
--- BugID: LOG4J2-143 Summary: MessagePatternConverter throws a NullPointerException if the log message is null Description: |- If the application does logger.debug(msg) where the value of msg is null MessagePatternConverter will get a NullPointerException. diff --git a/core/src/main/java/org/apache/logging/log4j/core/pattern/MessagePatternConverter.java b/core/src/main/java/org/apache/logging/log4j/core/pattern/MessagePatternConverter.java index 8db9313..c3850b3 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/pattern/MessagePatternConverter.java +++ b/core/src/main/java/org/apache/logging/log4j/core/pattern/MessagePatternConverter.java @@ -67,8 +67,12 @@ public final class MessagePatternConverter extends LogEventPatternConverter { } else { result = msg.getFormattedMessage(); } - toAppendTo.append(config != null && result.contains("${") ? - config.getSubst().replace(event, result) : result); + if (result != null) { + toAppendTo.append(config != null && result.contains("${") ? + config.getSubst().replace(event, result) : result); + } else { + toAppendTo.append("null"); + } } } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-143_1461f1f6.diff
bugs-dot-jar_data_LOG4J2-1069_e9b628ec
--- BugID: LOG4J2-1069 Summary: Improper handling of JSON escape chars when deserializing JSON log events Description: "There is an error in the handling of JSON escape characters while determining the log event boundaries in a JSON stream. This error is causing log events with JSON escaped characters in the message string to be skipped. The existing tests do not appear to cover this case, and other serialization types are not affected. \ Here is a test/fix patch: \n\n{code}\ndiff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java\nindex 1b81644..8ed2732 100644\n--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java\n+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java\n@@ -55,8 +55,10 @@ public class JsonInputStreamLogEventBridge extends InputStreamLogEventBridge {\n boolean inEsc = false;\n for (int i = start; i < charArray.length; i++) {\n final char c = charArray[i];\n- if (!inEsc) {\n- \ inEsc = false;\n+ if (inEsc) {\n+ \t// Skip this char and continue\n+ \tinEsc = false;\n+ } else { \n \ switch (c) {\n case EVENT_START_MARKER:\n if (!inStr) {\ndiff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/net/server/AbstractSocketServerTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/net/server/AbstractSocketServerTest.java\nindex 891e278..2bdb3c3 100644\n--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/net/server/AbstractSocketServerTest.java\n+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/net/server/AbstractSocketServerTest.java\n@@ -69,7 +69,9 @@ public abstract class AbstractSocketServerTest {\n private static final String MESSAGE = \"This is test message\";\n \n private static final String MESSAGE_2 = \"This is test message 2\";\n-\n+ \n+ private static final String MESSAGE_WITH_SPECIAL_CHARS = \"{This}\\n[is]\\\"n\\\"a\\\"\\r\\ntrue:\\n\\ttest,\\nmessage\";\n+ \ \n static final int PORT_NUM = AvailablePortFinder.getNextAvailable();\n \n static final String PORT = String.valueOf(PORT_NUM);\n@@ -158,6 +160,13 @@ public abstract class AbstractSocketServerTest {\n testServer(m1, m2);\n \ }\n }\n+ \n+ \n+ @Test\n+ public void testMessagesWithSpecialChars() throws Exception {\n+ testServer(MESSAGE_WITH_SPECIAL_CHARS);\n+ }\n+ \ \n \n private void testServer(final int size) throws Exception {\n final String[] messages = new String[size];\n{code}\n\nThe test provided is simplistic and does not attempt to cover all possible special characters as the bug has to do with escaped characters in general. XML and java serialization handle the special chars in my test string without issue - I did not attempt to locate similar cases in the other serialization types.\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java index 1b81644..8ed2732 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/net/server/JsonInputStreamLogEventBridge.java @@ -55,8 +55,10 @@ public class JsonInputStreamLogEventBridge extends InputStreamLogEventBridge { boolean inEsc = false; for (int i = start; i < charArray.length; i++) { final char c = charArray[i]; - if (!inEsc) { - inEsc = false; + if (inEsc) { + // Skip this char and continue + inEsc = false; + } else { switch (c) { case EVENT_START_MARKER: if (!inStr) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1069_e9b628ec.diff
bugs-dot-jar_data_LOG4J2-410_8f0c4871
--- BugID: LOG4J2-410 Summary: " java.io.NotSerializableException: org.slf4j.impl.SLF4JLogger" Description: When i use a the logger object in a model,and the model will set to some cache like memcached,this exception happens.Maybe this class and some other related class need implements Serializable interface? diff --git a/log4j-slf4j-impl/src/main/java/org/slf4j/impl/SLF4JLogger.java b/log4j-slf4j-impl/src/main/java/org/slf4j/impl/SLF4JLogger.java index eaac80e..767941e 100644 --- a/log4j-slf4j-impl/src/main/java/org/slf4j/impl/SLF4JLogger.java +++ b/log4j-slf4j-impl/src/main/java/org/slf4j/impl/SLF4JLogger.java @@ -17,6 +17,7 @@ package org.slf4j.impl; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.message.SimpleMessage; @@ -27,17 +28,23 @@ import org.slf4j.MarkerFactory; import org.slf4j.helpers.EventDataConverter; import org.slf4j.spi.LocationAwareLogger; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + /** * */ -public class SLF4JLogger implements LocationAwareLogger { +public class SLF4JLogger implements LocationAwareLogger, Serializable { + private static final long serialVersionUID = 7869000638091304316L; private static final String FQCN = SLF4JLogger.class.getName(); private static final Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT"); private final boolean eventLogger; - private final AbstractLoggerWrapper logger; + private transient AbstractLoggerWrapper logger; private final String name; - private final EventDataConverter converter; + private transient EventDataConverter converter; public SLF4JLogger(final AbstractLogger logger, final String name) { this.logger = new AbstractLoggerWrapper(logger, name, null); @@ -502,6 +509,27 @@ public class SLF4JLogger implements LocationAwareLogger { return name; } + /** + * Always treat de-serialization as a full-blown constructor, by + * validating the final state of the de-serialized object. + */ + private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { + //always perform the default de-serialization first + aInputStream.defaultReadObject(); + logger = new AbstractLoggerWrapper((AbstractLogger) LogManager.getLogger(name), name, null); + converter = createConverter(); + } + + /** + * This is the default implementation of writeObject. + * Customise if necessary. + */ + private void writeObject(ObjectOutputStream aOutputStream + ) throws IOException { + //perform the default serialization for all non-transient, non-static fields + aOutputStream.defaultWriteObject(); + } + private EventDataConverter createConverter() { try { Class.forName("org.slf4j.ext.EventData");
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-410_8f0c4871.diff
bugs-dot-jar_data_LOG4J2-1402_7792679c
--- BugID: LOG4J2-1402 Summary: Exception when using log4j2.properties and logger with dot Description: "After upgrading log4j2 from 2.5 to 2.6 I get the following exception:\n\n{quote}\nException in thread \"main\" org.apache.logging.log4j.core.config.ConfigurationException: No name attribute provided for Logger org\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationBuilder.createLogger(PropertiesConfigurationBuilder.java:215)\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationBuilder.build(PropertiesConfigurationBuilder.java:140)\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:52)\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:34)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:510)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:450)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:257)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:560)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:577)\n\tat org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:212)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:152)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)\n\tat org.apache.logging.log4j.LogManager.getContext(LogManager.java:194)\n\tat org.apache.logging.log4j.spi.AbstractLoggerAdapter.getContext(AbstractLoggerAdapter.java:103)\n\tat org.apache.logging.log4j.jcl.LogAdapter.getContext(LogAdapter.java:39)\n\tat org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:42)\n\tat org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:40)\n\tat org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:55)\n\tat org.apache.commons.logging.LogFactory.getLog(LogFactory.java:655)\n\tat org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:159)\n\tat org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:223)\n\tat org.springframework.context.support.AbstractRefreshableApplicationContext.<init>(AbstractRefreshableApplicationContext.java:88)\n\tat org.springframework.context.support.AbstractRefreshableConfigApplicationContext.<init>(AbstractRefreshableConfigApplicationContext.java:58)\n\tat org.springframework.context.support.AbstractXmlApplicationContext.<init>(AbstractXmlApplicationContext.java:61)\n\tat org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:136)\n\tat org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)\nx.y.z.Start.main(Start.java:12)\n{quote}\n\nThe parameter \"key\" has the value \"org\" and the parameter properties has the value {code}{activiti.engine.impl.level=info, activiti.engine.impl.name=org.activiti.engine.impl}{code}\n\nThe log4j2.properties in use:\n\n{code}\n# Root logger option\nrootLogger.level = info\nrootLogger.appenderRefs = stdout\nrootLogger.appenderRef.stdout.ref = STDOUT\n\n# Redirect log messages to console\nappenders = stdout\nappender.stdout.type = Console\nappender.stdout.name = STDOUT\nappender.stdout.layout.type = PatternLayout\nappender.stdout.layout.pattern = %d %-5p [%t] %c - %m%n\n{code}\n\nSadly I have not been able to reproduce the issue in a simple standalone application." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationBuilder.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationBuilder.java index 51bdcca..2c70234 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationBuilder.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationBuilder.java @@ -120,24 +120,56 @@ public class PropertiesConfigurationBuilder extends ConfigurationBuilderFactory } } - final Map<String, Properties> filters = PropertiesUtil.partitionOnCommonPrefixes( - PropertiesUtil.extractSubset(rootProperties, "filter")); - for (final Map.Entry<String, Properties> entry : filters.entrySet()) { - builder.add(createFilter(entry.getKey().trim(), entry.getValue())); + String filterProp = rootProperties.getProperty("filters"); + if (filterProp != null) { + String[] filterNames = filterProp.split(","); + for (String filterName : filterNames) { + String name = filterName.trim(); + builder.add(createFilter(name, PropertiesUtil.extractSubset(rootProperties, "filter." + name))); + } + } else { + + final Map<String, Properties> filters = PropertiesUtil + .partitionOnCommonPrefixes(PropertiesUtil.extractSubset(rootProperties, "filter")); + for (final Map.Entry<String, Properties> entry : filters.entrySet()) { + builder.add(createFilter(entry.getKey().trim(), entry.getValue())); + } } - final Map<String, Properties> appenders = PropertiesUtil.partitionOnCommonPrefixes( - PropertiesUtil.extractSubset(rootProperties, "appender")); - for (final Map.Entry<String, Properties> entry : appenders.entrySet()) { - builder.add(createAppender(entry.getKey().trim(), entry.getValue())); + String appenderProp = rootProperties.getProperty("appenders"); + if (appenderProp != null) { + String[] appenderNames = appenderProp.split(","); + for (String appenderName : appenderNames) { + String name = appenderName.trim(); + builder.add(createAppender(appenderName.trim(), + PropertiesUtil.extractSubset(rootProperties, "appender." + name))); + } + } else { + final Map<String, Properties> appenders = PropertiesUtil + .partitionOnCommonPrefixes(PropertiesUtil.extractSubset(rootProperties, "appender")); + for (final Map.Entry<String, Properties> entry : appenders.entrySet()) { + builder.add(createAppender(entry.getKey().trim(), entry.getValue())); + } } - final Map<String, Properties> loggers = PropertiesUtil.partitionOnCommonPrefixes( - PropertiesUtil.extractSubset(rootProperties, "logger")); - for (final Map.Entry<String, Properties> entry : loggers.entrySet()) { - final String name = entry.getKey().trim(); - if (!name.equals(LoggerConfig.ROOT)) { - builder.add(createLogger(name, entry.getValue())); + String loggerProp = rootProperties.getProperty("loggers"); + if (loggerProp != null) { + String[] loggerNames = loggerProp.split(","); + for (String loggerName : loggerNames) { + String name = loggerName.trim(); + if (!name.equals(LoggerConfig.ROOT)) { + builder.add(createLogger(name, PropertiesUtil.extractSubset(rootProperties, "logger." + + name))); + } + } + } else { + final Map<String, Properties> loggers = PropertiesUtil + .partitionOnCommonPrefixes(PropertiesUtil.extractSubset(rootProperties, "logger")); + for (final Map.Entry<String, Properties> entry : loggers.entrySet()) { + final String name = entry.getKey().trim(); + if (!name.equals(LoggerConfig.ROOT)) { + builder.add(createLogger(name, entry.getValue())); + } } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1402_7792679c.diff
bugs-dot-jar_data_LOG4J2-147_17296089
--- BugID: LOG4J2-147 Summary: ThreadContextMapFilter doesn't match properly when a single keyvalue is provided Description: |+ I was testing out a global ThreadContextMapFilter and noticed it wasn't matching properly. I took a closer look at the code and found because it wasn't matching the value to the value on the context but rather the key. I changed it to use the value as the argument to equals and this fixed it. Here is the diff of what I am running with. diff --git a/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java b/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java index 9ad6cab..b3f3838 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFi +++ b/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java @@ -96,7 +96,7 @@ public class ThreadContextMapFilter extends MapFilter { } } } else { - match = key.equals(ThreadContext.get(key)); + match = value.equals(ThreadContext.get(key)); } return match ? onMatch : onMismatch; } diff --git a/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java b/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java index 9ad6cab..b3f3838 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java +++ b/core/src/main/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilter.java @@ -96,7 +96,7 @@ public class ThreadContextMapFilter extends MapFilter { } } } else { - match = key.equals(ThreadContext.get(key)); + match = value.equals(ThreadContext.get(key)); } return match ? onMatch : onMismatch; }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-147_17296089.diff
bugs-dot-jar_data_LOG4J2-964_16ad8763
--- BugID: LOG4J2-964 Summary: StringFormattedMessage serialization is incorrect Description: |- The method {{writeObject(final ObjectOutputStream out)}} of the class {{org.apache.logging.log4j.message.StringFormattedMessage}} does not write the stringArgs array into the output stream. This causes {{readObject(final ObjectInputStream in)}} to throw an {{EOFException}} when trying to deserialize. There is another bug in the same method. The line {{stringArgs[i] = obj.toString();}} throws a {{NullPointerException}} when obj is null. diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java index f6007e4..4c8429a 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/StringFormattedMessage.java @@ -133,7 +133,9 @@ public class StringFormattedMessage implements Message { stringArgs = new String[argArray.length]; int i = 0; for (final Object obj : argArray) { - stringArgs[i] = obj.toString(); + final String string = obj.toString(); + stringArgs[i] = string; + out.writeUTF(string); ++i; } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-964_16ad8763.diff
bugs-dot-jar_data_LOG4J2-1058_c8fd3c53
--- BugID: LOG4J2-1058 Summary: Log4jMarker#contains(String) does not respect org.slf4j.Marker contract Description: | Expected behavior ============== 'org.apache.logging.slf4j.Log4jMarker' implements 'org.slf4j.Marker'. 'org.slf4j.Marker#contains(String name)' contract states that: "If 'name' is null the returned value is always false." http://www.slf4j.org/apidocs/org/slf4j/Marker.html#contains%28java.lang.String%29 Actual behavior ============= 'org.apache.logging.slf4j.Log4jMarker#contains(final String name)' throws 'IllegalArgumentException' if 'name' is null diff --git a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java index 50d126c..c2273f5 100644 --- a/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java +++ b/log4j-slf4j-impl/src/main/java/org/apache/logging/slf4j/Log4jMarker.java @@ -84,9 +84,12 @@ public class Log4jMarker implements Marker { } @Override - public boolean contains(final org.slf4j.Marker marker) { - return this.marker.isInstanceOf(marker.getName()); - } + public boolean contains(final org.slf4j.Marker marker) { + if (marker == null) { + throw new IllegalArgumentException(); + } + return this.marker.isInstanceOf(marker.getName()); + } @Override public boolean contains(final String s) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1058_c8fd3c53.diff
bugs-dot-jar_data_LOG4J2-260_9d817953
--- BugID: LOG4J2-260 Summary: XML layout does not specify charset in content type Description: XML layout does not specify charset in content type diff --git a/core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java b/core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java index ddd4548..aa40961 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java +++ b/core/src/main/java/org/apache/logging/log4j/core/layout/XMLLayout.java @@ -239,7 +239,7 @@ public class XMLLayout extends AbstractStringLayout { * @return The content type. */ public String getContentType() { - return "text/xml"; + return "text/xml; charset=" + this.getCharset(); } List<String> getThrowableString(final Throwable throwable) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-260_9d817953.diff
bugs-dot-jar_data_LOG4J2-619_3b4b370e
--- BugID: LOG4J2-619 Summary: Unable to recover after loading corrupted XML Description: |- Steps to reproduce: 1) auto-reloading of log4j 2.x configuration from XML is enabled 2) system is started and producing logs 3) change XML configuration, so it's not valid XML any longer 4) Wait till it would be picked up -> no more logging info is produced, exception can be found from logs (see below). 5) Fix XML configuration -> it's not getting reloaded anymore, only java restart can fix the problem. log4j2.xml org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 7; The processi ng instruction target matching "[xX][mM][lL]" is not allowed. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347) at org.apache.logging.log4j.core.config.XMLConfiguration.<init>(XMLConfiguration.java:145) at org.apache.logging.log4j.core.config.XMLConfiguration.reconfigure(XMLConfiguration.java:286) at org.apache.logging.log4j.core.LoggerContext.onChange(LoggerContext.java:421) at org.apache.logging.log4j.core.config.FileConfigurationMonitor.checkConfiguration(FileConfigurationMonitor.java:79) at org.apache.logging.log4j.core.Logger$PrivateConfig.filter(Logger.java:279) at org.apache.logging.log4j.core.Logger.isEnabled(Logger.java:117) at org.apache.logging.log4j.spi.AbstractLoggerWrapper.isEnabled(AbstractLoggerWrapper.java:82) at org.apache.logging.log4j.spi.AbstractLogger.isDebugEnabled(AbstractLogger.java:1071) at org.slf4j.impl.SLF4JLogger.isDebugEnabled(SLF4JLogger.java:174) at org.apache.commons.logging.impl.SLF4JLocationAwareLog.isDebugEnabled(SLF4JLocationAwareLog.java:67) .... ERROR No logging configuration diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java index fb7efa7..747f809 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java @@ -242,9 +242,7 @@ public class XmlConfiguration extends AbstractConfiguration implements Reconfigu final ConfigurationFactory.ConfigurationSource source = new ConfigurationFactory.ConfigurationSource(new FileInputStream(configFile), configFile); final XmlConfiguration config = new XmlConfiguration(source); - if (config.rootElement == null) { - return null; - } + return (config.rootElement == null) ? null : config; } catch (final FileNotFoundException ex) { LOGGER.error("Cannot locate file " + configFile, ex); }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-619_3b4b370e.diff
bugs-dot-jar_data_LOG4J2-1372_1d12bf0e
--- BugID: LOG4J2-1372 Summary: XMLLayout indents, but not the first child tag (<Event>) Description: "I am using log4j 2.5 to print the logs via XMLLayout. I have set compact=\"true\", hence the new line and indents of sub tags work correctly. However I have noticed that the first child tag is not indented correctly. \n\nFollowing is such a sample where <Events> and <Event> are at the same indent level (0 indent). \n\n{code:xml}\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">\n<Event xmlns=\"http://logging.apache.org/log4j/2.0/events\" timeMillis=\"1460974404123\" thread=\"main\" level=\"INFO\" loggerName=\"com.foo.Bar\" endOfBatch=\"true\" loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLogger\" threadId=\"11\" threadPriority=\"5\">\n <Message>First Msg tag must be in level 2 after correct indentation</Message>\n</Event>\n\n<Event xmlns=\"http://logging.apache.org/log4j/2.0/events\" timeMillis=\"1460974404133\" thread=\"main\" level=\"INFO\" loggerName=\"com.foo.Bar\" endOfBatch=\"true\" loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLogger\" threadId=\"11\" threadPriority=\"5\">\n <Message>Second Msg tag must also be in level 2 after correct indentation</Message>\n</Event>\n\n</Events>\n{code}\n" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java index 763f42a..3b34957 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java @@ -19,12 +19,15 @@ package org.apache.logging.log4j.core.layout; import java.util.HashSet; import java.util.Set; +import javax.xml.stream.XMLStreamException; + import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.apache.logging.log4j.core.jackson.JsonConstants; import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jYamlObjectMapper; import org.apache.logging.log4j.core.jackson.XmlConstants; +import org.codehaus.stax2.XMLStreamWriter2; import com.fasterxml.jackson.core.PrettyPrinter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; @@ -72,6 +75,8 @@ abstract class JacksonFactory { static class XML extends JacksonFactory { + static final int DEFAULT_INDENT = 1; + @Override protected String getPropertNameForContextMap() { return XmlConstants.ELT_CONTEXT_MAP; @@ -100,7 +105,7 @@ abstract class JacksonFactory { @Override protected PrettyPrinter newPrettyPrinter() { - return new DefaultXmlPrettyPrinter(); + return new Log4jXmlPrettyPrinter(DEFAULT_INDENT); } } @@ -137,6 +142,38 @@ abstract class JacksonFactory { } } + /** + * When &lt;Event&gt;s are written into a XML file; the "Event" object is not the root element, but an element named + * &lt;Events&gt; created using {@link #getHeader()} and {@link #getFooter()} methods.<br/> + * {@link com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter} is used to print the Event object into + * XML; hence it assumes &lt;Event&gt; tag as the root element, so it prints the &lt;Event&gt; tag without any + * indentation. To add an indentation to the &lt;Event&gt; tag; hence an additional indentation for any + * sub-elements, this class is written. As an additional task, to avoid the blank line printed after the ending + * &lt;/Event&gt; tag, {@link #writePrologLinefeed(XMLStreamWriter2)} method is also overridden. + */ + static class Log4jXmlPrettyPrinter extends DefaultXmlPrettyPrinter { + + private static final long serialVersionUID = 1L; + + Log4jXmlPrettyPrinter(int nesting) { + _nesting = nesting; + } + + @Override + public void writePrologLinefeed(XMLStreamWriter2 sw) throws XMLStreamException { + // nothing + } + + /** + * Sets the nesting level to 1 rather than 0, so the "Event" tag will get indentation of next level below root. + */ + @Override + public DefaultXmlPrettyPrinter createInstance() { + return new Log4jXmlPrettyPrinter(XML.DEFAULT_INDENT); + } + + } + abstract protected String getPropertNameForContextMap(); abstract protected String getPropertNameForSource();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1372_1d12bf0e.diff
bugs-dot-jar_data_LOG4J2-1153_9f924f10
--- BugID: LOG4J2-1153 Summary: Unable to define only rootLogger in a properties file. Description: "I've changed the version of log4j2 from *2.3* to *2.4* in order to load the configuration via properties file. So i have converted the xml file, that defines only {{<Root>}} in {{<Loggers>}} element, into a properties file. \nThis is a preview of the xml file :\n{code:xml}\n <Loggers>\n <Root level=\"info\">\n <AppenderRef ref=\"ConsoleAppender\"/>\n </Root>\n </Loggers>\n{code}\nAnd this is a preview of the properties file :\n\n{code}\nrootLogger.level = info\nrootLogger.appenderRefs = console\nrootLogger.appenderRef.console.ref = ConsoleAppender\n{code}\n\nThis configuration throw a null pointer exception :\n{noformat}Exception in thread \"main\" java.lang.ExceptionInInitializerError\nCaused by: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:132)\n\tat org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:44)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:491)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:461)\n\tat org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:257)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:493)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:510)\n\tat org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:199)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:146)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:41)\n\tat org.apache.logging.log4j.LogManager.getContext(LogManager.java:264)\n\tat org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:59)\n\tat org.apache.log4j.Logger.getLogger(Logger.java:41)\n{noformat}\n\nIn order to make this configuration work, i had to add the {{loggers}} component and fill the identifiers. My question is why in xml file we can define only a root logger and it works fine, and in a properties file it does not work ? \n " diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java index 50f9285..27644d8 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationFactory.java @@ -130,7 +130,7 @@ public class PropertiesConfigurationFactory extends ConfigurationFactory { } } String loggerProp = properties.getProperty("loggers"); - if (appenderProp != null) { + if (loggerProp != null) { String[] loggerNames = loggerProp.split(","); for (String loggerName : loggerNames) { String name = loggerName.trim(); @@ -343,7 +343,6 @@ public class PropertiesConfigurationFactory extends ConfigurationFactory { return componentBuilder; } - @SuppressWarnings({"unchecked", "rawtypes"}) private void processRemainingProperties(ComponentBuilder<?> builder, String name, Properties properties) { while (properties.size() > 0) { String propertyName = properties.stringPropertyNames().iterator().next();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1153_9f924f10.diff
bugs-dot-jar_data_LOG4J2-259_09175c8b
--- BugID: LOG4J2-259 Summary: HTML layout does not specify charset in content type Description: HTML layout does not specify charset in content type diff --git a/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java b/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java index 76dfdfe..bfb4939 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java +++ b/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java @@ -208,7 +208,7 @@ public final class HTMLLayout extends AbstractStringLayout { * @return The content type. */ public String getContentType() { - return "text/html"; + return "text/html; charset=" + this.getCharset(); } private void appendThrowableAsHTML(final Throwable throwable, final StringBuilder sbuf) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-259_09175c8b.diff
bugs-dot-jar_data_LOG4J2-310_3f1e0fdc
--- BugID: LOG4J2-310 Summary: SMTPAppender does not send mails with error or fatal level without prior info event Description: |- When using an SMTPAppender a mail is only delivered on a fatal event if there occured an info event before. Prior fatal events are ignored by SMTPAppender - other Appenders log them. A more detailed explanation/discussion including an example program can be found at: http://stackoverflow.com/questions/17657983/log4j2-smtpappender-does-not-send-mails-with-error-or-fatal-level diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/net/SMTPManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/net/SMTPManager.java index dd0b7fb..ebd45e1 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/net/SMTPManager.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/net/SMTPManager.java @@ -136,9 +136,8 @@ public class SMTPManager extends AbstractManager { } try { final LogEvent[] priorEvents = buffer.removeAll(); - if (priorEvents == null || priorEvents.length == 0) { - return; // nothing to do, another thread already took all events - } + // LOG4J-310: log appendEvent even if priorEvents is empty + final byte[] rawBytes = formatContentToBytes(priorEvents, appendEvent, layout); final String contentType = layout.getContentType();
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-310_3f1e0fdc.diff
bugs-dot-jar_data_LOG4J2-581_bb02fa15
--- BugID: LOG4J2-581 Summary: No header output in RollingRandomAccessFile Description: "No header output in RollingRandomAccessFile due to DummyOutputStream used when creating RollingRandomAccessFileManager. \n{code:title=RollingRandomAccessFileManager.java}\n...\n162: \ return new RollingRandomAccessFileManager(raf, name, data.pattern, +new DummyOutputStream()+, data.append,\n163: data.immediateFlush, size, time, data.policy, data.strategy, data.advertiseURI, data.layout);\n{code}\nWhen the superclass constructor (OutputStreamManager) writes header, it outputs thus header to nowhere:\n{code:title=OutputStreamManager.java}\n35: protected OutputStreamManager(final OutputStream os, final String streamName, final Layout<?> layout) {\n36: super(streamName);\n37: \ this.os = os;\n38: if (layout != null) {\n39: this.footer = layout.getFooter();\n40: this.header = layout.getHeader();\n41: if (this.header != null) {\n42: try {\n43:!!! this.os.write(header, 0, header.length);\n44: } catch (final IOException ioe) {\n45: LOGGER.error(\"Unable to write header\", ioe);\n46: }\n47: }\n48: } else {\n49: this.footer = null;\n50: this.header = null;\n51: }\n52: \ }\n{code}\nThe same fragment from RollingFileManager.java where header output works fine:\n{code:title=RollingFileManager.java}\n306: os = new FileOutputStream(name, data.append);\n307: if (data.bufferedIO) {\n308: \ os = new BufferedOutputStream(os);\n309: }\n310: \ final long time = file.lastModified(); // LOG4J2-531 create file first so time has valid value\n311: return new RollingFileManager(name, data.pattern, +os+, data.append, size, time, data.policy,\n312: data.strategy, data.advertiseURI, data.layout);\n{code}\n\nIn this case the \"os\" variable is a real stream which points to the file." diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java index 246abba..0065585 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java @@ -28,8 +28,7 @@ import org.apache.logging.log4j.core.Layout; public class OutputStreamManager extends AbstractManager { private volatile OutputStream os; - - private final Layout<?> layout; + protected final Layout<?> layout; protected OutputStreamManager(final OutputStream os, final String streamName, final Layout<?> layout) { super(streamName); @@ -66,11 +65,21 @@ public class OutputStreamManager extends AbstractManager { */ @Override public void releaseSub() { + writeFooter(); + close(); + } + + /** + * Writes the footer. + */ + protected void writeFooter() { + if (layout == null) { + return; + } byte[] footer = layout.getFooter(); if (footer != null) { write(footer); } - close(); } /** diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManager.java index c58b18c..3184702 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManager.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManager.java @@ -167,6 +167,7 @@ public class RollingFileManager extends FileManager { try { final RolloverDescription descriptor = strategy.rollover(this); if (descriptor != null) { + writeFooter(); close(); if (descriptor.getSynchronous() != null) { LOGGER.debug("RollingFileManager executing synchronous {}", descriptor.getSynchronous()); diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManager.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManager.java index cc63bfe..992ab09 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManager.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManager.java @@ -55,6 +55,26 @@ public class RollingRandomAccessFileManager extends RollingFileManager { this.randomAccessFile = raf; isEndOfBatch.set(Boolean.FALSE); this.buffer = ByteBuffer.allocate(bufferSize); + writeHeader(); + } + + /** + * Writes the layout's header to the file if it exists. + */ + private void writeHeader() { + if (layout == null) { + return; + } + byte[] header = layout.getHeader(); + if (header == null) { + return; + } + try { + // write to the file, not to the buffer: the buffer may not be empty + randomAccessFile.write(header, 0, header.length); + } catch (final IOException ioe) { + LOGGER.error("Unable to write header", ioe); + } } public static RollingRandomAccessFileManager getRollingRandomAccessFileManager(final String fileName, @@ -99,6 +119,7 @@ public class RollingRandomAccessFileManager extends RollingFileManager { if (isAppend()) { randomAccessFile.seek(randomAccessFile.length()); } + writeHeader(); } @Override
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-581_bb02fa15.diff
bugs-dot-jar_data_LOG4J2-763_b2ec5106
--- BugID: LOG4J2-763 Summary: Async loggers convert message parameters toString at log record writing not at log statement execution Description: "http://javaadventure.blogspot.com/2014/07/log4j-20-async-loggers-and-immutability.html\n\nWhen using parameterized messages, the toString() method of the log messages is not called when the log message is enqueued, rather after the log message has been dequeued for writing. If any of the message parameters are mutable, they can thus have changed state before the log message is written, thus resulting in the logged message content being incorrect.\n\nFrom the blog post, code that demonstrates the problem:\n{code}\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport java.util.concurrent.atomic.AtomicLong;\n\npublic class App {\n private static final AtomicLong value = new AtomicLong();\n public String toString() {\n return Long.toString(value.get());\n }\n public long next() {\n return value.incrementAndGet();\n \ }\n\n public static void main(String[] args) {\n for (int i = 0; i < 32; i++) {\n new Thread() {\n final Logger logger = LogManager.getLogger(App.class);\n final App instance = new App();\n \ @Override\n public void run() {\n for (int i = 0; i < 100000; i++) {\n logger.warn(\"{} == {}\", instance.next(), instance);\n }\n }\n }.start();\n \ }\n }\n}\n{code}\n\nHere is the first few lines of logging output\n{code}\n2014-07-28 15:59:45,729 WARN t.App [Thread-13] 13 == 13 \n2014-07-28 15:59:45,730 WARN t.App [Thread-29] 29 == 29 \n2014-07-28 15:59:45,729 WARN t.App [Thread-15] 15 == 15 \n2014-07-28 15:59:45,729 WARN t.App [Thread-6] 6 == 6 \n2014-07-28 15:59:45,730 WARN t.App [Thread-30] 30 == 30 \n2014-07-28 15:59:45,729 WARN t.App [Thread-20] 20 == 20 \n2014-07-28 15:59:45,729 WARN t.App [Thread-8] 8 == 8 \n2014-07-28 15:59:45,730 WARN t.App [Thread-28] 28 == 28 \n2014-07-28 15:59:45,729 WARN t.App [Thread-19] 19 == 19 \n2014-07-28 15:59:45,729 WARN t.App [Thread-18] 18 == 18 \n2014-07-28 15:59:45,729 WARN t.App [Thread-5] 5 == 6 \n2014-07-28 15:59:45,731 WARN t.App [Thread-13] 33 == 37 \n2014-07-28 15:59:45,731 WARN t.App [Thread-8] 39 == 39 \n2014-07-28 15:59:45,731 WARN t.App [Thread-28] 40 == 41 \n2014-07-28 15:59:45,731 WARN t.App [Thread-18] 42 == 43 \n2014-07-28 15:59:45,731 WARN t.App [Thread-5] 43 == 43\n{code}\n\nTo make my previous code work with Asynchronous loggers (other than by fixing the mutable state) I would need to log like this:\n\n{code}\nif (logger.isWarnEnabled()) {\n logger.warn(\"{} == {}\", instance.next(), instance.toString());\n}\n{code}\n\n" diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java b/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java index 021adcc..3441edb 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/message/ObjectMessage.java @@ -83,7 +83,11 @@ public class ObjectMessage implements Message { } final ObjectMessage that = (ObjectMessage) o; - return obj == null ? that.obj == null : obj.equals(that.obj); + return obj == null ? that.obj == null : equalObjectsOrStrings(obj, that.obj); + } + + private boolean equalObjectsOrStrings(Object left, Object right) { + return left.equals(right) || String.valueOf(left).equals(String.valueOf(right)); } @Override
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-763_b2ec5106.diff
bugs-dot-jar_data_LOG4J2-1251_424068f7
--- BugID: LOG4J2-1251 Summary: JUL bridge broken Description: |- org.apache.logging.log4j.jul.ApiLogger doesnt behave the same depending where we come from (logger.info() vs logger.log() typically) The main difference is the message factory used. for this statement: {code} logger.info("{foo}"); {code} a SimpleMessage will be emitted but for {code} logger.log(recordWithSameContent); {code} a MessageFormatMessage will be emitted making the log statement failling. org.apache.logging.log4j.jul.ApiLogger#log(java.util.logging.LogRecord) should be reworked to handle such a case. Here how to reproduce it: {code} Logger.getLogger("foo").info("{test}"); Logger.getLogger("foo").log(new LogRecord(Level.INFO, "{test}")); {code} The fix is as simple as testing org.apache.logging.log4j.jul.ApiLogger#log(java.util.logging.LogRecord) and if null don't call logger.getMessageFactory().newMessage(record.getMessage(), record.getParameters()) but logger.getMessageFactory().newMessage(record.getMessage()) diff --git a/log4j-jul/src/main/java/org/apache/logging/log4j/jul/ApiLogger.java b/log4j-jul/src/main/java/org/apache/logging/log4j/jul/ApiLogger.java index adac9be..92b2dff 100644 --- a/log4j-jul/src/main/java/org/apache/logging/log4j/jul/ApiLogger.java +++ b/log4j-jul/src/main/java/org/apache/logging/log4j/jul/ApiLogger.java @@ -23,6 +23,7 @@ import java.util.logging.LogRecord; import java.util.logging.Logger; import org.apache.logging.log4j.message.Message; +import org.apache.logging.log4j.message.MessageFactory; import org.apache.logging.log4j.spi.ExtendedLogger; /** @@ -36,7 +37,7 @@ import org.apache.logging.log4j.spi.ExtendedLogger; * accurate!</p> * <p>Also note that {@link #setParent(java.util.logging.Logger)} is explicitly unsupported. Parent loggers are * determined using the syntax of the logger name; not through an arbitrary graph of loggers.</p> - * + * * @since 2.1 */ public class ApiLogger extends Logger { @@ -56,7 +57,11 @@ public class ApiLogger extends Logger { return; } final org.apache.logging.log4j.Level level = LevelTranslator.toLevel(record.getLevel()); - final Message message = logger.getMessageFactory().newMessage(record.getMessage(), record.getParameters()); + final Object[] parameters = record.getParameters(); + final MessageFactory messageFactory = logger.getMessageFactory(); + final Message message = parameters == null ? + messageFactory.newMessage(record.getMessage()) /* LOG4J2-1251: not formatted case */ : + messageFactory.newMessage(record.getMessage(), parameters); final Throwable thrown = record.getThrown(); logger.logIfEnabled(FQCN, level, null, message, thrown); } @@ -94,6 +99,7 @@ public class ApiLogger extends Logger { /** * Unsupported operation. + * * @throws UnsupportedOperationException always */ @Override
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-1251_424068f7.diff
bugs-dot-jar_data_LOG4J2-302_300bc575
--- BugID: LOG4J2-302 Summary: NDCPatternConverter broken in beta7 Description: "After an upgrade from version 2.0-beta4 to beta7 the NDCPatternConverter writes an object-ID instead of the content of the NDC-stack. \n\nWe are using an pattern with \"[%0.50x]\". In beta4 the resulting output looks like \"[cbi@CE03178]\" which means username and machine. Now in beta7 it looks like \"[logging.log4j.spi.MutableThreadContextStack@875ef7]\".\n\nI analysed the issue in NDCPatternConverter.format(...) method, where event.getContextStack() is called and the result is passed to StringBuilder.append(...), which means, that the toString()-method will be invoked. \nIn beta4 getContextStack() returns an instance of ImmutableStack. This class inherits its toString() method from AbstractList, where the elements of the collection will be formatted human-readable. \nNow in beta7 there comes an instance of MutableThreadContextStack which isn't derived from AbstractList but implements the Collection-Interface. The toString() method comes from Object and returns the name of the class and an object-ID instead of the context of the unterlying stack/collection.\n\nIn my opinion you just need to copy or derive the toString() method from AbstractList to solve this issue. Thank you in advance!\n" diff --git a/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextMap.java b/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextMap.java index eca7126..953d1e5 100644 --- a/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextMap.java +++ b/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextMap.java @@ -139,4 +139,10 @@ public class DefaultThreadContextMap implements ThreadContextMap { final Map<String, String> map = localMap.get(); return map == null || map.size() == 0; } + + @Override + public String toString() { + Map<String, String> map = localMap.get(); + return map == null ? "{}" : map.toString(); + } } diff --git a/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextStack.java b/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextStack.java index 20f5afb..54ea256 100644 --- a/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextStack.java +++ b/api/src/main/java/org/apache/logging/log4j/spi/DefaultThreadContextStack.java @@ -251,4 +251,10 @@ public class DefaultThreadContextStack implements ThreadContextStack { stack.set(Collections.unmodifiableList(copy)); return result; } + + @Override + public String toString() { + final List<String> list = stack.get(); + return list == null ? "[]" : list.toString(); + } } diff --git a/api/src/main/java/org/apache/logging/log4j/spi/MutableThreadContextStack.java b/api/src/main/java/org/apache/logging/log4j/spi/MutableThreadContextStack.java index 164c5c0..1c1e654 100644 --- a/api/src/main/java/org/apache/logging/log4j/spi/MutableThreadContextStack.java +++ b/api/src/main/java/org/apache/logging/log4j/spi/MutableThreadContextStack.java @@ -161,4 +161,9 @@ public class MutableThreadContextStack implements ThreadContextStack { public boolean retainAll(final Collection<?> objects) { return list.retainAll(objects); } + + @Override + public String toString() { + return String.valueOf(list); + } }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-302_300bc575.diff
bugs-dot-jar_data_LOG4J2-258_7b38965d
--- BugID: LOG4J2-258 Summary: HTML layout does not output meta element for charset. Description: |- HTML layout does not output meta element for charset. HEAD element should include a child element, like: {code:xml} <meta charset="UTF-8"/> {code} diff --git a/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java b/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java index 7adce60..76dfdfe 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java +++ b/core/src/main/java/org/apache/logging/log4j/core/layout/HTMLLayout.java @@ -258,6 +258,7 @@ public final class HTMLLayout extends AbstractStringLayout { sbuf.append(Constants.LINE_SEP); sbuf.append("<html>").append(Constants.LINE_SEP); sbuf.append("<head>").append(Constants.LINE_SEP); + sbuf.append("<meta charset=\"").append(getCharset()).append("\"/>").append(Constants.LINE_SEP); sbuf.append("<title>").append(title).append("</title>").append(Constants.LINE_SEP); sbuf.append("<style type=\"text/css\">").append(Constants.LINE_SEP); sbuf.append("<!--").append(Constants.LINE_SEP); @@ -317,7 +318,7 @@ public final class HTMLLayout extends AbstractStringLayout { @PluginAttr("charset") final String charsetName, @PluginAttr("fontSize") String fontSize, @PluginAttr("fontName") String font) { - final Charset charset = Charsets.getSupportedCharset(charsetName); + final Charset charset = Charsets.getSupportedCharset(charsetName, Charsets.UTF_8); if (font == null) { font = "arial,sans-serif"; }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-258_7b38965d.diff
bugs-dot-jar_data_LOG4J2-813_0bea17d7
--- BugID: LOG4J2-813 Summary: MarkerManager Log4jMarker.hasParents() returns opposite of correct result Description: "Log4JMarker.hasParents() will return false when the marker has parents, and true when it has none. \n\nThe javadoc in the Marker interface indicates it should function the other way around: \n{quote}\n\"Indicates whether this Marker has references to any other Markers. Return true if the Marker has parent Markers\"\n{quote}\n\nThe code for the implementation (that I could find) demonstrates that it would function in the opposite way as it is described in that javadoc: \n{code}\n@Override \npublic boolean hasParents() { \n return this.parents == null; \n}\n{code}" diff --git a/log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java b/log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java index 2dea94e..5bf38e1 100644 --- a/log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java +++ b/log4j-api/src/main/java/org/apache/logging/log4j/MarkerManager.java @@ -228,7 +228,7 @@ public final class MarkerManager { @Override public boolean hasParents() { - return this.parents == null; + return this.parents != null; } @Override
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-813_0bea17d7.diff
bugs-dot-jar_data_LOG4J2-834_d3989b40
--- BugID: LOG4J2-834 Summary: ThrowableProxy throws NoClassDefFoundError Description: |- In method *loadClass* we expect {{ClassNotFoundException}}. But if class comes from another java machine we can get {{NoClassDefFoundError}}. Possible fix: {code:java} private Class<?> loadClass(final ClassLoader lastLoader, final String className) { // XXX: this is overly complicated Class<?> clazz; if (lastLoader != null) { try { clazz = Loader.initializeClass(className, lastLoader); if (clazz != null) { return clazz; } } catch (final Throwable ignore) { // Ignore exception. } } try { clazz = Loader.loadClass(className); } catch (final ClassNotFoundException | LinkageError ignored) { try { clazz = Loader.initializeClass(className, this.getClass().getClassLoader()); } catch (final ClassNotFoundException | LinkageError ignore) { return null; } } return clazz; } {code} diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java index 75c8564..3aadf6c 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThrowableProxy.java @@ -451,15 +451,23 @@ public class ThrowableProxy implements Serializable { try { clazz = Loader.loadClass(className); } catch (final ClassNotFoundException ignored) { - try { - clazz = Loader.initializeClass(className, this.getClass().getClassLoader()); - } catch (final ClassNotFoundException ignore) { - return null; - } + return initializeClass(className); + } catch (final NoClassDefFoundError ignored) { + return initializeClass(className); } return clazz; } + private Class<?> initializeClass(final String className) { + try { + return Loader.initializeClass(className, this.getClass().getClassLoader()); + } catch (final ClassNotFoundException ignore) { + return null; + } catch (final NoClassDefFoundError ignore) { + return null; + } + } + /** * Construct the CacheEntry from the Class's information. *
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-834_d3989b40.diff
bugs-dot-jar_data_LOG4J2-139_50e19247
--- BugID: LOG4J2-139 Summary: NPE while using SocketAppender Description: "I try to use the SocketAppender and get the following ERROR/NPE:\n\n2013-01-06 00:54:14,024 DEBUG Generated plugins in 0.000032000 seconds\n2013-01-06 00:54:14,044 DEBUG Calling createLayout on class org.apache.logging.log4j.core.layout.PatternLayout for element PatternLayout with params(pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} --- %msg%n\", Configuration(/Users/jhuxhorn/Documents/Projects/huxi/lilith/sandbox/log4j2-sandbox/build/resources/main/log4j2.xml), null, charset=\"null\")\n2013-01-06 00:54:14,045 DEBUG Generated plugins in 0.000029000 seconds\n2013-01-06 00:54:14,049 DEBUG Calling createAppender on class org.apache.logging.log4j.core.appender.ConsoleAppender for element Console with params(PatternLayout(%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} --- %msg%n), null, target=\"SYSTEM_OUT\", name=\"Console\", suppressExceptions=\"null\")\n2013-01-06 00:54:14,049 DEBUG Calling createLayout on class org.apache.logging.log4j.core.layout.SerializedLayout for element SerializedLayout\n2013-01-06 00:54:14,052 DEBUG Calling createAppender on class org.apache.logging.log4j.core.appender.SocketAppender for element Socket with params(host=\"localhost\", port=\"4560\", protocol=\"null\", reconnectionDelay=\"null\", name=\"Socket\", immediateFlush=\"null\", suppressExceptions=\"null\", SerializedLayout(org.apache.logging.log4j.core.layout.SerializedLayout@5cc4211b), null)\n2013-01-06 00:54:14,054 ERROR Unable to invoke method createAppender in class org.apache.logging.log4j.core.appender.SocketAppender for element Socket java.lang.reflect.InvocationTargetException\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:601)\n\tat org.apache.logging.log4j.core.config.BaseConfiguration.createPluginObject(BaseConfiguration.java:711)\n\tat org.apache.logging.log4j.core.config.BaseConfiguration.createConfiguration(BaseConfiguration.java:477)\n\tat org.apache.logging.log4j.core.config.BaseConfiguration.createConfiguration(BaseConfiguration.java:469)\n\tat org.apache.logging.log4j.core.config.BaseConfiguration.doConfigure(BaseConfiguration.java:156)\n\tat org.apache.logging.log4j.core.config.BaseConfiguration.start(BaseConfiguration.java:114)\n\tat org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:251)\n\tat org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:267)\n\tat org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:134)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:75)\n\tat org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:30)\n\tat org.apache.logging.log4j.LogManager.getLogger(LogManager.java:165)\n\tat org.apache.logging.log4j.LogManager.getLogger(LogManager.java:174)\n\tat de.huxhorn.lilith.sandbox.Log4j2Sandbox.main(Log4j2Sandbox.java:43)\nCaused by: java.lang.NullPointerException\n\tat org.apache.logging.log4j.core.appender.SocketAppender.createSocketManager(SocketAppender.java:95)\n\tat org.apache.logging.log4j.core.appender.SocketAppender.createAppender(SocketAppender.java:86)\n\t... 17 more\n\n2013-01-06 00:54:14,056 ERROR Null object returned for Socket in appenders\n\n\nMy configuration looks like this:\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration status=\"debug\">\n\t<appenders>\n\t\t<Console name=\"Console\" target=\"SYSTEM_OUT\">\n\t\t\t<PatternLayout pattern=\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} --- %msg%n\"/>\n\t\t</Console>\n\t\t<Socket name=\"Socket\" host=\"localhost\" port=\"4560\">\n\t\t\t<SerializedLayout />\n\t\t</Socket>\n\t</appenders>\n\t<loggers>\n\t\t<root level=\"all\">\n\t\t\t<appender-ref ref=\"Console\"/>\n\t\t\t<appender-ref ref=\"Socket\"/>\n\t\t</root>\n\t</loggers>\n</configuration>\n" diff --git a/core/src/main/java/org/apache/logging/log4j/core/appender/SocketAppender.java b/core/src/main/java/org/apache/logging/log4j/core/appender/SocketAppender.java index f9d0665..01701f6 100644 --- a/core/src/main/java/org/apache/logging/log4j/core/appender/SocketAppender.java +++ b/core/src/main/java/org/apache/logging/log4j/core/appender/SocketAppender.java @@ -115,8 +115,7 @@ public class SocketAppender<T extends Serializable> extends AbstractOutputStream return null; } - final String prot = protocol != null ? protocol : Protocol.TCP.name(); - final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol); + final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol != null ? protocol : Protocol.TCP.name()); if (p.equals(Protocol.UDP)) { isFlush = true; }
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-139_50e19247.diff
bugs-dot-jar_data_LOG4J2-466_7b9e48e8
--- BugID: LOG4J2-466 Summary: Cannot load log4j2 config file if path contains plus '+' characters Description: "Hello,\n\nI was trying to programmatically load a XML config file from the temporary data directory of a MacOS X system. The temp path consists of serveral '\\+' characters like MacOS automatically generates this path so we have to take it this way. Even I would agree that it is not nice to have '\\+' chars in a path name.\n\nWhen I tried to load the XML config the framework permanently loaded the DefaultConfig and not the desired XML configuration.\nBy stepping through the debugger I figured out that this was caused by the method fileFromURI() in org.apache.logging.log4j.core.helpers.FileUtils.java .\nThe misbehaviour was basically caused by the call of URL.decode() which converts '+' to ' ' (space) of a given String. \nNow I self-compiled the whole framework without the call of URL.decode() and the XML configuration loaded properly. \nI can not see why this call is necessary in this method so in my opinion this should be removed.\n\n\nKind regards" diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/FileUtils.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/FileUtils.java index 5752f77..2e38b52 100644 --- a/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/FileUtils.java +++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/helpers/FileUtils.java @@ -63,7 +63,11 @@ public final class FileUtils { } } try { - return new File(URLDecoder.decode(uri.toURL().getFile(), "UTF8")); + String fileName = uri.toURL().getFile(); + if (new File(fileName).exists()) { + return new File(fileName); + } + return new File(URLDecoder.decode(fileName, "UTF8")); } catch (final MalformedURLException ex) { LOGGER.warn("Invalid URL " + uri, ex); } catch (final UnsupportedEncodingException uee) {
bugs-dot-jar/logging-log4j2_extracted_diff/developer-patch_bugs-dot-jar_LOG4J2-466_7b9e48e8.diff