Java Code Examples for org.openide.filesystems.FileUtil#findFreeFileName()

The following examples show how to use org.openide.filesystems.FileUtil#findFreeFileName() . 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 File: PerformanceTestCase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private synchronized void stop(int round) throws Exception {
    ActionListener ss = (ActionListener) profiler;
    profiler = null;
    if (!profiling) {
        return;
    }
    FileObject wd = FileUtil.toFileObject(getWorkDir());
    String n = FileUtil.findFreeFileName(wd, "snapshot-" + round, "nps"); // NOI18N
    FileObject snapshot = wd.createData(n, "nps"); // NOI18N
    DataOutputStream dos = new DataOutputStream(snapshot.getOutputStream());
    ss.actionPerformed(new ActionEvent(dos, 0, "write")); // NOI18N
    dos.close();
    LOG.log(
            Level.WARNING, "Profiling snapshot taken into {0}", snapshot.getPath()
    );
}
 
Example 2
Source File: AutomaticRegistration.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Registers the server instance file object and set the default properties.
 *
 * @param serverInstanceDir /J2EE/InstalledServers folder
 * @param url server instance url/ID
 * @param displayName display name
 */
private static boolean registerServerInstanceFO(FileObject serverInstanceDir, String url, String displayName) {
    String name = FileUtil.findFreeFileName(serverInstanceDir, "tomcat_autoregistered_instance", null); // NOI18N
    FileObject instanceFO;
    try {
        instanceFO = serverInstanceDir.createData(name);
        instanceFO.setAttribute(InstanceProperties.URL_ATTR, url);
        instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, "ide"); // NOI18N
        String password = Utils.generatePassword(8);
        instanceFO.setAttribute(InstanceProperties.PASSWORD_ATTR, password);
        instanceFO.setAttribute(InstanceProperties.DISPLAY_NAME_ATTR, displayName);
        instanceFO.setAttribute(InstanceProperties.HTTP_PORT_NUMBER, "8084"); // NOI18N
        instanceFO.setAttribute(TomcatProperties.PROP_SHUTDOWN, "8025"); // NOI18N
        instanceFO.setAttribute(TomcatProperties.PROP_MONITOR, "true"); // NOI18N
        instanceFO.setAttribute(TomcatManager.PROP_BUNDLED_TOMCAT, "true"); // NOI18N
        instanceFO.setAttribute(TomcatProperties.PROP_AUTOREGISTERED, "true"); // NOI18N
        return true;
    } catch (IOException e) {
        LOGGER.log(Level.INFO, "Cannot register the default Tomcat server."); // NOI18N
        LOGGER.log(Level.INFO, null, e);
    }
    return false;
}
 
Example 3
Source File: ServerRegistry.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private synchronized void writeInstanceToFile(String url, String username,
        String password, String serverName) throws IOException {

    if (url == null) {
        Logger.getLogger("global").log(Level.SEVERE, NbBundle.getMessage(ServerRegistry.class, "MSG_NullUrl"));
        return;
    }

    FileObject dir = FileUtil.getConfigFile(DIR_INSTALLED_SERVERS);
    FileObject instanceFOs[] = dir.getChildren();
    FileObject instanceFO = null;
    for (int i=0; i<instanceFOs.length; i++) {
        if (url.equals(instanceFOs[i].getAttribute(URL_ATTR)))
            instanceFO = instanceFOs[i];
    }
    
    if (instanceFO == null) {
        String name = FileUtil.findFreeFileName(dir,"instance",null);
        instanceFO = dir.createData(name);
    }
    instanceFO.setAttribute(URL_ATTR, url);
    instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, username);
    savePassword(instanceFO, password,
            NbBundle.getMessage(ServerRegistry.class, "MSG_KeyringDisplayName", serverName));
}
 
