Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
   * Other names may be trademarks of their respective owners.
   *
   * The contents of this file are subject to the terms of either the GNU
  * General Public License Version 2 only ("GPL") or the Common
  * Development and Distribution License("CDDL") (collectively, the
  * "License"). You may not use this file except in compliance with the
  * License. You can obtain a copy of the License at
  * http://www.netbeans.org/cddl-gplv2.html
  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  * specific language governing permissions and limitations under the
  * License.  When distributing the software, include this License Header
  * Notice in each file and include the License file at
  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the GPL Version 2 section of the License file that
  * accompanied this code. If applicable, add the following below the
  * License Header, with the fields enclosed by brackets [] replaced by
  * your own identifying information:
  * "Portions Copyrighted [year] [name of copyright owner]"
  *
  * Contributor(s):
  * The Original Software is NetBeans. The Initial Developer of the Original
  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
  * Microsystems, Inc. All Rights Reserved.
  *
  * If you wish your version of this file to be governed by only the CDDL
  * or only the GPL Version 2, indicate your decision by adding
  * "[Contributor] elects to include this software in this distribution
  * under the [CDDL or GPL Version 2] license." If you do not indicate a
  * single choice of license, a recipient has the option to distribute
  * your version of this file under either the CDDL, the GPL Version 2 or
  * to extend the choice of license to its licensees as provided above.
  * However, if you add GPL Version 2 code and therefore, elected the GPL
  * Version 2 license, then the option applies only if the new code is
  * made subject to such option by the copyright holder.
  */
 
 package org.netbeans.modules.profiler.ppoints;
 
 import java.awt.Font;
 import java.io.File;
 import java.net.URL;
 import java.util.List;

Author(s):
Tomas Hurka
Jiri Sedlacek
 
     "StopwatchProfilingPoint_OneHitString=<b>1 hit</b> at {0}, <a href='#'>report</a>",
     "StopwatchProfilingPoint_NHitsString=<b>{0} hits</b>, last at {1}, <a href='#'>report</a>",
     "StopwatchProfilingPoint_NoResultsString=No results available",
     "StopwatchProfilingPoint_ReportAccessDescr=Report of {0}",
     "StopwatchProfilingPoint_HeaderTypeString=<b>Type:</b> {0}",
     "StopwatchProfilingPoint_HeaderEnabledString=<b>Enabled:</b> {0}",
     "StopwatchProfilingPoint_HeaderProjectString=<b>Project:</b> {0}",
     "StopwatchProfilingPoint_HeaderLocationString=<b>Location:</b> {0}, line {1}",
     "StopwatchProfilingPoint_HeaderStartLocationString=<b>Start location:</b> {0}, line {1}",
     "StopwatchProfilingPoint_HeaderEndLocationString=<b>Stop location:</b> {0}, line {1}",
     "StopwatchProfilingPoint_HeaderMeasureDurationString=<b>Measure:</b> Timestamp and duration",
     "StopwatchProfilingPoint_HeaderMeasureTimestampString=<b>Measure:</b> Timestamp",
     "StopwatchProfilingPoint_HeaderHitsString=<b>Hits:</b> {0}",
     "StopwatchProfilingPoint_HitString=<b>{0}.</b> hit at <b>{1}</b>",
     "StopwatchProfilingPoint_HitDurationPendingString=<b>{0}.</b> hit at <b>{1}</b>, duration pending...",
     "StopwatchProfilingPoint_HitDurationKnownString=<b>{0}.</b> hit at <b>{1}</b>, duration <b>{2} &micro;s</b>",
     "StopwatchProfilingPoint_DataString=Data:",
     "StopwatchProfilingPoint_AnnotationStartString={0} (start)",
     "StopwatchProfilingPoint_AnnotationEndString={0} (end)"
 })
