コード例 #1
0
 @Override
 public final boolean accept(FileObject file) {
   // the ProjectSharabilityQuery filters out nbproject/private,
   // but we need it for remote build
   if (file.getNameExt().equals("private")) { // NOI18N
     FileObject parent = file.getParent();
     if (parent != null && parent.getNameExt().equals("nbproject")) { // NOI18N
       return true;
     }
   }
   Sharability sharability = SharabilityQuery.getSharability(file);
   if (TRACE_SHARABILITY) {
     RemoteUtil.LOGGER.log(
         Level.INFO,
         "{0} sharability is {1}",
         new Object[] {file.getPath(), sharabilityToString(sharability)});
   }
   switch (sharability) {
     case NOT_SHARABLE:
       return false;
     case MIXED:
     case SHARABLE:
     case UNKNOWN:
       return true;
     default:
       CndUtils.assertTrueInConsole(
           false, "Unexpected sharability value: " + sharability); // NOI18N
       return true;
   }
 }
コード例 #2
0
 public FOBNode(Node n, FileObject fo) {
   super(n, fo.isData() ? org.openide.nodes.Children.LEAF : new FOBChildren(n));
   this.fo = fo;
   disableDelegation(
       DELEGATE_SET_NAME
           | DELEGATE_GET_NAME
           | DELEGATE_SET_DISPLAY_NAME
           | DELEGATE_GET_DISPLAY_NAME);
   setName(fo.getNameExt());
   setDisplayName(fo.getNameExt());
 }
コード例 #3
0
  private NbGradleProject(FileObject projectDir, ProjectState state) throws IOException {
    this.projectDir = projectDir;
    this.projectDirAsFile = FileUtil.toFile(projectDir);
    if (projectDirAsFile == null) {
      throw new IOException("Project directory does not exist.");
    }

    this.mergedCommandQueryRef = new AtomicReference<BuiltInGradleCommandQuery>(null);
    this.delayedInitTasks =
        new AtomicReference<Queue<Runnable>>(new LinkedBlockingQueue<Runnable>());
    this.state = state;
    this.defaultLookupRef = new AtomicReference<Lookup>(null);
    this.properties = new ProjectPropertiesProxy(this);
    this.projectInfoManager = new ProjectInfoManager();

    this.hasModelBeenLoaded = new AtomicBoolean(false);
    this.loadErrorRef = new AtomicReference<ProjectInfoRef>(null);
    this.modelChanges = new ChangeSupport(this);
    this.currentModelRef =
        new AtomicReference<NbGradleModelRef>(
            new NbGradleModelRef(GradleModelLoader.createEmptyModel(projectDirAsFile)));

    this.loadedAtLeastOnceSignal = new WaitableSignal();
    this.name = projectDir.getNameExt();
    this.exceptionDisplayer = new ExceptionDisplayer(NbStrings.getProjectErrorTitle(name));
    this.extensionRefs = Collections.emptyList();
    this.extensionsOnLookup = Lookup.EMPTY;
    this.lookupRef = new AtomicReference<DynamicLookup>(null);
    this.protectedLookupRef = new AtomicReference<Lookup>(null);
  }
コード例 #4
0
 @Override
 public String findMIMEType(FileObject fo) {
   if (fo.getExt().equals("coffee") || fo.getNameExt().equals("Cakefile")) {
     return CoffeeScriptLanguage.MIME_TYPE;
   }
   return null;
 }
コード例 #5
0
 private void processFaceletsLibraryDescriptors(
     Iterable<? extends FileObject> files, Context context) {
   if (files == null) {
     return;
   }
   for (FileObject file : findLibraryDescriptors(files, JsfIndexSupport.FACELETS_LIB_SUFFIX)) {
     // no special mimetype for facelet library descriptor AFAIK
     if (file.getNameExt().endsWith(JsfIndexSupport.FACELETS_LIB_SUFFIX)) {
       try {
         String namespace = FaceletsLibraryDescriptor.parseNamespace(file.getInputStream());
         if (namespace != null) {
           JsfIndexSupport.indexFaceletsLibraryDescriptor(context, file, namespace);
           LOGGER.log(
               Level.FINE,
               "The file {0} indexed as a Facelets Library Descriptor",
               file); // NOI18N
         }
       } catch (IOException ex) {
         LOGGER.info(
             String.format(
                 "Error parsing %s file: %s", file.getPath(), ex.getMessage())); // NOI18N
       }
     }
   }
 }