Example 4
Source File: JBDeploymentFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void register(FileObject serverInstanceDir, String serverLocation, String domainLocation, String host, String port) throws IOException {
    String displayName = generateDisplayName(serverInstanceDir);

    String url = URI_PREFIX + host + ":" + port + "#default&" + serverLocation;    // NOI18N

    String name = FileUtil.findFreeFileName(serverInstanceDir, "instance", null); // NOI18N
    FileObject instanceFO = serverInstanceDir.createData(name);

    instanceFO.setAttribute(InstanceProperties.URL_ATTR, url);
    instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, "");
    instanceFO.setAttribute(InstanceProperties.PASSWORD_ATTR, "");
    instanceFO.setAttribute(InstanceProperties.DISPLAY_NAME_ATTR, displayName);
    instanceFO.setAttribute(InstanceProperties.REMOVE_FORBIDDEN, "true");

    instanceFO.setAttribute(JBPluginProperties.PROPERTY_SERVER, "default"); // NOI18N
    String deployDir = JBPluginUtils.getDeployDir(domainLocation);
    instanceFO.setAttribute(JBPluginProperties.PROPERTY_DEPLOY_DIR, deployDir);
    instanceFO.setAttribute(JBPluginProperties.PROPERTY_SERVER_DIR, domainLocation);
    instanceFO.setAttribute(JBPluginProperties.PROPERTY_ROOT_DIR, serverLocation);
    instanceFO.setAttribute(JBPluginProperties.PROPERTY_HOST, host);
    instanceFO.setAttribute(JBPluginProperties.PROPERTY_PORT, port);
}
 
Example 5
Source File: AddPageActionProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    try {
        final PageFlowController pfc = scene.getPageFlowView().getPageFlowController();
        
        final FileObject webFileObject = pfc.getWebFolder();
        
        String name = FileUtil.findFreeFileName(webFileObject, "page", "jsp");
        name = JOptionPane.showInputDialog("Select Page Name", name);
        
        createIndexJSP(webFileObject, name);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    
    //            }
}
 
Example 6
Source File: PersistenceManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String createTopComponentPersistentID (TopComponent tc, String preferredID) throws IOException {
    String compName = preferredID != null ? preferredID : null;
    // be prepared for null names, empty names and convert to filesystem friendly name
    if ((compName == null) || (compName.length() == 0)) {
        compName = DEFAULT_TC_NAME;
    }
    //Check if component id is not already present in cache of invalid ids
    boolean isUsed = true;
    String origName = compName;
    compName = escape(compName);
    String srcName = compName;
    int i = 1;
    synchronized(LOCK_IDS) {
        while (isUsed) {
            isUsed = false;
            String uniqueName = FileUtil.findFreeFileName(
                getComponentsLocalFolder(), srcName, "settings" // NOI18N
            );

            if (!srcName.equals(uniqueName) || globalIDSet.contains(uniqueName.toUpperCase(Locale.ENGLISH))) {
                isUsed = true;
                // #44293 - proper escaping to keep name synced with InstanceDataObject naming
                srcName = escape(origName + "_" + i);
                i++;
            }
            
        }

        topComponent2IDMap.put(tc, srcName);
        id2TopComponentMap.put(srcName, new PersistenceManager.TopComponentReference(tc,srcName));
        globalIDSet.add(srcName.toUpperCase(Locale.ENGLISH));
        if (persistenceType(tc) == TopComponent.PERSISTENCE_ONLY_OPENED) {
            topComponentPersistentOnlyOpenedID.add(srcName);
        }
    }
    
    return srcName;
}
 
Example 7
Source File: TimedTakeSnapshotProfilingPoint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getCurrentHeapDumpFilename() {
    try {
        String fileName = TAKEN_HEAPDUMP_PREFIX + System.currentTimeMillis();
        FileObject folder = getSnapshotDirectory();

        //      FileObject folder = targetFolder == null ? IDEUtils.getProjectSettingsFolder(NetBeansProfiler.getDefaultNB().getProfiledProject()) : FileUtil.toFileObject(new File(targetFolder));            
        return FileUtil.toFile(folder).getAbsolutePath() + File.separator
               + FileUtil.findFreeFileName(folder, fileName, ResultsManager.HEAPDUMP_EXTENSION) + "."  // NOI18N
               + ResultsManager.HEAPDUMP_EXTENSION; // NOI18N
    } catch (IOException e) {
        return null;
    }
}
 
