Java Code Examples for org.openide.util.Utilities

The following examples show how to use org.openide.util.Utilities. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   Source File: ChromeBrowser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of BrowserImpl implementation.
 * @throws UnsupportedOperationException when method is called and OS is not Windows.
 * @return browserImpl implementation of browser.
 */
@Override
public HtmlBrowser.Impl createHtmlBrowserImpl() {
    ExtBrowserImpl impl = null;

    if (org.openide.util.Utilities.isWindows ()) {
        impl = new NbDdeBrowserImpl (this);
    } else if (Utilities.isMac()) {
        impl = new MacBrowserImpl(this);
    } else if (Utilities.isUnix() && !Utilities.isMac()) {
        impl = new UnixBrowserImpl(this);
    } else {
        throw new UnsupportedOperationException (NbBundle.
                getMessage(FirefoxBrowser.class, "MSG_CannotUseBrowser"));  // NOI18N
    }
    
    return impl;
}
 
Example 2
Source Project: netbeans   Source File: CategoryDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
private MouseListener createMouseListener() {
    return new MouseAdapter() {
        public void mouseClicked(MouseEvent event) {
            if (SwingUtilities.isRightMouseButton(event)) {
                JComponent comp = (JComponent)event.getSource();
                Item item = null;
                if (comp instanceof JList) {
                    JList list = (JList)comp;
                    Point p = event.getPoint();
                    int index = list.locationToIndex(p);
                    if (index >= 0 && !list.getCellBounds(index, index).contains(p)) {
                        index = -1;
                    }
                    if (index >= 0) {
                        item = (Item)list.getModel().getElementAt(index);
                    }
                }
                Action[] actions = null == item ? category.getActions() : item.getActions();
                JPopupMenu popup = Utilities.actionsToPopup( actions, getComponent() );
                Utils.addCustomizationMenuItems( popup, getPalettePanel().getController(), getPalettePanel().getSettings() );
                popup.show(comp, event.getX(), event.getY());
            }
        }
    };
}
 
Example 3
Source Project: netbeans   Source File: HudsonGitSCMTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testForFolder() throws Exception {
    TestFileUtils.writeFile(new File(getWorkDir(), ".git/config"),
              "[core]\n"
            + "\trepositoryformatversion = 0\n"
            + "[remote \"origin\"]\n"
            + "\tfetch = +refs/heads/*:refs/remotes/origin/*\n"
            + "\turl = [email protected]:x/y.git\n"
            + "[branch \"master\"]\n"
            + "\tremote = origin\n"
            + "\tmerge = refs/heads/master\n");
    // ref: http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#_git_urls_a_id_urls_a
    assertEquals("ssh://[email protected]/x/y.git", String.valueOf(HudsonGitSCM.getRemoteOrigin(Utilities.toURI(getWorkDir()), null)));
    HudsonSCM.Configuration cfg = new HudsonGitSCM().forFolder(getWorkDir());
    assertNotNull(cfg);
    Document doc = XMLUtil.createDocument("whatever", null, null, null);
    cfg.configure(doc);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLUtil.write(doc, baos, "UTF-8");
    String text = baos.toString("UTF-8");
    assertTrue(text, text.contains("x/y.git"));
}
 
Example 4
Source Project: netbeans   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/** Tries to set default L&F according to platform.
 * Uses:
 *   Metal L&F on Linux and Solaris
 *   Windows L&F on Windows
 *   Aqua L&F on Mac OS X
 *   System L&F on other OS
 */
public static void setDefaultLookAndFeel () {
    String uiClassName;
    if (Utilities.isWindows()) {
        uiClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; //NOI18N
    } else if (Utilities.isMac()) {
        uiClassName = "com.apple.laf.AquaLookAndFeel"; //NOI18N
    } else if (Utilities.isUnix()) {
        uiClassName = "javax.swing.plaf.metal.MetalLookAndFeel"; //NOI18N
    } else {
        uiClassName = UIManager.getSystemLookAndFeelClassName();
    }
    if (uiClassName.equals(UIManager.getLookAndFeel().getClass().getName())) {
        //Desired L&F is already set
        return;
    }
    try {
        UIManager.setLookAndFeel(uiClassName);
    } catch (Exception ex) {
        System.err.println("Cannot set L&F " + uiClassName); //NOI18N
        System.err.println("Exception:" + ex.getMessage()); //NOI18N
        ex.printStackTrace();
    }
}
 
