This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 218150
Collapse All | Expand All

(-)a/html.editor/src/org/netbeans/modules/html/editor/gsf/embedding/CssEmbeddingProvider.java (-38 / +16 lines)
Lines 47-92 Link Here
47
import org.netbeans.modules.parsing.api.Embedding;
47
import org.netbeans.modules.parsing.api.Embedding;
48
import org.netbeans.modules.parsing.api.Snapshot;
48
import org.netbeans.modules.parsing.api.Snapshot;
49
import org.netbeans.modules.parsing.spi.EmbeddingProvider;
49
import org.netbeans.modules.parsing.spi.EmbeddingProvider;
50
import org.netbeans.modules.parsing.spi.SchedulerTask;
51
import org.netbeans.modules.parsing.spi.TaskFactory;
52
50
53
/**
51
/**
54
 *
52
 *
55
 * @author marekfukala
53
 * @author marekfukala
56
 */
54
 */
55
@EmbeddingProvider.Registration(
56
        mimeType="text/html",
57
        targetMimeType="text/css"
58
)
57
public class CssEmbeddingProvider extends EmbeddingProvider {
59
public class CssEmbeddingProvider extends EmbeddingProvider {
58
60
59
    private static final Logger LOG = Logger.getLogger(CssEmbeddingProvider.class.getSimpleName());
61
    private static final Logger LOG = Logger.getLogger(CssEmbeddingProvider.class.getSimpleName());
60
    
61
    private static final long MAX_SNAPSHOT_SIZE = 4 * 1024 * 1024; //4MB
62
    private static final long MAX_SNAPSHOT_SIZE = 4 * 1024 * 1024; //4MB
62
    
63
    private static final String HTML_MIME_TYPE = "text/html"; // NOI18N
63
    public static class Factory extends TaskFactory {
64
64
65
        private static final String HTML_MIME_TYPE = "text/html"; // NOI18N
65
    private String sourceMimeType;
66
    private Translator translator;
66
67
67
        private static final Map<String, Translator> translators = new HashMap<String, Translator>();
68
    public CssEmbeddingProvider() {
68
69
        this.sourceMimeType = HTML_MIME_TYPE;
69
        static {
70
        this.translator = new CssHtmlTranslator();
70
            translators.put(HTML_MIME_TYPE, new CssHtmlTranslator()); //xxx can I use shared instance???
71
        }
72
73
        @Override
74
        public Collection<? extends SchedulerTask> create(Snapshot snapshot) {
75
            
76
            int slen = snapshot.getText().length();
77
            LOG.fine(String.format("CssEmbeddingProvider.create(snapshot): mimetype: %s, size: %s", snapshot.getMimeType(), slen)); //NOI18N
78
            if(slen > MAX_SNAPSHOT_SIZE) {
79
                LOG.fine(String.format("Size %s > maximum (%s) => providing no css embedding", slen, MAX_SNAPSHOT_SIZE)); //NOI18N
80
                return Collections.<SchedulerTask>emptyList();
81
            }
82
            
83
            Translator t = translators.get(snapshot.getMimeType());
84
            if (t != null) {
85
                return Collections.singleton(new CssEmbeddingProvider(snapshot.getMimeType(), t));
86
            } else {
87
                return Collections.<SchedulerTask>emptyList();
88
            }
89
        }
90
    }
71
    }
91
72
92
    public static interface Translator {
73
    public static interface Translator {
Lines 95-112 Link Here
95
    
76
    
96
    }
77
    }
97
78
98
99
    private String sourceMimeType;
100
    private Translator translator;
101
102
    private CssEmbeddingProvider(String sourceMimeType, Translator translator) {
103
        this.sourceMimeType = sourceMimeType;
104
        this.translator = translator;
105
    }
106
107
    @Override
79
    @Override
108
    public List<Embedding> getEmbeddings(Snapshot snapshot) {
80
    public List<Embedding> getEmbeddings(Snapshot snapshot) {
109
        if (sourceMimeType.equals(snapshot.getMimeType())) {
81
        if (sourceMimeType.equals(snapshot.getMimeType())) {
82
            int slen = snapshot.getText().length();
83
            LOG.fine(String.format("CssEmbeddingProvider.create(snapshot): mimetype: %s, size: %s", snapshot.getMimeType(), slen)); //NOI18N
84
            if(slen > MAX_SNAPSHOT_SIZE) {
85
                LOG.fine(String.format("Size %s > maximum (%s) => providing no css embedding", slen, MAX_SNAPSHOT_SIZE)); //NOI18N
86
                return Collections.<Embedding>emptyList();
87
            }
110
            List<Embedding> embeddings = translator.getEmbeddings(snapshot);
88
            List<Embedding> embeddings = translator.getEmbeddings(snapshot);
111
            if(embeddings.isEmpty()) {
89
            if(embeddings.isEmpty()) {
112
                return Collections.emptyList();
90
                return Collections.emptyList();
(-)a/html.editor/src/org/netbeans/modules/html/editor/resources/layer.xml (-4 / +1 lines)
Lines 85-94 Link Here
85
85
86
    <folder name="Editors">
86
    <folder name="Editors">
87
87
88
88
        
89
        <file name="org-netbeans-modules-html-editor-gsf-embedding-CssEmbeddingProvider$Factory.instance">
90
            <attr name="instanceOf" stringvalue="org.netbeans.modules.parsing.spi.TaskFactory"/>
91
        </file>
92
89
93
        <folder name="text">
90
        <folder name="text">
94
91
(-)a/parsing.api/apichanges.xml (+17 lines)
Lines 110-115 Link Here
110
<!-- ACTUAL CHANGES BEGIN HERE: -->
110
<!-- ACTUAL CHANGES BEGIN HERE: -->
111
111
112
  <changes>
112
  <changes>
113
  <change id="EmbeddingProvider.Registration">
114
      <api name="ParsingAPI"/>
115
      <summary>Added <code>EmbeddingProvider.Registration</code> annotation to register <code>EmbeddingProvider</code>s.</summary>
116
      <version major="1" minor="57"/>
117
      <date day="14" month="9" year="2012"/>
118
      <author login="tzezula"/>
119
      <compatibility source="compatible" binary="compatible" semantic="compatible" deletion="no" addition="yes" modification="no"/>
120
      <description>
121
          <p>
122
               Added <code>EmbeddingProvider.Registration</code> annotation to register <code>EmbeddingProvider</code>s.
123
               The registration provides a mime type of a generated embedding which allows the infrastructure to correctly
124
               handle embedded indexes.
125
          </p>
126
      </description>
127
      <class package="org.netbeans.modules.parsing.spi" name="EmbeddingProvider"/>
128
      <issue number="218148"/>
129
  </change>
113
  <change id="SuspendStatus">
130
  <change id="SuspendStatus">
114
      <api name="ParsingAPI"/>
131
      <api name="ParsingAPI"/>
115
      <summary>Added <code>SuspendStatus</code> service which can be used by indexers to find out if
132
      <summary>Added <code>SuspendStatus</code> service which can be used by indexers to find out if
(-)a/parsing.api/nbproject/project.properties (-1 / +1 lines)
Lines 3-9 Link Here
3
javac.source=1.6
3
javac.source=1.6
4
javadoc.apichanges=${basedir}/apichanges.xml
4
javadoc.apichanges=${basedir}/apichanges.xml
5
javadoc.arch=${basedir}/arch.xml
5
javadoc.arch=${basedir}/arch.xml
6
spec.version.base=1.56.0
6
spec.version.base=1.57.0
7
7
8
test.config.stableBTD.includes=**/*Test.class
8
test.config.stableBTD.includes=**/*Test.class
9
test.config.stableBTD.excludes=\
9
test.config.stableBTD.excludes=\
(-)a/parsing.api/src/org/netbeans/modules/parsing/impl/EmbeddingProviderFactory.java (+94 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.parsing.impl;
43
44
import java.util.Collection;
45
import java.util.Collections;
46
import java.util.Map;
47
import org.netbeans.api.annotations.common.NonNull;
48
import org.netbeans.modules.parsing.api.Snapshot;
49
import org.netbeans.modules.parsing.spi.EmbeddingProvider;
50
import org.netbeans.modules.parsing.spi.SchedulerTask;
51
import org.netbeans.modules.parsing.spi.TaskFactory;
52
import org.openide.util.Parameters;
53
54
/**
55
 *
56
 * @author Tomas Zezula
57
 */
58
public class EmbeddingProviderFactory extends TaskFactory {
59
60
    public static final String ATTR_TARGET_MIME_TYPE = "targetMimeType";   //NOI18N
61
    public static final String ATTR_PROVIDER = "provider";                 //NOI18N
62
    
63
    private final Map<String,Object> params;
64
    private final String targetMimeType;
65
66
    private EmbeddingProviderFactory(@NonNull final Map<String,Object> params) {
67
        Parameters.notNull("definition", params);   //NOI18N
68
        this.params = params;
69
        this.targetMimeType = (String) params.get(ATTR_TARGET_MIME_TYPE);
70
        if (this.targetMimeType == null) {
71
            throw new IllegalArgumentException(
72
                String.format(
73
                    "The definition file has no %s attribute.", //NOI18N
74
                    ATTR_TARGET_MIME_TYPE));
75
        }
76
    }
77
78
    public String getTargetMimeType() {
79
        return this.targetMimeType;
80
    }
81
82
    @NonNull
83
    @Override
84
    public Collection<? extends SchedulerTask> create (@NonNull final Snapshot snapshot) {
85
        final Object delegate = params.get(ATTR_PROVIDER);
86
        return (delegate instanceof EmbeddingProvider) ?
87
                Collections.singleton((EmbeddingProvider)delegate) :
88
                Collections.<EmbeddingProvider>emptySet();
89
    }
90
91
    public static TaskFactory create(@NonNull final Map<String,Object> params) {
92
        return new EmbeddingProviderFactory(params);
93
    }
94
}
(-)a/parsing.api/src/org/netbeans/modules/parsing/impl/EmbeddingProviderRegistrationProcessor.java (+99 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.parsing.impl;
43
44
import java.util.Collections;
45
import java.util.Set;
46
import javax.annotation.processing.Processor;
47
import javax.annotation.processing.RoundEnvironment;
48
import javax.annotation.processing.SupportedSourceVersion;
49
import javax.lang.model.SourceVersion;
50
import javax.lang.model.element.Element;
51
import javax.lang.model.element.TypeElement;
52
import org.netbeans.modules.parsing.spi.EmbeddingProvider;
53
import org.netbeans.modules.parsing.spi.TaskFactory;
54
import org.openide.filesystems.annotations.LayerGeneratingProcessor;
55
import org.openide.filesystems.annotations.LayerGenerationException;
56
import org.openide.util.lookup.ServiceProvider;
57
58
/**
59
 *
60
 * @author Tomas Zezula
61
 */
62
@ServiceProvider(service=Processor.class)
63
@SupportedSourceVersion(SourceVersion.RELEASE_6)
64
public class EmbeddingProviderRegistrationProcessor extends LayerGeneratingProcessor {
65
66
    @Override
67
    public Set<String> getSupportedAnnotationTypes() {
68
        return Collections.singleton(EmbeddingProvider.Registration.class.getCanonicalName());
69
    }
70
71
    @Override
72
    protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws LayerGenerationException {
73
        for (Element e :  roundEnv.getElementsAnnotatedWith(EmbeddingProvider.Registration.class)) {
74
            if (!e.getKind().isClass()) {
75
                throw new LayerGenerationException("Annotated Element has to be a class.", e);  //NOI18N
76
            }
77
            final EmbeddingProvider.Registration reg = e.getAnnotation(EmbeddingProvider.Registration.class);
78
            String mimeType = reg.mimeType();
79
            if (mimeType == null) {
80
                throw new LayerGenerationException("Mime type has to be given.", e);  //NOI18N
81
            } else if (!mimeType.isEmpty()) {
82
                mimeType =  '/' + mimeType; //NOI18N
83
            }
84
            String targetMimeType = reg.targetMimeType();
85
            if (targetMimeType == null || targetMimeType.isEmpty()) {
86
                throw new LayerGenerationException("Target mime type has to be given.", e);  //NOI18N
87
            }
88
            layer(e).
89
                instanceFile("Editors" + mimeType, null, null).    //NOI18N
90
                stringvalue("instanceOf", TaskFactory.class.getName()).         ///NOI18N
91
                methodvalue("instanceCreate", EmbeddingProviderFactory.class.getName(), "create").         //NOI18N
92
                stringvalue(EmbeddingProviderFactory.ATTR_TARGET_MIME_TYPE, targetMimeType).
93
                instanceAttribute(EmbeddingProviderFactory.ATTR_PROVIDER, EmbeddingProvider.class).
94
                write();
95
        }
96
        return true;
97
    }
98
99
}
(-)a/parsing.api/src/org/netbeans/modules/parsing/impl/indexing/RepositoryUpdater.java (-1 / +18 lines)
Lines 1398-1404 Link Here
1398
                            }
1398
                            }
1399
                        }
1399
                        }
1400
1400
1401
                        Collection<? extends IndexerCache.IndexerInfo<EmbeddingIndexerFactory>> eifInfos = IndexerCache.getEifCache().getIndexersFor(mimeType, true);
1401
                        Collection<? extends IndexerCache.IndexerInfo<EmbeddingIndexerFactory>> eifInfos = collectEmbeddingIndexers(mimeType);
1402
                        for(IndexerCache.IndexerInfo<EmbeddingIndexerFactory> info : eifInfos) {
1402
                        for(IndexerCache.IndexerInfo<EmbeddingIndexerFactory> info : eifInfos) {
1403
                            try {
1403
                            try {
1404
                                EmbeddingIndexerFactory factory = info.getIndexerFactory();
1404
                                EmbeddingIndexerFactory factory = info.getIndexerFactory();
Lines 1446-1451 Link Here
1446
        }
1446
        }
1447
    }
1447
    }
1448
1448
1449
    @NonNull
1450
    private static Collection<? extends IndexerCache.IndexerInfo<EmbeddingIndexerFactory>> collectEmbeddingIndexers(
1451
            @NonNull final String topMimeType){
1452
        final Collection<IndexerCache.IndexerInfo<EmbeddingIndexerFactory>> result = new ArrayDeque<IndexerInfo<EmbeddingIndexerFactory>>();
1453
        collectEmbeddingIndexers(topMimeType, result);
1454
        return result;
1455
    }
1456
1457
    private static void collectEmbeddingIndexers(
1458
            @NonNull final String mimeType,
1459
            @NonNull final Collection<? super IndexerCache.IndexerInfo<EmbeddingIndexerFactory>> collector) {
1460
        collector.addAll(IndexerCache.getEifCache().getIndexersFor(mimeType, true));
1461
        for (EmbeddingProviderFactory epf : MimeLookup.getLookup(MimePath.get(mimeType)).lookupAll(EmbeddingProviderFactory.class)) {
1462
            collectEmbeddingIndexers(epf.getTargetMimeType(), collector);
1463
        }
1464
    }
1465
1449
    /* test */ void scheduleWork(Iterable<? extends Work> multipleWork) {
1466
    /* test */ void scheduleWork(Iterable<? extends Work> multipleWork) {
1450
        recordCaller();
1467
        recordCaller();
1451
1468
(-)a/parsing.api/src/org/netbeans/modules/parsing/spi/EmbeddingProvider.java (+29 lines)
Lines 42-50 Link Here
42
42
43
package org.netbeans.modules.parsing.spi;
43
package org.netbeans.modules.parsing.spi;
44
44
45
import java.lang.annotation.ElementType;
46
import java.lang.annotation.Retention;
47
import java.lang.annotation.RetentionPolicy;
48
import java.lang.annotation.Target;
45
import java.util.List;
49
import java.util.List;
46
import org.netbeans.modules.parsing.api.Embedding;
50
import org.netbeans.modules.parsing.api.Embedding;
47
import org.netbeans.modules.parsing.api.Snapshot;
51
import org.netbeans.modules.parsing.api.Snapshot;
52
import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
48
53
49
54
50
/**
55
/**
Lines 83-88 Link Here
83
     * @return              priority of this source provider
88
     * @return              priority of this source provider
84
     */
89
     */
85
    public abstract int getPriority ();
90
    public abstract int getPriority ();
91
92
    /**
93
     * Registration of the {@link EmbeddingProvider}.
94
     * Creates a mime lookup registration of the {@link TaskFactory} for
95
     * annotated {@link EmbeddingProvider}. It also provides the target
96
     * mime type of the created embedding which allows the {@link QuerySupport}
97
     * to correctly mark dirty embedded indexers.
98
     *
99
     * @since 1.57
100
     */
101
    @Retention(RetentionPolicy.SOURCE)
102
    @Target(ElementType.TYPE)
103
    public @interface Registration {
104
105
        /**
106
         * Mime type to which should be the given {@link EmbeddingProvider} registered.
107
         */
108
         public String mimeType();
109
110
        /**
111
         * Mime type of the embedding created by the registered {@link EmbeddingProvider}
112
         */
113
        String targetMimeType();
114
    }
86
}
115
}
87
116
88
117
(-)a/parsing.api/test/unit/src/org/netbeans/modules/parsing/impl/indexing/EmbeddedIndexerTest.java (-50 / +116 lines)
Lines 41-53 Link Here
41
 */
41
 */
42
package org.netbeans.modules.parsing.impl.indexing;
42
package org.netbeans.modules.parsing.impl.indexing;
43
43
44
import java.awt.Color;
45
import java.awt.Font;
46
import java.beans.PropertyChangeEvent;
47
import java.io.File;
44
import java.io.File;
48
import java.io.IOException;
45
import java.io.IOException;
49
import java.lang.reflect.Constructor;
50
import java.lang.reflect.InvocationTargetException;
51
import java.util.ArrayList;
46
import java.util.ArrayList;
52
import java.util.Arrays;
47
import java.util.Arrays;
53
import java.util.Collection;
48
import java.util.Collection;
Lines 57-85 Link Here
57
import java.util.List;
52
import java.util.List;
58
import java.util.Map;
53
import java.util.Map;
59
import java.util.Set;
54
import java.util.Set;
60
import java.util.concurrent.CountDownLatch;
61
import java.util.concurrent.atomic.AtomicReference;
55
import java.util.concurrent.atomic.AtomicReference;
62
import java.util.logging.Level;
56
import java.util.logging.Level;
63
import java.util.logging.Logger;
57
import java.util.logging.Logger;
64
import javax.swing.JEditorPane;
58
import javax.swing.JEditorPane;
65
import javax.swing.SwingUtilities;
59
import javax.swing.SwingUtilities;
66
import javax.swing.event.ChangeListener;
60
import javax.swing.event.ChangeListener;
67
import javax.swing.text.AttributeSet;
68
import javax.swing.text.BadLocationException;
69
import javax.swing.text.DefaultEditorKit;
61
import javax.swing.text.DefaultEditorKit;
70
import javax.swing.text.Document;
62
import javax.swing.text.Document;
71
import javax.swing.text.EditorKit;
63
import javax.swing.text.EditorKit;
72
import javax.swing.text.Element;
73
import javax.swing.text.Style;
74
import javax.swing.text.StyledDocument;
64
import javax.swing.text.StyledDocument;
75
import org.netbeans.api.annotations.common.NonNull;
65
import org.netbeans.api.annotations.common.NonNull;
76
import org.netbeans.api.editor.EditorRegistry;
77
import org.netbeans.api.editor.mimelookup.MimePath;
66
import org.netbeans.api.editor.mimelookup.MimePath;
78
import org.netbeans.api.editor.mimelookup.test.MockMimeLookup;
67
import org.netbeans.api.editor.mimelookup.test.MockMimeLookup;
79
import org.netbeans.api.java.classpath.ClassPath;
68
import org.netbeans.api.java.classpath.ClassPath;
80
import org.netbeans.api.java.classpath.GlobalPathRegistry;
69
import org.netbeans.api.java.classpath.GlobalPathRegistry;
81
import org.netbeans.editor.AtomicLockEvent;
82
import org.netbeans.editor.BaseDocument;
83
import org.netbeans.editor.GuardedDocument;
70
import org.netbeans.editor.GuardedDocument;
84
import org.netbeans.junit.MockServices;
71
import org.netbeans.junit.MockServices;
85
import org.netbeans.junit.NbTestCase;
72
import org.netbeans.junit.NbTestCase;
Lines 91-103 Link Here
91
import org.netbeans.modules.parsing.api.Source;
78
import org.netbeans.modules.parsing.api.Source;
92
import org.netbeans.modules.parsing.api.Task;
79
import org.netbeans.modules.parsing.api.Task;
93
import org.netbeans.modules.parsing.api.UserTask;
80
import org.netbeans.modules.parsing.api.UserTask;
81
import org.netbeans.modules.parsing.impl.EmbeddingProviderFactory;
94
import org.netbeans.modules.parsing.spi.EmbeddingProvider;
82
import org.netbeans.modules.parsing.spi.EmbeddingProvider;
95
import org.netbeans.modules.parsing.spi.ParseException;
83
import org.netbeans.modules.parsing.spi.ParseException;
96
import org.netbeans.modules.parsing.spi.Parser;
84
import org.netbeans.modules.parsing.spi.Parser;
97
import org.netbeans.modules.parsing.spi.ParserFactory;
85
import org.netbeans.modules.parsing.spi.ParserFactory;
98
import org.netbeans.modules.parsing.spi.SchedulerTask;
99
import org.netbeans.modules.parsing.spi.SourceModificationEvent;
86
import org.netbeans.modules.parsing.spi.SourceModificationEvent;
100
import org.netbeans.modules.parsing.spi.TaskFactory;
101
import org.netbeans.modules.parsing.spi.indexing.Context;
87
import org.netbeans.modules.parsing.spi.indexing.Context;
102
import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer;
88
import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer;
103
import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory;
89
import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory;
Lines 123-134 Link Here
123
import org.openide.nodes.AbstractNode;
109
import org.openide.nodes.AbstractNode;
124
import org.openide.nodes.Children;
110
import org.openide.nodes.Children;
125
import org.openide.nodes.Node;
111
import org.openide.nodes.Node;
126
import org.openide.nodes.Node.Cookie;
127
import org.openide.text.DataEditorSupport;
112
import org.openide.text.DataEditorSupport;
128
import org.openide.text.NbDocument;
113
import org.openide.text.NbDocument;
129
import org.openide.util.Exceptions;
114
import org.openide.util.Exceptions;
130
import org.openide.util.Lookup;
115
import org.openide.util.Lookup;
131
import org.openide.util.lookup.Lookups;
132
import org.openide.util.test.TestFileUtils;
116
import org.openide.util.test.TestFileUtils;
133
117
134
/**
118
/**
Lines 159-168 Link Here
159
        final FileObject wd = FileUtil.toFileObject(_wd);
143
        final FileObject wd = FileUtil.toFileObject(_wd);
160
        final FileObject cache = wd.createFolder("cache");  //NOI18N
144
        final FileObject cache = wd.createFolder("cache");  //NOI18N
161
        CacheFolder.setCacheFolder(cache);
145
        CacheFolder.setCacheFolder(cache);
146
        final Map<String,Object> attrMap = new HashMap<String,Object>();
147
        attrMap.put(EmbeddingProviderFactory.ATTR_TARGET_MIME_TYPE, MIME_INNER);
148
        attrMap.put(EmbeddingProviderFactory.ATTR_PROVIDER, new TopToInnerEmbProvider());
162
        MockMimeLookup.setInstances(
149
        MockMimeLookup.setInstances(
163
                MimePath.get(MIME_TOP),
150
                MimePath.get(MIME_TOP),
164
                new TopParser.Factory(),
151
                new TopParser.Factory(),
165
                new TopToInnerEmbProvider.Factory(),
152
                EmbeddingProviderFactory.create(attrMap),
166
                new TopIndexer.Factory());
153
                new TopIndexer.Factory());
167
        MockMimeLookup.setInstances(
154
        MockMimeLookup.setInstances(
168
                MimePath.get(MIME_INNER),
155
                MimePath.get(MIME_INNER),
Lines 179-185 Link Here
179
                "   <A>   <B>   < A> < >"));                        //NOI18N
166
                "   <A>   <B>   < A> < >"));                        //NOI18N
180
        FileUtil.setMIMEType(EXT_TOP, MIME_TOP);
167
        FileUtil.setMIMEType(EXT_TOP, MIME_TOP);
181
        RepositoryUpdaterTest.setMimeTypes(MIME_TOP, MIME_INNER);
168
        RepositoryUpdaterTest.setMimeTypes(MIME_TOP, MIME_INNER);
182
        ClassPathProviderImpl.root = srcRoot;
169
        ClassPathProviderImpl.setRoot(srcRoot);
183
        RepositoryUpdaterTest.waitForRepositoryUpdaterInit();
170
        RepositoryUpdaterTest.waitForRepositoryUpdaterInit();
184
    }
171
    }
185
172
Lines 193-199 Link Here
193
        super.tearDown();
180
        super.tearDown();
194
    }
181
    }
195
182
196
    public void testEmbeddingIndexer() throws Exception {
183
    public void testEmbeddingIndexerQueryOnOuterAndInner() throws Exception {
197
        RepositoryUpdater ru = RepositoryUpdater.getDefault();
184
        RepositoryUpdater ru = RepositoryUpdater.getDefault();
198
        assertEquals(0, ru.getScannedBinaries().size());
185
        assertEquals(0, ru.getScannedBinaries().size());
199
        assertEquals(0, ru.getScannedBinaries().size());
186
        assertEquals(0, ru.getScannedBinaries().size());
Lines 206-211 Link Here
206
193
207
        srcCp = ClassPath.getClassPath(srcRoot, PATH_TOP_SOURCES);
194
        srcCp = ClassPath.getClassPath(srcRoot, PATH_TOP_SOURCES);
208
        assertNotNull(srcCp);
195
        assertNotNull(srcCp);
196
        assertEquals(1, srcCp.getRoots().length);
197
        assertEquals(srcRoot, srcCp.getRoots()[0]);
209
        globalPathRegistry_register(PATH_TOP_SOURCES, srcCp);
198
        globalPathRegistry_register(PATH_TOP_SOURCES, srcCp);
210
        assertTrue (handler.await());
199
        assertTrue (handler.await());
211
        assertEquals(0, handler.getBinaries().size());
200
        assertEquals(0, handler.getBinaries().size());
Lines 267-280 Link Here
267
        assertEquals(1,res.size());
256
        assertEquals(1,res.size());
268
        assertEquals(Boolean.TRUE.toString(), res.iterator().next().getValue("valid")); //NOI18N
257
        assertEquals(Boolean.TRUE.toString(), res.iterator().next().getValue("valid")); //NOI18N
269
258
270
//        sup = QuerySupport.forRoots(InnerIndexer.NAME, InnerIndexer.VERSION, srcRoot);
259
        sup = QuerySupport.forRoots(InnerIndexer.NAME, InnerIndexer.VERSION, srcRoot);
271
//        res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
260
        res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
272
//        assertEquals(5,res.size());
261
        assertEquals(5,res.size());
273
//        count = countModes(res);
262
        count = countModes(res);
274
//        assertEquals(Integer.valueOf(1), count.get(0));
263
        assertEquals(Integer.valueOf(1), count.get(0));
275
//        assertEquals(Integer.valueOf(2), count.get(1));
264
        assertEquals(Integer.valueOf(2), count.get(1));
276
//        assertEquals(Integer.valueOf(1), count.get(2));
265
        assertEquals(Integer.valueOf(1), count.get(2));
277
//        assertEquals(Integer.valueOf(1), count.get(3));
266
        assertEquals(Integer.valueOf(1), count.get(3));
267
    }
268
269
    public void testEmbeddingIndexerQueryOnInnerOnly() throws Exception {
270
        RepositoryUpdater ru = RepositoryUpdater.getDefault();
271
        assertEquals(0, ru.getScannedBinaries().size());
272
        assertEquals(0, ru.getScannedBinaries().size());
273
        assertEquals(0, ru.getScannedUnknowns().size());
274
275
        final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
276
        final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
277
        logger.setLevel (Level.FINEST);
278
        logger.addHandler(handler);
279
280
        srcCp = ClassPath.getClassPath(srcRoot, PATH_TOP_SOURCES);
281
        assertNotNull(srcCp);
282
        assertEquals(1, srcCp.getRoots().length);
283
        assertEquals(srcRoot, srcCp.getRoots()[0]);
284
        globalPathRegistry_register(PATH_TOP_SOURCES, srcCp);
285
        assertTrue (handler.await());
286
        assertEquals(0, handler.getBinaries().size());
287
        assertEquals(1, handler.getSources().size());
288
        assertEquals(srcRoot.toURL(), handler.getSources().get(0));
289
290
        QuerySupport sup = QuerySupport.forRoots(TopIndexer.NAME, TopIndexer.VERSION, srcRoot);
291
        Collection<? extends IndexResult> res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
292
        assertEquals(1,res.size());
293
        assertEquals(Boolean.TRUE.toString(), res.iterator().next().getValue("valid")); //NOI18N
294
295
        sup = QuerySupport.forRoots(InnerIndexer.NAME, InnerIndexer.VERSION, srcRoot);
296
        res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
297
        assertEquals(4,res.size());
298
        Map<? extends Integer,? extends Integer> count = countModes(res);
299
        assertEquals(Integer.valueOf(1), count.get(0));
300
        assertEquals(Integer.valueOf(2), count.get(1));
301
        assertEquals(Integer.valueOf(1), count.get(2));
302
303
        //Symulate EditorRegistry
304
        final Source src = Source.create(srcFile);
305
        ParserManager.parse(Collections.<Source>singleton(src), new UserTask() {
306
            @Override
307
            public void run(ResultIterator resultIterator) throws Exception {
308
            }
309
        });
310
        final DataObject dobj = DataObject.find(srcFile);
311
        final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
312
        final StyledDocument doc = ec.openDocument();
313
        SwingUtilities.invokeAndWait(new Runnable() {
314
            @Override
315
            public void run() {
316
                final JEditorPane jp = new JEditorPane() {
317
                    @Override
318
                    public boolean isFocusOwner() {
319
                        return true;
320
                    }
321
                };
322
                jp.setDocument(doc);
323
                EditorApiPackageAccessor.get().register(jp);
324
            }
325
        });
326
327
        //Do modification
328
        NbDocument.runAtomic(doc, new Runnable() {
329
            @Override
330
            public void run() {
331
                try {
332
                    doc.insertString(doc.getLength(), "<C>", null); //NOI18N
333
                } catch (Exception e) {
334
                    Exceptions.printStackTrace(e);
335
                }
336
            }
337
        });
338
339
        //Query should be updated
340
        sup = QuerySupport.forRoots(InnerIndexer.NAME, InnerIndexer.VERSION, srcRoot);
341
        res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
342
        assertEquals(5,res.size());
343
        count = countModes(res);
344
        assertEquals(Integer.valueOf(1), count.get(0));
345
        assertEquals(Integer.valueOf(2), count.get(1));
346
        assertEquals(Integer.valueOf(1), count.get(2));
347
        assertEquals(Integer.valueOf(1), count.get(3));
278
    }
348
    }
279
349
280
    private static Map<? extends Integer, ? extends Integer> countModes(@NonNull final Collection<? extends IndexResult> docs)  {
350
    private static Map<? extends Integer, ? extends Integer> countModes(@NonNull final Collection<? extends IndexResult> docs)  {
Lines 399-404 Link Here
399
                } else if (text.charAt(i) == 'B') {
469
                } else if (text.charAt(i) == 'B') {
400
                    res.setMode(InnerResult.B);
470
                    res.setMode(InnerResult.B);
401
                    break;
471
                    break;
472
                } else if (text.charAt(i) == 'C') {
473
                    res.setMode(InnerResult.C);
474
                    break;
402
                }
475
                }
403
            }
476
            }
404
            resultCache = res;
477
            resultCache = res;
Lines 480-493 Link Here
480
        @Override
553
        @Override
481
        public void cancel() {
554
        public void cancel() {
482
        }
555
        }
483
484
        public static class Factory extends TaskFactory {
485
            @Override
486
            public Collection<? extends SchedulerTask> create(Snapshot snapshot) {
487
                return Collections.<SchedulerTask>singleton(new TopToInnerEmbProvider());
488
            }
489
490
        }
491
    }
556
    }
492
557
493
    public static class TopIndexer extends EmbeddingIndexer {
558
    public static class TopIndexer extends EmbeddingIndexer {
Lines 525-531 Link Here
525
590
526
            @Override
591
            @Override
527
            public void filesDirty(Iterable<? extends Indexable> dirty, Context context) {
592
            public void filesDirty(Iterable<? extends Indexable> dirty, Context context) {
528
                System.out.println("FILES DIRTY!");
529
                try {
593
                try {
530
                    final IndexingSupport is = IndexingSupport.getInstance(context);
594
                    final IndexingSupport is = IndexingSupport.getInstance(context);
531
                    for (Indexable df : dirty) {
595
                    for (Indexable df : dirty) {
Lines 591-597 Link Here
591
655
592
            @Override
656
            @Override
593
            public void filesDirty(Iterable<? extends Indexable> dirty, Context context) {
657
            public void filesDirty(Iterable<? extends Indexable> dirty, Context context) {
594
                System.out.println("INNER DIRTY");
595
                try {
658
                try {
596
                    final IndexingSupport is = IndexingSupport.getInstance(context);
659
                    final IndexingSupport is = IndexingSupport.getInstance(context);
597
                    for (Indexable df : dirty) {
660
                    for (Indexable df : dirty) {
Lines 646-669 Link Here
646
709
647
    public static class ClassPathProviderImpl implements ClassPathProvider {
710
    public static class ClassPathProviderImpl implements ClassPathProvider {
648
711
649
        static volatile FileObject root;
712
        //@GuardedBy("ClassPathProviderImpl.class")
713
        private static FileObject root;
714
        //@GuardedBy("ClassPathProviderImpl.class")
715
        private static ClassPath cp;
650
716
651
        private final AtomicReference<ClassPath> cpRef = new AtomicReference<ClassPath>();
652
717
718
        static synchronized  void setRoot(@NonNull final FileObject r) {
719
            cp = null;
720
            root = r;
721
        }
653
722
654
        @Override
723
        @Override
655
        public ClassPath findClassPath(FileObject file, String type) {
724
        public ClassPath findClassPath(FileObject file, String type) {
656
            if (PATH_TOP_SOURCES.equals(type) &&
725
            synchronized(ClassPathProviderImpl.class) {
657
               (FileUtil.isParentOf(root, file) || root.equals(file))) {
726
                if (PATH_TOP_SOURCES.equals(type) &&
658
               ClassPath cp = cpRef.get();
727
                   (FileUtil.isParentOf(root, file) || root.equals(file))) {
659
               if (cp == null) {
728
                   if (cp == null) {
660
                   cp = ClassPathSupport.createClassPath(root);
729
                       cp = ClassPathSupport.createClassPath(root);
661
                   if (!cpRef.compareAndSet(null, cp)) {
662
                       cp = cpRef.get();
663
                   }
730
                   }
664
               }
731
                   return cp;
665
               assert cp != null;
732
                }
666
               return cp;
667
            }
733
            }
668
            return null;
734
            return null;
669
        }
735
        }

Return to bug 218150