Example 8
Source File: TriggeredTakeSnapshotProfilingPoint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getCurrentHeapDumpFilename() {
    try {
        String fileName = TAKEN_HEAPDUMP_PREFIX + System.currentTimeMillis();
        FileObject folder = getSnapshotDirectory();

        //      FileObject folder = targetFolder == null ? IDEUtils.getProjectSettingsFolder(NetBeansProfiler.getDefaultNB().getProfiledProject()) : FileUtil.toFileObject(new File(targetFolder));                          
        return FileUtil.toFile(folder).getAbsolutePath() + File.separator
               + FileUtil.findFreeFileName(folder, fileName, ResultsManager.HEAPDUMP_EXTENSION) + "." // NOI18N
               + ResultsManager.HEAPDUMP_EXTENSION; // NOI18N
    } catch (IOException e) {
        return null;
    }
}
 
Example 9
Source File: HeapDumpAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getCurrentHeapDumpFilename(String targetFolder) {
    try {
        String fileName = ResultsManager.getDefault().getDefaultHeapDumpFileName(System.currentTimeMillis());
        FileObject folder = (targetFolder == null)
                            ? ProfilerStorage.getProjectFolder(NetBeansProfiler.getDefaultNB().getProfiledProject(), true)
                            : FileUtil.toFileObject(FileUtil.normalizeFile(new File(targetFolder)));

        return FileUtil.toFile(folder).getAbsolutePath() + File.separator
               + FileUtil.findFreeFileName(folder, fileName, ResultsManager.HEAPDUMP_EXTENSION) + "."
               + ResultsManager.HEAPDUMP_EXTENSION; // NOI18N
    } catch (IOException e) {
        return null;
    }
}
 
Example 10
Source File: HeapDumpAction.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private String getCurrentHeapDumpFilename(String targetFolder) {
    try {
        String fileName = ResultsManager.getDefault().getDefaultHeapDumpFileName(System.currentTimeMillis());
        FileObject folder = (targetFolder == null)
                            ? ProfilerStorage.getProjectFolder(NetBeansProfiler.getDefaultNB().getProfiledProject(), true)
                            : FileUtil.toFileObject(FileUtil.normalizeFile(new File(targetFolder)));

        return FileUtil.toFile(folder).getAbsolutePath() + File.separator
               + FileUtil.findFreeFileName(folder, fileName, ResultsManager.HEAPDUMP_EXTENSION) + "."
               + ResultsManager.HEAPDUMP_EXTENSION; // NOI18N
    } catch (IOException e) {
        return null;
    }
}
 
