Java Code Examples for org.openide.loaders.DataObject#getPrimaryFile()

The following examples show how to use org.openide.loaders.DataObject#getPrimaryFile() . 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: BrowseFolders.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void actionPerformed( ActionEvent e ) {
    String command = e.getActionCommand();

    if ( COMMAND_SELECT.equals( command ) ) {
        Node selection[] = browsePanel.getExplorerManager().getSelectedNodes();
        
        if ( selection != null && selection.length > 0 ) {
            DataObject dobj = (DataObject)selection[0].getLookup().lookup( DataObject.class );
            //if (dobj!=null && dobj.getClass().isAssignableFrom(target)) {
                result = dobj.getPrimaryFile();
            //}
            /*
            if ( dobj != null ) {
                FileObject fo = dobj.getPrimaryFile();
                if ( fo.isFolder() ) {
                    result = fo;
                }
            }
            */
        }
        
        
    }
}
 
Example 2
Source File: BrowseFolders.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed( ActionEvent e ) {
    String command = e.getActionCommand();

    if ( COMMAND_SELECT.equals( command ) ) {
        Node selection[] = browsePanel.getExplorerManager().getSelectedNodes();
        
        if ( selection != null && selection.length > 0 ) {
            DataObject dobj = selection[0].getLookup().lookup(DataObject.class);
            if ( dobj != null ) {
                FileObject fo = dobj.getPrimaryFile();
                if ( fo.isFolder() ) {
                    result = fo;
                }
            }
        }
        
        
    }
}
 
Example 3
Source File: ClientStubsGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected FileObject createDataObjectFromTemplate(final String template, 
         final FileObject dir,final String fileName, final String ext, 
         final boolean overwrite, Map<String,String> parameters ) throws IOException 
{
     FileObject rF0 = dir.getFileObject(fileName, ext);
     if(rF0 != null) {
         if(overwrite) {
             DataObject d = DataObject.find(rF0);
             if(d != null)
                 d.delete();
         } else {
             return rF0;
         }
     }
     DataObject d0 = RestUtils.createDataObjectFromTemplate(template, dir, 
             fileName, parameters);
     return d0.getPrimaryFile();
 }
 
Example 4
Source File: DiffResultsViewForLine.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Document getSourceDocument(StreamSource ss) {
    Document sdoc = null;
    FileObject fo = ss.getLookup().lookup(FileObject.class);
    if (fo != null) {
        try {
            DataObject dao = DataObject.find(fo);
            if (dao.getPrimaryFile() == fo) {
                EditorCookie ec = dao.getCookie(EditorCookie.class);
                if (ec != null) {
                    sdoc = ec.openDocument();
                }
            }
        } catch (Exception e) {
            // fallback to other means of obtaining the source
        }
    } else {
        sdoc = ss.getLookup().lookup(Document.class);
    }
    return sdoc;
}
 
Example 5
Source File: SetKarmaConfAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup context) {
    FileObject file = context.lookup(FileObject.class);
    if (file == null) {
        DataObject dataObject = context.lookup(DataObject.class);
        if (dataObject != null) {
            file = dataObject.getPrimaryFile();
        }
    }
    if (file == null) {
        return this;
    }
    Project owner = FileOwnerQuery.getOwner(file);
    if (owner == null) {
        return this;
    }
    if (!KarmaPreferences.isEnabled(owner)) {
        return this;
    }
    return new SetKarmaConfAction(owner, file);
}
 
Example 6
Source File: BrowseFolders.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    if (COMMAND_SELECT.equals(command)) {
        Node[] selection = browsePanel.getExplorerManager().getSelectedNodes();

        if (selection != null && selection.length > 0) {
            // XXX hack because of GsfDataObject is not API
            DataObject dobj = selection[0].getLookup().lookup(DataObject.class);
            if (dobj != null && target.isInstance(dobj)) {
                result = dobj.getPrimaryFile();
                if (DataObject.class == target && result.isFolder()) {
                    result = null;
                }
            }
            /*if (dobj != null) {
                FileObject fo = dobj.getPrimaryFile();
                if (fo.isFolder()) {
                    result = fo;
                }
            }*/
        }
    }
}
 