Example 5
Source Project: netbeans   Source File: URLsAreEqualTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testURLsAreEqual() throws Exception {
    final File wd = new File(getWorkDir(), "work#dir");
    wd.mkdirs();
    
    File jar = new File(wd, "default-package-resource.jar");
    
    URL orig = new URL("jar:" + Utilities.toURI(jar) + "!/package/resource.txt");
    URLConnection conn = orig.openConnection();
    assertFalse("JDK connection: " + conn, conn.getClass().getName().startsWith("org.netbeans"));
    
    
    TestFileUtils.writeZipFile(jar, "package/resource.txt:content", "root.txt:empty");
    JarClassLoader jcl = new JarClassLoader(Collections.singletonList(jar), new ProxyClassLoader[0]);

    URL root = jcl.getResource("root.txt");
    URL u = new URL(root, "/package/resource.txt");
    assertNotNull("Resource found", u);
    URLConnection uC = u.openConnection();
    assertTrue("Our connection: " + uC, uC.getClass().getName().startsWith("org.netbeans"));

    assertEquals("Both URLs are equal", u, orig);
    assertEquals("Equality is symetrical", orig, u);
}
 
Example 6
Source Project: netbeans   Source File: Win32Protect.java    License: Apache License 2.0 6 votes vote down vote up
public @Override boolean enabled() {
    if (!Utilities.isWindows()) {
        LOG.fine("not running on Windows");
        return false;
    }
    if (Boolean.getBoolean("netbeans.keyring.no.native")) {
        LOG.fine("native keyring integration disabled");
        return false;
    }
    try {
        if (CryptLib.INSTANCE == null) {
            LOG.fine("loadLibrary -> null");
            return false;
        }
        return true;
    } catch (Throwable t) {
        LOG.log(Level.FINE, null, t);
        return false;
    }
}
 
Example 7
Source Project: netbeans   Source File: OrderingItemPanel.java    License: Apache License 2.0 6 votes vote down vote up
private void check() {
    if (desc == null)
        return;

    NotificationLineSupport supp = desc.getNotificationLineSupport();
    if (rbName.isSelected()) {
        String s = tfNameRef.getText();
        if (s == null || s.length() < 1) {
            supp.setInformationMessage(NbBundle.getMessage(OrderingItemPanel.class, "ERR_NO_NAME"));
            desc.setValid(false);
            return;
        }
        if (!Utilities.isJavaIdentifier(s)) {
            supp.setErrorMessage(NbBundle.getMessage(OrderingItemPanel.class, "ERR_WRONG_NAME"));
            desc.setValid(false);
            return;
        }
    }
    supp.clearMessages();
    desc.setValid(true);
}
 
Example 8
Source Project: netbeans   Source File: CompileClassPathImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
URI[] createPath() {
    List<URI> lst = new ArrayList<>();
    boolean broken = getCompileArtifacts(getMavenProject().getOriginalMavenProject(), lst);
    if(addOutputDir) {
        lst.add(Utilities.toURI(getProject().getProjectWatcher().getOutputDirectory(false)));
    }
    
    if (incomplete != broken) {
        incomplete = broken;
        firePropertyChange(PROP_FLAGS, null, null);
    }
    URI[] uris = new URI[lst.size()];
    uris = lst.toArray(uris);
    return uris;
}
 
Example 9
Source Project: netbeans   Source File: EditorContextDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
private EditorContextDispatcher() {
    refreshProcessor = new RequestProcessor("Refresh Editor Context", 1);   // NOI18N
    
    resFileObject = Utilities.actionsGlobalContext().lookupResult(FileObject.class);
    EditorLookupListener ell = new EditorLookupListener(FileObject.class);
    resFileObject.addLookupListener(ell);
    ell.lookupChanged(false); // To initialize data
    
    erListener = new EditorRegistryListener();
    EditorRegistry.addPropertyChangeListener(WeakListeners.propertyChange(erListener, EditorRegistry.class));
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            // To initialize data:
            ((EditorRegistryListener) erListener).update(false);
        }
    });
    
}
 
