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):
Jiri Sedlacek
 
     "TriggeredTakeSnapshotProfilingPoint_NoDataAvailableMsg=no data available",
     "TriggeredTakeSnapshotProfilingPoint_NoDataRemoteMsg=no data available: not supported for remote profiling",
     "TriggeredTakeSnapshotProfilingPoint_NoDataJdkMsg=no data available: JDK 1.6, 1.7 or 1.5.0_12 is required",
     "TriggeredTakeSnapshotProfilingPoint_OneHitString=<b>1 hit</b> at {0}, <a href='#'>report</a>",
     "TriggeredTakeSnapshotProfilingPoint_NHitsString=<b>{0} hits</b>, last at {1}, <a href='#'>report</a>",
     "TriggeredTakeSnapshotProfilingPoint_NoResultsString=No results available",
     "TriggeredTakeSnapshotProfilingPoint_ReportAccessDescr=Report of {0}",
     "TriggeredTakeSnapshotProfilingPoint_HeaderTypeString=<b>Type:</b> {0}",
    "TriggeredTakeSnapshotProfilingPoint_HeaderEnabledString=<b>Enabled:</b> {0}",
    "TriggeredTakeSnapshotProfilingPoint_HeaderProjectString=<b>Project:</b> {0}",
    "TriggeredTakeSnapshotProfilingPoint_HeaderModeDataString=<b>Snapshot type:</b> profiling data",
    "TriggeredTakeSnapshotProfilingPoint_HeaderModeDumpString=<b>Snapshot type:</b> heap dump",
    "TriggeredTakeSnapshotProfilingPoint_HeaderTargetProjectString=<b>Save to:</b> project",
    "TriggeredTakeSnapshotProfilingPoint_HeaderTargetCustomString=<b>Save to:</b> {0}",
    "TriggeredTakeSnapshotProfilingPoint_HeaderResetResultsString=<b>Reset results:</b> {0}",
    "TriggeredTakeSnapshotProfilingPoint_HeaderHitsString=<b>Hits:</b> {0}",
    "TriggeredTakeSnapshotProfilingPoint_OpenSnapshotString=open snapshot",
    "TriggeredTakeSnapshotProfilingPoint_UsedHeapResultString=(hit for {0}MB used heap)",
    "TriggeredTakeSnapshotProfilingPoint_HeapUsageResultString=(hit for {0}% heap usage)",
    "TriggeredTakeSnapshotProfilingPoint_SurvGenResultString=(hit for {0} surviving generations)",
    "TriggeredTakeSnapshotProfilingPoint_LoadedClassesResultString=(hit for {0} loaded classes)",
    "TriggeredTakeSnapshotProfilingPoint_HitString=<b>{0}.</b> hit at <b>{1}</b>, {2} {3}",
    "TriggeredTakeSnapshotProfilingPoint_SnapshotNotAvailableMsg=Saved snapshot is no longer available.",
    "TriggeredTakeSnapshotProfilingPoint_DataString=Data:"
})
    //~ Inner Classes ------------------------------------------------------------------------------------------------------------
    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(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(TriggeredTakeSnapshotProfilingPoint.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(TriggeredTakeSnapshotProfilingPoint.this.getName());
        }
        private String getDataResultItem(int index) {
            synchronized() {
                Result result = .get(index);
                String resultString = result.getResultString();
                String snapshotInformation = resultString.startsWith()
                                             ? ("<a href='" + resultString + "'>" + Bundle.TriggeredTakeSnapshotProfilingPoint_OpenSnapshotString() + "</a>") : resultString// NOI18N
                String hitValueInformation = ""// NOI18N
                    hitValueInformation = Bundle.TriggeredTakeSnapshotProfilingPoint_UsedHeapResultString(
                                            (result.getHitValue() / (1024f * 1024f)));
                } else if (getCondition().getMetric() == ..) {
                    hitValueInformation = Bundle.TriggeredTakeSnapshotProfilingPoint_HeapUsageResultString(result.getHitValue());
                } else if (getCondition().getMetric() == ..) {
                    hitValueInformation = Bundle.TriggeredTakeSnapshotProfilingPoint_SurvGenResultString(result.getHitValue());
                } else if (getCondition().getMetric() == ..) {
                    hitValueInformation = Bundle.TriggeredTakeSnapshotProfilingPoint_LoadedClassesResultString(result.getHitValue());
                }
                return Bundle.TriggeredTakeSnapshotProfilingPoint_HitString(
                            (index + 1), Utils.formatLocalProfilingPointTime(result.getTimestamp()),
                            snapshotInformationhitValueInformation);
            }
        }
        private String getHeaderEnabled() {
        }
        private String getHeaderHitsCount() {
            synchronized() {
                return Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderHitsString(.size());
            }
        }
        private String getHeaderMode() {
                    Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderModeDataString()
                    : Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderModeDumpString();
        }
        private String getHeaderName() {
            return "<h2><b>" + TriggeredTakeSnapshotProfilingPoint.this.getName() + "</b></h2>"// NOI18N
        }
        private String getHeaderProject() {
            return Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderProjectString(
                        ProjectUtilities.getDisplayName(TriggeredTakeSnapshotProfilingPoint.this.getProject()));
        }
        private String getHeaderResetResults() {
                        TriggeredTakeSnapshotProfilingPoint.this.getResetResults());
        }
        private String getHeaderTarget() {
                   ? Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderTargetProjectString()
                   : Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderTargetCustomString(
                        TriggeredTakeSnapshotProfilingPoint.this.getSnapshotFile());
        }
        private String getHeaderType() {
            return Bundle.TriggeredTakeSnapshotProfilingPoint_HeaderTypeString(
                        TriggeredTakeSnapshotProfilingPoint.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();
            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 = TriggeredTakeSnapshotProfilingPoint.this.getSnapshotType();
                            if (type.equals() || type.equals()) {
                                ResultsManager.getDefault().openSnapshot(snapshotFile);
                            }
                        } else {
                            ProfilerDialogs.displayWarning(
                                    Bundle.TriggeredTakeSnapshotProfilingPoint_SnapshotNotAvailableMsg());
                        }
                    }
                };
            JScrollPane dataAreaScrollPane = new JScrollPane(.,
                                                             .);
            TitledBorder tb = new TitledBorder(Bundle.TriggeredTakeSnapshotProfilingPoint_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 long hitValue;
        private final long timestamp;
        //~ Constructors ---------------------------------------------------------------------------------------------------------
        public Result(long timestamplong hitValueString resultString) {
            this. = timestamp;
            this. = hitValue;
            this. = resultString;
        }
        //~ Methods --------------------------------------------------------------------------------------------------------------
        public long getHitValue() {
            return ;
        }
        public String getResultString() {
            return ;
        }
        public long getTimestamp() {
            return ;
        }
    }
    //~ Static fields/initializers -----------------------------------------------------------------------------------------------
    public static final String TAKEN_HEAPDUMP_PREFIX = "heapdump-"// NOI18N // should differ from generated OOME heapdumps not to be detected as OOME
    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
    //~ Instance fields ----------------------------------------------------------------------------------------------------------
    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 -------------------------------------------------------------------------------------------------------------
        super(nameprojectfactory);
    }
    //~ 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();
    }
    protected String getResultsText() {
        synchronized() {
            if (hasResults()) {
                int size = .size();
                long timeStamp = .get(size - 1).getTimestamp();
                String time = Utils.formatLocalProfilingPointTime(timeStamp);
                return (size == 1)
                       ? Bundle.TriggeredTakeSnapshotProfilingPoint_OneHitString(time)
                       : Bundle.TriggeredTakeSnapshotProfilingPoint_NHitsString(sizetime);
            } else {
                return Bundle.TriggeredTakeSnapshotProfilingPoint_NoResultsString();
            }
        }
    }
    protected void updateCustomizer(ValidityAwarePanel c) {
        customizer.setPPName(getName());
        customizer.setPPType(.equals(getSnapshotType()));
        customizer.setPPFile(getSnapshotFile());
        customizer.setPPResetResults(getResetResults());
        customizer.setTriggerCondition(getCondition());
    }
    // ---
        if (.equals()) {
            return ProjectStorage.getSettingsFolder(getProject(), true);
        } else {
            File f = new File();
            f.mkdirs();
            return FileUtil.toFileObject(FileUtil.normalizeFile(f));
        }
    }
    void setValues(ValidityAwarePanel c) {
        setName(customizer.getPPName());
        setSnapshotType(customizer.getPPType() ?  : );
        setSnapshotFile(customizer.getPPFile());
        setResetResults(customizer.getPPResetResults());
        setCondition(customizer.getTriggerCondition());
    }
    void hit(long hitValue) {
        String snapshotFilename;
        long currentTime = System.currentTimeMillis();
        if (.equals()) {
            snapshotFilename = takeHeapdumpHit();
        } else {
            snapshotFilename = takeSnapshotHit();
            if (getResetResults()) {
                try {
                    ResultsManager.getDefault().reset();
                    
                    TargetAppRunner runner = Profiler.getDefault().getTargetAppRunner();
                    if (runner.targetJVMIsAlive()) {
                        runner.resetTimers();
                    }
                } catch (ClientUtils.TargetAppOrVMTerminated targetAppOrVMTerminated) {
                } // ignore
            }
        }
        synchronized() {
            if (ProfilingPointsManager.getDefault().belowMaxHits(.size()))
                .add(new Result(currentTimehitValuesnapshotFilename));
        }
        getChangeSupport().firePropertyChange(falsetrue);
    }
    void reset() {
        synchronized() {
            boolean change = hasResults();
            .clear();
            if (change) {
                getChangeSupport().firePropertyChange(falsetrue);
            }
        }
    }
    private String getCurrentHeapDumpFilename() {
        try {
            String fileName =  + System.currentTimeMillis();
            FileObject folder = getSnapshotDirectory();
            //      FileObject folder = targetFolder == null ? IDEUtils.getProjectSettingsFolder(NetBeansProfiler.getDefaultNB().getProfiledProject()) : FileUtil.toFileObject(new File(targetFolder));                          
            return FileUtil.toFile(folder).getAbsolutePath() + .
                   + FileUtil.findFreeFileName(folderfileName.) + "." // NOI18N
                   + .// NOI18N
        } catch (IOException e) {
            return null;
        }
    }
    private Report getReport(boolean create) {
        Report report =  == null ? null : .get();
        if (report == null && create) {
            report = new Report();
             = new WeakReference<Report>(report);
        }
        return report;
    }
    private String takeHeapdumpHit() {
        TargetAppRunner runner = Profiler.getDefault().getTargetAppRunner();
        if (runner.getProfilingSessionStatus().) {
            return Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataRemoteMsg();
        }
        if (!runner.hasSupportedJDKForHeapDump()) {
            return Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataJdkMsg();
        }
        String dumpFileName = getCurrentHeapDumpFilename();
        if (dumpFileName == null) {
            return Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataAvailableMsg();
        }
        boolean heapdumpTaken = false;
        try {
            heapdumpTaken = runner.getProfilerClient().takeHeapDump(dumpFileName);
        } catch (Exception ex) {
            ProfilerLogger.log(ex);
        }
        if (heapdumpTaken) {
            if (ProfilerControlPanel2.hasDefault())
                ProfilerControlPanel2.getDefault().refreshSnapshotsList();
            try {
                return new File(dumpFileName).toURI().toURL().toExternalForm();
            } catch (MalformedURLException ex) {
                ProfilerLogger.log(ex);
                return Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataAvailableMsg();
            }
        } else {
            return Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataAvailableMsg();
        }
    }
    private static LoadedSnapshot takeSnapshot() {
        return ResultsManager.getDefault().prepareSnapshot();
    }
    private String takeSnapshotHit() {        
        LoadedSnapshot loadedSnapshot = null;
        String snapshotFilename = null;
        loadedSnapshot = takeSnapshot();
        if (loadedSnapshot != null) {
            try {
                FileObject snapshotDirectory = getSnapshotDirectory();
                FileObject profFile = snapshotDirectory.createData(ResultsManager.getDefault()
                                                                                 .getDefaultSnapshotFileName(loadedSnapshot),
                                                                   .);
                ResultsManager.getDefault().saveSnapshot(loadedSnapshotprofFile); // Also updates list of snapshots in ProfilerControlPanel2
                snapshotFilename = FileUtil.toFile(profFile).toURI().toURL().toExternalForm();
            } catch (IOException e) {
                ErrorManager.getDefault().notify(.e);
            }
        }
        return (snapshotFilename == null) ? Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataAvailableMsg() : snapshotFilename;
    }