public final class StopwatchProfilingPoint extends CodeProfilingPoint.Paired implements PropertyChangeListener {
    //~ Inner Classes ------------------------------------------------------------------------------------------------------------
    private class Annotation extends CodeProfilingPoint.Annotation {
        //~ Instance fields ------------------------------------------------------------------------------------------------------
        private boolean isStartAnnotation;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        public Annotation(boolean isStartAnnotation) {
            super();
            this. = isStartAnnotation;
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
        @Override
        public String getAnnotationType() {
            return StopwatchProfilingPoint.this.isEnabled() ?  : ;
        }
        @Override
        public String getShortDescription() {
            if (!usesEndLocation()) {
                return getName();
            }
            return  ? Bundle.StopwatchProfilingPoint_AnnotationStartString(getName())
                                     : Bundle.StopwatchProfilingPoint_AnnotationEndString(getName());
        }
        @Override
        public CodeProfilingPoint profilingPoint() {
            return StopwatchProfilingPoint.this;
        }
    }
    private class Report extends ProfilingPointReport {
        //~ Static fields/initializers -------------------------------------------------------------------------------------------
        private static final String START_LOCATION_URLMASK = "file:/1"// NOI18N
        private static final String END_LOCATION_URLMASK = "file:/2"// NOI18N
        //~ Instance fields ------------------------------------------------------------------------------------------------------
        private HTMLTextArea dataArea;
        private HTMLTextArea headerArea;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        public Report() {
            initDefaults();
            initComponents();
            refresh();
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
//        public int getPersistenceType() {
//            return TopComponent.PERSISTENCE_NEVER;
//        }
//
//        protected String preferredID() {
//            return this.getClass().getName();
//        }
        protected void refresh() {
            StringBuilder headerAreaTextBuilder = new StringBuilder();
            headerAreaTextBuilder.append(getHeaderName());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderType());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderEnabled());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderProject());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderStartLocation());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            if (StopwatchProfilingPoint.this.usesEndLocation()) {
                headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
                headerAreaTextBuilder.append(getHeaderEndLocation());
                headerAreaTextBuilder.append("<br>");
            } // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderMeasureLocation());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderHitsCount()); // NOI18N
            .setText(headerAreaTextBuilder.toString());
            StringBuilder dataAreaTextBuilder = new StringBuilder();
            synchronized() {
                if (.isEmpty()) {
                    dataAreaTextBuilder.append(ProfilingPointReport.getNoDataHint(StopwatchProfilingPoint.this));
                } else {
                    for (int i = 0; i < .size(); i++) {
                        dataAreaTextBuilder.append("&nbsp;&nbsp;");
                        dataAreaTextBuilder.append(getDataResultItem(i));
                        dataAreaTextBuilder.append("<br>"); // NOI18N
                    }
                    ProfilingPointsManager m = ProfilingPointsManager.getDefault();
                    if (!m.belowMaxHits(.size()))
                        dataAreaTextBuilder.append(m.getTruncatedResultsText());
                }
            }
            .setText(dataAreaTextBuilder.toString());
        }
        void refreshProperties() {
            setName(StopwatchProfilingPoint.this.getName());
            setIcon(((ImageIconStopwatchProfilingPoint.this.getFactory().getIcon()).getImage());
        }
        private String getDataResultItem(int index) {
            synchronized() {
                Result result = .get(index);
                // TODO: enable once thread name by id is available
                //String threadName = Utils.getThreadName(result.getThreadID());
                //String threadClassName = Utils.getThreadClassName(result.getThreadID());
                //String threadInformation = (threadName == null ? "&lt;unknown thread&gt;" : (threadClassName == null ? threadName : threadName + " (" + threadClassName + ")"));
                String hitTime = Utils.formatProfilingPointTimeHiRes(result.getTimestamp());
                if (!StopwatchProfilingPoint.this.usesEndLocation()) {
                    //return "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b> by " + threadInformation;
                    return Bundle.StopwatchProfilingPoint_HitString((index + 1), hitTime);
                } else if (result.getEndTimestamp() == -1) {
                    //return "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b>, duration pending..., thread " + threadInformation;
                    return Bundle.StopwatchProfilingPoint_HitDurationPendingString((index + 1), hitTime);
                } else {
                    //return "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b>, duration <b>" + Utils.getDurationInMicroSec(result.getTimestamp(),result.getEndTimestamp()) + " &micro;s</b>, thread " + threadInformation;
                    return Bundle.StopwatchProfilingPoint_HitDurationKnownString(
                                (index + 1), 
                                hitTime,
                                Utils.getDurationInMicroSec(result.getTimestamp(),
                                    result.getEndTimestamp() - result.getTimeAdjustment()));
                }
            }
        }
        private String getHeaderEnabled() {
        }
        private String getHeaderEndLocation() {
            CodeProfilingPoint.Location location = StopwatchProfilingPoint.this.getEndLocation();
            File file = new File(location.getFile());
            String shortFileName = file.getName();
            int lineNumber = location.getLine();
            String locationUrl = "<a href='" +  + "'>"// NOI18N
            return Bundle.StopwatchProfilingPoint_HeaderEndLocationString(locationUrl + shortFileNamelineNumber)
                   + "</a>"// NOI18N
        }
        private String getHeaderHitsCount() {
            synchronized() {
                return Bundle.StopwatchProfilingPoint_HeaderHitsString(.size());
            }
        }
        private String getHeaderMeasureLocation() {
            return StopwatchProfilingPoint.this.usesEndLocation() ?
                        Bundle.StopwatchProfilingPoint_HeaderMeasureDurationString() : 
                        Bundle.StopwatchProfilingPoint_HeaderMeasureTimestampString();
        }
        private String getHeaderName() {
            return "<h2><b>" + StopwatchProfilingPoint.this.getName() + "</b></h2>"// NOI18N
        }
        private String getHeaderProject() {
            return Bundle.StopwatchProfilingPoint_HeaderProjectString(
                        ProjectUtilities.getDisplayName(StopwatchProfilingPoint.this.getProject()));
        }
        private String getHeaderStartLocation() {
            CodeProfilingPoint.Location location = StopwatchProfilingPoint.this.getStartLocation();
            File file = new File(location.getFile());
            String shortFileName = file.getName();
            int lineNumber = location.getLine();
            String locationUrl = "<a href='" +  + "'>"// NOI18N
            return StopwatchProfilingPoint.this.usesEndLocation()
                   ? (Bundle.StopwatchProfilingPoint_HeaderStartLocationString(locationUrl + shortFileNamelineNumber)
                   + "</a>")
                   : (Bundle.StopwatchProfilingPoint_HeaderLocationString(locationUrl + shortFileNamelineNumber)
                   + "</a>"); // NOI18N
        }
        private String getHeaderType() {
        }
        private void initComponents() {
            setLayout(new BorderLayout());
            JPanel contentsPanel = new JPanel(new BorderLayout());
            contentsPanel.setBackground(UIUtils.getProfilerResultsBackground());
            contentsPanel.setOpaque(true);
            contentsPanel.setBorder(BorderFactory.createMatteBorder(0, 15, 15, 15, UIUtils.getProfilerResultsBackground()));
             = new HTMLTextArea() {
                    protected void showURL(URL url) {
                        String urlString = url.toString();
                        if (.equals(urlString)) {
                            Utils.openLocation(StopwatchProfilingPoint.this.getStartLocation());
                        } else if (StopwatchProfilingPoint.this.usesEndLocation()) {
                            Utils.openLocation(StopwatchProfilingPoint.this.getEndLocation());
                        }
                    }
                };
            JScrollPane headerAreaScrollPane = new JScrollPane(.,
                                                               .);
            headerAreaScrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 15, 0, UIUtils.getProfilerResultsBackground()));
            headerAreaScrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
            contentsPanel.add(headerAreaScrollPane.);
             = new HTMLTextArea();
            JScrollPane dataAreaScrollPane = new JScrollPane(.,
                                                             .);
            TitledBorder tb = new TitledBorder(Bundle.StopwatchProfilingPoint_DataString());
            tb.setTitleFont(Utils.getTitledBorderFont(tb).deriveFont(.));
            tb.setTitleColor(javax.swing.UIManager.getColor("Label.foreground")); // NOI18N
            dataAreaScrollPane.setBorder(tb);
            dataAreaScrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
            dataAreaScrollPane.setBackground(UIUtils.getProfilerResultsBackground());
            contentsPanel.add(dataAreaScrollPane.);
            add(contentsPanel.);
        }
        private void initDefaults() {
            refreshProperties();
            setFocusable(true);
        }
    }
    private static class Result {
        //~ Instance fields ------------------------------------------------------------------------------------------------------
        private final int threadId;
        private final long timestamp;
        private long endTimestamp = -1;
        private long timeAdjustment;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        private Result(long timestampint threadId) {
            this. = timestamp;
            this. = threadId;
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
        private void setEndTimestamp(long endTimestamp) {
            this. = endTimestamp;
        }
        private long getEndTimestamp() {
            return ;
        }
        private int getThreadID() {
            return ;
        }
        private long getTimeAdjustment() {
            return ;
        }
        private long getTimestamp() {
            return ;
        }
        private void timeAdjust(long timeDiff) {
             += timeDiff;
        }
    }
    //~ Static fields/initializers -----------------------------------------------------------------------------------------------
    // --- Implementation --------------------------------------------------------
    private static final String ANNOTATION_ENABLED = "stopwatchProfilingPoint"// NOI18N
    private static final String ANNOTATION_DISABLED = "stopwatchProfilingPointD"// NOI18N
    //~ Instance fields ----------------------------------------------------------------------------------------------------------
    private Annotation endAnnotation;
    private Annotation startAnnotation;
    private List<Resultresults = new ArrayList();
    private final Object resultsSync = new Object();
    //~ Constructors -------------------------------------------------------------------------------------------------------------
    public StopwatchProfilingPoint(String nameLocation startLocationLocation endLocationLookup.Provider projectProfilingPointFactory factory) {
        super(namestartLocationendLocationprojectfactory);
    }
    //~ Methods ------------------------------------------------------------------------------------------------------------------
    public boolean hasResults() {
        synchronized() {
            return .size() > 0;
        }
    }
    public void hideResults() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Report report = getReport(false);
                if (report != nullreport.close();
            }
        });
    }
    public void propertyChange(PropertyChangeEvent evt) {
        Report report = getReport(false);
        if (report != null) {
            if (evt.getPropertyName() == ) {
                report.refreshProperties();
            }
            report.refresh();
        }
    }
    public void showResults(URL url) {
        TopComponent topComponent = getReport(true);
        topComponent.open();
        topComponent.requestActive();
    }
        if (!usesEndLocation()) {
             = null;
        } else if ( == null) {
             = new Annotation(false);
        }
        return ;
    }
    protected String getResultsText() {
        synchronized() {
            if (hasResults()) {
                return (.size() == 1)
                       ? Bundle.StopwatchProfilingPoint_OneHitString(
                            Utils.formatProfilingPointTime(.get(.size() - 1).getTimestamp()))
                       : Bundle.StopwatchProfilingPoint_NHitsString(
                            .size(),
                            Utils.formatProfilingPointTime(.get(.size() - 1).getTimestamp()));
            } else {
                return Bundle.StopwatchProfilingPoint_NoResultsString();
            }
        }
    }
        if ( == null) {
             = new Annotation(true);
        }
        return ;
    }
    protected void timeAdjust(final int threadIdfinal long timeDiff0final long timeDiff1) {
        if (usesEndLocation()) { // we have start and stop StopwatchProfilingPoint
            synchronized() {
                for (Result result : ) {
                    if ((result.getEndTimestamp() == -1) && (result.getThreadID() == threadId)) {
                        //System.out.println("Time adjust thread "+threadId+" time "+Long.toHexString(timeDiff1)+ " diff "+Long.toHexString(timeDiff0));
                        result.timeAdjust(timeDiff0);
                    }
                }
            }
        }
    }
    protected void updateCustomizer(ValidityAwarePanel c) {
        StopwatchCustomizer customizer = (StopwatchCustomizerc;
        customizer.setPPName(getName());
        customizer.setPPStartLocation(getStartLocation());
        customizer.setPPEndLocation(getEndLocation());
    }
    protected boolean usesEndLocation() {
        return getEndLocation() != null;
    }
    void setValues(ValidityAwarePanel c) {
        StopwatchCustomizer customizer = (StopwatchCustomizerc;
        setName(customizer.getPPName());
        setStartLocation(customizer.getPPStartLocation());
        setEndLocation(customizer.getPPEndLocation());
        
        Utils.checkLocation(this);
    }
    void hit(RuntimeProfilingPoint.HitEvent hitEventint index) {
        synchronized() {
            if (!usesEndLocation() || (index == 0)) {
                // TODO: should endpoint hit before startpoint hit be processed somehow?
                if (ProfilingPointsManager.getDefault().belowMaxHits(.size()))
                    .add(new Result(hitEvent.getTimestamp(), hitEvent.getThreadId()));
                //System.out.println("Time start  thread "+hitEvent.getThreadId()+" time "+Long.toHexString(hitEvent.getTimestamp()));
            } else {
                for (Result result : ) {
                    if ((result.getEndTimestamp() == -1) && (result.getThreadID() == hitEvent.getThreadId())) {
                        result.setEndTimestamp(hitEvent.getTimestamp());
                        //System.out.println("Time end    thread "+hitEvent.getThreadId()+" time "+Long.toHexString(hitEvent.getTimestamp()));
                        break;
                    }
                }
                // TODO: endpoind hit without startpoint hit, what to do?
            }
        }
        getChangeSupport().firePropertyChange(falsetrue);
    }
    void reset() {
        synchronized() {
            boolean change = .size() > 0;
            .clear();
            if (change) {
                getChangeSupport().firePropertyChange(falsetrue);
            }
        }
    }
    
    private Report getReport(boolean create) {
        Report report =  == null ? null : .get();
        if (report == null && create) {
            report = new Report();
             = new WeakReference<Report>(report);
        }
        return report;
    }