@Test
  public void sourceBelongsToContentAndCanBeReadMultipleTimes() throws IOException {
    when(repository.findOne(new QueryImpl().eq("Name", "template1"))).thenReturn(template1);
    when(repository.findOne(new QueryImpl().eq("Name", "template2"))).thenReturn(template2);

    Object source1 = repositoryTemplateLoader.findTemplateSource("template1");
    Object source2 = repositoryTemplateLoader.findTemplateSource("template2");

    assertTrue(
        IOUtils.contentEquals(
            repositoryTemplateLoader.getReader(source2, null),
            new StringReader(template2.getValue())));

    assertTrue(
        IOUtils.contentEquals(
            repositoryTemplateLoader.getReader(source1, null),
            new StringReader(template1.getValue())));

    assertTrue(
        IOUtils.contentEquals(
            repositoryTemplateLoader.getReader(source1, null),
            new StringReader(template1.getValue())));

    assertTrue(
        IOUtils.contentEquals(
            repositoryTemplateLoader.getReader(source1, null),
            new StringReader(template1.getValue())));

    assertTrue(
        IOUtils.contentEquals(
            repositoryTemplateLoader.getReader(source2, null),
            new StringReader(template2.getValue())));
  }
  @Test
  public void testSetContentViaOutputStream() throws Exception {
    int attachLength = 20;
    int seed = (int) System.currentTimeMillis();
    final XWikiAttachment attach = new XWikiAttachment();
    final InputStream ris = new RandomInputStream(attachLength, seed);
    attach.setContent(ris);
    assertTrue(
        IOUtils.contentEquals(
            new RandomInputStream(attachLength, seed),
            attach.getAttachment_content().getContentInputStream()));
    // Now write to the attachment via an OutputStream.
    final XWikiAttachmentContent xac = attach.getAttachment_content();
    xac.setContentDirty(false);
    final OutputStream os = xac.getContentOutputStream();

    // Adding content with seed+1 will make a radically different set of content.
    IOUtils.copy(new RandomInputStream(attachLength, seed + 1), os);

    // It should still be the old content.
    assertTrue(
        IOUtils.contentEquals(
            new RandomInputStream(attachLength, seed), xac.getContentInputStream()));
    assertFalse(xac.isContentDirty());

    os.close();

    // Now it should be the new content.
    assertTrue(
        IOUtils.contentEquals(
            new RandomInputStream(attachLength, seed + 1), xac.getContentInputStream()));
    assertTrue(xac.isContentDirty());
  }
Exemple #3
0
  public void testFileStream() throws IOException {
    InputStream is = new SolrResourceLoader(null, null).openResource("solrj/README");
    assertNotNull(is);
    File file = new File(TEMP_DIR, "README");
    FileOutputStream os = new FileOutputStream(file);
    IOUtils.copy(is, os);
    os.close();

    ContentStreamBase stream = new ContentStreamBase.FileStream(file);
    assertEquals(file.length(), stream.getSize().intValue());
    assertTrue(IOUtils.contentEquals(new FileInputStream(file), stream.getStream()));
    assertTrue(IOUtils.contentEquals(new FileReader(file), stream.getReader()));
  }