Example 7
Source File: WebReplaceTokenProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Just gets the array of FOs from lookup.
 */
protected static FileObject[] extractFileObjectsfromLookup(Lookup lookup) {
    List<FileObject> files = new ArrayList<>();
    Iterator<? extends DataObject> it = lookup.lookupAll(DataObject.class).iterator();
    while (it.hasNext()) {
        DataObject d = it.next();
        FileObject f = d.getPrimaryFile();
        files.add(f);
    }
    return files.toArray(new FileObject[files.size()]);
}
 
Example 8
Source File: RunPhingTargetAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup context) {
    Project contextProject = context.lookup(Project.class);
    if (contextProject != null) {
        // project action
        return createAction(contextProject);
    }
    // file action?
    FileObject file = context.lookup(FileObject.class);
    if (file == null) {
        DataObject dataObject = context.lookup(DataObject.class);
        if (dataObject != null) {
            file = dataObject.getPrimaryFile();
        }
    }
    if (file == null) {
        return this;
    }
    contextProject = ProjectConvertors.getNonConvertorOwner(file);
    if (contextProject == null) {
        return this;
    }
    if (file.getParent().equals(contextProject.getProjectDirectory())) {
        return createAction(contextProject);
    }
    return createAction(contextProject, file);
}
 
Example 9
Source File: MatchingObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Update data object. Can be called when a module is enabled and new data
 * loader produces new data object.
 */
public void updateDataObject(DataObject updatedDataObject) {
    FileObject updatedPF = updatedDataObject.getPrimaryFile();
    if (dataObject == null
            || dataObject.getPrimaryFile().equals(updatedPF)) {
        if (updatedPF.isValid()) {
            this.invalidityStatus = null;
            if (fileListener == null) {
                this.fileListener = new FileListener();
                updatedPF.addFileChangeListener(fileListener);
            } else if (updatedPF != dataObject.getPrimaryFile()) {
                dataObject.getPrimaryFile().removeFileChangeListener(
                        fileListener);
                updatedPF.addFileChangeListener(fileListener);
            }
            this.dataObject = updatedDataObject;
            this.nodeDelegate = updatedDataObject.getNodeDelegate();
            this.valid = true;
            for (TextDetail td : textDetails) {
                td.updateDataObject(updatedDataObject);
            }
        }
    } else {
        throw new IllegalArgumentException(
                "Expected data object for the same file");          //NOI18N
    }
}
 
Example 10
Source File: IsOverriddenAnnotationAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getFile(JTextComponent component) {
    Document doc = component.getDocument();
    DataObject od = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);
    
    if (od == null) {
        return null;
    }
    
    return od.getPrimaryFile();
}
 
Example 11
Source File: EventSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
public DataObjectListener(final DataObject dobj) {            
    this.dobj = dobj;
    this.fobj = dobj.getPrimaryFile();
    wlistener = WeakListeners.propertyChange(this, dobj);
    this.dobj.addPropertyChangeListener(wlistener);
}
 
Example 12
Source File: OpenJAXBCustomizerAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected boolean enable(Node[] activatedNodes) {
    if ( activatedNodes.length != 1 )
        return false;
    
    DataObject dataobj = activatedNodes[0].getCookie(DataObject.class);
    if ( dataobj != null ) {
        FileObject fo = dataobj.getPrimaryFile();
    }
    
    return true;
}
 
Example 13
Source File: RestControllerWizardIterator.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
public Set<?> instantiate() throws IOException {
    // Create file from template
    String targetName = Templates.getTargetName(wizard);
    FileObject foDir = Templates.getTargetFolder(wizard);
    FileObject foTemplate = Templates.getTemplate(wizard);
    DataObject doTemplate = DataObject.find(foTemplate);
    DataFolder df = DataFolder.findFolder(foDir);
    Map<String, Object> props = new HashMap<>();
    props.put(WIZ_CRUD_METHODS, wizard.getProperty(WIZ_CRUD_METHODS));
    props.put(WIZ_ERROR_HANDLING, wizard.getProperty(WIZ_ERROR_HANDLING));
    DataObject doCreated = doTemplate.createFromTemplate(df, targetName, props);
    FileObject foCreated = doCreated.getPrimaryFile();
    return Collections.singleton(foCreated);
}
 
