Java Code Examples for org.netbeans.api.progress.ProgressHandle#start()

The following examples show how to use org.netbeans.api.progress.ProgressHandle#start() . 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: WebSocketEndpointIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Set<?> instantiate( ProgressHandle handle ) throws IOException {
    handle.start();
    
    handle.progress(NbBundle.getMessage(WebSocketEndpointIterator.class, 
            "TXT_GenerateEndpoint"));                       // NOI18N
    
    FileObject targetFolder = Templates.getTargetFolder(getWizard());
    String name = Templates.getTargetName(getWizard());
    FileObject endpoint = GenerationUtils.createClass(targetFolder,
            name, null );
    
    generateEndpoint(endpoint);
    
    handle.finish();
    return Collections.singleton(endpoint);
}
 
Example 2
Source File: InstanceNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected List getReferences() {
    if (hasInstance()) {
        ProgressHandle pHandle = null;
        ChangeListener cl = null;
        
        try {
            pHandle = ProgressHandle.createHandle(Bundle.InstanceNode_References());
            pHandle.setInitialDelay(200);
            pHandle.start(HeapProgress.PROGRESS_MAX);

            cl = setProgress(pHandle);
            return getInstance().getReferences();
        } finally {
            if (pHandle != null) {
                pHandle.finish();
            }
            if (cl != null) {
                HeapProgress.getProgress().removeChangeListener(cl);
            }
        }
    }
    return Collections.EMPTY_LIST;
}
 
Example 3
Source File: AbstractContainerAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected final void performAction(Node[] activatedNodes) {
    for (final Node node : activatedNodes) {
        final StatefulDockerContainer container = node.getLookup().lookup(StatefulDockerContainer.class);
        if (container != null) {
            final ProgressHandle handle = ProgressHandle.createHandle(getProgressMessage(container.getContainer()));
            handle.start();
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    try {
                        performAction(container.getContainer());
                    } catch (Exception ex) {
                        handleException(ex);
                    } finally {
                        handle.finish();
                    }
                }
            };
            requestProcessor.post(task);
        }
    }
}
 
Example 4
Source File: ImportBlueprintEarWizardIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Set<FileObject> instantiate(ProgressHandle handle) throws IOException {
    handle.start(3);
    handle.progress(NbBundle.getMessage(ImportBlueprintEarWizardIterator.class, "LBL_NewEarProjectWizardIterator_WizardProgress_CreatingProject"), 1);
    
    File dirF = (File) wiz.getProperty(ProjectLocationWizardPanel.PROJECT_DIR);
    if (dirF != null) {
        dirF = FileUtil.normalizeFile(dirF);
    }
    File srcF = (File) wiz.getProperty(WizardProperties.SOURCE_ROOT);
    if (srcF != null) {
        srcF = FileUtil.normalizeFile(srcF);
    }
    String name = (String) wiz.getProperty(ProjectLocationWizardPanel.NAME);
    Profile j2eeProfile = (Profile) wiz.getProperty(ProjectServerWizardPanel.J2EE_LEVEL);
    //        String contextPath = (String) wiz.getProperty(WizardProperties.CONTEXT_PATH);
    String serverInstanceID = (String) wiz.getProperty(ProjectServerWizardPanel.SERVER_INSTANCE_ID);
    String platformName = (String)wiz.getProperty(ProjectServerWizardPanel.JAVA_PLATFORM);
    String sourceLevel = (String)wiz.getProperty(ProjectServerWizardPanel.SOURCE_LEVEL);
    @SuppressWarnings("unchecked")
    Map<FileObject, ModuleType> userModules = (Map<FileObject, ModuleType>)
            wiz.getProperty(WizardProperties.USER_MODULES);
    String librariesDefinition =
            SharabilityUtility.getLibraryLocation((String) wiz.getProperty(ProjectServerWizardPanel.WIZARD_SHARED_LIBRARIES));
    return testableInstantiate(platformName, sourceLevel, j2eeProfile, dirF,
            srcF, serverInstanceID, name, userModules, handle, librariesDefinition);
}
 