Exemple #4
0
 public void testDeployUndeploy() throws Exception {
   Upload.deployZipFile(m_expandDir, m_zipFile, new FileSetting());
   File file1 = new File(m_expandDir, "zip-test/subdir/file1.txt");
   assertTrue(file1.exists());
   assertTrue(
       IOUtils.contentEquals(
           getClass().getResourceAsStream("file1.txt"), new FileInputStream(file1)));
   File file3 = new File(m_expandDir, "zip-test/file3.bin");
   assertTrue(file3.exists());
   InputStream stream3 = getClass().getResourceAsStream("file3.bin");
   assertTrue(IOUtils.contentEquals(stream3, new FileInputStream(file3)));
   Upload.undeployZipFile(m_expandDir, m_zipFile, new FileSetting());
   assertFalse(file1.exists());
 }
 @Test
 public void newSourceReturnedWhenContentChanges() throws IOException {
   when(repository.findOne(new QueryImpl().eq("Name", "template1")))
       .thenReturn(template1, template1Modified);
   Object source = repositoryTemplateLoader.findTemplateSource("template1");
   assertTrue(
       IOUtils.contentEquals(
           repositoryTemplateLoader.getReader(source, null),
           new StringReader(template1.getValue())));
   Object modifiedSource = repositoryTemplateLoader.findTemplateSource("template1");
   assertNotEquals(source, modifiedSource);
   assertTrue(
       IOUtils.contentEquals(
           repositoryTemplateLoader.getReader(modifiedSource, null),
           new StringReader(template1Modified.getValue())));
 }
  public void test_loadDataFromNetwork_returns_a_bitmap_with_right_size() throws Exception {
    // given;
    byte[] data =
        IOUtils.toByteArray(
            getInstrumentation().getContext().getResources().openRawResource(R.raw.binary));
    mockWebServer.enqueue(new MockResponse().setBody(data));
    mockWebServer.play();

    BitmapRequest binaryRequest =
        new BitmapRequest(
            mockWebServer.getUrl("/").toString(),
            TEST_BITMAP_REDUCED_WIDTH,
            TEST_BITMAP_REDUCED_HEIGHT,
            cacheFile);
    Bitmap bitmapReturned = binaryRequest.loadDataFromNetwork();
    InputStream cacheInputStream = new FileInputStream(cacheFile);

    // then
    assertTrue(
        IOUtils.contentEquals(
            cacheInputStream,
            getInstrumentation().getContext().getResources().openRawResource(R.raw.binary)));
    assertEquals(TEST_BITMAP_REDUCED_WIDTH, bitmapReturned.getWidth());
    assertEquals(TEST_BITMAP_REDUCED_HEIGHT, bitmapReturned.getHeight());
  }
  @Test
  public void testFullFileDecryption() throws IOException, URISyntaxException {
    final URL testResourceUrl = new URL(VAULT_BASE_URI.toURL(), "fullFileDecryptionTestFile.txt");
    final HttpClient client = new HttpClient();

    // prepare 64MiB test data:
    final byte[] plaintextData = new byte[16777216 * Integer.BYTES];
    final ByteBuffer bbIn = ByteBuffer.wrap(plaintextData);
    for (int i = 0; i < 16777216; i++) {
      bbIn.putInt(i);
    }
    final InputStream plaintextDataInputStream = new ByteArrayInputStream(plaintextData);

    // put request:
    final EntityEnclosingMethod putMethod = new PutMethod(testResourceUrl.toString());
    putMethod.setRequestEntity(new ByteArrayRequestEntity(plaintextData));
    final int putResponse = client.executeMethod(putMethod);
    putMethod.releaseConnection();
    Assert.assertEquals(201, putResponse);

    // get request:
    final HttpMethod getMethod = new GetMethod(testResourceUrl.toString());
    final int statusCode = client.executeMethod(getMethod);
    Assert.assertEquals(200, statusCode);
    // final byte[] received = new byte[plaintextData.length];
    // IOUtils.read(getMethod.getResponseBodyAsStream(), received);
    // Assert.assertArrayEquals(plaintextData, received);
    Assert.assertTrue(
        IOUtils.contentEquals(plaintextDataInputStream, getMethod.getResponseBodyAsStream()));
    getMethod.releaseConnection();
  }
  // I have 3 views on my adapter, name, number and photo
  public void testGetView_fills_list_item_view_with_data_and_executes_request()
      throws IOException, InterruptedException {
    // given;
    byte[] data =
        IOUtils.toByteArray(
            getInstrumentation().getContext().getResources().openRawResource(R.raw.binary));
    mockWebServer.enqueue(new MockResponse().setBody(data));
    mockWebServer.play();

    // when
    View view = adapter.getView(0, null, null);
    adapter.await(ADAPTER_UPDATE_TIME_OUT);
    assertTrue(adapter.isLoadBitmapHasBeenCalled());

    // then
    TextView nameView = (TextView) view.findViewById(R.id.user_name_textview);
    ImageView photoView = (ImageView) view.findViewById(R.id.thumbnail_imageview);

    assertNotNull("View is null. ", view);
    assertNotNull("Name TextView is null. ", nameView);
    assertNotNull("Photo ImageView is null. ", photoView);

    assertEquals("Names doesn't match.", data1.getFoo(), nameView.getText());

    // could we get notified of this request ?
    assertEquals(1, mockWebServer.getRequestCount());
    RecordedRequest first = mockWebServer.takeRequest();
    assertEquals("GET /" + data1.getImageUrl() + " HTTP/1.1", first.getRequestLine());

    InputStream cacheInputStream = new FileInputStream(cacheFile);
    assertTrue(
        IOUtils.contentEquals(
            cacheInputStream,
            getInstrumentation().getContext().getResources().openRawResource(R.raw.binary)));
  }
  @Test
  public void codecTest() throws Exception {
    log.info("Codec: " + getCodec().toString());

    long fileLength = testFile.contentLength();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    StopWatch compressionStopWatch = new StopWatch();
    compressionStopWatch.start();
    Compressor compressor = getCodec();
    try (InputStream is = testFile.getInputStream()) {
      compressor.compress(is, bos);
    }
    compressionStopWatch.endAndLog("Compression");

    byte[] compressedData = bos.toByteArray();
    assertTrue(
        "Compressed file size should be less than original", compressedData.length < fileLength);

    InputStream bis = new ByteArrayInputStream(compressedData);
    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();

    StopWatch decompressionStopWatch = new StopWatch();
    decompressionStopWatch.start();
    Decompressor decompressor = getCodec();
    decompressor.decompress(bis, bos2);
    decompressionStopWatch.endAndLog("Decompression");

    byte[] decompressedData = bos2.toByteArray();
    assertEquals(decompressedData.length, fileLength);

    try (InputStream is = testFile.getInputStream()) {
      assertTrue(IOUtils.contentEquals(is, new ByteArrayInputStream(bos2.toByteArray())));
    }
  }
 @Test
 public void loadAndRead() throws IOException {
   when(repository.findOne(new QueryImpl().eq("Name", "template1"))).thenReturn(template1);
   Object source = repositoryTemplateLoader.findTemplateSource("template1");
   assertNotNull(source);
   Reader reader = repositoryTemplateLoader.getReader(source, null);
   assertTrue(IOUtils.contentEquals(reader, new StringReader(template1.getValue())));
 }
