Пример #1
0
 private void assertHeader(FileObject fo, String header, String expectedMimeType)
     throws IOException {
   OutputStream os = fo.getOutputStream();
   os.write(header.getBytes());
   os.close();
   assertEquals("Header " + header + " wrongly resolved.", expectedMimeType, fo.getMIMEType());
 }
 private static void unZipFile(InputStream source, FileObject projectRoot) throws IOException {
   try {
     ZipInputStream str = new ZipInputStream(source);
     ZipEntry entry;
     while ((entry = str.getNextEntry()) != null) {
       if (entry.isDirectory()) {
         FileUtil.createFolder(projectRoot, entry.getName());
       } else {
         FileObject fo = FileUtil.createData(projectRoot, entry.getName());
         FileLock lock = fo.lock();
         try {
           OutputStream out = fo.getOutputStream(lock);
           try {
             FileUtil.copy(str, out);
           } finally {
             out.close();
           }
         } finally {
           lock.releaseLock();
         }
       }
     }
   } finally {
     source.close();
   }
 }
 private static void writeFile(ZipInputStream str, FileObject fo) throws IOException {
   OutputStream out = fo.getOutputStream();
   try {
     FileUtil.copy(str, out);
   } finally {
     out.close();
   }
 }
  private void writeIntoFile(FileObject file, String what) throws Exception {
    FileLock lock = file.lock();
    OutputStream out = file.getOutputStream(lock);

    try {
      out.write(what.getBytes());
    } finally {
      out.close();
      lock.releaseLock();
    }
  }
Пример #5
0
 public static final FileObject copyStringToFileObject(FileObject fo, String content)
     throws IOException {
   OutputStream os = fo.getOutputStream();
   try {
     InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
     FileUtil.copy(is, os);
     return fo;
   } finally {
     os.close();
   }
 }
Пример #6
0
 private void writeFile(String content, FileObject file) {
   OutputStream os = null;
   try {
     os = file.getOutputStream();
     os.write(content.getBytes("UTF-8"));
     os.close();
   } catch (FileAlreadyLockedException ex) {
     Exceptions.printStackTrace(ex);
   } catch (IOException ex) {
     Exceptions.printStackTrace(ex);
   } finally {
     try {
       os.close();
     } catch (IOException ex) {
       Exceptions.printStackTrace(ex);
     }
   }
 }
 /**
  * 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();
   }
 }
Пример #8
0
  private static File copyCompleteJarToTempDir() throws IOException {
    File tempFile = File.createTempFile("antlr4-complete", ".jar");
    tempFile.deleteOnExit();
    FileObject tempFileObject = FileUtil.toFileObject(tempFile);
    try (OutputStream outputStream = tempFileObject.getOutputStream()) {
      ClassLoader resourceLoader = CodeGenerator.class.getClassLoader();
      try (InputStream inputStream = resourceLoader.getResourceAsStream(ANTLR4_COMPLETE_JAR)) {
        byte[] buffer = new byte[1 << 16];
        while (true) {
          int read = inputStream.read(buffer);
          if (read < 0) {
            break;
          }

          outputStream.write(buffer, 0, read);
        }
      }
    }

    return tempFile;
  }
Пример #9
0
 /**
  * Stores the Ant deployment properties in the specified file.
  *
  * @param create if false the deployment properties file won't be created if it does not exist.
  * @throws IOException if a problem occurs.
  */
 public void storeAntDeploymentProperties(File file, boolean create) throws IOException {
   if (!create && !file.exists()) {
     return;
   }
   EditableProperties antProps = new EditableProperties(false);
   antProps.setProperty("tomcat.home", homeDir.getAbsolutePath()); // NOI18N
   antProps.setProperty("tomcat.url", getWebUrl()); // NOI18N
   antProps.setProperty("tomcat.username", getUsername()); // NOI18N
   file.createNewFile();
   FileObject fo = FileUtil.toFileObject(file);
   FileLock lock = fo.lock();
   try {
     OutputStream os = fo.getOutputStream(lock);
     try {
       antProps.store(os);
     } finally {
       os.close();
     }
   } finally {
     lock.releaseLock();
   }
 }
 private static void filterProjectXML(FileObject fo, ZipInputStream str, String name)
     throws IOException {
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     FileUtil.copy(str, baos);
     Document doc =
         XMLUtil.parse(
             new InputSource(new ByteArrayInputStream(baos.toByteArray())),
             false,
             false,
             null,
             null);
     NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
     if (nl != null) {
       for (int i = 0; i < nl.getLength(); i++) {
         Element el = (Element) nl.item(i);
         if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
           NodeList nl2 = el.getChildNodes();
           if (nl2.getLength() > 0) {
             nl2.item(0).setNodeValue(name);
           }
           break;
         }
       }
     }
     OutputStream out = fo.getOutputStream();
     try {
       XMLUtil.write(doc, out, "UTF-8");
     } finally {
       out.close();
     }
   } catch (Exception ex) {
     Exceptions.printStackTrace(ex);
     writeFile(str, fo);
   }
 }