Example 14
Source File: BowerInstallAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup context) {
    Project contextProject = context.lookup(Project.class);
    BowerJson bowerJson = null;
    if (contextProject != null) {
        // project action
        bowerJson = new BowerJson(contextProject.getProjectDirectory());
    } else {
        // package.json directly
        FileObject file = context.lookup(FileObject.class);
        if (file == null) {
            DataObject dataObject = context.lookup(DataObject.class);
            if (dataObject != null) {
                file = dataObject.getPrimaryFile();
            }
        }
        if (file != null) {
            bowerJson = new BowerJson(file.getParent());
        }
    }
    if (bowerJson == null) {
        return this;
    }
    if (!bowerJson.exists()) {
        return this;
    }
    if (bowerJson.getDependencies().isEmpty()) {
        return this;
    }
    return new BowerInstallAction(contextProject != null ? contextProject : FileOwnerQuery.getOwner(Utilities.toURI(bowerJson.getFile())));
}
 
Example 15
Source File: EditorConfigProcessor.java    From editorconfig-netbeans with MIT License 4 votes vote down vote up
/**
 * Applies properties defined in an ".editorconfig" file to a DataObject.
 *
 * If a supported property is found, then changes are made to a StringBuilder
 * instance.
 *
 * The StringBuilder instance is passed as a reference to operations that can
 * then perform their actions on this instance.
 *
 * After all operations were performed, the changes will be flushed.
 *
 * @param dataObject Object that represents the file which was recognized by
 * an EditorConfig rule
 */
public void applyRulesToFile(DataObject dataObject) {
  LOG.log(Level.INFO, "Getting Primary File");
  FileObject primaryFile = dataObject.getPrimaryFile();
  LOG.log(Level.INFO, "Getting Path");
  filePath = primaryFile.getPath();

  LOG.log(Level.INFO, "Apply rules to file: {0} (MIME type: {1})",
          new Object[]{filePath, primaryFile.getMIMEType()});

  // Check if the file's MIME type can be edited
  // Allowed MIME types are: text/html, text/javascript, text/x-java, text/xml, ...
  if (!primaryFile.getMIMEType().startsWith("text/")) {
    LOG.log(Level.INFO, "Skipping file because it has an unsupported MIME type.");
    return;
  }

  // Check if file is stored in a critical path
  for (String directoryName : SmartSkip.IGNORED_FILES) {
    // Note: Always use forward slashes here
    String path = projectPath + "/" + directoryName;
    if (filePath.startsWith(path)) {
      LOG.log(Level.INFO, "Skipping file because it is located in an unsupported directory.", path);
      return;
    }
  }

  MappedEditorConfig config = readRulesForFile(filePath);
  FileInfo info = excuteOperations(dataObject, config);

  // Apply EditorConfig operations
  LOG.log(Level.INFO, "Flush style changes for: {0}", filePath);
  flushStyles(info);

  if (info.isFileChangeNeeded()) {
    LOG.log(Level.INFO, "Flush file changes for: {0}", filePath);
    flushFile(info);
  }
  LOG.log(Level.INFO, "Flush style changes for: {0}", filePath);
  flushStyles(info);
}
 