Exemple #11
0
  public void testURLStream() throws IOException {
    byte[] content = null;
    String contentType = null;
    URL url = new URL("http://svn.apache.org/repos/asf/lucene/dev/trunk/");
    InputStream in = null;
    try {
      URLConnection conn = url.openConnection();
      in = conn.getInputStream();
      contentType = conn.getContentType();
      content = IOUtils.toByteArray(in);

      assumeTrue("not enough content for test to be useful", content.length > 10);

    } catch (IOException ex) {
      assumeNoException("Unable to connect to " + url + " to run the test.", ex);
    } finally {
      if (in != null) {
        IOUtils.closeQuietly(in);
      }
    }

    ContentStreamBase stream = new ContentStreamBase.URLStream(url);
    assertEquals(content.length, stream.getSize().intValue());

    // Test the stream
    in = stream.getStream();
    try {
      assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(content), in));
    } finally {
      IOUtils.closeQuietly(in);
    }

    String charset = ContentStreamBase.getCharsetFromContentType(contentType);
    if (charset == null) charset = ContentStreamBase.DEFAULT_CHARSET;
    // Re-open the stream and this time use a reader
    stream = new ContentStreamBase.URLStream(url);
    assertTrue(
        IOUtils.contentEquals(new StringReader(new String(content, charset)), stream.getReader()));
  }
