public void testGeneratedSources() throws Exception { // #187595
   TestFileUtils.writeFile(
       d,
       "pom.xml",
       "<project xmlns='http://maven.apache.org/POM/4.0.0'>"
           + "<modelVersion>4.0.0</modelVersion>"
           + "<groupId>grp</groupId>"
           + "<artifactId>art</artifactId>"
           + "<packaging>jar</packaging>"
           + "<version>0</version>"
           + "</project>");
   FileObject src = FileUtil.createFolder(d, "src/main/java");
   FileObject gsrc = FileUtil.createFolder(d, "target/generated-sources/xjc");
   gsrc.createData("Whatever.class");
   FileObject tsrc = FileUtil.createFolder(d, "src/test/java");
   FileObject gtsrc = FileUtil.createFolder(d, "target/generated-test-sources/jaxb");
   gtsrc.createData("Whatever.class");
   assertEquals(
       Arrays.asList(src, gsrc),
       Arrays.asList(
           SourceForBinaryQuery.findSourceRoots(new URL(d.toURL(), "target/classes/"))
               .getRoots()));
   assertEquals(
       Arrays.asList(tsrc, gtsrc),
       Arrays.asList(
           SourceForBinaryQuery.findSourceRoots(new URL(d.toURL(), "target/test-classes/"))
               .getRoots()));
 }
  protected @Override void setUp() throws Exception {
    MockLookup.setLayersAndInstances(TestUtil.testProjectFactory());
    ProjectManager.getDefault().reset();
    FileOwnerQuery.reset();
    scratch = TestUtil.makeScratchDir(this);
    projdir = scratch.createFolder("my-project");
    projdir.createFolder("testproject");
    randomfile = scratch.createData("randomfile");
    projfile = projdir.createData("projfile");
    FileObject projsubdir = projdir.createFolder("projsubdir");
    projfile2 = projsubdir.createData("projfile2");
    subprojdir = projdir.createFolder("subproject");
    subprojdir.createFolder("testproject");
    subprojfile = subprojdir.createData("subprojfile");
    scratch.createFolder("external1").createFolder("subdir").createData("file");
    scratch.createFolder("external2").createFolder("subdir").createData("file");
    scratch.createFolder("external3").createFolder("subproject").createFolder("testproject");
    p = ProjectManager.getDefault().findProject(projdir);
    assertNotNull("found a project successfully", p);

    // make jar:file:/.../projdir/foo.jar!/zipfile/zippedfile
    FileObject foojar = TestFileUtils.writeZipFile(projdir, "foo.jar", "zipdir/zippedfile:");
    FileObject foojarRoot = FileUtil.getArchiveRoot(foojar);
    assertNotNull("have an archive in " + foojar, foojarRoot);
    zippedfile = foojarRoot.getFileObject("zipdir/zippedfile");
    assertNotNull("zippedfile found in it", zippedfile);

    hashedFile = TestFileUtils.writeZipFile(projdir, ".#webapp.jar.1.45", "zipdir/zippedfile:");
    foojarRoot = FileUtil.getArchiveRoot(hashedFile);
    assertNotNull("have an archive in " + hashedFile, foojarRoot);
    hashedFile = foojarRoot.getFileObject("zipdir/zippedfile");
  }
 public void testGetSourceLevelWithBrokenPlatform() throws Exception {
   this.prepareProject("BrokenPlatform");
   FileObject file = scratch.createData("some.java");
   String sl = SourceLevelQuery.getSourceLevel(file);
   assertEquals("Non-project Java file does not have any source level", null, sl);
   file = sources.createData("a.java");
   sl = SourceLevelQuery.getSourceLevel(file);
   assertEquals("Project's Java file must have project's source", "4.3", sl);
 }