Example 5
Source File: JaxRsFilterIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Set<?> instantiate( ProgressHandle handle ) throws IOException {
    handle.start();
    
    handle.progress(NbBundle.getMessage(JaxRsFilterIterator.class, 
            "TXT_GenerateFilterFile"));
    
    FileObject targetFolder = Templates.getTargetFolder(getWizard());
    String name = Templates.getTargetName(getWizard());
    FileObject filterClass = GenerationUtils.createClass(targetFolder,name, null );
    
    implementFilters(filterClass);
    
    handle.finish();
    return Collections.singleton(filterClass);
}
 
Example 6
Source File: DiffPresenter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates <i>just computing diff</i> presenter. The mode
 * is left on {@link #initWithDiffInfo} call.
 */
public DiffPresenter() {
    String label = NbBundle.getMessage(DiffPresenter.class, "diff.prog");
    ProgressHandle progress = ProgressHandle.createHandle(label);
    progressPanel = ProgressHandleFactory.createProgressComponent(progress);
    add(progressPanel);
    progress.start();
}
 
Example 7
Source File: AbstractGroovyWizard.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Set instantiate(ProgressHandle handle) throws IOException {
    handle.start();
    handle.progress(NbBundle.getMessage(AbstractGroovyWizard.class, "LBL_NewGroovyFileWizardIterator_WizardProgress_CreatingFile"));

    FileObject template = findCorrectTemplate();
    FileObject targetFolder = Templates.getTargetFolder(wiz);
    String targetName = Templates.getTargetName(wiz);

    DataFolder dFolder = DataFolder.findFolder(targetFolder);
    DataObject dTemplate = DataObject.find(template);

    String pkgName = getPackageName(targetFolder);
    DataObject dobj;
    if (pkgName == null) {
        dobj = dTemplate.createFromTemplate(dFolder, targetName);
    } else {
        dobj = dTemplate.createFromTemplate(dFolder, targetName, Collections.singletonMap("package", pkgName)); // NOI18N
    }

    FileObject createdFile = dobj.getPrimaryFile();
    
    Project proj = Templates.getProject(wiz);
    if (!GroovyExtender.isActive(proj)) {
        GroovyExtender.activate(proj);
    }

    handle.finish();
    return Collections.singleton(createdFile);
}
 
Example 8
Source File: SampledCPUSnapshot.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private void initSamples() throws IOException {
    SamplesInputStream stream = new SamplesInputStream(npssFile.getInputStream());
    int samplesGuess = (int)(npssFile.getSize()/130);
    ProgressHandle ph = ProgressHandle.createSystemHandle("Computing snapshot samples", null);
    ph.start(samplesGuess);
    
    for(ThreadsSample s = stream.readSample(); s != null; s = stream.readSample()) {
        samples++;
        lastTimestamp = s.getTime();
        if (samples < samplesGuess) {
            ph.progress(samples);
        }
    }
    ph.finish();
}
 
Example 9
Source File: RetrieverEngineImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void run() {
    ProgressHandle ph = ProgressHandleFactory.createHandle(
            NbBundle.getMessage(RetrieverEngineImpl.class,"LBL_PROGRESSBAR_Retrieve_XML"),
            new Cancellable(){
        public boolean cancel() {
            synchronized(RetrieverEngineImpl.this){
                if(!RetrieverEngineImpl.this.STOP_PULL){
                    RetrieverEngineImpl.this.STOP_PULL = true;
                    //taskThread.interrupt();
                }
            }
            return true;
        }
    }, new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
            getOPWindow().setOutputVisible(true);
            getOPWindow().select();
        }
    });
    ph.start();
    ph.switchToIndeterminate();
    try{
        pullRecursively();
    }finally{
        ph.finish();
    }
}
 
