示例#1
1
  /** INTERNAL: Creates a directory with some nested directories and some files. */
  protected File createNestedDirectory() throws IOException {
    // Structure:
    //
    // FILEUTILS_DIR1
    //   FILEUTILS_DIR2a
    //     FILEUTILS_DIR3
    //       temp_file
    //   FILEUTILS_DIR2b
    //     temp_file1
    //     temp_file2

    // DIR1
    File dir1 = new File(testdir, "FILEUTILS_DIR1");
    dir1.mkdir();

    // DIR1/DIR2A
    File dir2a = new File(dir1, "FILEUTILS_DIR2a");
    dir2a.mkdir();

    // DIR1/DIR2A/DIR3
    File dir3 = new File(dir2a, "FILEUTILS_DIR3");
    dir3.mkdir();
    File file3 = File.createTempFile("FILEUTILS", "TEST", dir3);

    // DIR1/DIR2B
    File dir2b = new File(dir1, "FILEUTILS_DIR2b");
    dir2b.mkdir();
    File file2b1 = File.createTempFile("FILEUTILS", "TEST", dir2b);
    File file2b2 = File.createTempFile("FILEUTILS", "TEST", dir2b);

    // Return the top level directory
    return dir1;
  }
示例#2
1
文件: Handler.java 项目: blarty/glyph
  /** @see java.net.URLStreamHandler#openConnection(URL) */
  protected URLConnection openConnection(URL u) throws IOException {

    try {

      URL otherURL = new URL(u.getFile());
      String host = otherURL.getHost();
      String protocol = otherURL.getProtocol();
      int port = otherURL.getPort();
      String file = otherURL.getFile();
      String query = otherURL.getQuery();
      // System.out.println("Trying to load: " + u.toExternalForm());
      String internalFile = null;
      if (file.indexOf("!/") != -1) {
        internalFile = file.substring(file.indexOf("!/") + 2);
        file = file.substring(0, file.indexOf("!/"));
      }
      URL subURL = new URL(protocol, host, port, file);
      File newFile;
      if (cacheList.containsKey(subURL.toExternalForm())) {
        newFile = cacheList.get(subURL.toExternalForm());
      } else {
        InputStream is = (InputStream) subURL.getContent();
        String update = subURL.toExternalForm().replace(":", "_");
        update = update.replace("/", "-");
        File f = File.createTempFile("pack", update);
        f.deleteOnExit();
        FileOutputStream fostream = new FileOutputStream(f);
        copyStream(new BufferedInputStream(is), fostream);

        // Unpack
        newFile = File.createTempFile("unpack", update);
        newFile.deleteOnExit();
        fostream = new FileOutputStream(newFile);
        BufferedOutputStream bos = new BufferedOutputStream(fostream, 50 * 1024);
        JarOutputStream jostream = new JarOutputStream(bos);
        Unpacker unpacker = Pack200.newUnpacker();
        long start = System.currentTimeMillis();

        unpacker.unpack(f, jostream);
        printMessage(
            "Unpack of " + update + " took " + (System.currentTimeMillis() - start) + "ms");
        jostream.close();
        fostream.close();
        cacheList.put(subURL.toExternalForm(), newFile);
      }
      if (internalFile != null) {

        URL directoryURL = new URL("jar:" + newFile.toURL().toExternalForm() + "!/" + internalFile);
        printMessage("Using DirectoryURL:" + directoryURL);
        return directoryURL.openConnection();
      } else return newFile.toURL().openConnection();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    printMessage("Returning null for: " + u.toExternalForm());
    return null;
  }
  @BeforeTest
  void setupBuilder() throws IOException {
    tempSamFileChrM_O = File.createTempFile("CollectGcBias", ".bam", TEST_DIR);
    tempSamFileAllChr = File.createTempFile("CollectGcBias", ".bam", TEST_DIR);
    tempSamFileChrM_O.deleteOnExit();
    tempSamFileAllChr.deleteOnExit();

    final File tempSamFileUnsorted = File.createTempFile("CollectGcBias", ".bam", TEST_DIR);
    tempSamFileUnsorted.deleteOnExit();

    final SAMFileHeader header = new SAMFileHeader();

    try {
      header.setSequenceDictionary(SAMSequenceDictionaryExtractor.extractDictionary(dict));
      header.setSortOrder(SAMFileHeader.SortOrder.unsorted);
    } catch (final SAMException e) {
      e.printStackTrace();
    }

    // build different levels to put into the same bam file for testing multi level collection
    setupTest1(
        1,
        readGroupId1,
        readGroupRecord1,
        sample1,
        library1,
        header,
        setBuilder1); // Sample 1, Library 1, RG 1
    setupTest1(
        2,
        readGroupId2,
        readGroupRecord2,
        sample1,
        library2,
        header,
        setBuilder2); // Sample 1, Library 2, RG 2
    setupTest1(
        3,
        readGroupId3,
        readGroupRecord3,
        sample2,
        library3,
        header,
        setBuilder3); // Sample 2, Library 3, RG 3

    // build one last readgroup for comparing that window count stays the same whether you use all
    // contigs or not
    setupTest2(1, readGroupId1, readGroupRecord1, sample1, library1, header, setBuilder4);

    final List<SAMRecordSetBuilder> test1Builders = new ArrayList<SAMRecordSetBuilder>();
    test1Builders.add(setBuilder1);
    test1Builders.add(setBuilder2);
    test1Builders.add(setBuilder3);

    final List<SAMRecordSetBuilder> test2Builders = new ArrayList<SAMRecordSetBuilder>();
    test2Builders.add(setBuilder4);

    tempSamFileChrM_O = build(test1Builders, tempSamFileUnsorted, header);
    tempSamFileAllChr = build(test2Builders, tempSamFileUnsorted, header);
  }
 @Before
 public void setUp() throws IOException {
   firstFastqFile = File.createTempFile("interleaveFastqTest", ".fq.gz");
   secondFastqFile = File.createTempFile("interleaveFastqTest", ".fq.gz");
   pairedFile = File.createTempFile("interleaveFastqTest", ".fq");
   unpairedFile = File.createTempFile("interleaveFastqTest", ".fq");
 }
  /**
   * testStringFunction
   *
   * @throws IOException
   */
  public void testBackgroundProposals() throws IOException {
    File bundleFile = File.createTempFile("editor_unit_tests", "rb");
    bundleFile.deleteOnExit();

    BundleElement bundleElement = new BundleElement(bundleFile.getAbsolutePath());
    bundleElement.setDisplayName("Editor Unit Tests");

    File f = File.createTempFile("snippet", "rb");
    SnippetElement se =
        createSnippet(f.getAbsolutePath(), "background-color-template", "background", "source.css");
    bundleElement.addChild(se);
    BundleManager.getInstance().addBundle(bundleElement);

    // note template is interleaved into proposals
    this.checkProposals(
        "contentAssist/background.css",
        true,
        true,
        "backface-visibility",
        "background",
        "background-attachment",
        "background-clip",
        "background-color",
        "background-color-template",
        "background-image",
        "background-origin",
        "background-position",
        "background-position-x",
        "background-position-y",
        "background-repeat",
        "background-size");

    BundleManager.getInstance().unloadScript(f);
  }
示例#6
0
  /**
   * tests case when Main-Class is not in the zip launched but in another zip referenced by
   * Class-Path
   *
   * @throws Exception in case of troubles
   */
  public void test_main_class_in_another_zip() throws Exception {
    File fooZip = File.createTempFile("hyts_", ".zip");
    File barZip = File.createTempFile("hyts_", ".zip");
    fooZip.deleteOnExit();
    barZip.deleteOnExit();

    // create the manifest
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
    att.put(Attributes.Name.CLASS_PATH, fooZip.getName());

    File resources = Support_Resources.createTempFolder();

    ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip));
    zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
    zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
    zoutFoo.close();

    ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(barZip));
    zoutBar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zoutBar);

    zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
    zoutBar.write(getResource(resources, "hyts_Bar.ser"));
    zoutBar.close();

    String[] args = new String[] {"-jar", barZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing JAR : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
示例#7
0
  public static File tmpdir() {
    try {
      File file = null;
      try {
        file = File.createTempFile("temp", "dir");
      } catch (Throwable e) {
        // Use a local tmp directory
        final File tmp = new File("tmp");
        if (!tmp.exists() && !tmp.mkdirs()) {
          throw new IOException("Failed to create local tmp directory: " + tmp.getAbsolutePath());
        }

        file = File.createTempFile("temp", "dir", tmp);
      }

      if (!file.delete()) {
        throw new IOException("Failed to create temp dir. Delete failed");
      }

      mkdir(file);
      deleteOnExit(file);

      return file;

    } catch (IOException e) {
      throw new FileRuntimeException(e);
    }
  }
 /**
  * Test the creation of a profile which depends on another profile. Doesn't use the {@link
  * ProfileMother#createXmiDependentProfile(File, ProfileMother.DependencyCreator, File, String)}
  * method, but, it serves as good executable documentation of how this is done as a whole.
  *
  * @throws IOException When saving the profile models fails.
  * @throws UmlException When something in the model subsystem goes wrong.
  */
 public void testXmiDependentProfile() throws IOException, UmlException {
   Object model = mother.createSimpleProfileModel();
   File file = File.createTempFile("simple-profile", ".xmi");
   mother.saveProfileModel(model, file);
   XmiReader xmiReader = Model.getXmiReader();
   xmiReader.addSearchPath(file.getParent());
   InputSource pIs = new InputSource(file.toURI().toURL().toExternalForm());
   pIs.setPublicId(file.getName());
   Collection simpleModelTopElements = xmiReader.parse(pIs, true);
   Object model2 = mother.createSimpleProfileModel();
   Object theClass = Model.getCoreFactory().buildClass("TheClass", model2);
   Collection stereotypes = getFacade().getStereotypes(simpleModelTopElements.iterator().next());
   Object stereotype = stereotypes.iterator().next();
   Model.getCoreHelper().addStereotype(theClass, stereotype);
   File dependentProfileFile = File.createTempFile("dependent-profile", ".xmi");
   mother.saveProfileModel(model2, dependentProfileFile);
   assertTrue(
       "The file to where the file was supposed to be saved " + "doesn't exist.",
       dependentProfileFile.exists());
   assertStringInLineOfFile(
       "The name of the file which contains the profile "
           + "from which the dependent profile depends must occur in the "
           + "file.",
       file.getName(),
       dependentProfileFile);
   // Clean up our two models and the extent that we read profile in to
   Model.getUmlFactory().delete(model);
   Model.getUmlFactory().delete(model2);
   Model.getUmlFactory().deleteExtent(simpleModelTopElements.iterator().next());
 }
 @SuppressFBWarnings(
     value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
     justification = "createTempFile will fail anyway if there is a problem with mkdirs")
 private String createLocalSocketAddress() throws IOException {
   String name;
   if (temp != null) {
     temp.mkdirs();
   }
   if (OsUtils.isUNIX()) {
     File socket = File.createTempFile("ssh", "", temp);
     if (socket.getAbsolutePath().length() >= /*UNIX_PATH_MAX*/ 108) {
       LOGGER.log(
           Level.WARNING,
           "Cannot use {0} due to UNIX_PATH_MAX; falling back to system temp dir",
           socket);
       socket = File.createTempFile("ssh", "");
     }
     FileUtils.deleteQuietly(socket);
     name = socket.getAbsolutePath();
   } else {
     File socket = File.createTempFile("ssh", "", temp);
     FileUtils.deleteQuietly(socket);
     name = "\\\\.\\pipe\\" + socket.getName();
   }
   return name;
 }
示例#10
0
    @Override
    public void export(
        MolgenisRequest request,
        String fileName,
        TupleTable tupleTable,
        int totalPages,
        int currentPage)
        throws TableException, IOException {
      try {
        final File tempDir = new File(System.getProperty("java.io.tmpdir"));
        final File spssFile = File.createTempFile("spssExport", ".sps", tempDir);
        final File spssCsvFile = File.createTempFile("csvSpssExport", ".csv", tempDir);
        // TODO: instruction .txt file.
        final File zipExport = File.createTempFile("spssExport", ".zip", tempDir);

        final FileOutputStream spssFileStream = new FileOutputStream(spssFile);
        final FileOutputStream spssCsvFileStream = new FileOutputStream(spssCsvFile);
        final SPSSExporter spssExporter = new SPSSExporter(tupleTable);
        spssExporter.export(spssCsvFileStream, spssFileStream, spssCsvFile.getName());

        spssCsvFileStream.close();
        spssFileStream.close();
        ZipUtils.compress(
            Arrays.asList(spssFile, spssCsvFile), zipExport, DirectoryStructure.EXCLUDE_DIR);
        HeaderHelper.setHeader(
            request.getResponse(), "application/octet-stream", fileName + ".zip");
        exportFile(zipExport, request.getResponse());
      } catch (Exception e) {
        throw new TableException(e);
      }
    }
示例#11
0
 @Test
 public void testZipAndUnzipDirectory() throws IOException {
   File basedir = File.createTempFile(ZipUtils.class.getSimpleName(), ".tmp");
   basedir.delete();
   assertTrue("Could not create temporary base directory.", basedir.mkdir());
   for (int i = 0; i < 5; i++) {
     createSubDirWithFiles(basedir, i);
   }
   File zipFile = File.createTempFile(ZipUtils.class.getSimpleName(), ".zip");
   ZipArchiveOutputStream zipOutputStream =
       new ZipArchiveOutputStream(new FileOutputStream(zipFile));
   ZipUtils.addFilesToZipRecursively("mybase", basedir, null, zipOutputStream);
   zipOutputStream.close();
   final File unzipBase = File.createTempFile(ZipUtils.class.getSimpleName(), ".unzipped");
   ZipUtils.unzip(zipFile, unzipBase);
   IOUtils.processFiles(
       unzipBase,
       new FileProcessor() {
         public void process(File file) {
           try {
             assertEquals(
                 IOUtils.getFileIdentifier(unzipBase, file), FileUtils.readFileToString(file));
           } catch (IOException e) {
             throw new RuntimeException("Could not process file.", e);
           }
         }
       },
       null);
 }
示例#12
0
文件: TestMain.java 项目: scr/pig
  @Test
  public void testRun_setsErrorThrowableForParamSubstitution() {
    File outputFile = null;
    try {
      String filename =
          this.getClass().getSimpleName() + "_" + "testRun_setsErrorThrowableForParamSubstitution";
      outputFile = File.createTempFile(filename, ".out");
      outputFile.delete();

      File scriptFile = File.createTempFile(filename, ".pig");
      BufferedWriter bw = new BufferedWriter(new FileWriter(scriptFile));
      bw.write("a = load '$NOEXIST';\n");
      bw.write("b = group a by $0\n");
      bw.write("c = foreach b generate group, COUNT(a) as cnt;\n");
      bw.write("store c into 'out'\n");
      bw.close();

      Main.run(new String[] {"-x", "local", scriptFile.getAbsolutePath()}, null);
      PigStats stats = PigStats.get();

      Throwable t = stats.getErrorThrowable();
      assertTrue(t instanceof IOException);

      Throwable cause = t.getCause();
      assertTrue(cause instanceof ParameterSubstitutionException);

      ParameterSubstitutionException pse = (ParameterSubstitutionException) cause;
      assertTrue(pse.getMessage().contains("NOEXIST"));
    } catch (Exception e) {
      log.error("Encountered exception", e);
      fail("Encountered Exception");
    }
  }
示例#13
0
  public static Map<String, Object> createSslConfig(
      boolean useClientCert, boolean trustStore, Mode mode, File trustStoreFile, String certAlias)
      throws IOException, GeneralSecurityException {
    Map<String, X509Certificate> certs = new HashMap<String, X509Certificate>();
    File keyStoreFile;
    Password password;

    if (mode == Mode.SERVER) password = new Password("ServerPassword");
    else password = new Password("ClientPassword");

    Password trustStorePassword = new Password("TrustStorePassword");

    if (useClientCert) {
      keyStoreFile = File.createTempFile("clientKS", ".jks");
      KeyPair cKP = generateKeyPair("RSA");
      X509Certificate cCert = generateCertificate("CN=localhost, O=client", cKP, 30, "SHA1withRSA");
      createKeyStore(keyStoreFile.getPath(), password, "client", cKP.getPrivate(), cCert);
      certs.put(certAlias, cCert);
    } else {
      keyStoreFile = File.createTempFile("serverKS", ".jks");
      KeyPair sKP = generateKeyPair("RSA");
      X509Certificate sCert = generateCertificate("CN=localhost, O=server", sKP, 30, "SHA1withRSA");
      createKeyStore(keyStoreFile.getPath(), password, password, "server", sKP.getPrivate(), sCert);
      certs.put(certAlias, sCert);
    }

    if (trustStore) {
      createTrustStore(trustStoreFile.getPath(), trustStorePassword, certs);
    }

    Map<String, Object> sslConfig =
        createSslConfig(mode, keyStoreFile, password, password, trustStoreFile, trustStorePassword);
    return sslConfig;
  }
  public static void openAttachment(
      final Project project, String name, EntityRef parent, int size) {
    try {
      final File file;
      boolean agmLink = name.endsWith(".agmlink");
      if (agmLink) {
        // for the file to open correctly, there must be no trailing extension
        file = File.createTempFile("tmp", "_" + name.replaceFirst("\\.agmlink$", ""));
      } else {
        file = File.createTempFile("tmp", "_" + name);
      }
      final Runnable openFile =
          new Runnable() {
            @Override
            public void run() {
              String url =
                  VirtualFileManager.constructUrl(
                      LocalFileSystem.PROTOCOL,
                      FileUtil.toSystemIndependentName(file.getAbsolutePath()));
              final VirtualFile virtualFile =
                  VirtualFileManager.getInstance().refreshAndFindFileByUrl(url);
              UIUtil.invokeLaterIfNeeded(
                  new Runnable() {
                    public void run() {
                      if (virtualFile != null) {
                        FileEditor[] editors =
                            project
                                .getComponent(FileEditorManager.class)
                                .openFile(virtualFile, true);
                        if (editors.length > 0) {
                          return;
                        }

                        FileType type =
                            FileTypeManager.getInstance()
                                .getKnownFileTypeOrAssociate(virtualFile, project);
                        if (type instanceof INativeFileType
                            && ((INativeFileType) type)
                                .openFileInAssociatedApplication(project, virtualFile)) {
                          return;
                        }
                      }
                      Messages.showWarningDialog(
                          "No editor seems to be associated with this file type. Try to download and open the file manually.",
                          "Not Supported");
                    }
                  });
            }
          };
      if (agmLink) {
        ProgressManager.getInstance()
            .run(new AttachmentAgmLinkDownloadTask(project, file, name, size, parent, openFile));
      } else {
        ProgressManager.getInstance()
            .run(new AttachmentDownloadTask(project, file, name, size, parent, openFile));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
示例#15
0
  public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params)
      throws DjatokaException {
    File in;
    // Copy to tmp file
    try {
      String cacheDir = OpenURLJP2KService.getCacheDir();
      if (cacheDir != null) {
        in = File.createTempFile("tmp", ".pdf", new File(cacheDir));
      } else {
        in = File.createTempFile("tmp", ".pdf");
      }
      FileOutputStream fos = new FileOutputStream(in);
      in.deleteOnExit();
      IOUtils.copyStream(input, fos);
    } catch (IOException e) {
      logger.error(e, e);
      throw new DjatokaException(e);
    }

    BufferedImage bi = process(in.getAbsolutePath(), params);

    if (in != null) {
      in.delete();
    }

    return bi;
  }
  @Test
  public void testRedirectionCycle() throws IOException, XMLStreamException {
    // source dump
    File tmpSrcDump = File.createTempFile("wiki-src-dump", "xml");
    File tmpTargetDump = File.createTempFile("wiki-target-dump", "xml");

    // base structure - "<mediawiki><page><title></title><id><id></page></mediawiki>"
    BufferedWriter bw = new BufferedWriter(new FileWriter(tmpSrcDump));
    bw.write(
        "<mediawiki>"
            + "<page>"
            + "<title>Test1</title>"
            + "<id>1</id>"
            + "</page>"
            + "<page>"
            + "<title>Test2</title>"
            + "<id>2</id>"
            + "</page>"
            + "<page>"
            + "<title>Test3</title>"
            + "<id>3</id>"
            + "</page>"
            + "</mediawiki>");
    bw.close();

    bw = new BufferedWriter(new FileWriter(tmpTargetDump));
    bw.write(
        "<mediawiki>"
            + "<page>"
            + "<title>Test1</title>"
            + "<id>1</id>"
            + "<redirect/>"
            + "<revision>"
            + "<id>1234556</id>"
            + "<text xml:space=\"preserve\">#REDIRECT [[Test3]] {{R from CamelCase}}</text>"
            + "</revision>"
            + "</page>"
            + "<page>"
            + "<title>NEW_Test2</title>"
            + "<id>2</id>"
            + "</page>"
            + "<page>"
            + "<title>Test3</title>"
            + "<id>3</id>"
            + "<redirect/>"
            + "<revision>"
            + "<id>1234556</id>"
            + "<text xml:space=\"preserve\">#REDIRECT [[Test1]] {{R from CamelCase}}</text>"
            + "</revision>"
            + "</page>"
            + "</mediawiki>");
    bw.close();
    Map<String, String> hshResults = WikipediaRevisionMapper.map(tmpSrcDump, tmpTargetDump);
    assertEquals(3, hshResults.size());
    // Test1 REDIRECTS TO Test3, but since it forms a cycle, Test1 is mapped to itself
    assertEquals(true, !hshResults.get("Test1").equals("Test3"));

    tmpSrcDump.delete();
    tmpTargetDump.delete();
  }
  private void updateVersionFile(final Wagon wagon)
      throws IOException, TransferFailedException, ResourceDoesNotExistException,
          AuthorizationException {

    // update the version.txt accordingly
    final File versionOldFile = File.createTempFile("version-old", "txt");
    final File versionNewFile = File.createTempFile("version-new", "txt");
    wagon.get("version.txt", versionOldFile);

    boolean updated = false;

    // look for our artifactId entry
    final BufferedReader reader = new BufferedReader(new FileReader(versionOldFile));
    final BufferedWriter writer = new BufferedWriter(new FileWriter(versionNewFile));
    for (String line = reader.readLine(); null != line; line = reader.readLine()) {
      if (line.equals(project.getArtifactId())) {
        updateArtifactEntry(reader, writer);
        updated = true;
      } else {
        // line remains the same
        writer.write(line);
        writer.newLine();
      }
    }
    if (!updated) {
      writer.newLine();
      updateArtifactEntry(reader, writer);
    }
    reader.close();
    writer.close();
    wagon.put(versionNewFile, "version.txt");
  }
  @SuppressWarnings("ResultOfMethodCallIgnored")
  @Test
  public void testUnchangedPageEntries() throws IOException, XMLStreamException {
    // source dump
    File tmpSrcDump = File.createTempFile("wiki-src-dump", "xml");
    File tmpTargetDump = File.createTempFile("wiki-target-dump", "xml");

    // base structure - "<mediawiki><page><title></title><id><id></page></mediawiki>"
    BufferedWriter bw = new BufferedWriter(new FileWriter(tmpSrcDump));
    bw.write(
        "<mediawiki><page><title>Test1</title><id>1</id></page><page><title>Test2</title><id>2</id></page></mediawiki>");
    bw.close();

    bw = new BufferedWriter(new FileWriter(tmpTargetDump));
    bw.write(
        "<mediawiki><page><title>Test1</title><id>1</id></page><page><title>Test2</title><id>2</id></page></mediawiki>");
    bw.close();

    // default diff will also include all unchanged entries
    Map<String, String> hshResults = WikipediaRevisionMapper.map(tmpSrcDump, tmpTargetDump);
    assertEquals(2, hshResults.size());

    // setting the flag to false will include unchanged entries
    hshResults = WikipediaRevisionMapper.map(tmpSrcDump, tmpTargetDump, false);
    assertEquals(0, hshResults.size());
    // remove tmp files
    tmpSrcDump.delete();
    tmpTargetDump.delete();
  }
        @Override
        public void onClick(View v) {
          recorder = new MediaRecorder();
          String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
          File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestData");
          if (!sampleDir.exists()) {
            sampleDir.mkdirs();
          }

          String file_name = "Record";
          try {
            if (spinType == "mp3") path = File.createTempFile(file_name + out, ".mp3", sampleDir);
            else path = File.createTempFile(file_name + out, ".wav", sampleDir);

          } catch (IOException e) {
            e.printStackTrace();
          }

          // path=new File(Environment.getExternalStorageDirectory(),"myRecording.3gpp");
          resetRecorder();
          try {
            recorder.start();
            Toast.makeText(MainActivity.this, "Start Record", Toast.LENGTH_SHORT).show();
            start.setEnabled(false);
            stop.setEnabled(true);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
 /**
  * Creates a process builder for the application, using the config, logging, and system
  * properties.
  */
 ProcessBuilder createProcessBuilder() throws Exception {
   /* Create the application configuration file */
   File configFile = File.createTempFile("SimpleApp", "config");
   OutputStream configOut = new FileOutputStream(configFile);
   config.store(configOut, null);
   configOut.close();
   /* Create the logging configuration file */
   File loggingFile = File.createTempFile("SimpleApp", "logging");
   OutputStream loggingOut = new FileOutputStream(loggingFile);
   logging.store(loggingOut, null);
   loggingOut.close();
   /* Create the command line for running the Kernel */
   List<String> command = new ArrayList<String>();
   command.add(System.getProperty("java.home") + "/bin/java");
   command.add("-cp");
   command.add(System.getProperty("java.class.path"));
   command.add("-Djava.util.logging.config.file=" + loggingFile);
   command.add("-Djava.library.path=" + System.getProperty("java.library.path"));
   Enumeration<?> names = system.propertyNames();
   while (names.hasMoreElements()) {
     Object name = names.nextElement();
     command.add("-D" + name + "=" + system.get(name));
   }
   command.add("com.sun.sgs.impl.kernel.Kernel");
   command.add(configFile.toURI().toURL().getPath());
   /* Return the process builder */
   return new ProcessBuilder(command);
 }
示例#21
0
  @Test
  public void testBamIntegers() throws IOException {
    final List<String> errorMessages = new ArrayList<String>();
    final SamReader bamReader = SamReaderFactory.makeDefault().open(BAM_INPUT);
    final File bamOutput = File.createTempFile("test", ".bam");
    final File samOutput = File.createTempFile("test", ".sam");
    final SAMFileWriter samWriter =
        new SAMFileWriterFactory().makeWriter(bamReader.getFileHeader(), true, samOutput, null);
    final SAMFileWriter bamWriter =
        new SAMFileWriterFactory().makeWriter(bamReader.getFileHeader(), true, bamOutput, null);
    final SAMRecordIterator iterator = bamReader.iterator();
    while (iterator.hasNext()) {
      try {
        final SAMRecord rec = iterator.next();
        samWriter.addAlignment(rec);
        bamWriter.addAlignment(rec);
      } catch (final Throwable e) {
        System.out.println(e.getMessage());
        errorMessages.add(e.getMessage());
      }
    }

    CloserUtil.close(bamReader);
    samWriter.close();
    bamWriter.close();
    Assert.assertEquals(errorMessages.size(), 0);
    bamOutput.deleteOnExit();
    samOutput.deleteOnExit();
  }
  /**
   * Creates the script file.
   *
   * @return the string
   * @throws Exception the exception
   */
  public String createScriptFile() throws Exception {
    File tempScriptFile;

    if (meta.getGenerateScript()) {
      tempScriptFile = File.createTempFile(FilenameUtils.getBaseName(meta.getScriptFileName()), "");
    } else {
      tempScriptFile =
          File.createTempFile(FilenameUtils.getBaseName(meta.getExistingScriptFile()), "");
    }
    tempScriptFile.deleteOnExit();

    try {
      scriptFile = FileUtils.openOutputStream(tempScriptFile);
      scriptFilePrintStream = new PrintStream(scriptFile);
    } catch (IOException e) {
      throw new KettleException(
          BaseMessages.getString(
              PKG, "TeraDataBulkLoaderMeta.Exception.OpenScriptFile", scriptFile),
          e);
    }

    if (meta.getGenerateScript()) {
      createGeneratedScriptFile();
    } else {
      createFromExistingScriptFile();
    }
    scriptFilePrintStream.close();
    IOUtils.closeQuietly(scriptFile);
    return tempScriptFile.getAbsolutePath();
  }
示例#23
0
  public void split(File firstHalf, File lastHalf, File source, int page) throws IOException {
    File temporal;

    if (firstHalf == null && lastHalf == null)
      throw new IllegalArgumentException("firstHalf and lastHalf are null");
    temporal = null;
    if (firstHalf == null)
      firstHalf = temporal = File.createTempFile(this.getClass().getName() + '.', ".pdf");
    if (lastHalf == null)
      lastHalf = temporal = File.createTempFile(this.getClass().getName() + '.', ".pdf");
    try {
      int result;

      result =
          this.launch(
              "-split",
              source.getAbsolutePath(),
              firstHalf.getAbsolutePath(),
              lastHalf.getAbsolutePath(),
              Integer.toString(page, 10));
      if (result != 0)
        throw new IOException(
            String.format("failed on split documents" + " (process exit with %d)", result));
    } finally {
      if (temporal != null) temporal.delete();
    }
  }
示例#24
0
  /** 准备录音 */
  private void initRecorder() {
    try {
      /* 创建一个临时文件,用来存放录音 */
      File[] datafiles = SDPathDir.listFiles();
      for (File file : datafiles) {
        if (!file.isDirectory()) {
          if (file.getName().endsWith(".mp3")) {
            file.delete();
          }
        }
      }
      tempFile = File.createTempFile("tempFile", ".mp3", SDPathDir);
      tempFile2 = File.createTempFile("tempFile", ".mp3", SDPathDir);
      tempFile3 = File.createTempFile("tempFile", ".mp3", SDPathDir);
      tempFile4 = File.createTempFile("tempFile", ".mp3", SDPathDir);
      Filename_1 = tempFile.getAbsolutePath();
      Filename_2 = tempFile2.getAbsolutePath();
      Filename_3 = tempFile3.getAbsolutePath();
      Filename_4 = tempFile4.getAbsolutePath();
      soundTouchClient.setfilename(Filename_1, Filename_2, Filename_3, Filename_4);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#25
0
  /**
   * Prepare file for download
   *
   * @param response An instance of the Response object
   * @throws IOException If fail to prepare file for download
   * @return Prepared file for the download
   */
  public File prepareDownloadFile(Response response) throws IOException {
    String filename = null;
    String contentDisposition = response.header("Content-Disposition");
    if (contentDisposition != null && !"".equals(contentDisposition)) {
      // Get filename from the Content-Disposition header.
      Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
      Matcher matcher = pattern.matcher(contentDisposition);
      if (matcher.find()) {
        filename = sanitizeFilename(matcher.group(1));
      }
    }

    String prefix = null;
    String suffix = null;
    if (filename == null) {
      prefix = "download-";
      suffix = "";
    } else {
      int pos = filename.lastIndexOf(".");
      if (pos == -1) {
        prefix = filename + "-";
      } else {
        prefix = filename.substring(0, pos) + "-";
        suffix = filename.substring(pos);
      }
      // File.createTempFile requires the prefix to be at least three characters long
      if (prefix.length() < 3) prefix = "download-";
    }

    if (tempFolderPath == null) return File.createTempFile(prefix, suffix);
    else return File.createTempFile(prefix, suffix, new File(tempFolderPath));
  }
示例#26
0
  @Test
  public void testGetActivityAttachmentFileName() throws Exception {
    RuntimeAPI runtimeAPI = AccessorUtil.getRuntimeAPI();
    ManagementAPI managementAPI = AccessorUtil.getManagementAPI();
    QueryRuntimeAPI queryRuntimeAPI = AccessorUtil.getQueryRuntimeAPI();

    File attachmentFile = File.createTempFile("attachment-test", ".txt");
    FileOutputStream fileOutputStream = new FileOutputStream(attachmentFile);
    fileOutputStream.write("test".getBytes("UTF-8"));
    fileOutputStream.close();

    ProcessDefinition attachmentProcess =
        ProcessBuilder.createProcess("attachment_process", "1.0")
            .addAttachment("attachment", attachmentFile.getPath(), attachmentFile.getName())
            .addHuman("john")
            .addHumanTask("task1", "john")
            .addHumanTask("task2", "john")
            .addTransition("transition", "task1", "task2")
            .done();

    BusinessArchive businessArchive = BusinessArchiveFactory.getBusinessArchive(attachmentProcess);
    attachmentProcess = managementAPI.deploy(businessArchive);

    ProcessInstanceUUID instanceUUID = runtimeAPI.instantiateProcess(attachmentProcess.getUUID());

    try {
      IFormWorkflowAPI api = FormAPIFactory.getFormWorkflowAPI();
      ActivityInstanceUUID activityInstanceUUID = null;
      Collection<TaskInstance> tasks =
          queryRuntimeAPI.getTaskList(instanceUUID, ActivityState.READY);
      for (TaskInstance activityInstance : tasks) {
        activityInstanceUUID = activityInstance.getUUID();
      }
      Assert.assertNotNull(activityInstanceUUID);
      String fileName = api.getAttachmentFileName(activityInstanceUUID, "${attachment}", true);
      Assert.assertEquals(attachmentFile.getName(), fileName);

      runtimeAPI.executeTask(activityInstanceUUID, true);
      fileName = api.getAttachmentFileName(activityInstanceUUID, "${attachment}", true);
      Assert.assertEquals(attachmentFile.getName(), fileName);

      File attachmentFile2 = File.createTempFile("new-attachment-test", ".txt");
      tasks = queryRuntimeAPI.getTaskList(instanceUUID, ActivityState.READY);
      for (TaskInstance activityInstance : tasks) {
        activityInstanceUUID = activityInstance.getUUID();
      }
      Assert.assertNotNull(activityInstanceUUID);
      runtimeAPI.addAttachment(
          instanceUUID, "attachment", attachmentFile2.getName(), "test".getBytes("UTF-8"));
      fileName = api.getAttachmentFileName(activityInstanceUUID, "${attachment}", true);
      Assert.assertEquals(attachmentFile2.getName(), fileName);
    } finally {
      AccessorUtil.getCommandAPI()
          .execute(new WebDeleteDocumentsOfProcessCommand(attachmentProcess.getUUID(), true));
      AccessorUtil.getRuntimeAPI().deleteProcessInstance(instanceUUID);
      AccessorUtil.getCommandAPI()
          .execute(new WebDeleteProcessCommand(attachmentProcess.getUUID()));
    }
  }
示例#27
0
  @Test
  public void updateImageShouldDeleteOldImage() throws IOException {
    final File currentFile = File.createTempFile("avatar", "tests");
    currentFile.deleteOnExit();

    final Avatar currentAvatar = new Avatar();
    currentAvatar.setId(1);
    currentAvatar.setAvatarType(AvatarType.AVATAR_GALLERY);
    currentAvatar.setFileName(currentFile.getName());

    context.checking(
        new Expectations() {
          {
            one(repository).get(1);
            will(returnValue(currentAvatar));
            atLeast(1).of(config).getApplicationPath();
            will(returnValue(currentFile.getParent()));
            atLeast(1).of(config).getValue(ConfigKeys.AVATAR_GALLERY_DIR);
            will(returnValue(""));
            one(config).getBoolean(ConfigKeys.AVATAR_ALLOW_GALLERY);
            will(returnValue(true));
            one(config).getBoolean(ConfigKeys.AVATAR_ALLOW_UPLOAD);
            will(returnValue(true));
            one(config).getLong(ConfigKeys.AVATAR_MAX_SIZE);
            will(returnValue(10000l));
            one(config).getInt(ConfigKeys.AVATAR_MAX_WIDTH);
            will(returnValue(800));
            one(config).getInt(ConfigKeys.AVATAR_MAX_HEIGHT);
            will(returnValue(600));
            one(config).getInt(ConfigKeys.AVATAR_MIN_WIDTH);
            will(returnValue(1));
            one(config).getInt(ConfigKeys.AVATAR_MIN_HEIGHT);
            will(returnValue(1));
            one(repository).update(currentAvatar);
          }
        });

    File originalFile = new File(this.getClass().getResource("/smilies/smilie.gif").getFile());
    File newFile = File.createTempFile("jforum", "tests");
    TestCaseUtils.copyFile(originalFile, newFile);

    UploadedFile uploadedFile =
        new DefaultUploadedFile(new FileInputStream(newFile), newFile.getAbsolutePath(), "");

    String oldDiskName = currentAvatar.getFileName();

    Avatar newAvatar = new Avatar();
    newAvatar.setId(1);
    newAvatar.setAvatarType(AvatarType.AVATAR_GALLERY);
    service.update(newAvatar, uploadedFile);
    context.assertIsSatisfied();

    Assert.assertEquals(newAvatar.getAvatarType(), currentAvatar.getAvatarType());
    Assert.assertFalse(currentFile.exists());
    Assert.assertFalse(currentAvatar.getFileName().equals(oldDiskName));

    new File(String.format("%s/%s", currentFile.getParent(), currentAvatar.getFileName())).delete();
  }
  @Test
  public void testSinglePageRedirection() throws IOException, XMLStreamException {
    // source dump
    File tmpOldDump = File.createTempFile("wiki-src-dump", "xml");
    File tmpNewDump = File.createTempFile("wiki-target-dump", "xml");

    // base structure - "<mediawiki><page><title></title><id><id></page></mediawiki>"
    BufferedWriter bw = new BufferedWriter(new FileWriter(tmpOldDump));
    bw.write(
        "<mediawiki>"
            + "<page>"
            + "<title>Test1</title>"
            + "<id>1</id>"
            + "<revision>"
            + "<id>1234556</id>"
            + "<text xml:space=\"preserve\">This is entry about Test1 and it will be redirected.</text>"
            + "</revision>"
            + "</page>"
            + "<page>"
            + "<title>Test2</title>"
            + "<id>2</id>"
            + "</page>"
            + "<page>"
            + "<title>Test3</title>"
            + "<id>3</id>"
            + "</page>"
            + "</mediawiki>");
    bw.close();

    bw = new BufferedWriter(new FileWriter(tmpNewDump));
    bw.write(
        "<mediawiki>"
            + "<page>"
            + "<title>Test1</title>"
            + "<id>1</id>"
            + "<redirect/>"
            + "<revision>"
            + "<id>1234556</id>"
            + "<text xml:space=\"preserve\">#REDIRECT [[Test3]] {{R from CamelCase}}</text>"
            + "</revision>"
            + "</page>"
            + "<page>"
            + "<title>NEW_Test2</title>"
            + "<id>2</id>"
            + "</page>"
            + "<page>"
            + "<title>Test3</title>"
            + "<id>3</id>"
            + "</page>"
            + "</mediawiki>");
    bw.close();
    Map<String, String> hshResults = WikipediaRevisionMapper.map(tmpOldDump, tmpNewDump);
    assertEquals(3, hshResults.size());
    assertEquals("Test3", hshResults.get("Test1"));

    tmpNewDump.delete();
    tmpOldDump.delete();
  }
示例#29
0
 private IWARProduct createPlainProducttWithLibraries() throws IOException {
   IWARProduct product = createPlainProduct();
   File testJar = File.createTempFile("test", ".jar");
   Path testPath = new Path(testJar.getAbsolutePath());
   product.addLibrary(testPath, false);
   File bridgeJar = File.createTempFile(SERVLETBRIDGE, ".jar");
   Path servletBridgePath = new Path(bridgeJar.getAbsolutePath());
   product.addLibrary(servletBridgePath, false);
   return product;
 }
示例#30
0
 static {
   try {
     testSampleDeliveryFile = File.createTempFile("test-sampleDeliveryForm", ".odt");
     testSampleBulkInputOdsFile = File.createTempFile("test-sampleBulkInputOds", ".ods");
     testSampleBulkInputXlsFile = File.createTempFile("test-sampleBulkInputXls", ".xlsx");
   } catch (IOException e) {
     e.printStackTrace();
     TestCase.fail();
   }
 }