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
 
     "TakeSnapshotProfilingPoint_NoDataAvailableMsg=no data available",
     "TakeSnapshotProfilingPoint_RemoteUnsupportedMsg=no data available: not supported for remote profiling",
     "TakeSnapshotProfilingPoint_NoDataJdkMsg=no data available: JDK 1.6, 1.7 or 1.5.0_12 is required",
     "TakeSnapshotProfilingPoint_OneHitString=<b>1 hit</b> at {0}, <a href='#'>report</a>",
     "TakeSnapshotProfilingPoint_NHitsString=<b>{0} hits</b>, last at {1}, <a href='#'>report</a>",
     "TakeSnapshotProfilingPoint_NoResultsString=No results available",
     "TakeSnapshotProfilingPoint_ReportAccessDescr=Report of {0}",
    "TakeSnapshotProfilingPoint_HeaderTypeString=<b>Type:</b> {0}",
    "TakeSnapshotProfilingPoint_HeaderEnabledString=<b>Enabled:</b> {0}",
    "TakeSnapshotProfilingPoint_HeaderProjectString=<b>Project:</b> {0}",
    "TakeSnapshotProfilingPoint_HeaderLocationString=<b>Location:</b> <a href='#'>{0}, line {1}</a>",
    "TakeSnapshotProfilingPoint_HeaderModeDataString=<b>Snapshot type:</b> profiling data",
    "TakeSnapshotProfilingPoint_HeaderModeDumpString=<b>Snapshot type:</b> heap dump",
    "TakeSnapshotProfilingPoint_HeaderTargetProjectString=<b>Save to:</b> project",
    "TakeSnapshotProfilingPoint_HeaderTargetCustomString=<b>Save to:</b> {0}",
    "TakeSnapshotProfilingPoint_HeaderResetResultsString=<b>Reset results:</b> {0}",
    "TakeSnapshotProfilingPoint_HeaderHitsString=<b>Hits:</b> {0}",
    "TakeSnapshotProfilingPoint_OpenSnapshotString=open snapshot",
    "TakeSnapshotProfilingPoint_HitString=<b>{0}.</b> hit at <b>{1}</b>, {2}",
    "TakeSnapshotProfilingPoint_SnapshotNotAvailableMsg=Saved snapshot is no longer available.",
    "TakeSnapshotProfilingPoint_DataString=Data:"
})
public final class TakeSnapshotProfilingPoint extends CodeProfilingPoint.Single implements PropertyChangeListener {
    //~ Inner Classes ------------------------------------------------------------------------------------------------------------
    private class Annotation extends CodeProfilingPoint.Annotation {
        //~ Methods --------------------------------------------------------------------------------------------------------------
        @Override
        public String getAnnotationType() {
            return TakeSnapshotProfilingPoint.this.isEnabled() ?  : ;
        }
        @Override
        public String getShortDescription() {
            return getName();
        }
        @Override
        public CodeProfilingPoint profilingPoint() {
            return TakeSnapshotProfilingPoint.this;
        }
    }
    private class Report extends ProfilingPointReport {
        //~ 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;");
            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(getHeaderLocation());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderMode());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderTarget());
            headerAreaTextBuilder.append("<br>"); // NOI18N
            headerAreaTextBuilder.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            headerAreaTextBuilder.append(getHeaderResetResults());
            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(TakeSnapshotProfilingPoint.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(TakeSnapshotProfilingPoint.this.getName());
            setIcon(((ImageIconTakeSnapshotProfilingPoint.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 resultString = result.getResultString();
                String snapshotInformation = resultString.startsWith()
                                             ? ("<a href='" + resultString + "'>" + Bundle.TakeSnapshotProfilingPoint_OpenSnapshotString() + "</a>") : resultString// NOI18N
                //return "<b>" + (index + 1) + ".</b> hit at <b>" + Utils.formatProfilingPointTimeHiRes(result.getTimestamp()) + "</b> by " + threadInformation + ", " + snapshotInformation;
                return Bundle.TakeSnapshotProfilingPoint_HitString(
                            (index + 1), Utils.formatProfilingPointTimeHiRes(result.getTimestamp()),
                            snapshotInformation);
            }
        }
        private String getHeaderEnabled() {
        }
        private String getHeaderHitsCount() {
            synchronized() {
                return Bundle.TakeSnapshotProfilingPoint_HeaderHitsString(.size());
            }
        }
        private String getHeaderLocation() {
            CodeProfilingPoint.Location location = TakeSnapshotProfilingPoint.this.getLocation();
            String shortFileName = new File(location.getFile()).getName();
            int lineNumber = location.getLine();
            return Bundle.TakeSnapshotProfilingPoint_HeaderLocationString(shortFileNamelineNumber);
        }
        private String getHeaderMode() {
            return TakeSnapshotProfilingPoint.this.getSnapshotType().equals() ? 
                        Bundle.TakeSnapshotProfilingPoint_HeaderModeDataString()
                        : Bundle.TakeSnapshotProfilingPoint_HeaderModeDumpString();
        }
        private String getHeaderName() {
            return "<h2><b>" + TakeSnapshotProfilingPoint.this.getName() + "</b></h2>"// NOI18N
        }
        private String getHeaderProject() {
            return Bundle.TakeSnapshotProfilingPoint_HeaderProjectString(
                        ProjectUtilities.getDisplayName(TakeSnapshotProfilingPoint.this.getProject()));
        }
        private String getHeaderResetResults() {
            return Bundle.TakeSnapshotProfilingPoint_HeaderResetResultsString(
                        TakeSnapshotProfilingPoint.this.getResetResults());
        }
        private String getHeaderTarget() {
            return TakeSnapshotProfilingPoint.this.getSnapshotTarget().equals() ? 
                        Bundle.TakeSnapshotProfilingPoint_HeaderTargetProjectString()
                        : Bundle.TakeSnapshotProfilingPoint_HeaderTargetCustomString(TakeSnapshotProfilingPoint.this.getSnapshotFile());
        }
        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) {
                        Utils.openLocation(TakeSnapshotProfilingPoint.this.getLocation());
                    }
                };
            JScrollPane headerAreaScrollPane = new JScrollPane(.,
                                                               .);
            headerAreaScrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 15, 0, UIUtils.getProfilerResultsBackground()));
            headerAreaScrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
            contentsPanel.add(headerAreaScrollPane.);
             = new HTMLTextArea() {
                    protected void showURL(URL url) {
                        File resolvedFile = null;
                        try {
                            resolvedFile = new File(url.toURI());
                        } catch (URISyntaxException ex) {
                            ex.printStackTrace();
                        }
                        final File snapshotFile = resolvedFile;
                        if ((snapshotFile != null) && snapshotFile.exists()) {
                            String type = TakeSnapshotProfilingPoint.this.getSnapshotType();
                            if (type.equals() || type.equals()) {
                                ResultsManager.getDefault().openSnapshot(snapshotFile);
                            }
                        } else {
                            ProfilerDialogs.displayWarning(
                                    Bundle.TakeSnapshotProfilingPoint_SnapshotNotAvailableMsg());
                        }
                    }
                };
            JScrollPane dataAreaScrollPane = new JScrollPane(.,
                                                             .);
            TitledBorder tb = new TitledBorder(Bundle.TakeSnapshotProfilingPoint_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 String resultString;
        private final int threadId;
        private final long timestamp;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        public Result(long timestampint threadIdString resultString) {
            this. = timestamp;
            this. = threadId;
            this. = resultString;
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
        public String getResultString() {
            return ;
        }
        public int getThreadID() {
            return ;
        }
        public long getTimestamp() {
            return ;
        }
    }
    //~ Static fields/initializers -----------------------------------------------------------------------------------------------
    static final String PROPERTY_TYPE = "p_snapshot"// NOI18N
    public static final String TYPE_PROFDATA_KEY = "profdata"// NOI18N
    public static final String TYPE_HEAPDUMP_KEY = "heapdump"// NOI18N
    static final String PROPERTY_TARGET = "p_target"// NOI18N
    public static final String TARGET_PROJECT_KEY = "project"// NOI18N
    public static final String TARGET_CUSTOM_KEY = "custom"// NOI18N
    static final String PROPERTY_CUSTOM_FILE = "p_file"// NOI18N
    static final String PROPERTY_RESET_RESULTS = "p_reset_results"// NOI18N
    // --- Implementation --------------------------------------------------------
    private static final String SNAPSHOT_LOCATION_URLMASK = "file:"// NOI18N
    private static final String ANNOTATION_ENABLED = "takeSnapshotProfilingPoint"// NOI18N
    private static final String ANNOTATION_DISABLED = "takeSnapshotProfilingPointD"// NOI18N
    //~ Instance fields ----------------------------------------------------------------------------------------------------------
    private Annotation annotation;
    private List<Resultresults = new ArrayList();
    private final Object resultsSync = new Object();
    private String snapshotFile = System.getProperty("java.io.tmpdir"); // NOI18N
    private boolean resetResults = false;
    //~ Constructors -------------------------------------------------------------------------------------------------------------
    public TakeSnapshotProfilingPoint(String nameLocation locationLookup.Provider projectProfilingPointFactory factory) {
        super(namelocationprojectfactory);
    }
    //~ Methods ------------------------------------------------------------------------------------------------------------------
    public void setResetResults(boolean resetResults) {
        if (this. == resetResults) {
            return;
        }
        this. = resetResults;
    }
    public boolean getResetResults() {
        return ;
    }
    public void setSnapshotFile(String snapshotFile) {
        if ((snapshotFile == null) || !new File(snapshotFile).exists()) {
            return;
        }
        if ((this. != null) && new File(this.).equals(new File(snapshotFile))) {
            return;
        }
        String oldSnapshotFile = this.;
        this. = snapshotFile;
        getChangeSupport().firePropertyChange(oldSnapshotFilesnapshotFile);
    }
    public String getSnapshotFile() {
        return ;
    }
    public void setSnapshotTarget(String snapshotTarget) {
        if (!snapshotTarget.equals() && !snapshotTarget.equals()) {
            throw new IllegalArgumentException("Invalid snapshot target category: " + snapshotTarget); // NOI18N
        }
        if (this..equals(snapshotTarget)) {
            return;
        }
        String oldSnapshotTarget = this.;
        this. = snapshotTarget;
        getChangeSupport().firePropertyChange(oldSnapshotTargetsnapshotTarget);
    }
    public String getSnapshotTarget() {
        return ;
    }
    public void setSnapshotType(String snapshotType) {
        if ((snapshotType == null) || !(snapshotType.equals() || snapshotType.equals())) {
            throw new IllegalArgumentException("Invalid snapshot type: " + snapshotType); // NOI18N
        }
        if (this..equals(snapshotType)) {
            return;
        }
        String oldSnapshotType = this.;
        this. = snapshotType;
        getChangeSupport().firePropertyChange(oldSnapshotTypesnapshotType);
    }
    public String getSnapshotType() {
        return ;
    }
    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 ( == null) {
             = new Annotation();
        }
        return ;
    }
    protected String getResultsText() {
        synchronized() {
            if (hasResults()) {
                int size = .size();
                return (.size() == 1)
                       ? Bundle.TakeSnapshotProfilingPoint_OneHitString(
                            Utils.formatProfilingPointTime(.get(.size() - 1).getTimestamp()))
                       : Bundle.TakeSnapshotProfilingPoint_NHitsString(
                            .size(),
                            Utils.formatProfilingPointTime(.get(.size() - 1).getTimestamp()));
            } else {
                return Bundle.TakeSnapshotProfilingPoint_NoResultsString();
            }
        }
    }
    protected void updateCustomizer(ValidityAwarePanel c) {
        TakeSnapshotCustomizer customizer = (TakeSnapshotCustomizerc;
        customizer.setPPName(getName());
        customizer.setPPLocation(getLocation());
        customizer.setPPType(.equals(getSnapshotType()));
        customizer.setPPFile(getSnapshotFile());
        customizer.setPPResetResults(getResetResults());
    }
        if (getSnapshotType().equals()) {
            return "org.netbeans.lib.profiler.server.TakeHeapdumpProfilingPointHandler"// NOI18N
        }
        if (getResetResults()) {
            return "org.netbeans.lib.profiler.server.TakeSnapshotWithResetProfilingPointHandler"// NOI18N
        }
        return "org.netbeans.lib.profiler.server.TakeSnapshotProfilingPointHandler"// NOI18N
    }
    String getServerInfo() {
        if (getSnapshotType().equals()) {
            try {
                return FileUtil.toFile(getSnapshotDirectory()).getAbsolutePath();
            } catch (IOException ex) {
                ErrorManager.getDefault().notify(.ex);
            }
        }
        return null;
    }
        if (.equals()) {
            return ProjectStorage.getSettingsFolder(getProject(), true);
        } else {
            File f = new File();
            f.mkdirs();
            return FileUtil.toFileObject(FileUtil.normalizeFile(f));
        }
    }
    void setValues(ValidityAwarePanel c) {
        TakeSnapshotCustomizer customizer = (TakeSnapshotCustomizerc;
        setName(customizer.getPPName());
        setLocation(customizer.getPPLocation());
        setSnapshotType(customizer.getPPType() ?  : );
        setSnapshotFile(customizer.getPPFile());
        setResetResults(customizer.getPPResetResults());
        
        Utils.checkLocation(this);
    }
    void hit(RuntimeProfilingPoint.HitEvent hitEventint index) {
        String snapshotFilename;
        if (.equals()) {
            TargetAppRunner runner = Profiler.getDefault().getTargetAppRunner();
            if (runner.getProfilingSessionStatus().) {
                snapshotFilename = Bundle.TakeSnapshotProfilingPoint_RemoteUnsupportedMsg();
            } else if (!runner.hasSupportedJDKForHeapDump()) {
                snapshotFilename = Bundle.TakeSnapshotProfilingPoint_NoDataJdkMsg();
            } else {
                snapshotFilename = takeHeapdumpHit(hitEvent.getTimestamp());
            }
        } else {
            snapshotFilename = takeSnapshotHit();
        }
        synchronized() {
            if (ProfilingPointsManager.getDefault().belowMaxHits(.size()))
                .add(new Result(hitEvent.getTimestamp(), hitEvent.getThreadId(), snapshotFilename));
        }
        getChangeSupport().firePropertyChange(falsetrue);
    }
    void reset() {
        synchronized() {
            boolean change = hasResults();
            .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;
    }
    private File constructHeapDumpFile(long timethrows IOException {
        String dir = FileUtil.toFile(getSnapshotDirectory()).getAbsolutePath();
        String heapDumpFileName = dir + . + . + time + "."  // NOI18N
                                  + .// NOI18N
        return new File(heapDumpFileName);
    }
    private String takeHeapdumpHit(long time) {
        try {
            File heapdumpFile = constructHeapDumpFile(time);
            if (heapdumpFile.exists()) {
                File fixedHeapdumpFile = constructHeapDumpFile(Utils.getTimeInMillis(time));
                heapdumpFile.renameTo(fixedHeapdumpFile);
                ProfilerControlPanel2.getDefault().refreshSnapshotsList();
                return fixedHeapdumpFile.toURI().toURL().toExternalForm();
            }
        } catch (IOException ex) {
            ErrorManager.getDefault().notify(.ex);
            return Bundle.TakeSnapshotProfilingPoint_NoDataAvailableMsg();
        }
        return Bundle.TakeSnapshotProfilingPoint_NoDataAvailableMsg();
    }
        return ResultsManager.getDefault().prepareSnapshot();
    }
    private String takeSnapshotHit() {
        LoadedSnapshot loadedSnapshot = null;
        String snapshotFilename = null;
        try {
            loadedSnapshot = takeSnapshot();
        } catch (CPUResultsSnapshot.NoDataAvailableException e) {
            //ErrorManager.getDefault().notify(ErrorManager.ERROR, e);
            // NOTE: this is actually a supported state - taking snapshots when no data are available, resultString remains null
        }
        if (loadedSnapshot != null) {
            try {
                FileObject snapshotDirectory = getSnapshotDirectory();
                FileObject profFile = snapshotDirectory.createData(ResultsManager.getDefault()
                                                                                 .getDefaultSnapshotFileName(loadedSnapshot),
                                                                   .);
                ResultsManager.getDefault().saveSnapshot(loadedSnapshotprofFile);
                snapshotFilename = FileUtil.toFile(profFile).toURI().toURL().toExternalForm();
            } catch (IOException e) {
                ErrorManager.getDefault().notify(.e);
            }
        }
        return (snapshotFilename == null) ? Bundle.TakeSnapshotProfilingPoint_NoDataAvailableMsg() : snapshotFilename;
    }