Example 10
Source Project: netbeans   Source File: SourceForBinaryQueryTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSFBQDelegatingImpl2 () throws Exception {
    DelegatingSFBImpl.impl = new LeafSFBQImpl();
    MockServices.setServices(DelegatingSFBImpl.class);
    SourceForBinaryQuery.Result2 res = SourceForBinaryQuery.findSourceRoots2(br1.toURL());
    assertNotNull(res);
    assertEquals(1, res.getRoots().length);
    assertEquals(Collections.singletonList(sr1), Arrays.asList(res.getRoots()));
    assertFalse(res.preferSources());
    
    res = SourceForBinaryQuery.findSourceRoots2(br2.toURL());
    assertNotNull(res);
    assertEquals(1, res.getRoots().length);
    assertEquals(Collections.singletonList(sr2), Arrays.asList(res.getRoots()));
    assertTrue(res.preferSources());
    
    res = SourceForBinaryQuery.findSourceRoots2(Utilities.toURI(getWorkDir()).toURL());
    assertNotNull(res);
    assertEquals(0, res.getRoots().length);
    assertFalse(res.preferSources());
}
 
Example 11
Source Project: netbeans   Source File: ContextActionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testContextInstancesDoNotInterfereWithEachOtherOrParent() throws Exception {
    System.out.println("testContextInstancesDoNotInterfereWithEachOtherOrParent");
    A a = new A();
    assertNull(Utilities.actionsGlobalContext().lookup(String.class)); //sanity check
    assertEquals("A", a.getValue(Action.NAME));
    Action a1 = a.createContextAwareInstance(Lookup.EMPTY);
    assertFalse(a.isEnabled());
    assertEquals("A", a1.getValue(Action.NAME));
    Action a2 = a.createContextAwareInstance(Lookups.fixed("testGeneralBehavior"));
    assertTrue(a2.isEnabled());
    assertFalse(a.isEnabled());
    setContent("foo");
    assertTrue(a.isEnabled());
    assertFalse(a1.isEnabled());
    assertTrue(a2.isEnabled());
    clearContent();
    assertFalse(a.isEnabled());
    assertTrue(a2.isEnabled());
}
 
Example 12
Source Project: netbeans   Source File: FilesystemHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tries to determine if the <code>file</code> is supposed to be really removed by svn or not.<br/>
 * i.e. unversioned files should not be removed at all.
 * @param file file sheduled for removal
 * @return <code>true</code> if the <code>file</code> shall be really removed, <code>false</code> otherwise.
 */
private boolean shallRemove(SvnClient client, File file) throws SVNClientException {
    boolean retval = true;
    if (!"true".equals(System.getProperty("org.netbeans.modules.subversion.deleteMissingFiles", "false"))) { //NOI18N
        // prevents automatic svn remove for those who dislike such behavior
        Subversion.LOG.log(Level.FINE, "File {0} deleted externally, metadata not repaired (org.netbeans.modules.subversion.deleteMissingFiles=false by default)", new String[] {file.getAbsolutePath()}); //NOI18N
        retval = false;
    } else {
        ISVNStatus status = getStatus(client, file);
        if (!SVNStatusKind.MISSING.equals(status.getTextStatus())) {
            Subversion.LOG.fine(" shallRemove: skipping delete due to correct metadata");
            retval = false;
        } else if (Utilities.isMac() || Utilities.isWindows()) {
            String existingFilename = FileUtils.getExistingFilenameInParent(file);
            if (existingFilename != null) {
                retval = false;
            }
        }
    }
    return retval;
}
 
Example 13
Source Project: netbeans   Source File: JavadocForBinaryImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find Javadoc roots for classpath extensions ("wrapped" JARs) of the project
 * added by naming convention <tt>&lt;jar name&gt;-javadoc(.zip)</tt>
 * See issue #66275
 * @param binaryRoot
 * @return
 */