コード例 #6
0
ファイル: Utils.java プロジェクト: JSansalone/NetBeansIDE
 /**
  * Determines all files and folders that belong to a given project and adds them to the supplied
  * Collection.
  *
  * @param filteredFiles destination collection of Files
  * @param project project to examine
  */
 public static void addProjectFiles(
     Collection filteredFiles,
     Collection rootFiles,
     Collection rootFilesExclusions,
     Project project) {
   FileStatusCache cache = CvsVersioningSystem.getInstance().getStatusCache();
   Sources sources = ProjectUtils.getSources(project);
   SourceGroup[] sourceGroups = sources.getSourceGroups(Sources.TYPE_GENERIC);
   for (int j = 0; j < sourceGroups.length; j++) {
     SourceGroup sourceGroup = sourceGroups[j];
     FileObject srcRootFo = sourceGroup.getRootFolder();
     File rootFile = FileUtil.toFile(srcRootFo);
     try {
       getCVSRootFor(rootFile);
     } catch (IOException e) {
       // the folder is not under a versioned root
       continue;
     }
     rootFiles.add(rootFile);
     boolean containsSubprojects = false;
     FileObject[] rootChildren = srcRootFo.getChildren();
     Set projectFiles = new HashSet(rootChildren.length);
     for (int i = 0; i < rootChildren.length; i++) {
       FileObject rootChildFo = rootChildren[i];
       if (CvsVersioningSystem.FILENAME_CVS.equals(rootChildFo.getNameExt())) continue;
       File child = FileUtil.toFile(rootChildFo);
       // #67900 Added special treatment for .cvsignore files
       if (sourceGroup.contains(rootChildFo)
           || CvsVersioningSystem.FILENAME_CVSIGNORE.equals(rootChildFo.getNameExt())) {
         // TODO: #60516 deep scan is required here but not performed due to performace reasons
         projectFiles.add(child);
       } else {
         int status = cache.getStatus(child).getStatus();
         if (status != FileInformation.STATUS_NOTVERSIONED_EXCLUDED) {
           rootFilesExclusions.add(child);
           containsSubprojects = true;
         }
       }
     }
     if (containsSubprojects) {
       filteredFiles.addAll(projectFiles);
     } else {
       filteredFiles.add(rootFile);
     }
   }
 }
コード例 #7
0
 /**
  * Get file name. If ASSET_TYPE is IMAGE, get name with extention, otherwise only name.
  *
  * @param fo target FileObject
  * @return file name if type is image, with extention.
  */
 private String getFileName(FileObject fo) {
   String name;
   if (type == ASSET_TYPE.IMAGE) {
     name = fo.getNameExt();
   } else {
     name = fo.getName();
   }
   return name;
 }
コード例 #8
0
 public static Collection<FileObject> findLibraryDescriptors(
     Iterable<? extends FileObject> fos, String suffix) {
   Collection<FileObject> files = new ArrayList<FileObject>();
   for (FileObject file : fos) {
     if (file.getNameExt().toLowerCase(Locale.US).endsWith(suffix)) { // NOI18N
       // found library, create a new instance and cache it
       files.add(file);
     }
   }
   return files;
 }
コード例 #9
0
ファイル: TestcaseChildren.java プロジェクト: bflavius/nb-soa
  private static boolean isValidTestCaseResult(FileObject fo) {

    if (fo.isFolder()) {
      return false;
    }
    String name = fo.getNameExt();

    // e.x., Actual_20060803211027.xml, Actual_20060803211027_F.xml,
    // Actual_20060803211027_S.xml

    return name.matches(TestcaseNode.ACTUAL_OUTPUT_REGEX);
  }
コード例 #10
0
ファイル: TestcaseChildren.java プロジェクト: bflavius/nb-soa
  private FileObject getRealTestCaseResultsFolder() {
    FileObject dir = null;

    String testcaseName = mTestcaseDir.getNameExt();
    FileObject testDir = mProject.getTestDirectory();
    if (testDir != null) {
      FileObject testResultsDir = testDir.getFileObject("results"); // TMP  // NOI18N
      if (testResultsDir != null) {
        dir = testResultsDir.getFileObject(testcaseName);
      }
    }

    return dir;
  }
コード例 #11
0
 public FileObject copyFile(FileObject source) {
   FileObject result = null;
   Path target = createRegistry().resolve(source.getNameExt());
   if (Files.exists(target)) {
     result = FileUtil.toFileObject(target.toFile());
   } else {
     Path sourcePath = FileUtil.toFile(source).toPath();
     try {
       Path p = Files.copy(sourcePath, target);
       result = FileUtil.toFileObject(p.toFile());
     } catch (IOException ex) {
       LOG.log(Level.INFO, ex.getMessage());
     }
   }
   return result;
 }