Example 16
Source File: SaasClientPhpAuthenticationGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static void createSessionKeyAuthorizationClassesForWeb(
            SaasBean bean, Project project,
            String groupName, String saasServicePackageName, 
            FileObject targetFolder, FileObject loginFile, FileObject callbackFile,
            final String[] parameters, final Object[] paramTypes, boolean isUseTemplates,
            DropFileType dropFileType) throws IOException {
        SaasAuthenticationType authType = bean.getAuthenticationType();
        if (authType == SaasAuthenticationType.SESSION_KEY ||
                authType == SaasAuthenticationType.HTTP_BASIC) {
            UseTemplates useTemplates = null;
            if (bean.getAuthentication() instanceof SessionKeyAuthentication) {
                SessionKeyAuthentication sessionKey = (SessionKeyAuthentication) bean.getAuthentication();
                useTemplates = sessionKey.getUseTemplates();
            } else if (bean.getAuthentication() instanceof HttpBasicAuthentication) {
                HttpBasicAuthentication httpBasic = (HttpBasicAuthentication) bean.getAuthentication();
                useTemplates = httpBasic.getUseTemplates();
            }
            if (useTemplates != null) {
                String dropType = dropFileType.prefix();
                for (Template template : useTemplates.getTemplates()) {
                    if (!template.getDropTypeList().contains(dropType)) {
                        continue;
                    }
                    String id = template.getId();
                    String type = template.getType() == null ? "" : template.getType();
                    String templateUrl = template.getUrl();
                    if (templateUrl == null || templateUrl.trim().equals("")) {
                        throw new IOException("Authentication template is empty.");
                    }
                    //FIXME - Hack
                    if (templateUrl.contains("Desktop")) {
                        continue;
                    }
                    String fileName = null;
//                        if (type.equals(Constants.LOGIN)) {
                    if (templateUrl.contains("Login")) {
                        fileName = bean.getSaasName() + Util.upperFirstChar(Constants.LOGIN);
//                        } else if (type.equals(Constants.CALLBACK)) {
                    } else if (templateUrl.contains("Callback")) {
                        fileName = bean.getSaasName() + Util.upperFirstChar(Constants.CALLBACK);
                    } else if (templateUrl.contains("Authenticator")) {
//                        } else if (type.equals(Constants.AUTH)) {
                        continue;
                    }
                    FileObject fObj = null;
                    if (fileName != null) {
                        fObj = targetFolder.getFileObject(fileName);
                        if (fObj == null) {
                            DataObject d = Util.createDataObjectFromTemplate(templateUrl, targetFolder,
                                    fileName);
                            if (d != null) {
                                fObj = d.getPrimaryFile();
                                Map<String, String> tokens = new HashMap<String, String>();
                                tokens.put("__GROUP__", targetFolder.getName());
                                replaceTokens(targetFolder.getFileObject(fileName, Constants.PHP_EXT), tokens);
                            }
                        }
                    }
                    if (fObj != null) {
                        if (type.equals(Constants.LOGIN)) {
                            loginFile = fObj;
                        } else if (type.equals(Constants.CALLBACK)) {
                            callbackFile = fObj;
                        }
                    }
                }
            }
        }
    }
 
Example 17
Source File: MovePanel.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
private void initValues() {
  final String text;
  if (this.files.length > 1) {
    text = String.format(BUNDLE.getString("MovePanel.multiFileText"), Integer.toString(this.files.length));
  }
  else {
    text = String.format(BUNDLE.getString("MovePanel.singleFileText"), this.files[0].getName());
  }
  this.labelMessage.setText(text);

  final List<Project> projects = new ArrayList<Project>();
  for (final Project p : OpenProjects.getDefault().getOpenProjects()) {
    projects.add(p);
  }
  final ComboBoxModel<Project> projectModel = new DefaultComboBoxModel<Project>(projects.toArray(new Project[projects.size()]));

  final ItemListener listener = new ItemListener() {
    @Override
    public void itemStateChanged(final ItemEvent e) {
      if (comboProjects.equals(e.getSource())) {
        updateFolders();
        parent.stateChanged(null);
      }
      else if (comboFolders.equals(e.getSource())) {
        parent.stateChanged(null);
      }
    }
  };

  this.comboProjects.addItemListener(listener);
  this.comboFolders.addItemListener(listener);

  this.comboProjects.setModel(projectModel);
  this.comboProjects.setSelectedItem(FileOwnerQuery.getOwner(this.files[0]));
  updateFolders();

  final ExplorerContext explorerContext = this.lookup.lookup(ExplorerContext.class);
  if (explorerContext != null) {
    final Node targetNode = explorerContext.getTargetNode();
    if (targetNode != null) {
      final DataObject dobj = targetNode.getLookup().lookup(DataObject.class);
      if (dobj != null) {
        final FileObject fo = dobj.getPrimaryFile();
        if (fo != null && fo.isValid() && fo.isFolder()) {
          final Project proj = FileOwnerQuery.getOwner(fo);
          if (proj != null) {
            this.comboProjects.setSelectedItem(proj);
            this.comboFolders.setSelectedItem(FileUtil.getRelativePath(proj.getProjectDirectory(), fo));
          }
        }
      }
    }
  }
}
 