private Result findForCPExt(URL binaryRoot) {
    URL jar = FileUtil.getArchiveFile(binaryRoot);
    if (jar == null)
        return null;    // not a class-path-extension
    File binaryRootF = Utilities.toFile(URI.create(jar.toExternalForm()));
    // XXX this will only work for modules following regular naming conventions:
    String n = binaryRootF.getName();
    if (!n.endsWith(".jar")) { // NOI18N
        // ignore
        return null;
    }
    // convention-over-cfg per mkleint's suggestion: <jarname>-javadoc(.zip) folder or ZIP
    File jFolder = new File(binaryRootF.getParentFile(), 
            n.substring(0, n.length() - ".jar".length()) + "-javadoc");
    if (jFolder.isDirectory()) {
            return new R(new URL[]{FileUtil.urlForArchiveOrDir(jFolder)});
    } else {
        File jZip = new File(jFolder.getAbsolutePath() + ".zip");
        if (jZip.isFile()) {
            return new R(new URL[]{FileUtil.urlForArchiveOrDir(jZip)});
        }
    }
    return null;
}
 
Example 14
Source Project: netbeans   Source File: BinaryAnalyserTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testTransactionalFlush() throws Exception {
    requireFullIndex(true);
    FileObject workDir = FileUtil.toFileObject(getWorkDir());
    FileObject indexDir = workDir.createFolder("index");
    File binaryAnalyzerDataDir = annotationsJar();

    final Index index = IndexManager.createIndex(FileUtil.toFile(indexDir), DocumentUtil.createAnalyzer());
    BinaryAnalyser a = new BinaryAnalyser(
        new IndexWriter(index) {
            @Override
            public void deleteAndFlush(List<Pair<Pair<BinaryName, String>, Object[]>> refs, Set<Pair<String, String>> toDelete) throws IOException {
                super.deleteAndFlush(refs, toDelete);
            try {
                dataFlushed(index);
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
            }
        }, getWorkDir()
    );

    LowMemoryWatcherAccessor.setLowMemory(true);
    assertTrue(a.analyse(Utilities.toURI(binaryAnalyzerDataDir).toURL()).done);
    // at least one flush occured.
    assertFalse(flushCount == 0);

    assertReference(index, "annotations.NoArgAnnotation", "usages.ClassAnnotations", "usages.MethodAnnotations", "usages.FieldAnnotations");
    assertReference(index, "annotations.ArrayOfStringArgAnnotation", "usages.ClassAnnotations", "usages.ClassArrayAnnotations", "usages.MethodAnnotations", "usages.MethodArrayAnnotations", "usages.FieldAnnotations", "usages.FieldArrayAnnotations");
    assertReference(index, "annotations.TestEnum", "usages.ClassAnnotations", "usages.ClassArrayAnnotations", "usages.MethodAnnotations", "usages.MethodArrayAnnotations", "usages.FieldAnnotations", "usages.FieldArrayAnnotations");
    assertReference(index, "java.util.List", "usages.ClassAnnotations", "usages.ClassArrayAnnotations", "usages.MethodAnnotations", "usages.MethodArrayAnnotations", "usages.FieldAnnotations", "usages.FieldArrayAnnotations");
}
 
Example 15
Source Project: netbeans   Source File: CallableSystemAction.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(ActionEvent ev) {
    if (isEnabled()) {
        org.openide.util.actions.ActionInvoker.invokeAction(
            this, ev, asynchronous(), new Runnable() {
                public void run() {
                    performAction();
                }
            }
        );
    } else {
        // Should not normally happen.
        Utilities.disabledActionBeep();
    }
}
 
Example 16
Source Project: openjdk-8   Source File: FilterTopComponent.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void resultChanged(LookupEvent lookupEvent) {
    setChain(Utilities.actionsGlobalContext().lookup(FilterChain.class));
/*
EditorTopComponent tc = EditorTopComponent.getActive();
if (tc != null) {
setChain(tc.getFilterChain());
}*/
}
 
Example 17
Source Project: netbeans   Source File: EditorContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** throws IllegalComponentStateException when can not return the data in AWT. */
private String getCurrentElement(FileObject fo, JEditorPane ep,
                                 final ElementKind kind, final String[] elementSignaturePtr)
        throws java.awt.IllegalComponentStateException {

    if (fo == null) {
        return null;
    }
    final int currentOffset;
    final String selectedIdentifier;
    if (ep != null) {
        String s;
        Caret caret = ep.getCaret();
        if (caret == null) {
            s = null;
            currentOffset = 0;
        } else {
            s = ep.getSelectedText ();
            currentOffset = ep.getCaretPosition();
            if (ep.getSelectionStart() > currentOffset || ep.getSelectionEnd() < currentOffset) {
                s = null; // caret outside of the selection
            }
        }
        if (s != null && Utilities.isJavaIdentifier (s)) {
            selectedIdentifier = s;
        } else {
            selectedIdentifier = null;
        }
    } else {
        selectedIdentifier = null;
        currentOffset = 0;
    }
    return EditorContextSupport.getCurrentElement(fo, currentOffset, selectedIdentifier, kind, elementSignaturePtr);
}
 
Example 18
Source Project: netbeans   Source File: CreateRelationshipPanel.java    License: Apache License 2.0 5 votes vote down vote up
public NameStatus checkName(String name){
    if (!Utilities.isJavaIdentifier(name)){
        return NameStatus.ILLEGAL_JAVA_ID;
    }
    
    if (JavaPersistenceQLKeywords.isKeyword(name)){
        return NameStatus.ILLEGAL_SQL_KEYWORD;
    }
    
    if (existingFieldNames != null && existingFieldNames.contains(name)){
        return NameStatus.DUPLICATE;
    }
    
    return NameStatus.VALID;
}
 
Example 19
Source Project: netbeans   Source File: ActionsSearchProvider.java    License: Apache License 2.0 5 votes vote down vote up
private static ActionEvent createActionEvent (Action action) {
    Object evSource = null;
    int evId = ActionEvent.ACTION_PERFORMED;

    // text (editor) actions
    if (action instanceof TextAction) {
        EditorCookie ec = Utilities.actionsGlobalContext().lookup(EditorCookie.class);
        if (ec == null) {
            return null;
        }

        JEditorPane[] editorPanes = ec.getOpenedPanes();
        if (editorPanes == null || editorPanes.length <= 0) {
            return null;
        }
        evSource = editorPanes[0];
    }

    if (evSource == null) {
        evSource = TopComponent.getRegistry().getActivated();
    }
    if (evSource == null) {
        evSource = WindowManager.getDefault().getMainWindow();
    }

    
    return new ActionEvent(evSource, evId, null);
}
 
Example 20
Source Project: netbeans   Source File: RefreshWorkTest.java    License: Apache License 2.0 5 votes vote down vote up
protected @Override void setUp() throws IOException {
    this.clearWorkDir();
    final File _wd = this.getWorkDir();
    final FileObject wd = FileUtil.toFileObject(_wd);
    final FileObject cache = wd.createFolder("cache");
    CacheFolder.setCacheFolder(cache);
    
    outerFolder1 = new File(getWorkDir(), "OuterFolder-1");
    outerFolder1.mkdirs();
    outerFolder2 = new File(getWorkDir(), "OuterFolder-2");
    outerFolder2.mkdirs();

    File rootAFile = new File(outerFolder1, "rootA");
    rootAFile.mkdirs();
    rootAUrl = Utilities.toURI(rootAFile).toURL();
    scannedRoots2Dependencies.put(rootAUrl, Collections.<URL>emptyList());
    File rootBFile = new File(outerFolder1, "rootB");
    rootBFile.mkdirs();
    rootBUrl = Utilities.toURI(rootBFile).toURL();
    scannedRoots2Dependencies.put(rootBUrl, Collections.<URL>emptyList());

    File rootCFile = new File(outerFolder2, "rootC");
    rootCFile.mkdirs();
    populateFolderStructure(rootCFile,
            "org/pckg1/file1.txt",
            "org/pckg1/pckg2/file1.txt",
            "org/pckg1/pckg2/file2.txt",
            "org/pckg2/"
    );
    rootCUrl = Utilities.toURI(rootCFile).toURL();
    scannedRoots2Dependencies.put(rootCUrl, Collections.<URL>emptyList());

    RepositoryUpdater.getDefault().rootsListeners.setListener(new FileChangeAdapter(), new FileChangeAdapter());
}
 
Example 21
Source Project: netbeans   Source File: XMLUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testEntityIncludes() throws Exception {
    clearWorkDir();
    // #146081: xml:base attributes get inserted sometimes and can mess up validation.
    // #160806: problems writing: no system ID, xml:base inserted.
    SchemaFactory f = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    String xsd =
            "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='some://where' xmlns='some://where' elementFormDefault='qualified'>\n" +
            " <xsd:element name='root'>\n" +
            "  <xsd:complexType>\n" +
            "   <xsd:sequence>\n" +
            "    <xsd:element name='hello' type='xsd:NMTOKEN'/>\n" +
            "   </xsd:sequence>\n" +
            "  </xsd:complexType>\n" +
            " </xsd:element>\n" +
            "</xsd:schema>\n";
    Schema s = f.newSchema(new StreamSource(new StringReader(xsd)));
    File d = getWorkDir();
    File main = new File(d, "main.xml");
    File ent = new File(d, "ent.xml");
    TestFileUtils.writeFile(main, "<!DOCTYPE root [<!ENTITY ent SYSTEM 'ent.xml'>]> <root xmlns='some://where'>&ent;</root>");
    TestFileUtils.writeFile(ent, "<hello xmlns='some://where'>there</hello>");
    Document doc = XMLUtil.parse(new InputSource(Utilities.toURI(main).toString()), false, true, null, null);
    XMLUtil.validate(doc.getDocumentElement(), s);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLUtil.write(doc, baos, "UTF-8");
    String expanded =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<root xmlns=\"some://where\">\n" +
            "    <hello>there</hello>\n" +
            "</root>\n";
    assertEquals(expanded, baos.toString("UTF-8").replace("\r\n", "\n"));
    // XXX #160806 reported a problem with "xml:base" being consider a no-NS attr; not yet caught by test
    // Try again with no xmlns specified in entity; should inherit from main.xml:
    TestFileUtils.writeFile(ent, "<hello>there</hello>");
    doc = XMLUtil.parse(new InputSource(Utilities.toURI(main).toString()), false, true, null, null);
    XMLUtil.validate(doc.getDocumentElement(), s);
    baos = new ByteArrayOutputStream();
    XMLUtil.write(doc, baos, "UTF-8");
    assertEquals(expanded, baos.toString("UTF-8").replace("\r\n", "\n"));
}
 
Example 22
Source Project: netbeans   Source File: NexusTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected void setUp() throws Exception {
    clearWorkDir();
    PlacesTestUtils.setUserDirectory(getWorkDir());
    File repo = new File(getWorkDir(), "repo");
    embedder = EmbedderFactory.getProjectEmbedder();
    System.setProperty("no.local.settings", "true");
    defaultArtifactRepository = embedder.lookupComponent(ArtifactRepositoryFactory.class).createArtifactRepository("test", Utilities.toURI(repo).toString(), "default", null, null);
    embedder.setUpLegacySupport(); // XXX could use org.sonatype.aether.RepositorySystem to avoid maven-compat
    artifactInstaller = embedder.lookupComponent(ArtifactInstaller.class);
    info = new RepositoryInfo("test", "Test", repo.getAbsolutePath(), null);
    RepositoryPreferences.getInstance().addOrModifyRepositoryInfo(info);
    nrii = Lookup.getDefault().lookup(NexusRepositoryIndexerImpl.class);
}
 
Example 23
@Test
public void itMapsIndentSizeTabToMinusTwo() throws IOException {
  StringBuilder config = new StringBuilder("root = true");
  config.append(System.lineSeparator()).append(System.lineSeparator());
  config.append("[*]").append(System.lineSeparator());
  config.append("charset = utf-8").append(System.lineSeparator());
  config.append("end_of_line = lf").append(System.lineSeparator());
  config.append(System.lineSeparator());
  config.append("[*.js]").append(System.lineSeparator());
  config.append("indent_style = tab").append(System.lineSeparator());

  File ecFile = File.createTempFile(this.getClass().getSimpleName(), ".editorconfig");
  Path path = Paths.get(Utilities.toURI(ecFile));
  Files.write(path, config.toString().getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);

  MappedEditorConfig mappedConfig = EditorConfigPropertyMapper.createEditorConfig(jsFile, ecFile.getName());
  // LOG.log(Level.INFO, "Config:\r\n{0}", mappedConfig.toString());

  assertEquals(true, ecFile.delete());
  assertEquals(StandardCharsets.UTF_8.name(), mappedConfig.getCharset().getName());
  assertEquals("\n", mappedConfig.getEndOfLine());
  assertEquals(-2, mappedConfig.getIndentSize());
  assertEquals(EditorConfigConstant.INDENT_STYLE_TAB, mappedConfig.getIndentStyle());
  assertEquals(false, mappedConfig.isInsertFinalNewLine());
  assertEquals(-1, mappedConfig.getTabWidth());
  assertEquals(false, mappedConfig.isTrimTrailingWhiteSpace());
}
 
Example 24
Source Project: visualvm   Source File: AttachModelProvider.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AttachModel createModelFor(Application app) {
    if (Host.LOCALHOST.equals(app.getHost())) {
        JvmJvmstatModel jvmstat = JvmJvmstatModelFactory.getJvmstatModelFor(app);
        
        if (jvmstat != null && jvmstat.isAttachable()) {
            if (Utilities.isWindows()) {
                // on Windows Attach API can only attach to the process of the same
                // architecture ( 32bit / 64bit )
                Boolean this64bitArch = is64BitArchitecture();
                Boolean app64bitArch = is64BitArchitecture(jvmstat);
                if (this64bitArch != null && app64bitArch != null) {
                    if (!this64bitArch.equals(app64bitArch)) {
                        return null;
                    }
                }
            }
            // check that application is running under the same user as VisualVM
            String pid = String.valueOf(app.getPid());
            for (VirtualMachineDescriptor descr : VirtualMachine.list()) {
                if (pid.equals(descr.id())) {
                    String vmName = jvmstat.getVmName();
                    if (vmName != null) {
                        if ("BEA JRockit(R)".equals(vmName)) {  // NOI18N
                            return new JRockitAttachModelImpl(app);
                        }
                        if ("Oracle JRockit(R)".equals(vmName)) {  // NOI18N
                            return new OracleJRockitAttachModelImpl(app);
                        }                            
                    }
                    return new AttachModelImpl(app);
                }
            }
        }
    }
    return null;
}
 
Example 25
Source Project: netbeans   Source File: ElementNode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Action[] getActions( boolean context ) {
    if ( context || description.name == null ) {
        return description.ui.getActions();
    } else {
        final Action panelActions[] = description.ui.getActions();
        final List<? extends Action> standardActions;
        final List<? extends Action> additionalActions;
        if (description.kind == ElementKind.OTHER) {
            standardActions = Collections.singletonList(getOpenAction());
            additionalActions = Collections.<Action>emptyList();
        } else {
            standardActions = Arrays.asList(new Action[] {
                getOpenAction(),
                RefactoringActionsFactory.whereUsedAction(),
                RefactoringActionsFactory.popupSubmenuAction()
            });
            additionalActions = Utilities.actionsForPath(ACTION_FOLDER);
        }
        final int standardActionsSize = standardActions.isEmpty() ? 0 : standardActions.size() + 1;
        final int additionalActionSize = additionalActions.isEmpty() ? 0 : additionalActions.size() + 1;
        final List<Action> actions = new ArrayList<>(standardActionsSize + additionalActionSize + panelActions.length);
        if (standardActionsSize > 0) {
            actions.addAll(standardActions);
            actions.add(null);
        }
        if (additionalActionSize > 0) {
            actions.addAll(additionalActions);
            actions.add(null);
        }
        actions.addAll(Arrays.asList(panelActions));
        return actions.toArray(new Action[actions.size()]);
    }
}
 
Example 26
Source Project: netbeans   Source File: VCSFileProxy.java    License: Apache License 2.0 5 votes vote down vote up
public static VCSFileProxy createFileProxy(URI uri) {
    if (uri.getScheme().equals("file")) { //NOI18N
        return createFileProxy(Utilities.toFile(uri));
    } else {
        VCSFileProxyOperations fileProxyOperations = getFileProxyOperations(uri);
        if (fileProxyOperations != null) {
            VCSFileProxy file = new VCSFileProxy(uri.getPath(), fileProxyOperations);
            return file;
        }
        return null;
    }
}
 
Example 27
Source Project: netbeans   Source File: ArchiveURLMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doFunnyZipEntryNames(String file) throws Exception {
    File docx = new File(getWorkDir(), "ms-docx.jar");
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(docx));
    ZipEntry entry = new ZipEntry(file);
    jos.putNextEntry(entry);
    jos.write("content".getBytes());
    jos.close();
    
    FileObject docxFO = URLMapper.findFileObject(Utilities.toURI(docx).toURL());
    assertNotNull(docxFO);
    assertTrue(FileUtil.isArchiveFile(docxFO));
    
    FileObject docxRoot = FileUtil.getArchiveRoot(docxFO);
    assertNotNull("Root found", docxRoot);
    FileObject content = docxRoot.getFileObject(file);
    assertNotNull("content.xml found", content);
    
    assertEquals("Has right bytes", "content", content.asText());
    
    CharSequence log = Log.enable("", Level.WARNING);
    URL u = URLMapper.findURL(content, URLMapper.EXTERNAL);
    InputStream is = u.openStream();
    byte[] arr = new byte[30];
    int len = is.read(arr);
    assertEquals("Len is content", "content".length(), len);
    assertEquals("OK", "content", new String(arr, 0, len));
    
    assertEquals("No warnings:\n" + log, 0, log.length());
    assertEquals(u.toString(), content, URLMapper.findFileObject(u));
}
 