コード例 #12
0
  @NbBundle.Messages({
    "CakePhpCustomizerValidator.error.dotcake.notFound=[.cake] Existing .cake file must be set.",
    "CakePhpCustomizerValidator.error.dotcake.notFile=[.cake] File path must be set.",
    "CakePhpCustomizerValidator.error.dotcake.invalid.file.format=[.cake] Invalid format. Can't get data from .cake.",
    "CakePhpCustomizerValidator.error.dotcake.invalid.file.name=[.cake] File name must be .cake."
  })
  public CakePhpCustomizerValidator validateDotcakeFilePath(
      FileObject sourceDirectory, String path) {
    // ignore if file path is empy
    if (StringUtils.isEmpty(path)) {
      return this;
    }

    FileObject targetFile = sourceDirectory.getFileObject(path);
    if (targetFile == null) {
      result.addWarning(
          new ValidationResult.Message(
              "dotcake.path",
              Bundle.CakePhpCustomizerValidator_error_dotcake_notFound())); // NOI18N
      return this;
    }

    if (targetFile.isFolder()) {
      result.addWarning(
          new ValidationResult.Message(
              "dotcake.path", Bundle.CakePhpCustomizerValidator_error_dotcake_notFile())); // NOI18N
      return this;
    }

    if (!targetFile.getNameExt().equals(".cake")) { // NOI18N
      result.addWarning(
          new ValidationResult.Message(
              "dotcake.path",
              Bundle.CakePhpCustomizerValidator_error_dotcake_invalid_file_name())); // NOI18N
      return this;
    }

    // invalid format
    Dotcake dotcake = Dotcake.fromJson(targetFile);
    if (dotcake == null || dotcake.getCake() == null || dotcake.getBuildPath() == null) {
      result.addWarning(
          new ValidationResult.Message(
              "dotcake.path",
              Bundle.CakePhpCustomizerValidator_error_dotcake_invalid_file_format())); // NOI18N
    }
    return this;
  }