Пример #11
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);
    }
  }
  /** @throws java.lang.Exception */
  @RandomlyFails
  public void testDocumentModification() throws Exception {

    // 1) register tasks and parsers
    MockServices.setServices(MockMimeLookup.class, MyScheduler.class);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(2);
    final CountDownLatch latch3 = new CountDownLatch(3);
    final int[] fooParser = {1};
    final int[] fooParserResult = {1};
    final int[] fooEmbeddingProvider = {1};
    final int[] fooTask = {1};
    final int[] booParser = {1};
    final int[] booParserResult = {1};
    final int[] booTask = {1};
    final TestComparator test =
        new TestComparator(
            "1 - reschedule all schedulers\n"
                + "foo get embeddings 1 (Snapshot 1), \n"
                + "Snapshot 1: Toto je testovaci file, na kterem se budou delat hnusne pokusy!!!, \n"
                + "Snapshot 2: stovaci fi, \n"
                + "foo parse 1 (Snapshot 1, FooParserResultTask 1, SourceModificationEvent -1:-1), \n"
                + "foo get result 1 (FooParserResultTask 1), \n"
                + "foo task 1 (FooResult 1 (Snapshot 1), SchedulerEvent 1), \n"
                + "foo invalidate 1, \n"
                + "boo parse 1 (Snapshot 2, BooParserResultTask 1, SourceModificationEvent -1:-1), \n"
                + "boo get result 1 (BooParserResultTask 1), \n"
                + "boo task 1 (BooResult 1 (Snapshot 2), SchedulerEvent 1), \n"
                + "boo invalidate 1, \n"
                + "2 - insert 14 chars on offset 22\n"
                + "foo get embeddings 1 (Snapshot 3), \n"
                + "Snapshot 3: Toto je testovaci file (druha verze), na kterem se budou delat hnusne pokusy!!!, \n"
                + "Snapshot 4: stovaci fi, \n"
                + "foo parse 1 (Snapshot 3, FooParserResultTask 1, SourceModificationEvent 18:37), \n"
                + "foo get result 1 (FooParserResultTask 1), \n"
                + "foo task 1 (FooResult 2 (Snapshot 3), SchedulerEvent 1), \n"
                + "foo invalidate 2, \n"
                + "boo parse 1 (Snapshot 4, BooParserResultTask 1, SourceModificationEvent -1:-1), \n"
                + // !! source unchanged
                "boo get result 1 (BooParserResultTask 1), \n"
                + "boo task 1 (BooResult 2 (Snapshot 4), SchedulerEvent 1), \n"
                + "boo invalidate 2, \n"
                + "3 - remove 5 chars on offset 44\n"
                + "foo get embeddings 1 (Snapshot 5), \n"
                + "Snapshot 5: Toto je testovaci file (druha verze), na ktee budou delat hnusne pokusy!!!, \n"
                + "Snapshot 6: stovaci fi, \n"
                + "foo parse 1 (Snapshot 5, FooParserResultTask 1, SourceModificationEvent 41:45), \n"
                + "foo get result 1 (FooParserResultTask 1), \n"
                + "foo task 1 (FooResult 3 (Snapshot 5), SchedulerEvent 2), \n"
                + "foo invalidate 3, \n"
                + "boo parse 1 (Snapshot 6, BooParserResultTask 1, SourceModificationEvent -1:-1), \n"
                + // !! source unchanged
                "boo get result 1 (BooParserResultTask 1), \n"
                + "boo task 1 (BooResult 3 (Snapshot 6), SchedulerEvent 2), \n"
                + "boo invalidate 3, \n"
                + "4 - end\n");

    MockMimeLookup.setInstances(
        MimePath.get("text/foo"),
        new ParserFactory() {
          public Parser createParser(Collection<Snapshot> snapshots2) {
            return new Parser() {

              private Snapshot last;
              private int i = fooParser[0]++;

              public void parse(Snapshot snapshot, Task task, SourceModificationEvent event)
                  throws ParseException {
                test.check(
                    "foo parse "
                        + i
                        + " (Snapshot "
                        + test.get(snapshot)
                        + ", "
                        + task
                        + ", "
                        + event
                        + "), \n");
                last = snapshot;
              }

              public Result getResult(Task task) throws ParseException {
                test.check("foo get result " + i + " (" + task + "), \n");
                return new Result(last) {

                  public void invalidate() {
                    test.check("foo invalidate " + i + ", \n");
                  }

                  private int i = fooParserResult[0]++;

                  @Override
                  public String toString() {
                    return "FooResult " + i + " (Snapshot " + test.get(getSnapshot()) + ")";
                  }
                };
              }

              public void cancel() {}

              public void addChangeListener(ChangeListener changeListener) {}

              public void removeChangeListener(ChangeListener changeListener) {}
            };
          }
        },
        new TaskFactory() {
          public Collection<SchedulerTask> create(Snapshot snapshot) {
            return Arrays.asList(
                new SchedulerTask[] {
                  new EmbeddingProvider() {

                    private int i = fooEmbeddingProvider[0]++;

                    public List<Embedding> getEmbeddings(Snapshot snapshot) {
                      test.check(
                          "foo get embeddings " + i + " (Snapshot " + test.get(snapshot) + "), \n");
                      test.check(
                          "Snapshot " + test.get(snapshot) + ": " + snapshot.getText() + ", \n");
                      Embedding embedding = snapshot.create(10, 10, "text/boo");
                      test.get(embedding.getSnapshot());
                      test.check(
                          "Snapshot "
                              + test.get(embedding.getSnapshot())
                              + ": "
                              + embedding.getSnapshot().getText()
                              + ", \n");
                      return Arrays.asList(new Embedding[] {embedding});
                    }

                    public int getPriority() {
                      return 10;
                    }

                    public void cancel() {}
                  },
                  new ParserResultTask() {

                    public void run(Result result, SchedulerEvent event) {
                      test.check(
                          "foo task "
                              + i
                              + " ("
                              + result
                              + ", SchedulerEvent "
                              + test.get(event)
                              + "), \n");
                    }

                    public int getPriority() {
                      return 100;
                    }

                    public Class<? extends Scheduler> getSchedulerClass() {
                      return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
                    }

                    public void cancel() {}

                    private int i = fooTask[0]++;

                    @Override
                    public String toString() {
                      return "FooParserResultTask " + i;
                    }
                  }
                });
          }
        });
    MockMimeLookup.setInstances(
        MimePath.get("text/boo"),
        new ParserFactory() {
          public Parser createParser(Collection<Snapshot> snapshots2) {
            return new Parser() {

              private Snapshot last;
              private int i = booParser[0]++;

              public void parse(Snapshot snapshot, Task task, SourceModificationEvent event)
                  throws ParseException {
                test.check(
                    "boo parse "
                        + i
                        + " (Snapshot "
                        + test.get(snapshot)
                        + ", "
                        + task
                        + ", "
                        + event
                        + "), \n");
                last = snapshot;
              }

              public Result getResult(Task task) throws ParseException {
                test.check("boo get result " + i + " (" + task + "), \n");
                return new Result(last) {
                  public void invalidate() {
                    test.check("boo invalidate " + i + ", \n");
                    latch1.countDown();
                    latch2.countDown();
                    latch3.countDown();
                  }

                  private int i = booParserResult[0]++;

                  @Override
                  public String toString() {
                    return "BooResult " + i + " (Snapshot " + test.get(getSnapshot()) + ")";
                  }
                };
              }

              public void cancel() {}

              public void addChangeListener(ChangeListener changeListener) {}

              public void removeChangeListener(ChangeListener changeListener) {}
            };
          }
        },
        new TaskFactory() {
          public Collection<SchedulerTask> create(Snapshot snapshot) {
            return Arrays.asList(
                new SchedulerTask[] {
                  new ParserResultTask() {

                    private int i = booTask[0]++;

                    public void run(Result result, SchedulerEvent event) {
                      test.check(
                          "boo task "
                              + i
                              + " ("
                              + result
                              + ", SchedulerEvent "
                              + test.get(event)
                              + "), \n");
                    }

                    public int getPriority() {
                      return 150;
                    }

                    public Class<? extends Scheduler> getSchedulerClass() {
                      return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
                    }

                    public void cancel() {}

                    @Override
                    public String toString() {
                      return "BooParserResultTask " + i;
                    }
                  }
                });
          }
        });

    // 2) create source file
    clearWorkDir();
    FileObject workDir = FileUtil.toFileObject(getWorkDir());
    FileObject testFile = FileUtil.createData(workDir, "bla.foo");
    FileUtil.setMIMEType("foo", "text/foo");
    OutputStream outputStream = testFile.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    writer.append("Toto je testovaci file, na kterem se budou delat hnusne pokusy!!!");
    writer.close();
    Source source = Source.create(testFile);
    Document document = source.getDocument(true);
    document.putProperty("mimeType", "text/foo");
    document.putProperty(Language.class, new ALanguageHierarchy().language());
    TokenHierarchy th = TokenHierarchy.get(document);
    TokenSequence ts = th.tokenSequence();
    ts.tokenCount();
    test.check("1 - reschedule all schedulers\n");

    // 3) shcedulle CurrentDocumentScheduler
    for (Scheduler scheduler : Schedulers.getSchedulers())
      if (scheduler instanceof CurrentDocumentScheduler)
        ((CurrentDocumentScheduler) scheduler).schedule(source);
    latch1.await();
    test.check("2 - insert 14 chars on offset 22\n");

    document.insertString(22, " (druha verze)", null);
    latch2.await();
    test.check("3 - remove 5 chars on offset 44\n");

    document.remove(44, 5);
    latch3.await();
    test.check("4 - end\n");

    assertEquals("", test.getResult());
  }
Пример #13
0
  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) {;
        }
      }
    }
  }