public void testStandardTemplate() throws Exception {
    // Create a temporary directory for the tests
    final File testDir = new File(System.getProperty("java.io.tmpdir"), "VelocityTestCase");
    testDir.mkdir();

    // Create a temporary template file
    final File testFile = File.createTempFile("test", ".vm", testDir);
    final FileWriter fw = new FileWriter(testFile);
    fw.write("Value=$value");
    fw.close();

    final Map<String, Object> map = new TreeMap<String, Object>();
    map.put("value", "myValue");

    // Standard approach
    final TemplateRepresentation tr =
        new TemplateRepresentation(testFile.getName(), map, MediaType.TEXT_PLAIN);
    tr.getEngine().setProperty("file.resource.loader.path", testDir.getAbsolutePath());
    final String result = tr.getText();
    assertEquals("Value=myValue", result);

    // Clean-up
    BioUtils.delete(testFile);
    BioUtils.delete(testDir, true);
  }
  public void testRepresentationTemplate() throws Exception {
    // Create a temporary directory for the tests
    File testDir = new File(System.getProperty("java.io.tmpdir"), "VelocityTestCase");
    testDir.mkdir();

    // Create a temporary template file
    File testFile = File.createTempFile("test", ".vm", testDir);
    FileWriter fw = new FileWriter(testFile);
    fw.write("Value=$value");
    fw.close();

    Map<String, Object> map = new TreeMap<String, Object>();
    map.put("value", "myValue");

    // Representation approach
    Reference ref = LocalReference.createFileReference(testFile);
    ClientResource r = new ClientResource(ref);
    Representation templateFile = r.get();
    TemplateRepresentation tr = new TemplateRepresentation(templateFile, map, MediaType.TEXT_PLAIN);
    final String result = tr.getText();
    assertEquals("Value=myValue", result);

    // Clean-up
    BioUtils.delete(testFile);
    BioUtils.delete(testDir, true);
  }
  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
    BioUtils.delete(this.testKeystoreFile);
    BioUtils.delete(this.testDir, true);

    // Restore a clean engine
    org.restlet.engine.Engine.register();
  }
  @Override
  public void setUp() throws Exception {
    super.setUp();

    try {
      if (!testKeystoreFile.exists()) {
        // Prepare a temporary directory for the tests
        BioUtils.delete(this.testDir, true);
        this.testDir.mkdir();
        // Copy the keystore into the test directory
        Response response =
            new Client(Protocol.CLAP)
                .handle(new Request(Method.GET, "clap://class/org/restlet/test/engine/dummy.jks"));

        if (response.getEntity() != null) {
          OutputStream outputStream = new FileOutputStream(testKeystoreFile);
          response.getEntity().write(outputStream);
          outputStream.flush();
          outputStream.close();
        } else {
          throw new Exception("Unable to find the dummy.jks file in the classpath.");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Tests partial Put requests.
   *
   * @throws Exception
   */
  public void testPut() throws Exception {
    if (!SystemUtils.isWindows()) {
      Request request;
      Response response;

      BioUtils.delete(testDir, true);
      Client client = new Client(new Context(), Protocol.HTTP);
      client.getContext().getParameters().add("tracing", "true");

      // PUT on a file that does not exist
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("1234567890"));
      request.setRanges(Arrays.asList(new Range(0, 10)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("1234567890", response.getEntity().getText());

      // Partial PUT on a file, the provided representation overflowed the
      // existing file
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("0000000000"));
      request.setRanges(Arrays.asList(new Range(1, 10)));
      response = client.handle(request);
      System.out.println(response.getStatus() + " / " + response.getStatus().getThrowable());
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10000000000", response.getEntity().getText());

      // Partial PUT on a file that does not exists, the provided range
      // does not start at the 0 index.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai2.txt");
      request.setEntity(new StringRepresentation("0000000000"));
      request.setRanges(Arrays.asList(new Range(1, 10)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      request.setMethod(Method.GET);
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("0000000000", response.getEntity().getText());

      // Partial PUT on a file, simple range
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("22"));
      request.setRanges(Arrays.asList(new Range(2, 2)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000000", response.getEntity().getText());

      // Partial PUT on a file, the provided representation will be padded
      // at the very end of the file.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("888"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000888", response.getEntity().getText());

      // Partial PUT on a file that does not exist, the range does not
      // specify the range size.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai3.txt");
      request.setEntity(new StringRepresentation("888"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      request.setMethod(Method.GET);
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("888", response.getEntity().getText());

      // Partial PUT on a file, the provided representation will be padded
      // just before the end of the file.
      request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setEntity(new StringRepresentation("99"));
      request.setRanges(Arrays.asList(new Range(8, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      response = client.handle(new Request(Method.GET, request.getResourceRef()));
      assertEquals(Status.SUCCESS_OK, response.getStatus());
      assertEquals("10220000998", response.getEntity().getText());

      request = new Request(Method.GET, "http://localhost:" + TEST_PORT + "/testPut/essai.txt");
      request.setRanges(Arrays.asList(new Range(3, Range.SIZE_MAX)));
      response = client.handle(request);
      assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
      assertEquals("20000998", response.getEntity().getText());

      BioUtils.delete(testDir, true);
      client.stop();
    }
  }
Ejemplo n.º 6
0
  /**
   * Handles a PUT call.
   *
   * @param request The request to answer.
   * @param response The response to update.
   * @param file The Zip archive file.
   * @param entryName The Zip archive entry name.
   */
  protected void handlePut(Request request, Response response, File file, String entryName) {
    boolean zipExists = file.exists();
    ZipOutputStream zipOut = null;

    if ("".equals(entryName)
        && request.getEntity() != null
        && request.getEntity().getDisposition() != null) {
      entryName = request.getEntity().getDisposition().getFilename();
    }
    if (entryName == null) {
      response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Must specify an entry name.");
      return;
    }
    // boolean canAppend = true;
    boolean canAppend = !zipExists;
    boolean isDirectory = entryName.endsWith("/");
    boolean wrongReplace = false;
    try {
      if (zipExists) {
        ZipFile zipFile = new ZipFile(file);
        // Already exists ?
        canAppend &= null == zipFile.getEntry(entryName);
        // Directory with the same name ?
        if (isDirectory) {
          wrongReplace = null != zipFile.getEntry(entryName.substring(0, entryName.length() - 1));
        } else {
          wrongReplace = null != zipFile.getEntry(entryName + "/");
        }

        canAppend &= !wrongReplace;
        zipFile.close();
      }

      Representation entity;
      if (isDirectory) {
        entity = null;
      } else {
        entity = request.getEntity();
      }

      if (canAppend) {
        try {
          // zipOut = new ZipOutputStream(new BufferedOutputStream(new
          // FileOutputStream(file, true)));
          zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
          writeEntityStream(entity, zipOut, entryName);
          zipOut.close();
        } catch (Exception e) {
          response.setStatus(Status.SERVER_ERROR_INTERNAL, e);
          return;
        } finally {
          if (zipOut != null) zipOut.close();
        }
        response.setStatus(Status.SUCCESS_CREATED);
      } else {
        if (wrongReplace) {
          response.setStatus(
              Status.CLIENT_ERROR_BAD_REQUEST,
              "Directory cannot be replace by a file or file by a directory.");
        } else {
          File writeTo = null;
          ZipFile zipFile = null;
          try {
            writeTo = File.createTempFile("restlet_zip_", "zip");
            zipFile = new ZipFile(file);
            zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(writeTo)));
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            boolean replaced = false;
            while (entries.hasMoreElements()) {
              ZipEntry e = entries.nextElement();
              if (!replaced && entryName.equals(e.getName())) {
                writeEntityStream(entity, zipOut, entryName);
                replaced = true;
              } else {
                zipOut.putNextEntry(e);
                BioUtils.copy(new BufferedInputStream(zipFile.getInputStream(e)), zipOut);
                zipOut.closeEntry();
              }
            }
            if (!replaced) {
              writeEntityStream(entity, zipOut, entryName);
            }
            zipFile.close();
            zipOut.close();
          } finally {
            try {
              if (zipFile != null) zipFile.close();
            } finally {
              if (zipOut != null) zipOut.close();
            }
          }

          if (!(BioUtils.delete(file) && writeTo.renameTo(file))) {
            if (!file.exists()) file.createNewFile();
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
              fis = new FileInputStream(writeTo);
              fos = new FileOutputStream(file);
              // ByteUtils.write(fis.getChannel(),
              // fos.getChannel());
              BioUtils.copy(fis, fos);
              response.setStatus(Status.SUCCESS_OK);
            } finally {
              try {
                if (fis != null) fis.close();
              } finally {
                if (fos != null) fos.close();
              }
            }
          } else {
            response.setStatus(Status.SUCCESS_OK);
          }
        }
      }
    } catch (Exception e) {
      response.setStatus(Status.SERVER_ERROR_INTERNAL, e);
      return;
    }
  }