コード例 #13
0
  private void loadFromWebServicesHome() {
    for (FileObject fo : getWebServiceHome().getChildren()) {
      if (!fo.isFolder()) {
        continue;
      }
      for (FileObject file : fo.getChildren()) {
        if (!file.getNameExt().endsWith("-saas.xml")) { // NOI18N

          continue;
        }
        try {
          loadSaasServiceFile(file, true);
        } catch (Exception ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    }
  }
コード例 #14
0
 private static FileObject substituteIfNeed(FileObject dir, Document projectXml) {
   if (!dir.getNameExt().endsWith("shadow")) { // NOI18N
     return null;
   }
   Element root = projectXml.getDocumentElement();
   if (root != null) {
     String mode = getNodeValue(root, MakeProject.REMOTE_MODE);
     if (RemoteProject.Mode.REMOTE_SOURCES.name().equals(mode)) {
       String hostUid = getNodeValue(root, MakeProject.REMOTE_FILESYSTEM_HOST);
       String remotebaseDir = getNodeValue(root, MakeProject.REMOTE_FILESYSTEM_BASE_DIR);
       if (hostUid != null && remotebaseDir != null) {
         ExecutionEnvironment env = ExecutionEnvironmentFactory.fromUniqueID(hostUid);
         FileObject fo = FileSystemProvider.getFileObject(env, remotebaseDir);
         return fo;
       }
     }
   }
   return null;
 }
コード例 #15
0
ファイル: TestcaseChildren.java プロジェクト: bflavius/nb-soa
  protected Node[] createNodes(Object key) {
    // interpret your key here...usually one node generated, but could be zero or more
    FileObject fo = (FileObject) key;

    try {
      DataObject dataObject = DataFolder.find(fo);

      String name = fo.getNameExt();

      if (name.equals("Input.xml")) { // NOI18N
        return new Node[] {new TestCaseInputNode(mProject, dataObject)};
      } else if (name.equals("Output.xml")) { // NOI18N
        return new Node[] {new TestCaseOutputNode(mProject, dataObject)};
      } else {
        return new Node[] {new TestCaseResultNode(mProject, dataObject)};
      }
    } catch (DataObjectNotFoundException e) {
      // Ignore on purpose. This could happen on test case deletion.
    }

    return new Node[0];
  }
コード例 #16
0
  private void loadFromDefaultFileSystem() {
    FileObject f = FileUtil.getConfigFile("SaaSServices"); // NOI18N

    if (f != null && f.isFolder()) {
      Enumeration<? extends FileObject> en = f.getFolders(false);
      while (en.hasMoreElements()) {
        FileObject groupFolder = en.nextElement();
        for (FileObject fo : groupFolder.getChildren()) {
          if (fo.isFolder()) {
            continue;
          }
          if (PROFILE_PROPERTIES_FILE.equals(fo.getNameExt())) {
            continue;
          }
          loadSaasServiceFile(fo, false);
        }
        SaasGroup g = rootGroup.getChildGroup(groupFolder.getName());
        if (g != null) {
          g.setIcon16Path((String) groupFolder.getAttribute("icon16"));
          g.setIcon32Path((String) groupFolder.getAttribute("icon32"));
        }
      }
    }
  }
コード例 #17
0
    public String getDisplayHtml(HtmlFormatter formatter) {
      formatter.setMaxLength(120);
      if (cachedDisplayItem == null) {
        formatter.reset();

        boolean nodoc = element.isNoDoc();
        boolean documented = element.isDocumented();
        if (isPreferred) {
          formatter.emphasis(true);
        } else if (nodoc) {
          formatter.deprecated(true);
        }

        if (element instanceof IndexedMethod) {
          //                    if (element.getFqn() != null) {
          //                        formatter.appendText(element.getFqn());
          //                        formatter.appendText(".");
          //                    }
          formatter.appendText(element.getName());
          IndexedMethod method = (IndexedMethod) element;
          String[] parameters = method.getParams();

          if ((parameters != null) && (parameters.length > 0)) {
            formatter.appendText("("); // NOI18N

            boolean first = true;
            for (String parameter : parameters) {
              if (first) {
                first = false;
              } else {
                formatter.appendText(", "); // NOI18N
              }
              formatter.parameters(true);
              formatter.appendText(parameter);
              formatter.parameters(false);
            }

            formatter.appendText(")"); // NOI18N
          }
        } else {
          // formatter.appendText(element.getFqn());
          formatter.appendText(element.getName());
        }

        if (element.getClz() != null) {
          formatter.appendText(" ");
          formatter.appendText(NbBundle.getMessage(PythonDeclarationFinder.class, "In"));
          formatter.appendText(" ");
          formatter.appendText(element.getClz());
          formatter.appendHtml(" "); // NOI18N
        }

        String filename = null;
        String url = element.getFilenameUrl();
        if (url == null) {
          // Deleted file?
          // Just leave out the file name
        } else if (url.indexOf("pythonstubs") != -1) { // NOI18N
          filename = NbBundle.getMessage(PythonDeclarationFinder.class, "PythonLib");
          //
          //                    if (url.indexOf("/stub_") == -1) {
          //                        // Not a stub file, such as ftools.py
          //                        // TODO - don't hardcode for version
          //                        String stub = "pythonstubs/2.5/";
          //                        int stubStart = url.indexOf(stub);
          //                        if (stubStart != -1) {
          //                            filename = filename+": " + url.substring(stubStart);
          //                        }
          //                    }
        } else {
          FileObject fo = element.getFileObject();
          if (fo != null) {
            filename = fo.getNameExt();
          } else {
            // Perhaps a file that isn't present here, such as something in site_ruby
            int lastIndex = url.lastIndexOf('/');
            if (lastIndex != -1) {
              String s = url.substring(0, lastIndex);
              int almostLastIndex = s.lastIndexOf('/');
              if (almostLastIndex != -1 && ((url.length() - almostLastIndex) < 40)) {
                filename = url.substring(almostLastIndex + 1);
                if (filename.indexOf(':') != -1) {
                  // Don't include prefix like cluster:, file:, etc.
                  filename = url.substring(lastIndex + 1);
                }
              } else {
                filename = url.substring(lastIndex + 1);
              }
            }
          }

          //                    // TODO - make this work with 1.9 etc.
          //                    //final String GEM_LOC = "lib/ruby/gems/1.8/gems/";
          //                    Pattern p = Pattern.compile("lib/ruby/gems/\\d+\\.\\d+/gems/");
          //                    Matcher m = p.matcher(url);
          //                    //int gemIndex = url.indexOf(GEM_LOC);
          //                    //if (gemIndex != -1) {
          //                    if (m.find()) {
          //                        //int gemIndex = m.start();
          //                        //gemIndex += GEM_LOC.length();
          //                        int gemIndex = m.end();
          //                        int gemEnd = url.indexOf('/', gemIndex);
          //                        if (gemEnd != -1) {
          //                            //int libIndex = url.indexOf("lib/", gemEnd);
          //                            //if (libIndex != -1) {
          //                            //    filename = url.substring(libIndex+4);
          //                            //}
          //                            filename = url.substring(gemIndex, gemEnd) + ": " +
          // filename;
          //                        }
          //                    }
        }

        if (filename != null) {
          formatter.appendText(" ");
          formatter.appendText(NbBundle.getMessage(PythonDeclarationFinder.class, "In"));
          formatter.appendText(" ");
          formatter.appendText(filename);
        }

        if (documented) {
          formatter.appendText(" ");
          formatter.appendText(NbBundle.getMessage(PythonDeclarationFinder.class, "Documented"));
        } else if (nodoc) {
          formatter.appendText(" ");
          formatter.appendText(NbBundle.getMessage(PythonDeclarationFinder.class, "NoDoced"));
        }

        if (isPreferred) {
          formatter.emphasis(false);
        } else if (nodoc) {
          formatter.deprecated(false);
        }

        cachedDisplayItem = formatter.getText();
      }

      return cachedDisplayItem;
    }
コード例 #18
0
ファイル: FileNodeUtil.java プロジェクト: bflavius/nb-soa
  public static void overwriteFile(Node srcNode, Node destNode) throws IOException {

    DataObject srcDO = srcNode.getLookup().lookup(DataObject.class);
    FileObject srcFO = srcDO.getPrimaryFile();

    DataObject destDO = destNode.getLookup().lookup(DataObject.class);
    FileObject destFO = destDO.getPrimaryFile();

    // To avoid any confusion, save modified source first.
    if (srcDO.isModified()) {
      NotifyDescriptor d =
          new NotifyDescriptor.Confirmation(
              NbBundle.getMessage(
                  FileNodeUtil.class, "MSG_SaveModifiedSource", srcFO.getNameExt()), // NOI18N
              NbBundle.getMessage(FileNodeUtil.class, "TTL_SaveModifiedSource"), // NOI18N
              NotifyDescriptor.OK_CANCEL_OPTION);
      if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.OK_OPTION) {
        EditorCookie srcEditorCookie = srcDO.getCookie(EditorCookie.class);
        srcEditorCookie.saveDocument();
      }
    }
    //        // Alternatively, we could use the in-memory copy of the source file
    //        EditorCookie srcEditorCookie =
    //                (EditorCookie) srcDO.getCookie(EditorCookie.class);
    //        Document srcDocument = srcEditorCookie.getDocument();
    //        if (srcDocument == null) {
    //            Task loadTask = srcEditorCookie.prepareDocument();
    //            new RequestProcessor().post(loadTask);
    //
    //            loadTask.waitFinished();
    //            srcDocument = srcEditorCookie.getDocument();
    //        }
    //        String srcText = srcDocument.getText(0, srcDocument.getLength());

    // From now on, we will only be using the on-disk copy of the source file.

    if (destDO.isModified()) {
      NotifyDescriptor d =
          new NotifyDescriptor.Confirmation(
              NbBundle.getMessage(
                  FileNodeUtil.class,
                  "MSG_OverwriteModifiedDestination",
                  destFO.getNameExt()), // NOI18N
              NbBundle.getMessage(FileNodeUtil.class, "TTL_OverwriteModifiedDestination"), // NOI18N
              NotifyDescriptor.OK_CANCEL_OPTION);
      if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.CANCEL_OPTION) {
        return;
      }

      EditorCookie destEditorCookie = destDO.getCookie(EditorCookie.class);

      InputStream inputStream = null;
      try {
        inputStream = srcFO.getInputStream();
        String srcText = getInputStreamContents(inputStream);

        Document outputDocument = destEditorCookie.getDocument();
        try {
          outputDocument.remove(0, outputDocument.getLength());
        } catch (java.lang.Exception e) {
          // Ignore exception here on purpose.
          // One of the listener from xml module throws NPE:
          // at
          // org.netbeans.modules.xml.text.completion.GrammarManager.isGuarded(GrammarManager.java:170)
          // at
          // org.netbeans.modules.xml.text.completion.GrammarManager.removeUpdate(GrammarManager.java:140)
          // at
          // org.netbeans.lib.editor.util.swing.PriorityDocumentListenerList.removeUpdate(PriorityDocumentListenerList.java:63)
          // at javax.swing.text.AbstractDocument.fireRemoveUpdate(AbstractDocument.java:242)
          // at org.netbeans.editor.BaseDocument.fireRemoveUpdate(BaseDocument.java:1305)
          // at org.netbeans.editor.BaseDocument.remove(BaseDocument.java:737)
        }
        outputDocument.insertString(0, srcText, null);
        destEditorCookie.saveDocument();
      } catch (BadLocationException e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
      } finally {
        try {
          if (inputStream != null) {
            inputStream.close();
          }
        } catch (Exception e) {;
        }
      }
    } else {
      FileLock lock = destFO.lock();
      InputStream inputStream = null;
      OutputStream outputStream = null;

      try {
        outputStream = destFO.getOutputStream(lock);
        inputStream = srcFO.getInputStream();
        FileUtil.copy(inputStream, outputStream);
      } finally {
        try {
          if (inputStream != null) {
            inputStream.close();
          }
          if (outputStream != null) {
            outputStream.close();
          }

          lock.releaseLock();
        } catch (Exception e) {;
        }
      }
    }
  }