Example 10
Source File: ConvertOgreBinaryMeshesAction.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void scanDir(String dir2scan, boolean delete) {
    ProgressHandle handle = ProgressHandleFactory.createHandle("Convert Ogre Binary Files");
    handle.start();
    try {
        File zipDir = new File(dir2scan);
        String[] dirList = zipDir.list();
        for (int i = 0; i < dirList.length; i++) {
            File f = new File(zipDir, dirList[i]);
            if (f.isDirectory()) {
                String filePath = f.getPath();
                scanDir(filePath, delete);
                continue;
            }
            FileObject fobj = FileUtil.toFileObject(f);
            if (fobj.getExt().equalsIgnoreCase("mesh")||fobj.getExt().equalsIgnoreCase("skeleton")) {
                OgreXMLConvertOptions options = new OgreXMLConvertOptions(fobj.getPath());
                options.setBinaryFile(true);
                OgreXMLConvert conv = new OgreXMLConvert();
                conv.doConvert(options, handle);
                if (delete) {
                    fobj.delete();
                }
            }
        }
    } catch (Exception e) {
        Logger.getLogger(ConvertOgreBinaryMeshesAction.class.getName()).log(Level.SEVERE, "Error scanning directory", e);
    } finally {
        handle.finish();
    }
}
 
Example 11
Source File: SampledCPUSnapshot.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void initSamples() throws IOException {
    SamplesInputStream stream = new SamplesInputStream(npssFile.getInputStream());
    int samplesGuess = (int)(npssFile.getSize()/130);
    ProgressHandle ph = ProgressHandle.createSystemHandle("Computing snapshot samples", null);
    ph.start(samplesGuess);
    
    for(ThreadsSample s = stream.readSample(); s != null; s = stream.readSample()) {
        samples++;
        lastTimestamp = s.getTime();
        if (samples < samplesGuess) {
            ph.progress(samples);
        }
    }
    ph.finish();
}
 
Example 12
Source File: RecentSearches.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Find action by display name and run it.
 */
@NbBundle.Messages({
    "LBL_SearchingRecentResult=Searching for a Quick Search Item",
    "MSG_RecentResultNotFound=Recent Quick Search Item was not found."})
private void findAndRunAction() {
    final AtomicBoolean cancelled = new AtomicBoolean(false);
    ProgressHandle handle = ProgressHandleFactory.createHandle(
            Bundle.LBL_SearchingRecentResult(), new Cancellable() {
        @Override
        public boolean cancel() {
            cancelled.set(true);
            return true;
        }
    });
    handle.start();
    ResultsModel model = ResultsModel.getInstance();
    Task evaluate = CommandEvaluator.evaluate(
            stripHTMLandPackageNames(name), model);
    RP.post(evaluate);
    int tries = 0;
    boolean found = false;
    while (tries++ < 30 && !cancelled.get()) {
        if (checkActionWasFound(model, true)) {
            found = true;
            break;
        } else if (evaluate.isFinished()) {
            found = checkActionWasFound(model, false);
            break;
        }
    }
    handle.finish();
    if (!found && !cancelled.get()) {
        NotifyDescriptor nd = new NotifyDescriptor.Message(
                Bundle.MSG_RecentResultNotFound(),
                NotifyDescriptor.INFORMATION_MESSAGE);
        DialogDisplayer.getDefault().notifyLater(nd);
    }
}
 
Example 13
Source File: EditTerrainAction.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void actionPerformed(ActionEvent ev) {
    final ProjectAssetManager manager = context.getLookup().lookup(ProjectAssetManager.class);
    if (manager == null) {
        return;
    }
    Runnable call = new Runnable() {

        public void run() {
            ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Opening in Terrain Editor");
            progressHandle.start();

            
            final Spatial asset = context.loadAsset();

            if(asset!=null){
                java.awt.EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        ((DesktopAssetManager)manager.getManager()).clearCache();
                        TerrainEditorTopComponent composer = TerrainEditorTopComponent.findInstance();
                        composer.openScene(asset, context, manager);
                    }
                });
            }else {
                Confirmation msg = new NotifyDescriptor.Confirmation(
                        "Error opening " + context.getPrimaryFile().getNameExt(),
                        NotifyDescriptor.OK_CANCEL_OPTION,
                        NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notify(msg);
            }
            progressHandle.finish();
        }
    };
    new Thread(call).start();
}
 