Example 18
Source File: JaxWsServiceCreator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void generateWebServiceFromEJB(String wsName, FileObject pkg, Node[] nodes) throws IOException {

        if (nodes != null && nodes.length == 1) {

            EjbReference ejbRef = nodes[0].getLookup().lookup(EjbReference.class);
            if (ejbRef != null) {

                DataFolder df = DataFolder.findFolder(pkg);
                FileObject template = Templates.getTemplate(wiz);
                FileObject templateParent = template.getParent();
                if ((Boolean)wiz.getProperty(WizardProperties.IS_STATELESS_BEAN)) {
                    template = templateParent.getFileObject("EjbWebServiceNoOp", "java"); //NOI18N
                } else {
                    template = templateParent.getFileObject("WebServiceNoOp", "java"); //NOI18N
                }
                DataObject dTemplate = DataObject.find(template);
                DataObject dobj = dTemplate.createFromTemplate(df, wsName);
                FileObject createdFile = dobj.getPrimaryFile();
                /*createdFile.setAttribute("jax-ws-service", java.lang.Boolean.TRUE); // NOI18N
                try {
                    dobj.setValid(false);
                }
                catch( PropertyVetoException e ){
                    LOG.log(Level.WARNING, null , e);
                }*/
                dobj = DataObject.find(createdFile);
                

                ClassPath classPath = getClassPathForFile(project, createdFile);
                if (classPath != null) {
                    if (classPath.findResource("javax/ejb/EJB.class") == null) { //NOI19\8N
                        // ad EJB API on classpath
                        ContainerClassPathModifier modifier = project.getLookup().lookup(ContainerClassPathModifier.class);
                        if (modifier != null) {
                            modifier.extendClasspath(createdFile, new String[] {
                                ContainerClassPathModifier.API_EJB
                            });
                        }
                    }
                    generateDelegateMethods(createdFile, ejbRef);
                    openFileInEditor(dobj);
                }
            }
        }
    }
 
Example 19
Source File: CssActionsImplementationProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static FileObject getFileObjectFromNode(Node node) {
    DataObject dobj = node.getLookup().lookup(DataObject.class);
    return dobj != null ? dobj.getPrimaryFile() : null;
}
 
Example 20
Source File: ErrorDescriptionFactory.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**Create a new {@link ErrorDescription} with the given parameters.
 *
 * Call from inside a document read lock to ensure the meaning of lineNumber
 * does not change while this method runs.
 * 
 * If the lineNumber is greater than the number of lines in the given document,
 * the very last line will be used.
 * 
 * @param id an optional ID of the {@link ErrorDescription}. Should represent a "type" of an error/warning.
 *           It is recommended that providers prefix the ID with their unique prefix.
 * @param severity the desired {@link Severity}
 * @param description the text of the error/warning
 * @param details optional "more details" describing the error/warning
 * @param fixes a collection of {@link Fix}es that should be shown for the error/warning
 * @param doc document for which the {@link ErrorDescription} should be created
 * @param lineNumber line on which the error/warning should be shown
 * @return a newly created {@link ErrorDescription} based on the given parameters
 * @since 1.22
 */
public static @NonNull ErrorDescription createErrorDescription(@NullAllowed String id, @NonNull Severity severity, @NonNull String description, @NullAllowed CharSequence details, @NonNull LazyFixList fixes, @NonNull Document doc, int lineNumber) {
    Parameters.notNull("severity", severity);
    Parameters.notNull("description", description);
    Parameters.notNull("fixes", fixes);
    Parameters.notNull("doc", doc);
    
    DataObject od = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);
    FileObject file = od != null ? od.getPrimaryFile() : null;
    
    return new ErrorDescription(file, id, description, details, severity, fixes, HintsControllerImpl.fullLine(doc, lineNumber));
}