コード例 #19
0
  @Override
  public List<String> getElements(int argCount, String filter) {
    CakePhpModule cakeModule = CakePhpModule.forPhpModule(phpModule);
    if (cakeModule == null) {
      return Collections.emptyList();
    }
    CakeVersion version = cakeModule.getCakeVersion();
    if (version == null) {
      return Collections.emptyList();
    }
    int cakeVersion = version.getMajor();
    List<String> elements = new LinkedList<String>();
    if (type == null) {
      return elements;
    }

    if (argCount == 1) {
      String pluginName = null;
      boolean isPlugin = false;

      // CakePHP 2.x
      if (cakeVersion >= 2) {
        String[] split = filter.split("\\.", 2); // NOI18N
        int splitLength = split.length;

        // is plugin?
        if (splitLength > 0) {
          isPlugin = isPlugin(split[0]);
          if (isPlugin) {
            if (splitLength > 1) {
              filter = split[1];
            } else {
              filter = ""; // NOI18N
            }
            pluginName = split[0];
          }
        }
      }

      // check subdirectory
      filter = setSubDirectoryPath(filter);

      // add elements
      for (DIR_TYPE dirType : dirTypes) {
        if (!isPlugin) {
          if (PLUGINS.contains(dirType)) {
            continue;
          }
        }

        FileObject webrootDirectory =
            cakeModule.getDirectory(dirType, FILE_TYPE.WEBROOT, pluginName);
        if (webrootDirectory != null) {
          FileObject targetDirectory = null;
          if (filter.startsWith(SLASH)) {
            targetDirectory = webrootDirectory;
          } else {
            targetDirectory = webrootDirectory.getFileObject(getRelativePath());
          }
          if (targetDirectory != null) {
            for (FileObject element : targetDirectory.getChildren()) {
              addElement(element, filter, elements, pluginName);
            }
            break;
          }
        }
        if (isPlugin && !elements.isEmpty()) {
          return elements;
        }
      }

      if (!subDirectoryPath.isEmpty() || isPlugin) {
        return elements;
      }

      // plugin names
      // CakePHP 2.x
      if (cakeVersion >= 2) {
        for (DIR_TYPE dirType : PLUGINS) {
          FileObject pluginDirectory = cakeModule.getDirectory(dirType);
          if (pluginDirectory != null) {
            for (FileObject child : pluginDirectory.getChildren()) {
              if (child.isFolder()) {
                String name = child.getNameExt();
                FileObject webrootDirectory =
                    cakeModule.getDirectory(dirType, FILE_TYPE.WEBROOT, name);
                if (webrootDirectory != null
                    && webrootDirectory.getFileObject(type.toString()) != null) {
                  if (name.startsWith(filter)) {
                    name = name + DOT;
                    elements.add(name);
                  }
                }
              }
            }
          }
        }
      }
    }
    return elements;
  }