Example 14
Source File: ContextAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void startProgress() {
    getLogger().logCommandLine("==[IDE]== " + DateFormat.getDateTimeInstance().format(new Date()) + " " + runningName); // NOI18N
    ProgressHandle progress = getProgressHandle();
    progress.setInitialDelay(500);
    progressStamp = System.currentTimeMillis() + 500;
    progress.start();
}
 
Example 15
Source File: Installer.java    From minifierbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Downloads a file from a URL
 *
 * @param fileURL HTTP URL of the file to be downloaded
 * @param saveDir path of the directory to save the file
 * @throws IOException
 */
private void downloadFile(String fileURL, String saveDir)
        throws IOException {
    final ProgressHandle handle = ProgressHandle.createHandle("Downloading minifierbeans archive");
    handle.start(0);

    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "custom-packages.zip";

        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();

        final File theFile = new File(saveDir + "/.netbeans/minifierbeans");
        theFile.mkdirs();

        final String saveFilePath = saveDir + "/.netbeans/minifierbeans/" + fileName;

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();
        handle.finish();

        RP.post(new Runnable() {
            @Override
            public void run() {
                try {
                    extractArchive(saveFilePath, theFile.getAbsolutePath() + "/");
                } catch (IOException ex) {
                    handle.finish();
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    } else {
        handle.finish();
        NotificationDisplayer.getDefault().notify("Error while downloading", NotificationDisplayer.Priority.HIGH.getIcon(), "No file to download. Server replied HTTP code: " + responseCode, null);
    }

    httpConn.disconnect();
}
 
Example 16
Source File: VersioningPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     * Must NOT be run from AWT.
     */
    private void setupModels() {
        if (context == null) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    syncTable.setTableModel(new SyncFileNode[0]);
                    btnCommit.setEnabled(false);
//                    File root = HgUtils.getRootFile(HgUtils.getCurrentContext(null));
                    /* #126311: Optimize UI for Large repos
                     if (root != null) {
                        String[] info = getRepositoryBranchInfo(root);
                        String rev = info != null ? info[1] : null;
                        String changeset = info != null ? info[2] : null;
                        setRepositoryBranchInfo(rev, changeset);
                    }*/
                 }
            });
            return;
        }
        // XXX attach Cancelable hook
        final ProgressHandle ph = ProgressHandleFactory.createHandle(NbBundle.getMessage(VersioningPanel.class, "MSG_Refreshing_Versioning_View")); // NOI18N
        try {
            Thread.interrupted();  // clear interupted status
            ph.start();
            final SyncFileNode [] nodes = getNodes(context, displayStatuses);  // takes long
            
            if (nodes == null) {
                return;
                // finally section
            }
            
            final String [] tableColumns;
            final String branchTitle;
            File [] files = context.getRootFiles().toArray(new File[context.getRootFiles().size()]);
            if (files == null || files.length == 0) return;

            /* #126311: Optimize UI for Large repos
            File root = mercurial.getTopmostManagedParent(files[0]);
            String[] info = getRepositoryBranchInfo(root);
            String branchName = info != null ? info[0] : null;
            String rev = info != null ? info[1] : null;
            String changeset = info != null ? info[2] : null;
            if (branchName != null && !branchName.equals("")) {
                branchTitle = NbBundle.getMessage(VersioningPanel.class, "CTL_VersioningView_BranchTitle", branchName); // NOI18N
            } else {
                branchTitle = NbBundle.getMessage(VersioningPanel.class, "CTL_VersioningView_UnnamedBranchTitle"); // NOI18N
            }*/
            if (nodes.length > 0) {
                boolean stickyCommon = false;
                for (int i = 1; i < nodes.length; i++) {
                    if (Thread.interrupted()) {
                        // TODO set model that displays that fact to user
                        return;
                    }
                }                
                tableColumns = new String [] { SyncFileNode.COLUMN_NAME_NAME, SyncFileNode.COLUMN_NAME_STATUS, SyncFileNode.COLUMN_NAME_PATH };
            } else {
                tableColumns = null;
            }
            /* #126311: Optimize UI for Large repos
            setRepositoryBranchInfo(rev, changeset);                
            */
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    if (nodes.length > 0) {
                        syncTable.setColumns(tableColumns);
                        setVersioningComponent(syncTable.getComponent());
                        if (focused) {
                            syncTable.focus();
                        }
                    } else {
                        /* #126311: Optimize UI for Large repos
                        parentTopComponent.setBranchTitle(branchTitle); */
                        setVersioningComponent(noContentComponent);
                        if (focused) {
                            noContentComponent.requestFocusInWindow();
                        }
                    }
                    syncTable.setTableModel(nodes);
                    btnCommit.setEnabled(nodes.length > 0);
                    // finally section, it's enqueued after this request
                }
            });
        } finally {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    ph.finish();
                }
            });
        }
    }
 