Exemple #4
0
  private void writeResultsXml(GtaResult resultsObject) throws IOException {

    String newAnResFileName =
        FileUtil.findFreeFileName(
            resultsfolder,
            resultsfolder.getName() + "_" + modelReference.getFilename() + "_results",
            "xml");
    FileObject newAnResFile = resultsfolder.createData(newAnResFileName, "xml");
    resultsObject.setSummary(new Summary());
    resultsObject.getSummary().setFitModelCall(fitModelCall);
    // TODO resolve problem with multiple modelcalls
    resultsObject.getSummary().setInitModelCall(modelCalls.get(0));

    for (int i = 0; i < relationsList.size(); i++) {
      resultsObject.getDatasetRelations().add(new DatasetRelation());
      resultsObject
          .getDatasetRelations()
          .get(i)
          .setTo(String.valueOf((int) floor(relationsList.get(i)[0])));
      resultsObject
          .getDatasetRelations()
          .get(i)
          .setFrom(String.valueOf((int) floor(relationsList.get(i)[1])));
      // TODO do this in a different way
      // resultsObject.getDatasetRelations().get(i).getValues().add(relationsList.get(i)[2]);
      String cmd =
          timpcontroller.NAME_OF_RESULT_OBJECT
              + "$currTheta[["
              + (int) floor(relationsList.get(i)[0])
              + "]]@drel";
      resultsObject.getDatasetRelations().get(i).getValues().add(timpcontroller.getDouble(cmd));
    }

    createAnalysisResultsFile(resultsObject, FileUtil.toFile(newAnResFile));
  }
  public void savePreset(String name, Layout layout) {
    Preset preset = addPreset(new Preset(name, layout));

    try {
      // Create file if dont exist
      FileObject folder = FileUtil.getConfigFile("layoutpresets");
      if (folder == null) {
        folder = FileUtil.getConfigRoot().createFolder("layoutpresets");
      }
      FileObject presetFile = folder.getFileObject(name, "xml");
      if (presetFile == null) {
        presetFile = folder.createData(name, "xml");
      }

      // Create doc
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = factory.newDocumentBuilder();
      final Document document = documentBuilder.newDocument();
      document.setXmlVersion("1.0");
      document.setXmlStandalone(true);

      // Write doc
      preset.writeXML(document);

      // Write XML file
      Source source = new DOMSource(document);
      Result result = new StreamResult(FileUtil.toFile(presetFile));
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Test of validateDirectory method, of class YiiCustomizerValidator.
   *
   * @throws java.io.IOException
   */
  @Test
  public void testValidateDirectory() throws IOException {
    FileSystem fileSystem = FileUtil.createMemoryFileSystem();
    FileObject sourceDirectory = fileSystem.getRoot();
    sourceDirectory.createFolder("myfolder");
    sourceDirectory.createData("test.php");

    // existing directory
    YiiCustomizerValidator validator =
        new YiiCustomizerValidator().validateDirectory(sourceDirectory, "myfolder");
    ValidationResult result = validator.getResult();
    assertFalse(result.hasErrors());
    assertFalse(result.hasWarnings());

    // not existing directory
    validator = new YiiCustomizerValidator().validateDirectory(sourceDirectory, "dummy");
    result = validator.getResult();
    assertFalse(result.hasErrors());
    assertTrue(result.hasWarnings());

    // file
    validator = new YiiCustomizerValidator().validateDirectory(sourceDirectory, "test.php");
    result = validator.getResult();
    assertFalse(result.hasErrors());
    assertTrue(result.hasWarnings());
  }
  @BeforeClass
  public static void setUpClass() throws Exception {
    MockServices.setServices();
    DalvikPlatformManager.getDefault().setSdkLocation(SDK_DIR);
    tempFolder = File.createTempFile("junit", "");
    tempFolder.delete();
    tempFolder.mkdir();

    FileObject scratch = FileUtil.toFileObject(tempFolder);
    FileObject cacheDir = scratch.createFolder("cache");
    CacheFolder.setCacheFolder(cacheDir);
    FileObject sdkDirFo = FileUtil.toFileObject(new File(SDK_DIR));

    projdir = scratch.createFolder("Snake");
    FileUtilities.recursiveCopy(sdkDirFo.getFileObject("samples/android-8/Snake"), projdir);

    FileObject dir = projdir;
    for (String dirName : Splitter.on('/').split("gen/com/example/android/snake")) {
      dir = dir.createFolder(dirName);
    }
    OutputStream os = dir.createData("R.java").getOutputStream();
    FileUtil.copy(ProjectRefResolverTest.class.getResourceAsStream("Snake_R_java.txt"), os);
    os.close();

    pp = ProjectManager.getDefault().findProject(projdir);
  }
 public void testUnowned() throws Exception {
   FileObject subdir = projdir.createFolder("subUnowned");
   FileObject subfile = subdir.createData("subfile");
   assertEquals(p, FileOwnerQuery.getOwner(subfile));
   FileOwnerQuery.markExternalOwner(
       subdir, FileOwnerQuery.UNOWNED, FileOwnerQuery.EXTERNAL_ALGORITHM_TRANSIENT);
   assertEquals(null, FileOwnerQuery.getOwner(subfile));
   FileOwnerQuery.markExternalOwner(subdir, null, FileOwnerQuery.EXTERNAL_ALGORITHM_TRANSIENT);
   assertEquals(p, FileOwnerQuery.getOwner(subfile));
 }
Exemple #9
0
  public FileObject createEmptyClickFO() {
    LOGGER.log(Level.ALL, "enter  @createModel");

    try {
      FileObject clickFO = fsRoot.createData("click", "xml");
      return clickFO;
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    }
    return null;
  }
 private static void setModules(final FileObject dir, final WizardDescriptor wiz) {
   final Properties properties =
       (Properties) wiz.getProperty(ModuleSelectionWizardPanel1.MODULE_SELECTION_PROPS);
   if (properties != null) {
     final FileObject jinferProjectDir = dir.getFileObject("jinferproject");
     try {
       final FileObject projectProperties = jinferProjectDir.createData("project", "properties");
       properties.store(new FileOutputStream(FileUtil.toFile(projectProperties)), null);
     } catch (IOException ex) {
       Exceptions.printStackTrace(ex);
     }
   }
 }
  private File getStorageFile() {
    File storage = null;
    if (dbFolder != null) {
      FileObject storageFO = dbFolder.getFileObject(STORAGE, STORAGE_EXT);
      try {
        if (storageFO == null) {
          storageFO = dbFolder.createData(STORAGE, STORAGE_EXT);
        }
      } catch (IOException e) {
      }

      if (storageFO != null) {
        storage = NbClassPath.toFile(storageFO);
      }
    }
    return storage;
  }
 /**
  * Create a new application manifest file with minimal initial contents.
  *
  * @param dir the directory to create it in
  * @param path the relative path of the file
  * @throws IOException in case of problems
  */
 private static void createManifest(FileObject dir, String path) throws IOException {
   FileObject manifest = dir.createData(MANIFEST_FILE);
   FileLock lock = manifest.lock();
   try {
     OutputStream os = manifest.getOutputStream(lock);
     try {
       PrintWriter pw = new PrintWriter(os);
       pw.println("Manifest-Version: 1.0"); // NOI18N
       pw.println("X-COMMENT: Main-Class will be added automatically by build"); // NOI18N
       pw.println(); // safest to end in \n\n due to JRE parsing bug
       pw.flush();
     } finally {
       os.close();
     }
   } finally {
     lock.releaseLock();
   }
 }
Exemple #13
0
 public static void registerXMLKit() {
   String[] path = new String[] {"Editors", "text", "x-xml"};
   FileObject target = FileUtil.getConfigRoot();
   try {
     for (int i = 0; i < path.length; i++) {
       FileObject f = target.getFileObject(path[i]);
       if (f == null) {
         f = target.createFolder(path[i]);
       }
       target = f;
     }
     String name = "EditorKit.instance";
     if (target.getFileObject(name) == null) {
       FileObject f = target.createData(name);
       f.setAttribute("instanceClass", "org.netbeans.modules.xml.text.syntax.XMLKit");
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
Exemple #14
0
  private void writeResults(
      TimpResultDataset[] results, GtaModelReference modelReference, String[] nlsprogressResult) {
    Tgm model = getModel(modelReference);
    GtaResult newResultsObject = new GtaResult();
    String freeResultsFilename =
        FileUtil.findFreeFileName(resultsfolder, resultsfolder.getName(), "summary");
    try {
      writeSummary(resultsfolder, freeResultsFilename);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    }

    if (nlsprogressResult != null) {
      for (int i = 0; i < nlsprogressResult.length; i++) {
        NlsProgress progress = new NlsProgress();
        progress.setRss(nlsprogressResult[i]);
        newResultsObject.getNlsprogress().add(progress);
      }
    }

    for (int i = 0; i < results.length; i++) {
      TimpResultDataset timpResultDataset = results[i];
      timpResultDataset.setType(datasets[i].getType());

      newResultsObject.getDatasets().add(new Dataset());
      newResultsObject.getDatasets().get(i).setDatasetFile(new OutputFile());
      newResultsObject
          .getDatasets()
          .get(i)
          .getDatasetFile()
          .setFilename(datasetContainer.getDatasets().get(i).getFilename());
      newResultsObject
          .getDatasets()
          .get(i)
          .getDatasetFile()
          .setPath(datasetContainer.getDatasets().get(i).getPath());
      newResultsObject.getDatasets().get(i).getDatasetFile().setFiletype(datasets[i].getType());
      newResultsObject.getDatasets().get(i).setId(String.valueOf(i + 1));

      if (model.getDat().getIrfparPanel().getLamda() != null) {
        timpResultDataset.setLamdac(model.getDat().getIrfparPanel().getLamda());
      }

      if (datasets[i].getType().equalsIgnoreCase("flim")) {
        timpResultDataset.setOrheigh(datasets[i].getOriginalHeight());
        timpResultDataset.setOrwidth(datasets[i].getOriginalWidth());
        timpResultDataset.setIntenceIm(datasets[i].getIntenceIm().clone());
        timpResultDataset.setMaxInt(datasets[i].getMaxInt());
        timpResultDataset.setMinInt(datasets[i].getMinInt());
        timpResultDataset.setX(datasets[i].getX().clone());
        timpResultDataset.setX2(datasets[i].getX2().clone());
      }

      try {
        String freeFilename =
            FileUtil.findFreeFileName(
                resultsfolder,
                resultsfolder.getName() + "_d" + (i + 1) + "_" + timpResultDataset.getDatasetName(),
                "timpres");
        timpResultDataset.setDatasetName(freeFilename);
        writeTo = resultsfolder.createData(freeFilename, "timpres");
        ObjectOutputStream stream = new ObjectOutputStream(writeTo.getOutputStream());
        stream.writeObject(timpResultDataset);
        stream.close();

        newResultsObject.getDatasets().get(i).setResultFile(new OutputFile());
        newResultsObject.getDatasets().get(i).getResultFile().setFilename(freeFilename);
        newResultsObject
            .getDatasets()
            .get(i)
            .getResultFile()
            .setPath(FileUtil.getRelativePath(project.getProjectDirectory(), resultsfolder));

      } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
      }
    }
    try {
      writeResultsXml(newResultsObject);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    }
  }
Exemple #15
0
  private void writeSummary(FileObject resultsfolder, String freeFilename) throws IOException {
    writeTo = resultsfolder.createData(freeFilename, "summary");
    BufferedWriter outputWriter = new BufferedWriter(new FileWriter(FileUtil.toFile(writeTo)));
    // TODO: Complete the summary here:
    outputWriter.append("Summary");
    outputWriter.newLine();
    //        outputWriter.append("Used dataset(s): ");
    //        for (int j = 0; j < datasets.length; j++) {
    //            DatasetTimp dataset = datasets[j];
    //            if (j > 0) {
    //                outputWriter.append(", ");
    //            }
    //            outputWriter.append(dataset.getDatasetName());
    //        }
    //        outputWriter.newLine();
    //        outputWriter.newLine();
    //        outputWriter.append("Used model(s): ");
    //        for (int j = 0; j < models.length; j++) {
    //            if (j > 0) {
    //                outputWriter.append(", ");
    //            }
    //            outputWriter.append(models[j].getDat().getModelName());
    //        }
    //        outputWriter.newLine();
    //        outputWriter.newLine();

    outputWriter.append("Number of iterations: ");
    outputWriter.append(String.valueOf(numIterations));
    outputWriter.newLine();
    outputWriter.newLine();

    outputWriter.append("R Call for the TIMP function \"initModel\": ");
    outputWriter.newLine();
    ArrayList<String> list = modelCalls;
    for (String string : list) {
      outputWriter.append(string);
      outputWriter.newLine();
    }
    outputWriter.newLine();
    outputWriter.append("R Call for the TIMP function \"fitModel\": ");
    outputWriter.newLine();
    outputWriter.write(fitModelCall);
    outputWriter.newLine();
    outputWriter.newLine();

    if (results != null) {

      outputWriter.append("Final residual standard error: ");
      outputWriter.append((new Formatter().format("%g", results[0].getRms())).toString());
      outputWriter.newLine();
      outputWriter.newLine();

      String[] slots = {
        "getKineticParameters",
        "getSpectralParameters",
        "getIrfpar",
        "getSpecdisppar",
        "getParmu",
        "getPartau",
        "getKinscal",
        "getPrel",
        "getJvec"
      };
      String[] slotsName = {
        "Kinetic parameters",
        "Spectral parameters",
        "Irf parameters",
        "Specdisppar",
        "Parmu",
        "Partau",
        "Kinscal",
        "Prel",
        "J vector"
      };
      double[] params = null;

      for (int k = 0; k < slots.length; k++) {
        try {
          try {
            for (int i = 0; i < results.length; i++) {
              // TODO: verify the next line
              // params = (double[]) results[i].getClass().getMethod(slots[k], new
              // Class[]{results[i].getClass().getClass()}).invoke(results[i], new
              // Object[]{results});
              params =
                  (double[])
                      results[i].getClass().getMethod(slots[k], null).invoke(results[i], null);
              if (params != null) {
                if (i == 0) {
                  outputWriter.newLine();
                  outputWriter.append("Estimated " + slotsName[k] + ": ");
                }
                outputWriter.append("Dataset" + (i + 1) + ": ");
                for (int j = 0; j < params.length / 2; j++) {
                  if (j > 0) {
                    outputWriter.append(", ");
                  }
                  outputWriter.append((new Formatter().format("%g", params[j])).toString());
                }
                outputWriter.newLine();
                outputWriter.append("Standard errors: ");
                for (int j = 0; j < params.length / 2; j++) {
                  if (j > 0) {
                    outputWriter.append(", ");
                  }
                  outputWriter.append(
                      (new Formatter().format("%g", params[j + params.length / 2])).toString());
                }
                outputWriter.newLine();
              }
            }
          } catch (IllegalAccessException ex) {
            Exceptions.printStackTrace(ex);
          } catch (IllegalArgumentException ex) {
            Exceptions.printStackTrace(ex);
          } catch (InvocationTargetException ex) {
            Exceptions.printStackTrace(ex);
          }
        } catch (NoSuchMethodException ex) {
          Exceptions.printStackTrace(ex);
        } catch (SecurityException ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    } else {
      outputWriter.newLine();
      outputWriter.append("Error: The analysis did not return valid results.");
      outputWriter.newLine();
      outputWriter.append("Try again with different parameters.");
    }
    outputWriter.close();
  }
  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;
  }