コード例 #20
0
 @Override
 public boolean isVisible(FileObject file) {
   return isVisible(file.getNameExt());
 }
コード例 #21
0
  public boolean generateTarget(ProgressHandle ph, String target) {
    if (mapping.getServiceMapping(target) != null) {
      String msg = NbBundle.getMessage(ClientJavonTemplate.class, "MSG_Client"); // NOI18N
      ph.progress(msg);
      OutputLogger.getInstance().log(msg);
      mapping.setProperty("target", "client");

      JavonMapping.Service service = mapping.getServiceMapping(target);
      FileObject outputDir =
          FileUtil.toFileObject(
              FileUtil.normalizeFile(new File(mapping.getClientMapping().getOutputDirectory())));
      outputDir =
          outputDir.getFileObject(mapping.getClientMapping().getPackageName().replace('.', '/'));

      FileObject outputFile =
          outputDir.getFileObject(mapping.getClientMapping().getClassName(), "java");
      if (outputFile == null) {
        OutputLogger.getInstance()
            .log(
                MessageFormat.format(
                    NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ClientJavonCreation"),
                    mapping.getClientMapping().getClassName())); // NOI18N
        try {
          outputFile = outputDir.createData(mapping.getClientMapping().getClassName(), "java");
        } catch (IOException e) {
          OutputLogger.getInstance()
              .log(
                  LogLevel.ERROR,
                  MessageFormat.format(
                      NbBundle.getMessage(ClientJavonTemplate.class, "MSG_FailClientJavonCreation"),
                      mapping.getClientMapping().getClassName())); // NOI18N
        }
      }
      OutputFileFormatter off = null;
      try {
        off = new OutputFileFormatter(outputFile);
      } catch (DataObjectNotFoundException e) {
        generationFailed(e, outputFile);
        return false;
      } catch (IOException e) {
        generationFailed(e, outputFile);
        return false;
      }

      ScriptEngineManager mgr = new ScriptEngineManager();
      ScriptEngine eng = mgr.getEngineByName("freemarker");
      Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);

      FileObject template = FileUtil.getConfigFile("Templates/Client/Client.java");

      OutputLogger.getInstance()
          .log(NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ConfigureBindings")); // NOI18N
      Set<ClassData> returnTypes = service.getReturnTypes();
      Set<ClassData> parameterTypes = service.getParameterTypes();
      bind.put("mapping", mapping);
      bind.put("registry", mapping.getRegistry());
      bind.put("returnTypes", returnTypes);
      bind.put("parameterTypes", parameterTypes);
      bind.put("service", service);
      bind.put("utils", new Utils(mapping.getRegistry()));

      // Compute imports for JavaBeans
      Set<String> imports = new HashSet<String>();
      for (ClassData cd : parameterTypes) {
        while (cd.isArray()) {
          cd = cd.getComponentType();
        }
        if (cd.isPrimitive()) continue;
        if (cd.getPackage().equals("java.lang")) continue;
        if (cd.getFullyQualifiedName().equals("java.util.List")) continue;
        imports.add(cd.getFullyQualifiedName());
      }
      for (ClassData cd : returnTypes) {
        while (cd.isArray()) {
          cd = cd.getComponentType();
        }
        if (cd.isPrimitive()) continue;
        if (cd.getPackage().equals("java.lang")) continue;
        if (cd.getFullyQualifiedName().equals("java.util.List")) continue;
        imports.add(cd.getFullyQualifiedName());
      }
      bind.put("imports", imports);

      OutputLogger.getInstance()
          .log(
              MessageFormat.format(
                  NbBundle.getMessage(ClientBeanGeneratorTemplate.class, "MSG_GenerateJavonClient"),
                  FileUtil.toFile(outputFile))); // NOI18N
      Writer w = null;
      Reader is = null;
      try {
        try {
          w = new StringWriter();
          is = new InputStreamReader(template.getInputStream());

          eng.getContext().setWriter(w);
          eng.getContext()
              .setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
          eng.getContext()
              .setAttribute(
                  ScriptEngine.FILENAME, template.getNameExt(), ScriptContext.ENGINE_SCOPE);

          eng.eval(is);
        } catch (FileNotFoundException e) {
          OutputLogger.getInstance().log(e);
          ErrorManager.getDefault().notify(e);
          return false;
        } catch (ScriptException e) {
          OutputLogger.getInstance().log(e);
          ErrorManager.getDefault().notify(e);
          return false;
        } finally {
          if (w != null) {
            off.write(w.toString());
            // System.err.println( "" + w.toString());
            w.close();
          }
          if (is != null) is.close();
          off.close();
        }
      } catch (IOException e) {
        generationFailed(e, FileUtil.toFile(outputFile));
        return false;
      }

      OutputLogger.getInstance()
          .log(
              MessageFormat.format(
                  NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ClientGenerated"),
                  FileUtil.toFile(outputFile)));
    }
    return true;
  }