Example 17
Source File: GradleHandlerImpl.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
private void deserializeModels() {
    cancellation.set(false);
    cancellationReference.set(new DefaultBuildCancellationToken());
    GradleHome gradleHome = lookupResult.allInstances().iterator().next();
    if (gradleHome.getStatus() == GradleDownloader.Status.OK) {
        synchronized (gradleLocations) {
            gradleLocations.put(project, gradleHome);
        }
        //      modelContent.set(Collections.emptyList(), null);
        GradleConnector connector = GradleConnector.newConnector();
        connector.useInstallation(gradleHome.getGradleHome());
        connector.forProjectDirectory(FileUtil.toFile(project.getProjectDirectory()));
        try (ProjectConnection connection = connector.connect()) {
            List<Object> modelList = new ArrayList<>();
            for (Class model : models) {
                ModelBuilder modelBuilder = connection.model(model);
                modelBuilder.withCancellationToken(this);
                //Emulate Android studio
                modelBuilder.addArguments("-Pandroid.injected.build.model.only.versioned=3");
                //Prepare load of plugin to retreive tasks from Gradle
                modelBuilder.addJvmArguments("-DANDROID_TOOLING_JAR=" + TOOLING_JAR);
                modelBuilder.addArguments("-I");
                modelBuilder.addArguments(INIT_SCRIPT);
                if (argsConfiguration != null) {
                    modelBuilder.addArguments(argsConfiguration.getJvmArguments());
                }
                if (jvmConfiguration == null) {
                    modelBuilder.addJvmArguments("-Xms800m", "-Xmx2000m");
                } else {
                    modelBuilder.addJvmArguments(jvmConfiguration.getJvmArguments());
                }
                InputOutput io = project.getLookup().lookup(InputOutput.class);
                if (io != null) {
                    io.show(ImmutableSet.of(ShowOperation.OPEN, ShowOperation.MAKE_VISIBLE));
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    io.getOut().println(BLUE + "Deserializing model: " + model.getSimpleName() + BLACK);
                    io.getOut().print("\n\r");
                    io.getOut().print("\n\r");
                    CustomWriterOutputStream cwos = new CustomWriterOutputStream(io.getOut(), "UTF-8");
                    modelBuilder.setStandardOutput(cwos);
                    modelBuilder.setStandardError(cwos);
                    modelBuilder.setColorOutput(true);
                }
                final ProgressHandle progressHandle = ProgressHandleFactory.createSystemHandle(project.getProjectDirectory().getName() + ": Loading Gradle model..", this);
                progressHandle.start();
                modelBuilder.addProgressListener(new ProgressListener() {
                    @Override
                    public void statusChanged(ProgressEvent event) {
                        progressHandle.progress(event.getDisplayName());
                    }
                });
                try {
                    modelList.add(modelBuilder.get());
                } catch (GradleConnectionException | IllegalStateException gradleConnectionException) {
                    if (!(gradleConnectionException instanceof BuildCancelledException)) {
                        Exceptions.printStackTrace(gradleConnectionException);
                    }
                }
                progressHandle.finish();
            }
            modelContent.set(modelList, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 18
Source File: TestMethodDebuggerProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
    * Handle/Debug the selected test method
    * @param activatedNode the selected node
    */
   public final void debugTestMethod(Node activatedNode) {
       final Node activeNode = activatedNode;
       final Document doc;
       final int caret;

       final EditorCookie ec = activeNode.getLookup().lookup(EditorCookie.class);
       if (ec != null) {
           JEditorPane pane = Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane>() {
	@Override
	public JEditorPane run() {
	    return NbDocument.findRecentEditorPane(ec);
	}
    });
           if (pane != null) {
               doc = pane.getDocument();
               caret = pane.getCaret().getDot();
           } else {
               doc = null;
               caret = -1;
           }
       } else {
           doc = null;
           caret = -1;
       }

       singleMethod = activeNode.getLookup().lookup(SingleMethod.class);
if (singleMethod == null) {
    RequestProcessor RP = new RequestProcessor("TestMethodDebuggerProvider", 1, true);   // NOI18N
    singleMethodTask = RP.create(new Runnable() {
	@Override
	public void run() {
	    singleMethod = getTestMethod(doc, caret);
	}
    });
    final ProgressHandle ph = ProgressHandleFactory.createHandle(Bundle.Search_For_Test_Method(), singleMethodTask);
    singleMethodTask.addTaskListener(new TaskListener() {
	@Override
	public void taskFinished(org.openide.util.Task task) {
	    ph.finish();
	    if (singleMethod == null) {
		StatusDisplayer.getDefault().setStatusText(Bundle.No_Test_Method_Found());
	    } else {
		Mutex.EVENT.readAccess(new Runnable() {
		    @Override
		    public void run() {
			ActionProvider ap = CommonUtils.getInstance().getActionProvider(singleMethod.getFile());
			if (ap != null) {
			    if (Arrays.asList(ap.getSupportedActions()).contains(command) && ap.isActionEnabled(command, Lookups.singleton(singleMethod))) {
				ap.invokeAction(command, Lookups.singleton(singleMethod));
			    }
			}
		    }
		});
	    }
	}
    });
    ph.start();
    singleMethodTask.schedule(0);
}
   }
 
Example 19
Source File: EntityResourcesIterator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Set instantiate(ProgressHandle pHandle) throws IOException {
    pHandle.start(100);
    final Project project = Templates.getProject(wizard);

    String restAppPackage = (String) wizard.getProperty(WizardProperties.APPLICATION_PACKAGE);
    String restAppClass = (String) wizard.getProperty(WizardProperties.APPLICATION_CLASS);
    
    final RestSupport restSupport = project.getLookup().lookup(RestSupport.class);
    boolean useJersey = Boolean.TRUE.equals(wizard.getProperty(WizardProperties.USE_JERSEY));
    if (!useJersey) {
        RestSupport.RestConfig.IDE.setAppClassName(restAppPackage+"."+restAppClass); //NOI18N
    }
    if ( restSupport!= null ){
        restSupport.ensureRestDevelopmentReady(useJersey ?
                RestSupport.RestConfig.DD : RestSupport.RestConfig.IDE);
    }

    FileObject targetFolder = Templates.getTargetFolder(wizard);
    FileObject wizardSrcRoot = (FileObject)wizard.getProperty(
            WizardProperties.TARGET_SRC_ROOT);
    /*
     *  Visual panel is used from several wizards. One of them
     *  has several options for target source roots ( different for 
     *  entities, generation classes ). 
     *  There is special property WizardProperties.TARGET_SRC_ROOT
     *  which is set up by wizard panel. This property should be used
     *  as target source root folder. 
     */
    if ( wizardSrcRoot != null ){
        targetFolder  = wizardSrcRoot;
    }
    
    String targetPackage = SourceGroupSupport.packageForFolder(targetFolder);
    final String resourcePackage = (String) wizard.getProperty(WizardProperties.RESOURCE_PACKAGE);
    String controllerPackage = (String) wizard.getProperty(WizardProperties.CONTROLLER_PACKAGE);
    List<String> entities = (List<String>) wizard.
        getProperty(org.netbeans.modules.j2ee.persistence.wizard.WizardProperties.ENTITY_CLASS);
    final PersistenceUnit pu = (PersistenceUnit) wizard.getProperty(WizardProperties.PERSISTENCE_UNIT);

    /* 
     * There should be ALL found entities but they needed to compute closure. 
     * Persistence wizard already has computed closure. So there is no need 
     * in all other entities.
     * Current CTOR of builder and method <code>build</code> is not changed 
     * for now but should be changed later after  review of its usage.
     */
    EntityResourceModelBuilder builder = new EntityResourceModelBuilder(
            project, entities );
    EntityResourceBeanModel model = builder.build();
    final EntityResourcesGenerator generator = EntityResourcesGeneratorFactory.newInstance(project);
    generator.initialize(model, project, targetFolder, targetPackage, 
            resourcePackage, controllerPackage, pu);
    pHandle.progress(50);
    
    // create application config class if required
    final FileObject restAppPack = restAppPackage == null ? null :  
        FileUtil.createFolder(targetFolder, restAppPackage.replace('.', '/'));
    final String appClassName = restAppClass;
    try {
        if ( restAppPack != null && appClassName!= null && !useJersey) {
            RestUtils.createApplicationConfigClass(restSupport, restAppPack, appClassName);
        }
        RestUtils.disableRestServicesChangeListner(project);
        generator.generate(null);
        pHandle.progress(80);
        restSupport.configure(resourcePackage);
    } catch(Exception iox) {
        Exceptions.printStackTrace(iox);
    } finally {
        RestUtils.enableRestServicesChangeListner(project);
    }

    // logging usage of wizard
    Object[] params = new Object[5];
    params[0] = LogUtils.WS_STACK_JAXRS;
    params[1] = project.getClass().getName();
    J2eeModule j2eeModule = RestUtils.getJ2eeModule(project);
    params[2] = j2eeModule == null ? null : j2eeModule.getModuleVersion()+"(WAR)"; //NOI18N
    params[3] = "REST FROM ENTITY"; //NOI18N
    LogUtils.logWsWizard(params);
    pHandle.finish();
    return Collections.<DataObject>singleton(DataFolder.findFolder(targetFolder));
}
 
Example 20
Source File: OgreXMLDataObject.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void saveAsset() throws IOException {
    ProjectAssetManager mgr = getLookup().lookup(ProjectAssetManager.class);
    if (mgr == null) {
        return;
    }
    String name = getPrimaryFile().getName();
    int idx = name.toLowerCase().indexOf(".mesh");
    if(idx!=-1){
        name = name.substring(0, idx);
    }
    
    ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Saving File..");
    progressHandle.start();
    BinaryExporter exp = BinaryExporter.getInstance();
    FileLock lock = null;
    OutputStream out = null;
    try {
        if (saveExtension == null) {
            out = getPrimaryFile().getOutputStream();
        } else {
            FileObject outFileObject = getPrimaryFile().getParent().getFileObject(name, saveExtension);
            if (outFileObject == null) {
                outFileObject = getPrimaryFile().getParent().createData(name, saveExtension);
            }
            out = outFileObject.getOutputStream();
            outFileObject.getParent().refresh();
        }
        exp.save(savable, out);
    } finally {
        if (lock != null) {
            lock.releaseLock();
        }
        if (out != null) {
            out.close();
        }
    }
    progressHandle.finish();
    StatusDisplayer.getDefault().setStatusText(getPrimaryFile().getNameExt() + " saved.");
    setModified(false);
    
    FileObject outFile = null;
    if (saveExtension == null) {
        outFile = getPrimaryFile();
    } else {
        outFile = getPrimaryFile().getParent().getFileObject(name, saveExtension);
        if (outFile == null) {
            Logger.getLogger(SpatialAssetDataObject.class.getName()).log(Level.SEVERE, "Could not locate saved file.");
            return;
        }
    }
    try {
        DataObject targetModel = DataObject.find(outFile);
        AssetData properties = targetModel.getLookup().lookup(AssetData.class);
        if (properties != null) {
            properties.loadProperties();
            properties.setProperty("ORIGINAL_PATH", mgr.getRelativeAssetPath(outFile.getPath()));
            properties.saveProperties();
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}