Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 2008-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]"
  *
  * 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.
  *
  * Contributor(s):
  *
  * Portions Copyrighted 2008-2009 Sun Microsystems, Inc.
  */
 
 package org.netbeans.modules.bugtracking.util;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import  org.jdesktop.layout.LayoutStyle;

Author(s):
Tomas Stupka, Jan Stola
Marian Petras
public class BugtrackingUtil {

    
Metrics logger
    private static Logger METRICS_LOG = Logger.getLogger("org.netbeans.ui.metrics.bugtracking"); // NOI18N

    
The automatic refresh was set on or off.
Parameters:
  1. connector name : String
  2. is on : Boolean
    public static final String USG_BUGTRACKING_AUTOMATIC_REFRESH = "USG_BUGTRACKING_AUTOMATIC_REFRESH"// NOI18N

    
A query was refreshed.
Parameters:
  1. connector name : String
  2. query name : String
  3. issues count : Integer
  4. is a kenai query : Boolean
  5. is a automatic refresh : Boolean
    public static final String USG_BUGTRACKING_QUERY             = "USG_BUGTRACKING_QUERY"// NOI18N
    private static final String USG_ISSUE_TRACKING = "USG_ISSUE_TRACKING"// NOI18N
    private static Set<StringloggedParams// to avoid logging same params more than once in a session
    public static boolean show(JPanel panelString titleString okName) {
        JButton ok = new JButton(okName);
        JButton cancel = new JButton(NbBundle.getMessage(BugtrackingUtil.class"LBL_Cancel")); // NOI18N
        cancel.getAccessibleContext().setAccessibleDescription(cancel.getText());
        final DialogDescriptor dd =
            new DialogDescriptor(
                    panel,
                    title,
                    true,
                    new Object[]{okcancel},
                    ok,
                    .,
                    new HelpCtx(panel.getClass()),
                    null);
        return DialogDisplayer.getDefault().notify(dd) == ok;
    }

    
Returns all curently openend issues which aren't new.

Returns:
issues
    public static Issue[] getOpenIssues() {
        Set<TopComponenttcs = TopComponent.getRegistry().getOpened();
        List<Issueissues = new ArrayList<Issue>();
        for (TopComponent tc : tcs) {
            if(tc instanceof IssueTopComponent) {
                Issue issue = ((IssueTopComponent)tc).getIssue();
                if(!issue.isNew()) {
                    issues.add(issue);
                }
            }
        }
        return issues.toArray(new Issue[issues.size()]);
    }

    
Determines if the gives issue is opened in the editor area

Parameters:
issue
Returns:
true in case the given issue is opened in the editor are, otherwise false
    public static boolean isOpened(Issue issue) {
        IssueTopComponent tc = IssueTopComponent.find(issuefalse);
        return tc != null ? tc.isOpened() : false;
    }

    
Determines if the gives issue is opened in the editor area and showing on the screen

Parameters:
issue
Returns:
true in case the given issue is opened in the editor area and showing on the screen, otherwise false
    public static boolean isShowing(Issue issue) {
        IssueTopComponent tc = IssueTopComponent.find(issuefalse);
        return tc != null ? tc.isShowing() : false;
    }

    
Determines if the gives query is opened in the editor area

Parameters:
query
Returns:
    public static boolean isOpened(Query query) {
        QueryTopComponent tc = QueryTopComponent.find(query);
        return tc != null ? tc.isOpened() : false;
    }

    
Determines if the gives query is opened in the editor area and showing on the screen

Parameters:
query
Returns:
    public static boolean isShowing(Query query) {
        QueryTopComponent tc = QueryTopComponent.find(query);
        return tc != null ? tc.isShowing() : false;
    }

    
Filters the given issue by the given criteria and returns those which either case unsensitively contain the criteria in their summary or those which id equals the criteria.

Parameters:
issues
criteria
Returns:
    public static Issue[] getByIdOrSummary(Issue[] issuesString criteria) {
        if(criteria == null) {
            return issues;
        }
        criteria = criteria.trim();
        if(criteria.equals("")) {                                               // NOI18N
            return issues;
        }
        criteria = criteria.toLowerCase();
        List<Issueret = new ArrayList<Issue>();
        for (Issue issue : issues) {
            if(issue.isNew()) continue;
            String id = issue.getID();
            if(id == nullcontinue;
            String summary = issue.getSummary();
            if(id.toLowerCase().startsWith(criteria) ||
               (summary != null && summary.toLowerCase().indexOf(criteria) > -1))
            {
                ret.add(issue);
            }  
        }
        return ret.toArray(new Issue[ret.size()]);
    }
    public static Repository createRepository() {
        RepositorySelector rs = new RepositorySelector();
        Repository repo = rs.create();
        return repo;
    }
    public static boolean editRepository(Repository repositoryString errorMessage) {
        RepositorySelector rs = new RepositorySelector();
        return rs.edit(repositoryerrorMessage);
    }
    public static boolean editRepository(Repository repository) {
        return editRepository(repositorynull);
    }
    public static Repository[] getKnownRepositories(boolean pingOpenProjects) {
        return BugtrackingManager.getInstance().getKnownRepositories(pingOpenProjects);
    }
    public static BugtrackingConnector[] getBugtrackingConnectors() {
        return BugtrackingManager.getInstance().getConnectors();
    }
    public static String scramble(String str) {
        return Scrambler.getInstance().scramble(str);
    }
    public static String descramble(String str) {
        return Scrambler.getInstance().descramble(str);
    }
    public static Issue selectIssue(String messageRepository repositoryJPanel callerHelpCtx helpCtx) {
        QuickSearchComboBar bar = new QuickSearchComboBar(caller);
        bar.setRepository(repository);
        bar.setAlignmentX(0f);
        JPanel panel = new JPanel();
        BoxLayout layout = new BoxLayout(panel.);
        panel.setLayout(layout);
        JLabel label = new JLabel();
        Mnemonics.setLocalizedText(labelmessage);
        panel.add(label);
        label.setLabelFor(bar.getIssueComponent());
        LayoutStyle layoutStyle = LayoutStyle.getSharedInstance();
        int gap = layoutStyle.getPreferredGap(labelbar, LayoutStyle.RELATED, .panel);
        panel.add(Box.createVerticalStrut(gap));
        panel.add(bar);
        panel.add(Box.createVerticalStrut(gap));
        ResourceBundle bundle = NbBundle.getBundle(BugtrackingUtil.class);
        JLabel hintLabel = new JLabel(bundle.getString("MSG_SelectIssueHint")); // NOI18N
        hintLabel.setEnabled(false);
        panel.add(hintLabel);
        panel.add(Box.createVerticalStrut(80));
        panel.setBorder(BorderFactory.createEmptyBorder(
                layoutStyle.getContainerGap(panel.null),
                layoutStyle.getContainerGap(panel.null),
                0,
                layoutStyle.getContainerGap(panel.null)));
        panel.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_IssueSelector"));
        Issue issue = null;
        JButton ok = new JButton(bundle.getString("LBL_Select")); // NOI18N
        JButton cancel = new JButton(bundle.getString("LBL_Cancel")); // NOI18N
        cancel.getAccessibleContext().setAccessibleDescription(cancel.getText());
        DialogDescriptor descriptor = new DialogDescriptor(
                panel,
                bundle.getString("LBL_Issues"), // NOI18N
                true,
                .,
                ok,
                null);
        descriptor.setOptions(new Object [] {okcancel});
        descriptor.setHelpCtx(helpCtx);
        DialogDisplayer.getDefault().createDialog(descriptor).setVisible(true);
        if (descriptor.getValue() == ok) {
            issue = bar.getIssue();
        }
        return issue;
    }
    public static File selectPatchContext() {
        PatchContextChooser chooser = new PatchContextChooser();
        ResourceBundle bundle = NbBundle.getBundle(BugtrackingUtil.class);
        JButton ok = new JButton(bundle.getString("LBL_Apply")); // NOI18N
        JButton cancel = new JButton(bundle.getString("LBL_Cancel")); // NOI18N
        DialogDescriptor descriptor = new DialogDescriptor(
                chooser,
                bundle.getString("LBL_ApplyPatch"), // NOI18N
                true,
                .,
                ok,
                null);
        descriptor.setOptions(new Object [] {okcancel});
        descriptor.setHelpCtx(new HelpCtx("org.netbeans.modules.bugtracking.patchContextChooser")); // NOI18N
        File context = null;
        DialogDisplayer.getDefault().createDialog(descriptor).setVisible(true);
        if (descriptor.getValue() == ok) {
            context = chooser.getSelectedFile();
        }
        return context;
    }

    
Recursively deletes all files and directories under a given file/directory.

Parameters:
file file/directory to delete
    public static void deleteRecursively(File file) {
        if (file.isDirectory()) {
            File [] files = file.listFiles();
            for (int i = 0; i < files.lengthi++) {
                deleteRecursively(files[i]);
            }
        }
        file.delete();
    }
    public static void logQueryEvent(String connectorString nameint countboolean isKenaiboolean isAutoRefresh) {
        name = obfuscateQueryName(name);
        logBugtrackingEvents(new Object[] {connectornamecountisKenaiisAutoRefresh} );
    }
    public static void logAutoRefreshEvent(String connectorString queryNameboolean isKenaiboolean on) {
        queryName = obfuscateQueryName(queryName);
        logBugtrackingEvents(new Object[] {connectorqueryNameisKenaion} );
    }
    public static synchronized void logBugtrackingUsage(Repository repositoryString operation) {
        if (repository == null) {
            return;
        }
        String btType = getBugtrackingType(repository);
        if (btType == null) {
            return;
        }
        // log Kenai usage
        if (KenaiUtil.isKenai(repository)) {
            KenaiUtil.logKenaiUsage("ISSUE_TRACKING"btType); // NOI18N
        }
        if (operation == null) {
            return;
        }
        // log general bugtracking usage
        String paramStr = getParamString(btTypeoperation);
        if ( == null || !.contains(paramStr)) {
            // not logged in this session yet
            LogRecord rec = new LogRecord(.);
            rec.setParameters(new Object[] { btTypeoperation });
            rec.setLoggerName(.getName());
            .log(rec);
            if ( == null) {
                 = new HashSet<String>();
            }
            .add(paramStr);
        }
    }
    private static String getParamString(Object... parameters) {
        if (parameters == null || parameters.length == 0) {
            return ""// NOI18N
        }
        if (parameters.length == 1) {
            return parameters[0].toString();
        }
        StringBuilder buf = new StringBuilder();
        for (Object p : parameters) {
            buf.append(p.toString());
        }
        return buf.toString();
    }
    private static String getBugtrackingType(Repository repository) {
        // XXX hack: there's no clean way to determine the type of bugtracking
        // from Repository (need BugtrackingConnector.getDisplayName)
        String clsName = repository.getClass().getName();
        if (clsName.contains(".bugzilla.")) { // NOI18N
            return "Bugzilla"// NOI18N
        }
        if (clsName.contains(".jira.")) { // NOI18N
            return "Jira"// NOI18N
        }
        return null;
    }

    
Logs bugtracking events

Parameters:
key - the events key
parameters - the parameters for the given event
    private static void logBugtrackingEvents(String keyObject[] parameters) {
        LogRecord rec = new LogRecord(.key);
        rec.setParameters(parameters);
        rec.setLoggerName(.getName());
        .log(rec);
    }
    private static String getMD5(String name) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");                          // NOI18N
        } catch (NoSuchAlgorithmException e) {
            // should not happen
            return null;
        }
        digest.update(name.getBytes());
        byte[] hash = digest.digest();
        StringBuffer ret = new StringBuffer();
        for (int i = 0; i < hash.lengthi++) {
            String hex = Integer.toHexString(hash[i] & 0x000000FF);
            if(hex.length()==1) {
                hex = "0" + hex;                                                // NOI18N
            }
            ret.append(hex);
        }
        return ret.toString();
    }
    private static String obfuscateQueryName(String name) {
        if (name == null) {
            name = "Find Issues"// NOI18N
        } else {
            name = getMD5(name);
        }
        return name;
    }
    public static void openPluginManager() {
        try {
            ClassLoader cl = Lookup.getDefault ().lookup (ClassLoader.class);
            Class<CallableSystemActionclz = (Class<CallableSystemAction>) cl.loadClass("org.netbeans.modules.autoupdate.ui.actions.PluginManagerAction");
            final CallableSystemAction a = CallableSystemAction.findObject(clztrue);
            a.putValue("InitialTab""available"); // NOI18N
            Runnable inAWT = new Runnable() {
                public void run() {
                    a.performAction ();
                }
            };
            if (EventQueue.isDispatchThread()) {
                inAWT.run();
            } else {
                EventQueue.invokeLater(inAWT);
            }
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    
    private static Pattern netbeansUrlPattern = Pattern.compile("(https|http)://(([a-z]|\\d)+\\.)*([a-z]|\\d)*netbeans([a-z]|\\d)*(([a-z]|\\d)*\\.)+org(.*)"); // NOI18N
    
Determines wheter the given Repository is the repository hosting netbeans or not

Parameters:
repo
Returns:
true if the given repository is the netbenas bugzilla, otherwise false
    public static boolean isNbRepository(Repository repo) {
        String url = repo.getUrl();
        return isNbRepository(url);
    }
    public static boolean isNbRepository(String url) {
        boolean ret = .matcher(url).matches();
        if(ret) {
            return true;
        }
        String nbUrl = System.getProperty("netbeans.bugzilla.url");  // NOI18N
        if(nbUrl == null || nbUrl.equals("")) {                      // NOI18N
            return false;
        }
        return url.startsWith(nbUrl);
    }

    

Parameters:
password
prefix
user
url
Throws:
MissingResourceException
    public static void savePassword(String passwordString prefixString userString urlthrows MissingResourceException {
        if (password != null && !password.trim().equals("")) {                  // NOI18N
            Keyring.save(getPasswordKey(prefixuserurl), password.toCharArray(), NbBundle.getMessage(BugtrackingUtil.class"password_keyring_description"url)); // NOI18N
        } else {
            Keyring.delete(getPasswordKey(prefixuserurl));
        }
    }

    

Parameters:
scrambledPassword
keyPrefix
url
user
Returns:
    public static char[] readPassword(String scrambledPasswordString keyPrefixString userString url) {
        if (!scrambledPassword.equals("")) {                                    // NOI18N
            return BugtrackingUtil.descramble(scrambledPassword).toCharArray();
        } else {
            char[] password = Keyring.read(getPasswordKey(keyPrefixuserurl));
            return password != null ? password : new char[0];
        }
    }
    
    private static String getPasswordKey(String prefixString userString url) {
        return (prefix != null ? prefix + "-" : "") + user + "@" + url;         // NOI18N
    }


    
Determines if the jira plugin is instaled or not

Returns:
true if jira plugin is installed, otherwise false
    public static boolean isJiraInstalled() {
        BugtrackingConnector[] connectors = BugtrackingManager.getInstance().getConnectors();
        for (BugtrackingConnector c : connectors) {
            // XXX hack
            if(c.getClass().getName().startsWith("org.netbeans.modules.jira")) {    // NOI18N
                return true;
            }
        }
        return false;
    }
    public static void openQuery(final Query queryfinal Repository repositoryfinal boolean suggestedSelectionOnly) {
        QueryAction.openQuery(queryrepositorysuggestedSelectionOnly);
    }
    public static void openIssue(File fileString issueId) {
        IssueAction.openIssue(fileissueId);
    }
    public static Map<StringList<RecentIssue>> getAllRecentIssues() {
        return BugtrackingManager.getInstance().getAllRecentIssues();
    }
    public static Collection<IssuegetRecentIssues(Repository repo) {
        return BugtrackingManager.getInstance().getRecentIssues(repo);
    }
    public static void closeQuery(Query query) {
        QueryAction.closeQuery(query);
    }
    public static void createIssue(Repository repo) {
        IssueAction.createIssue(repo);
    }
    public static String getPasswordLog(String psswd) {
        if(psswd == null) {
            return ""// NOI18N
        }
        if("true".equals(System.getProperty("org.netbeans.modules.bugtracking.logPasswords""false"))) { // NOI18N
            return psswd
        }
        return "******"// NOI18N
    }
    
New to GrepCode? Check out our FAQ X