コード例 #22
0
  @Override
  public void importFiles(FileObject[] fileObjects) {
    try {
      Map<ImporterUI, List<FileImporter>> importerUIs =
          new HashMap<ImporterUI, List<FileImporter>>();
      List<FileImporter> importers = new ArrayList<FileImporter>();
      for (FileObject fileObject : fileObjects) {
        FileImporter importer = controller.getFileImporter(FileUtil.toFile(fileObject));
        if (importer == null) {
          NotifyDescriptor.Message msg =
              new NotifyDescriptor.Message(
                  NbBundle.getMessage(
                      getClass(), "DesktopImportControllerUI.error_no_matching_file_importer"),
                  NotifyDescriptor.WARNING_MESSAGE);
          DialogDisplayer.getDefault().notify(msg);
          return;
        }
        importers.add(importer);
        ImporterUI ui = controller.getUI(importer);
        if (ui != null) {
          List<FileImporter> l = importerUIs.get(ui);
          if (l == null) {
            l = new ArrayList<FileImporter>();
            importerUIs.put(ui, l);
          }
          l.add(importer);
        }

        // MRU
        MostRecentFiles mostRecentFiles = Lookup.getDefault().lookup(MostRecentFiles.class);
        mostRecentFiles.addFile(fileObject.getPath());
      }

      for (Map.Entry<ImporterUI, List<FileImporter>> entry : importerUIs.entrySet()) {
        ImporterUI ui = entry.getKey();
        String title =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.file.ui.dialog.title",
                ui.getDisplayName());
        JPanel panel = ui.getPanel();
        ui.setup(entry.getValue().toArray(new FileImporter[0]));
        final DialogDescriptor dd = new DialogDescriptor(panel, title);
        if (panel instanceof ValidationPanel) {
          ValidationPanel vp = (ValidationPanel) panel;
          vp.addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  dd.setValid(!((ValidationPanel) e.getSource()).isProblem());
                }
              });
        }

        Object result = DialogDisplayer.getDefault().notify(dd);
        if (!result.equals(NotifyDescriptor.OK_OPTION)) {
          ui.unsetup(false);
          return;
        }
        ui.unsetup(true);
      }

      final List<Container> result = new ArrayList<Container>();
      for (int i = 0; i < importers.size(); i++) {
        final FileImporter importer = importers.get(i);
        FileObject fileObject = fileObjects[i];
        LongTask task = null;
        if (importer instanceof LongTask) {
          task = (LongTask) importer;
        }

        // Execute task
        fileObject = getArchivedFile(fileObject);
        final String containerSource = fileObject.getNameExt();
        final InputStream stream = fileObject.getInputStream();
        String taskName =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.taskName",
                containerSource);
        executor.execute(
            task,
            new Runnable() {
              @Override
              public void run() {
                try {
                  Container container = controller.importFile(stream, importer);
                  if (container != null) {
                    container.setSource(containerSource);
                    result.add(container);
                  }
                } catch (Exception ex) {
                  throw new RuntimeException(ex);
                }
              }
            },
            taskName,
            errorHandler);
      }
      executor.execute(
          null,
          new Runnable() {

            @Override
            public void run() {
              if (!result.isEmpty()) {
                finishImport(result.toArray(new Container[0]));
              }
            }
          });
    } catch (Exception ex) {
      Logger.getLogger("").log(Level.WARNING, "", ex);
    }
  }
