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):
Jaroslav Bachorik
 
     "LoadGenProfilingPoint_OneHitString=<b>1 hit</b> at {0}, <a href='#'>report</a>",
     "LoadGenProfilingPoint_NHitsString=<b>{0} hits</b>, last at {1}, <a href='#'>report</a>",
     "LoadGenProfilingPoint_NoResultsString=No results available",
     "LoadGenProfilingPoint_AnnotationStartString={0} (start)",
     "LoadGenProfilingPoint_AnnotationEndString={0} (end)",
     "LoadGenProfilingPoint_ReportAccessDescr=Report of {0}",
     "LoadGenProfilingPoint_HeaderTypeString=<b>Type:</b> {0}",
     "LoadGenProfilingPoint_HeaderEnabledString=<b>Enabled:</b> {0}",
     "LoadGenProfilingPoint_HeaderProjectString=<b>Project:</b> {0}",
     "LoadGenProfilingPoint_HeaderLocationString=<b>Location:</b> {0}, line {1}",
     "LoadGenProfilingPoint_HeaderStartLocationString=<b>Start location:</b> {0}, line {1}",
     "LoadGenProfilingPoint_HeaderEndLocationString=<b>Stop location:</b> {0}, line {1}",
     "LoadGenProfilingPoint_HeaderHitsString=<b>Hits:</b> {0}",
     "LoadGenProfilingPoint_HitSuccessString=<b>{0}.</b> hit at <b>{1}</b>",
     "LoadGenProfilingPoint_HitFailedString=<b>{0}.</b> hit at <b>{1}</b>, <b>action failed!</b>",
     "LoadGenProfilingPoint_DataString=Data:"
 })
    //~ Inner Classes ------------------------------------------------------------------------------------------------------------
    private class Annotation extends CodeProfilingPoint.Annotation {
        //~ Instance fields ------------------------------------------------------------------------------------------------------
        private boolean isStartAnnotation;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        public Annotation(boolean isStartAnnotation) {
            this. = isStartAnnotation;
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
        @Override
        public String getAnnotationType() {
            return LoadGenProfilingPoint.this.isEnabled() ?  : ;
        }
        @Override
        public String getShortDescription() {
            if (!usesEndLocation()) {
                return getName();
            }
            return  ? Bundle.LoadGenProfilingPoint_AnnotationStartString(getName())
                                     : Bundle.LoadGenProfilingPoint_AnnotationEndString(getName());
        }
        @Override
        public CodeProfilingPoint profilingPoint() {
            return LoadGenProfilingPoint.this;
        }
    }
    private static class Result {
        //~ Instance fields ------------------------------------------------------------------------------------------------------
        private final int threadId;
        private final long timestamp;
        private boolean success = false;
        private long endTimestamp = -1;
        private long startTime;
        private long stopTime;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        public Result(long timestampint threadIdboolean success) {
            this. = timestamp;
            this. = threadId;
            this. = success;
            this. = System.currentTimeMillis();
            this. = 0L;
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
        public long getDuration() {
            return ( > ) ? ( - ) : (-1L);
        }
        public void setEndTimestamp(long endTimestamp) {
            this. = endTimestamp;
        }
        public long getEndTimestamp() {
            return ;
        }
        public void setStopTime() {
            this. = System.currentTimeMillis();
        }
        public boolean isSuccess() {
            return ;
        }
        public int getThreadID() {
            return ;
        }
        public long getTimestamp() {
            return ;
        }
    }
    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 --------------------------------------------------------------------------------------------------------------
        protected void refresh() {
            StringBuilder headerAreaTextBuilder = new StringBuilder();
            headerAreaTextBuilder.append(getHeaderName());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;"); // NOI18N
            headerAreaTextBuilder.append(getHeaderType());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;"); // NOI18N
            headerAreaTextBuilder.append(getHeaderEnabled());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;"); // NOI18N
            headerAreaTextBuilder.append(getHeaderProject());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;"); // NOI18N
            headerAreaTextBuilder.append(getHeaderStartLocation());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            if (LoadGenProfilingPoint.this.usesEndLocation()) {
                headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;"); // NOI18N
                headerAreaTextBuilder.append(getHeaderEndLocation());
                headerAreaTextBuilder.append("<br>"); // NOI18N
            }
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;"); // NOI18N
            headerAreaTextBuilder.append(getHeaderHitsCount());
            .setText(headerAreaTextBuilder.toString());
            StringBuilder dataAreaTextBuilder = new StringBuilder();
            synchronized() {
                if (.isEmpty()) {
                    dataAreaTextBuilder.append(ProfilingPointReport.getNoDataHint(LoadGenProfilingPoint.this));
                } else {
                    if (.size() > 1) {
                        Collections.sort(,
                                         new Comparator<LoadGenProfilingPoint.Result>() {
                                public int compare(LoadGenProfilingPoint.Result o1LoadGenProfilingPoint.Result o2) {
                                    return Long.valueOf(o1.getTimestamp()).compareTo(Long.valueOf(o2.getTimestamp()));
                                }
                            });
                    }
                    for (int i = 0; i < .size(); i++) {
                        dataAreaTextBuilder.append("&nbsp;&nbsp;"); // NOI18N
                        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(LoadGenProfilingPoint.this.getName());
            setIcon(((ImageIconLoadGenProfilingPoint.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 (!LoadGenProfilingPoint.this.usesEndLocation()) {
                //return "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b> by " + threadInformation;
                if (result.isSuccess()) {
                    return Bundle.LoadGenProfilingPoint_HitSuccessString((index + 1), hitTime);
                } else {
                    return Bundle.LoadGenProfilingPoint_HitFailedString((index + 1), hitTime);
                }
                //      } else if (result.getEndTimestamp() == -1) {
                //        //return "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b>, duration pending..., thread " + threadInformation;
                //        return "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b>, duration <b>" + (result.getDuration() / 1000d) + "s</b>(pending...)";
                //      } 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 "<b>" + (index + 1) + ".</b> hit at <b>" + hitTime + "</b>, duration <b>" + (result.getDuration() / 1000d) + " s</b>";
                //      }
            }
        }
        private String getHeaderEnabled() {
            return Bundle.LoadGenProfilingPoint_HeaderEnabledString(LoadGenProfilingPoint.this.isEnabled());
        }
        private String getHeaderEndLocation() {
            CodeProfilingPoint.Location location = LoadGenProfilingPoint.this.getEndLocation();
            File file = new File(location.getFile());
            String shortFileName = file.getName();
            int lineNumber = location.getLine();
            String locationUrl = "<a href='" +  + "'>"// NOI18N
            return Bundle.LoadGenProfilingPoint_HeaderEndLocationString(locationUrl + shortFileNamelineNumber)
                   + "</a>"// NOI18N
        }
        private String getHeaderHitsCount() {
            synchronized() {
                return Bundle.LoadGenProfilingPoint_HeaderHitsString(.size());
            }
        }
        private String getHeaderName() {
            return "<h2><b>" + LoadGenProfilingPoint.this.getName() + "</b></h2>"// NOI18N
        }
        private String getHeaderProject() {
            return Bundle.LoadGenProfilingPoint_HeaderProjectString(
                        ProjectUtilities.getDisplayName(LoadGenProfilingPoint.this.getProject()));
        }
        private String getHeaderStartLocation() {
            CodeProfilingPoint.Location location = LoadGenProfilingPoint.this.getStartLocation();
            File file = new File(location.getFile());
            String shortFileName = file.getName();
            int lineNumber = location.getLine();
            String locationUrl = "<a href='" +  + "'>"// NOI18N
            return LoadGenProfilingPoint.this.usesEndLocation()
                   ? (Bundle.LoadGenProfilingPoint_HeaderStartLocationString(locationUrl + shortFileNamelineNumber)
                   + "</a>")
                   : (Bundle.LoadGenProfilingPoint_HeaderLocationString(locationUrl + shortFileNamelineNumber)
                   + "</a>"); // NOI18N
        }
        private String getHeaderType() {
            return Bundle.LoadGenProfilingPoint_HeaderTypeString(LoadGenProfilingPoint.this.getFactory().getType());
        }
        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(LoadGenProfilingPoint.this.getStartLocation());
                        } else if (LoadGenProfilingPoint.this.usesEndLocation()) {
                            Utils.openLocation(LoadGenProfilingPoint.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.LoadGenProfilingPoint_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);
        }
    }
    //~ Static fields/initializers -----------------------------------------------------------------------------------------------
    private static final Logger LOGGER = Logger.getLogger(LoadGenProfilingPoint.class.getName());
    public static final String PROPERTY_SCRIPTNAME = "p_ScriptName"// NOI18N
    private static final String ANNOTATION_ENABLED = "loadgenProfilingPoint"// NOI18N
    private static final String ANNOTATION_DISABLED = "loadgenProfilingPointD"// NOI18N
    //~ Instance fields ----------------------------------------------------------------------------------------------------------
    private Annotation endAnnotation;
    private Annotation startAnnotation;
    private final List<Resultresults = new ArrayList<LoadGenProfilingPoint.Result>();
    private final Object resultsSync = new Object();
    private String scriptFileName;
    //~ Constructors -------------------------------------------------------------------------------------------------------------

    
Creates a new instance of LoadGenProfilingPoint
    public LoadGenProfilingPoint(String nameLocation startLocationLocation endLocationLookup.Provider projectProfilingPointFactory factory) {
        super(namestartLocationendLocationprojectfactory);
    }
    //~ Methods ------------------------------------------------------------------------------------------------------------------
    @Override
    public void setEnabled(boolean value) {
        LoadGenPlugin lg = Lookup.getDefault().lookup(LoadGenPlugin.class);
        if (lg != null) {
            super.setEnabled(value);
        } else {
            .warning("Can not enable the Load Generator profiling point. The appropriate modules are not installed."); // NOI18N
        }
    }
    @Override
    public boolean isEnabled() {
        boolean retValue;
        retValue = super.isEnabled();
        if (retValue) {
            LoadGenPlugin lg = Lookup.getDefault().lookup(LoadGenPlugin.class);
            retValue &= (lg != null);
        }
        return retValue;
    }
    public String getScriptFileName() {
        return ( != null) ?  : ""// NOI18N
    }
    public void setSriptFileName(String fileName) {
         = fileName;
    }
    public boolean hasResults() {
        synchronized() {
            return !.isEmpty();
        }
    }
    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()) {
                int size = .size();
                long timeStamp = .get(size - 1).getTimestamp();
                String time = Utils.formatProfilingPointTime(timeStamp);
                return (size == 1)
                       ? Bundle.LoadGenProfilingPoint_OneHitString(time)
                       : Bundle.LoadGenProfilingPoint_NHitsString(sizetime);
            } else {
                return Bundle.LoadGenProfilingPoint_NoResultsString();
            }
        }
    }
        if ( == null) {
             = new Annotation(true);
        }
        return ;
    }
    protected void updateCustomizer(ValidityAwarePanel c) {
        LoadGeneratorCustomizer customizer = (LoadGeneratorCustomizerc;
        customizer.setPPName(getName());
        customizer.setPPStartLocation(getStartLocation());
        customizer.setPPEndLocation(getEndLocation());
        customizer.setScriptFile(getScriptFileName());
        customizer.setProject(getProject());
    }
    protected boolean usesEndLocation() {
        return getEndLocation() != null;
    }
    void setValues(ValidityAwarePanel c) {
        LoadGeneratorCustomizer customizer = (LoadGeneratorCustomizerc;
        setName(customizer.getPPName());
        setStartLocation(customizer.getPPStartLocation());
        setEndLocation(customizer.getPPEndLocation());
        setSriptFileName(customizer.getScriptFile());
        
        Utils.checkLocation(this);
    }
    void hit(final HitEvent hitEventint index) {
        LoadGenPlugin lg = Lookup.getDefault().lookup(LoadGenPlugin.class);
        synchronized() {
            if (usesEndLocation() && (index == 1)) {
                if (lg != null) {
                    lg.stop(getScriptFileName());
                    for (Result result : ) {
                        if ((result.getEndTimestamp() == -1) && (result.getThreadID() == hitEvent.getThreadId())) {
                            result.setEndTimestamp(hitEvent.getTimestamp());
                            break;
                        }
                    }
                }
            } else {
                if (lg != null) {
                    lg.start(getScriptFileName(),
                             new LoadGenPlugin.Callback() {
                            private long correlationId = hitEvent.getTimestamp();
                            public void afterStart(LoadGenPlugin.Result result) {
                                if (ProfilingPointsManager.getDefault().belowMaxHits(.size())) {
                                    Result rslt = new Result(hitEvent.getTimestamp(), hitEvent.getThreadId(),
                                                            result == ..);
                                    .add(rslt);
                                     = hitEvent.getTimestamp();
                                    getChangeSupport().firePropertyChange(falsetrue);
                                }
                            }
                            public void afterStop(LoadGenPlugin.Result result) {
                                for (Result rslt : ) {
                                    if (rslt.getTimestamp() == ) {
                                        rslt.setEndTimestamp();
                                        rslt.setStopTime();
                                        break;
                                    }
                                }
                                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;
    }