Example 28
Source Project: netbeans   Source File: CyclicSymlinkTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testAcyclicSymlink() throws Exception {
    if (Utilities.isWindows()) {
        return;
    }
    clearWorkDir();
    assertAcyclic(getWorkDir());
}
 
Example 29
Source Project: netbeans   Source File: KeyStrokeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get human-readable name for a {@link KeyStroke}.
 */
public static String getKeyStrokeAsText(@NonNull KeyStroke keyStroke) {
    int modifiers = keyStroke.getModifiers ();
    StringBuilder sb = new StringBuilder ();
    if ((modifiers & InputEvent.CTRL_DOWN_MASK) > 0) {
        sb.append(EMACS_CTRL);
    }
    if ((modifiers & InputEvent.ALT_DOWN_MASK) > 0) {
        sb.append(STRING_ALT);
    }
    if ((modifiers & InputEvent.SHIFT_DOWN_MASK) > 0) {
        sb.append (EMACS_SHIFT);
    }
    if ((modifiers & InputEvent.META_DOWN_MASK) > 0) {
        sb.append(STRING_META);
    }
    if (keyStroke.getKeyCode () != KeyEvent.VK_SHIFT &&
        keyStroke.getKeyCode () != KeyEvent.VK_CONTROL &&
        keyStroke.getKeyCode () != KeyEvent.VK_META &&
        keyStroke.getKeyCode () != KeyEvent.VK_ALT &&
        keyStroke.getKeyCode () != KeyEvent.VK_ALT_GRAPH) {
        sb.append (Utilities.keyToString (
            KeyStroke.getKeyStroke (keyStroke.getKeyCode (), 0)
        ));
    }
    return sb.toString ();
}
 
Example 30
Source Project: editorconfig-netbeans   Source File: FileInfoReaderTest.java    License: MIT License 5 votes vote down vote up
private File createUTF_8_CR() {
  File file = null;
  // UTF-8 without BOM can be recognized by special chars like "\u2603"
  String content = "Hello\rWorld!\u2603";

  try {
    file = File.createTempFile("utf-8-cr", ".txt");
    Path path = Paths.get(Utilities.toURI(file));
    Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
  } catch (IOException ex) {
    Exceptions.printStackTrace(ex);
  }

  return file;
}