Example 11
Source File: ContainerItemSetupPanelVisual.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String findFreeClassName(String uri) {
    try {
        FileObject folder = SourceGroupSupport.getFolderForPackage(getLocationValue(), getPackage());
        if (folder != null) {
            return FileUtil.findFreeFileName(folder, Util.deriveResourceClassName(uri), Constants.JAVA_EXT);
        }
    } catch (IOException ex) {
        //OK just return null
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example 12
Source File: SingletonSetupPanelVisual.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String findFreeClassName(String uri) {
    try {
        FileObject folder = SourceGroupSupport.getFolderForPackage(getLocationValue(), getPackage());
        if (folder != null) {
            return FileUtil.findFreeFileName(folder, Util.deriveResourceClassName(uri), Constants.JAVA_EXT);
        }
    } catch (IOException ex) {
        //OK just return null
        Exceptions.printStackTrace(ex);
    }
    return null;
}
 
Example 13
Source File: AutomaticRegistration.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the server instance file object and set the default properties.
 *
 * @param serverInstanceDir /J2EE/InstalledServers folder
 * @param url server instance url/ID
 * @param displayName display name
 */
private static boolean registerServerInstanceFO(FileObject serverInstanceDir, String url, String displayName, File payaraRoot, File java7orLaterExecutable) {
    String name = FileUtil.findFreeFileName(serverInstanceDir, 
            PayaraInstanceProvider.PAYARA_AUTOREGISTERED_INSTANCE, null);
    FileObject instanceFO;
    try {
        instanceFO = serverInstanceDir.createData(name);
        instanceFO.setAttribute(PayaraModule.URL_ATTR, url);
        instanceFO.setAttribute(PayaraModule.USERNAME_ATTR, "admin"); // NOI18N
        //String password = Utils.generatePassword(8);
        instanceFO.setAttribute(PayaraModule.PASSWORD_ATTR, "");
        instanceFO.setAttribute(PayaraModule.DISPLAY_NAME_ATTR, displayName);
        instanceFO.setAttribute(PayaraModule.ADMINPORT_ATTR, "4848"); // NOI18N
        instanceFO.setAttribute(PayaraModule.INSTALL_FOLDER_ATTR, payaraRoot.getParent());
        instanceFO.setAttribute(PayaraModule.DEBUG_PORT, ""); // NOI18N
        instanceFO.setAttribute(PayaraModule.DOMAIN_NAME_ATTR, "domain1"); // NOI18N
        instanceFO.setAttribute(PayaraModule.DOMAINS_FOLDER_ATTR, (new File(payaraRoot, "domains")).getAbsolutePath());
        instanceFO.setAttribute(PayaraModule.DRIVER_DEPLOY_FLAG, "true");
        instanceFO.setAttribute(PayaraModule.INSTALL_FOLDER_ATTR, payaraRoot.getParent());
        instanceFO.setAttribute(PayaraModule.HOSTNAME_ATTR, "localhost"); // NOI18N
        instanceFO.setAttribute(PayaraModule.PAYARA_FOLDER_ATTR, payaraRoot.getAbsolutePath());
        instanceFO.setAttribute(PayaraModule.JAVA_PLATFORM_ATTR, java7orLaterExecutable == null ? "" : java7orLaterExecutable.getAbsolutePath()); // NOI18N
        instanceFO.setAttribute(PayaraModule.HTTPPORT_ATTR, "8080"); // NOI18N
        instanceFO.setAttribute(PayaraModule.HTTPHOST_ATTR, "localhost"); // NOI18N
        instanceFO.setAttribute(PayaraModule.JVM_MODE, PayaraModule.NORMAL_MODE);
        instanceFO.setAttribute(PayaraModule.HOT_DEPLOY, false);
        instanceFO.setAttribute(PayaraModule.SESSION_PRESERVATION_FLAG, true);
        instanceFO.setAttribute(PayaraModule.START_DERBY_FLAG, false);
        instanceFO.setAttribute(PayaraModule.USE_IDE_PROXY_FLAG, true);
        instanceFO.setAttribute(PayaraModule.USE_SHARED_MEM_ATTR, false);
        
        return true;
    } catch (IOException e) {
        LOGGER.log(Level.INFO, "Cannot register the default Payara server."); // NOI18N
        LOGGER.log(Level.INFO, null, e);
    }
    return false;
}
 
Example 14
Source File: WLJpa2SwitchSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void replaceManifest(File jarFile, Manifest manifest) throws IOException {
    FileObject fo = FileUtil.toFileObject(jarFile);
    String tmpName = FileUtil.findFreeFileName(fo.getParent(),
            jarFile.getName(), "tmp"); // NOI18N
    File tmpJar = new File(jarFile.getParentFile(), tmpName + ".tmp"); // NOI18N
    try {
        InputStream is = new BufferedInputStream(
                new FileInputStream(jarFile));
        try {
            OutputStream os = new BufferedOutputStream(
                    new FileOutputStream(tmpJar));
            try {
                replaceManifest(is, os, manifest);
            } finally {
                os.close();
            }
        } finally {
            is.close();
        }

        if (tmpJar.renameTo(jarFile)) {
            LOGGER.log(Level.FINE, "Successfully moved {0}", tmpJar);
            return;
        }
        LOGGER.log(Level.FINE, "Byte to byte copy {0}", tmpJar);
        copy(tmpJar, jarFile);
    } finally {
        tmpJar.delete();
    }
}
 
Example 15
Source File: AutomaticRegistration.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the server instance file object and set the default properties.
 *
 * @param serverInstanceDir /J2EE/InstalledServers folder
 * @param url server instance url/ID
 * @param displayName display name
 */
private static boolean registerServerInstanceFO(FileObject serverInstanceDir, String url, String displayName, File glassfishRoot, File java7orLaterExecutable) {
    String name = FileUtil.findFreeFileName(serverInstanceDir,
            GlassfishInstanceProvider.GLASSFISH_AUTOREGISTERED_INSTANCE, null);
    FileObject instanceFO;
    try {
        instanceFO = serverInstanceDir.createData(name);
        instanceFO.setAttribute(GlassfishModule.URL_ATTR, url);
        instanceFO.setAttribute(GlassfishModule.USERNAME_ATTR, "admin"); // NOI18N
        //String password = Utils.generatePassword(8);
        instanceFO.setAttribute(GlassfishModule.PASSWORD_ATTR, "");
        instanceFO.setAttribute(GlassfishModule.DISPLAY_NAME_ATTR, displayName);
        instanceFO.setAttribute(GlassfishModule.ADMINPORT_ATTR, "4848"); // NOI18N
        instanceFO.setAttribute(GlassfishModule.INSTALL_FOLDER_ATTR, glassfishRoot.getParent());
        instanceFO.setAttribute(GlassfishModule.DEBUG_PORT, ""); // NOI18N
        instanceFO.setAttribute(GlassfishModule.DOMAIN_NAME_ATTR, "domain1"); // NOI18N
        instanceFO.setAttribute(GlassfishModule.DOMAINS_FOLDER_ATTR, (new File(glassfishRoot, "domains")).getAbsolutePath());
        instanceFO.setAttribute(GlassfishModule.DRIVER_DEPLOY_FLAG, "true");
        instanceFO.setAttribute(GlassfishModule.INSTALL_FOLDER_ATTR, glassfishRoot.getParent());
        instanceFO.setAttribute(GlassfishModule.HOSTNAME_ATTR, "localhost"); // NOI18N
        instanceFO.setAttribute(GlassfishModule.GLASSFISH_FOLDER_ATTR, glassfishRoot.getAbsolutePath());
        instanceFO.setAttribute(GlassfishModule.JAVA_PLATFORM_ATTR, java7orLaterExecutable == null ? "" : java7orLaterExecutable.getAbsolutePath()); // NOI18N
        instanceFO.setAttribute(GlassfishModule.HTTPPORT_ATTR, "8080"); // NOI18N
        instanceFO.setAttribute(GlassfishModule.HTTPHOST_ATTR, "localhost"); // NOI18N
        instanceFO.setAttribute(GlassfishModule.JVM_MODE, GlassfishModule.NORMAL_MODE);
        instanceFO.setAttribute(GlassfishModule.SESSION_PRESERVATION_FLAG, true);
        instanceFO.setAttribute(GlassfishModule.START_DERBY_FLAG, true);
        instanceFO.setAttribute(GlassfishModule.USE_IDE_PROXY_FLAG, true);
        instanceFO.setAttribute(GlassfishModule.USE_SHARED_MEM_ATTR, false);

        return true;
    } catch (IOException e) {
        LOGGER.log(Level.INFO, "Cannot register the default GlassFish server."); // NOI18N
        LOGGER.log(Level.INFO, null, e);
    }
    return false;
}
 
Example 16
Source File: AutomaticRegistration.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the server instance file object and set the default properties.
 *
 * @param serverInstanceDir /J2EE/InstalledServers folder
 * @param url server instance url/ID
 * @param displayName display name
 */
private static boolean registerServerInstanceFO(FileObject serverInstanceDir, String url,
        String displayName, String serverRoot, String domainRoot, String domainName,
        String port, String username, String password, String javaOpts, Version version) {

    String name = FileUtil.findFreeFileName(serverInstanceDir, "weblogic_autoregistered_instance", null); // NOI18N
    FileObject instanceFO;
    try {
        instanceFO = serverInstanceDir.createData(name);
        instanceFO.setAttribute(InstanceProperties.URL_ATTR, url);
        instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, username);
        instanceFO.setAttribute(InstanceProperties.PASSWORD_ATTR, password);
        instanceFO.setAttribute(InstanceProperties.DISPLAY_NAME_ATTR, displayName);
        instanceFO.setAttribute(InstanceProperties.HTTP_PORT_NUMBER, port);
        instanceFO.setAttribute(WLPluginProperties.SERVER_ROOT_ATTR, serverRoot);
        instanceFO.setAttribute(WLPluginProperties.DOMAIN_ROOT_ATTR, domainRoot);
        instanceFO.setAttribute(WLPluginProperties.DEBUGGER_PORT_ATTR,
                WLInstantiatingIterator.DEFAULT_DEBUGGER_PORT);
        instanceFO.setAttribute(WLPluginProperties.PROXY_ENABLED,
                WLInstantiatingIterator.DEFAULT_PROXY_ENABLED);
        instanceFO.setAttribute(WLPluginProperties.DOMAIN_NAME, domainName);
        instanceFO.setAttribute(WLPluginProperties.PORT_ATTR, port);
        if (javaOpts != null) {
            instanceFO.setAttribute(WLPluginProperties.JAVA_OPTS, javaOpts);
        }
        if (Utilities.isMac()) {
            StringBuilder memOpts = new StringBuilder(WLInstantiatingIterator.DEFAULT_MAC_MEM_OPTS_HEAP);
            if (version != null && !JDK8_ONLY_SERVER_VERSION.isBelowOrEqual(version)) {
                memOpts.append(' '); // NOI18N
                memOpts.append(WLInstantiatingIterator.DEFAULT_MAC_MEM_OPTS_PERM);
            }
            instanceFO.setAttribute(WLPluginProperties.MEM_OPTS, memOpts.toString());
        }
        return true;
    } catch (IOException e) {
        LOGGER.log(Level.INFO, "Cannot register the default WebLogic server."); // NOI18N
        LOGGER.log(Level.INFO, null, e);
    }
    return false;
}
 
Example 17
Source File: ScriptingCreateFromTemplateHandler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<FileObject> createFromTemplate(CreateDescriptor desc) throws IOException {
    FileObject template = desc.getTemplate();
    String name = desc.getProposedName();
    Map<String, ?> values = desc.getParameters();
    FileObject f = desc.getTarget();
    
    boolean noExt = desc.hasFreeExtension() && name.indexOf('.') != -1;
    
    String extWithDot;
    if (noExt) {
        extWithDot = null;
    } else {
        extWithDot = '.' + template.getExt();
        if (name.endsWith(extWithDot)) { // Test whether the extension happens to be there already
            // And remove it if yes, it will be appended to the unique name.
            name = name.substring(0, name.length() - extWithDot.length());
        }
    }
    
    String nameUniq = FileUtil.findFreeFileName(f, name, noExt ? null : template.getExt());
    FileObject output = FileUtil.createData(f, noExt ? nameUniq : nameUniq + extWithDot);
    Charset targetEnc = FileEncodingQuery.getEncoding(output);
    Charset sourceEnc = FileEncodingQuery.getEncoding(template);
    
    ScriptEngine eng = engine(template);
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);
    
    if(!values.containsKey(ENCODING_PROPERTY_NAME)) {
        bind.put(ENCODING_PROPERTY_NAME, targetEnc.name());
    }
    
    //Document doc = createDocument(template.getMIMEType());
    FileLock lock = output.lock();
    try (Writer w = new OutputStreamWriter(output.getOutputStream(lock), targetEnc);
         Reader is = new InputStreamReader(template.getInputStream(), sourceEnc);
        /*IndentWriter w2 = new IndentWriter(doc, 0, w, false) */) {
        StringWriter sw = new StringWriter();
        ScriptEngine eng2 = desc.isPreformatted() ? null : indentEngine();
        
        eng.getContext().setWriter(new PrintWriter(eng2 != null ? sw : w));
        //eng.getContext().setBindings(bind, ScriptContext.ENGINE_SCOPE);
        eng.getContext().setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
        eng.getContext().setAttribute(ScriptEngine.FILENAME, template.getNameExt(), ScriptContext.ENGINE_SCOPE);
        eng.eval(is);
        
        if (eng2 != null) {
            eng2.getContext().setAttribute("mimeType", template.getMIMEType(), ScriptContext.ENGINE_SCOPE);
            eng2.getContext().setWriter(w);
            eng2.eval(new StringReader(sw.toString()));
        }
    }catch (ScriptException ex) {
        IOException io = new IOException(ex.getMessage(), ex);
        throw io;
    } finally {
        lock.releaseLock();
    }
    return Collections.singletonList(output);
}
 