コード例 #23
0
  @Override
  public void importFile(FileObject fileObject) {
    try {
      final FileImporter importer = controller.getFileImporter(FileUtil.toFile(fileObject));
      if (importer == null) {
        NotifyDescriptor.Message msg =
            new NotifyDescriptor.Message(
                NbBundle.getMessage(
                    getClass(), "DesktopImportControllerUI.error_no_matching_file_importer"),
                NotifyDescriptor.WARNING_MESSAGE);
        DialogDisplayer.getDefault().notify(msg);
        return;
      }

      // MRU
      MostRecentFiles mostRecentFiles = Lookup.getDefault().lookup(MostRecentFiles.class);
      mostRecentFiles.addFile(fileObject.getPath());

      ImporterUI ui = controller.getUI(importer);
      if (ui != null) {
        String title =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.file.ui.dialog.title",
                ui.getDisplayName());
        JPanel panel = ui.getPanel();
        ui.setup(new FileImporter[] {importer});
        final DialogDescriptor dd = new DialogDescriptor(panel, title);
        if (panel instanceof ValidationPanel) {
          ValidationPanel vp = (ValidationPanel) panel;
          vp.addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  dd.setValid(!((ValidationPanel) e.getSource()).isProblem());
                }
              });
        }

        Object result = DialogDisplayer.getDefault().notify(dd);
        if (!result.equals(NotifyDescriptor.OK_OPTION)) {
          ui.unsetup(false);
          return;
        }
        ui.unsetup(true);
      }

      LongTask task = null;
      if (importer instanceof LongTask) {
        task = (LongTask) importer;
      }

      // Execute task
      fileObject = getArchivedFile(fileObject);
      final String containerSource = fileObject.getNameExt();
      final InputStream stream = fileObject.getInputStream();
      String taskName =
          NbBundle.getMessage(
              DesktopImportControllerUI.class,
              "DesktopImportControllerUI.taskName",
              containerSource);
      executor.execute(
          task,
          new Runnable() {
            @Override
            public void run() {
              try {
                Container container = controller.importFile(stream, importer);
                if (container != null) {
                  container.setSource(containerSource);
                  finishImport(container);
                }
              } catch (Exception ex) {
                throw new RuntimeException(ex);
              }
            }
          },
          taskName,
          errorHandler);
    } catch (Exception ex) {
      Logger.getLogger("").log(Level.WARNING, "", ex);
    }
  }