Exemple #12
0
  public boolean responseMatchesFile() throws Throwable {
    File outFile = sendMessage();

    if (IOUtils.contentEquals(
        new BufferedInputStream(FileUtils.openInputStream(outFile)),
        getClass().getClassLoader().getResourceAsStream(this.expectedResponseFile))) {
      System.out.println("Response matches");
      return true;
    } else {
      System.out.println("Response does not match");
      return false;
    }
  }
 /**
  * Create an attachment, populate it with enough data to make it flush to disk cache, read back
  * data and make sure it's the same.
  */
 @Test
 public void testStoreContentInDiskCache() throws Exception {
   int attachLength = 20000;
   // Check for data dependent errors.
   int seed = (int) System.currentTimeMillis();
   final XWikiAttachment attach = new XWikiAttachment();
   final InputStream ris = new RandomInputStream(attachLength, seed);
   attach.setContent(ris);
   assertEquals("Not all of the stream was read", 0, ris.available());
   assertTrue(
       IOUtils.contentEquals(
           new RandomInputStream(attachLength, seed),
           attach.getAttachment_content().getContentInputStream()));
 }
Exemple #14
0
  public static void upgrade(File wrFile) throws Exception {
    System.out.println("Installing/upgrading Myna in '" + wrFile.toString() + "'...");
    wrFile.mkdirs();
    File web_inf = new File(wrFile.toURI().resolve("WEB-INF"));
    boolean isUpgrade = false;
    File backupDir = null;
    if (web_inf.exists()) {

      String dateString =
          new java.text.SimpleDateFormat("MM-dd-yyyy_HH.mm.ss.S").format(new Date());
      String backupBase = "WEB-INF/upgrade_backups/backup_" + dateString;
      backupDir = new File(wrFile.toURI().resolve(backupBase));
      backupDir.mkdirs();
      isUpgrade = true;
      System.out.println("Backups stored in " + backupDir);
      // backup entire /myna folder because we're wiping it out
      FileUtils.copyDirectory(
          new File(wrFile.toURI().resolve("myna")), new File(backupDir.toURI().resolve("myna")));
      FileUtils.deleteDirectory(new File(wrFile.toURI().resolve("myna")));
    }

    if (isJar) {
      String jarFilePath = classUrl.substring(classUrl.indexOf(":") + 1, classUrl.indexOf("!"));
      File jarFile = new File(new java.net.URL(jarFilePath).toURI());
      ZipFile zipFile = new ZipFile(jarFile);

      for (ZipEntry entry : java.util.Collections.list(zipFile.entries())) {;
        File outputFile =
            new File(wrFile.toURI().resolve(java.net.URLEncoder.encode(entry.getName(), "UTF-8")));
        File backupFile = null;
        if (isUpgrade) {
          backupFile =
              new File(
                  backupDir.toURI().resolve(java.net.URLEncoder.encode(entry.getName(), "UTF-8")));
        }
        if (entry.isDirectory()) {
          outputFile.mkdirs();
          if (isUpgrade) backupFile.mkdirs();
        } else {
          if (isUpgrade && outputFile.exists()) {

            java.io.InputStream sourceIS = zipFile.getInputStream(entry);
            java.io.InputStream targetIS = FileUtils.openInputStream(outputFile);
            boolean isSame = IOUtils.contentEquals(sourceIS, targetIS);
            sourceIS.close();
            targetIS.close();

            if (isSame
                || entry.toString().equals("index.html")
                || entry.toString().equals("application.sjs")
                || entry.toString().equals("WEB-INF/classes/general.properties")
                || entry.toString().startsWith("WEB-INF/myna/ds")) {
              continue;
            } else {
              System.out.println("...backing up " + entry);
              FileUtils.copyFile(outputFile, backupFile, true);
              // outputFile.copyTo(backupFile);
              // fusebox.upgradeLog("Backup: " + backupFile);
            }
          }
          java.io.InputStream is = zipFile.getInputStream(entry);
          java.io.OutputStream os = FileUtils.openOutputStream(outputFile);
          IOUtils.copyLarge(is, os);
          is.close();
          os.close();
        }
      }
      zipFile.close();
      // FileUtils.deleteDirectory()

      System.out.println("Done unpacking.");
    }
  }