Example 18
Source File: EjbFacadeWizardIterator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
String getUniqueClassName(String candidateName, FileObject targetFolder){
    return FileUtil.findFreeFileName(targetFolder, candidateName, "java"); //NOI18N
}
 
Example 19
Source File: EjbFacadeGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String getUniqueClassName(String candidateName, FileObject targetFolder){
    return FileUtil.findFreeFileName(targetFolder, candidateName, "java"); //NOI18N
}
 
Example 20
Source File: IndentFileEntry.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Creates a new Java source from the template. Unlike the standard FileEntry.Format,
       this indents the resulting text using an indentation engine.
   */
   @Override
   public FileObject createFromTemplate (FileObject f, String name) throws IOException {
       String ext = getFile ().getExt ();

       if (name == null) {
           name = FileUtil.findFreeFileName(f, getFile ().getName (), ext);
       }
       FileObject fo = f.createData (name, ext);
       java.text.Format frm = createFormat (f, name, ext);
       InputStream is=getFile ().getInputStream ();
       Charset encoding = FileEncodingQuery.getEncoding(getFile());
       Reader reader = new InputStreamReader(is,encoding);
       BufferedReader r = new BufferedReader (reader);
       StyledDocument doc = createDocument(createEditorKit(fo.getMIMEType()));
       IndentEngine eng = (IndentEngine)indentEngine.get();
       if (eng == null) eng = IndentEngine.find(doc);
       Object attr = getFile().getAttribute(EA_PREFORMATTED);
       boolean preformatted = false;
       
       if (attr != null && attr instanceof Boolean) {
           preformatted = ((Boolean)attr).booleanValue();
       }

       try {
           FileLock lock = fo.lock ();
           try {
               encoding = FileEncodingQuery.getEncoding(fo);
               OutputStream os=fo.getOutputStream(lock);
               OutputStreamWriter w = new OutputStreamWriter(os, encoding);
               try {
                   String line = null;
                   String current;
                   int offset = 0;

                   while ((current = r.readLine ()) != null) {
                       if (line != null) {
                           // newline between lines
                           doc.insertString(offset, NEWLINE, null);
                           offset++;
                       }
                       line = frm.format (current);

                       // partial indentation used only for pre-formatted sources
                       // see #19178 etc.
                       if (!preformatted || !line.equals(current)) {
                           line = fixupGuardedBlocks(safeIndent(eng, line, doc, offset));
                       }
                       doc.insertString(offset, line, null);
                           offset += line.length();
                   }
                   doc.insertString(doc.getLength(), NEWLINE, null);
                   w.write(doc.getText(0, doc.getLength()));
               } catch (javax.swing.text.BadLocationException e) {
               } finally {
                   w.close ();
               }
           } finally {
               lock.releaseLock ();
           }
       } finally {
           r.close ();
       }
       // copy attributes
       FileUtil.copyAttributes (getFile (), fo);
// hack to overcome package-private modifier in setTemplate(fo, boolean)
       fo.setAttribute(DataObject.PROP_TEMPLATE, null);
       return fo;
   }