Java Code Examples for com.google.common.io.Resources#toByteArray()

The following examples show how to use com.google.common.io.Resources#toByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DhcpTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Test option with option length > 128.
 */
@Test
public void longOptionTest() throws Exception {
    byte[] data = Resources.toByteArray(Dhcp6RelayTest.class.getResource(LONG_OPT));
    DHCP dhcp = DHCP.deserializer().deserialize(data, 0, data.length);
    assertEquals(2, dhcp.getOptions().size());
    DhcpOption hostnameOption = dhcp.getOption(DHCP.DHCPOptionCode.OptionCode_HostName);
    DhcpOption endOption = dhcp.getOption(DHCP.DHCPOptionCode.OptionCode_END);
    assertNotNull(hostnameOption);
    assertNotNull(endOption);

    // Host name contains 200 "A"
    StringBuilder hostnameBuilder = new StringBuilder();
    IntStream.range(0, 200).forEach(i -> hostnameBuilder.append("A"));
    String hostname = hostnameBuilder.toString();

    assertEquals((byte) 200, hostnameOption.getLength());
    assertArrayEquals(hostname.getBytes(Charsets.US_ASCII), hostnameOption.getData());
}
 
Example 2
Source File: HBaseIndexingOptionsTest.java    From hbase-indexer with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluateIndexingSpecification_AllFromCmdline() throws Exception {
    opts.hbaseIndexerZkHost = null;
    opts.hbaseTableName = "mytable";
    opts.hbaseIndexerConfigFile = new File(Resources.getResource(getClass(), "user_indexer.xml").toURI());
    opts.zkHost = "myZkHost/solr";
    opts.collection = "mycollection";

    opts.evaluateIndexingSpecification();

    IndexingSpecification expectedSpec = new IndexingSpecification(
                        "mytable", HBaseIndexingOptions.DEFAULT_INDEXER_NAME, DefaultIndexerComponentFactory.class.getName(),
            Resources.toByteArray(Resources.getResource(getClass(), "user_indexer.xml")), ImmutableMap.of(
                    "solr.zk", "myZkHost/solr",
                    "solr.collection", "mycollection"));

    assertEquals(expectedSpec, opts.getIndexingSpecification());

}
 
Example 3
Source File: ClasspathCache.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static byte[] getBytes(Location location, String className) throws IOException {
    String name = className.replace('.', '/') + ".class";
    File dir = location.directory();
    File jarFile = location.jarFile();
    if (dir != null) {
        URI uri = new File(dir, name).toURI();
        return Resources.toByteArray(uri.toURL());
    } else if (jarFile != null) {
        String jarFileInsideJarFile = location.jarFileInsideJarFile();
        String directoryInsideJarFile = location.directoryInsideJarFile();
        if (jarFileInsideJarFile == null && directoryInsideJarFile == null) {
            return getBytesFromJarFile(name, jarFile);
        } else if (jarFileInsideJarFile != null) {
            return getBytesFromJarFileInsideJarFile(name, jarFile, jarFileInsideJarFile);
        } else {
            // directoryInsideJarFile is not null based on above conditionals
            checkNotNull(directoryInsideJarFile);
            return getBytesFromDirectoryInsideJarFile(name, jarFile, directoryInsideJarFile);
        }
    } else {
        throw new AssertionError("Both Location directory() and jarFile() are null");
    }
}
 
Example 4
Source File: BloomFilters.java    From quarantyne with Apache License 2.0 5 votes vote down vote up
/**
 * Make a BF from its serialized form
 * @param resourceName a {@link BloomFilters} value
 * @return a {@link BloomFilter}
 */
public static BloomFilter<String> deserialize(String resourceName) throws IOException{
  InputStream is =
      new BufferedInputStream(
          new ByteArrayInputStream(
              Resources.toByteArray(Resources.getResource(resourceName))));
  return BloomFilter.readFrom(is, FUNNEL);
}
 
Example 5
Source File: Asset.java    From quarantyne with Apache License 2.0 5 votes vote down vote up
Asset(String name) throws AssetException {
  try {
    this.bytes = Resources.toByteArray(Resources.getResource(prefixed(name)));
  } catch (IOException ex) {
    throw new AssetException("Asset " + prefixed(name) + " cannot be read or found", ex);
  }
}
 
Example 6
Source File: KeyStoreIntegrationTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
private void assertTestPayloadDecryption(String studyId, PrivateKey key) throws Exception {
  String resource = String.format("pioneer/%s.ciphertext.json", studyId);
  byte[] ciphertext = Resources.toByteArray(Resources.getResource(resource));
  byte[] plaintext = Resources
      .toByteArray(Resources.getResource("pioneer/sample.plaintext.json"));

  String payload = Json.readObjectNode(ciphertext).get("payload").get("encryptedData")
      .textValue();
  byte[] decrypted = DecryptPioneerPayloads.decrypt(key, payload);
  byte[] decompressed = GzipUtil.maybeDecompress(decrypted);

  String actual = Json.readObjectNode(plaintext).toString();
  String expect = Json.readObjectNode(decompressed).toString();
  assertEquals(expect, actual);
}
 
Example 7
Source File: ConnectionResourcesBean.java    From morf with Apache License 2.0 5 votes vote down vote up
private static Properties propertiesFromUrl(URL propertiesUrl) {
  try (InputStream stream = new ByteArrayInputStream(Resources.toByteArray(propertiesUrl))) {
    return propertiesFromStream(stream);
  } catch (Exception e) {
    throw new RuntimeException("Failed to load properties from URL [" + propertiesUrl + "]", e);
  }
}
 
Example 8
Source File: HtmlGeneratorUtil.java    From protostuff-compiler with Apache License 2.0 5 votes vote down vote up
public static <T> T read(Class<T> type, String location) {
    try {
        URL url = Resources.getResource(location);
        byte[] bytes = Resources.toByteArray(url);
        ObjectReader reader = mapper.reader().forType(type);
        return reader.readValue(bytes);
    } catch (IOException e) {
        throw new RuntimeException("Could not read resource: " + location, e);
    }
}
 
Example 9
Source File: DocumentServiceRestApi_uploadGeneric_IntegTest.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Test
public void when_italian_tax_receipt() throws Exception {

    // given
    List<Document> incomingDocumentsBefore = repository.findIncomingDocuments();
    assertThat(incomingDocumentsBefore).isEmpty();

    // when
    final String fileName = "some_tax_receipt.pdf";
    final byte[] pdfBytes = Resources.toByteArray(
            Resources.getResource(DocumentServiceRestApi_uploadGeneric_IntegTest.class, fileName));
    final Blob blob = new Blob(fileName, MimeTypeData.APPLICATION_PDF.asStr(), pdfBytes);

    wrap(documentService).uploadGeneric(blob, "INCOMING_TAX_REGISTER", "/ITA");

    transactionService.nextTransaction();

    // then
    List<Document> incomingDocumentsAfter = repository.findAllIncomingDocuments();
    assertThat(incomingDocumentsAfter).hasSize(1);

    Document document = incomingDocumentsAfter.get(0);
    Blob documentBlob = document.getBlob();

    assertThat(document.getAtPath()).isEqualTo("/ITA");
    assertThat(documentBlob.getName()).isEqualTo(blob.getName());
    assertThat(documentBlob.getMimeType().getBaseType()).isEqualTo(blob.getMimeType().getBaseType());
    assertThat(documentBlob.getBytes()).isEqualTo(blob.getBytes());
    assertThat(JDOHelper.getVersion(document)).isEqualTo(1L);
    assertThat(document.getType()).isEqualTo(DocumentTypeData.INCOMING_TAX_REGISTER.findUsing(documentTypeRepository));

}
 
Example 10
Source File: AnalyzedWorld.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private AnalyzedClass createAnalyzedClass(String className, @Nullable ClassLoader loader)
        throws ClassNotFoundException, IOException {
    String path = ClassNames.toInternalName(className) + ".class";
    URL url;
    if (loader == null) {
        // null loader means the bootstrap class loader
        url = ClassLoader.getSystemResource(path);
    } else {
        url = loader.getResource(path);
        if (url != null) {
            AnalyzedClass parentLoaderAnalyzedClass =
                    tryToReuseFromParentLoader(className, loader, path, url);
            if (parentLoaderAnalyzedClass != null) {
                return parentLoaderAnalyzedClass;
            }
        }
    }
    if (url == null) {
        // what follows is just a best attempt in the sort-of-rare case when a custom class
        // loader does not expose .class file contents via getResource(), e.g.
        // org.codehaus.groovy.runtime.callsite.CallSiteClassLoader
        return createAnalyzedClassPlanB(className, loader);
    }
    byte[] bytes = Resources.toByteArray(url);
    List<Advice> advisors =
            mergeInstrumentationAnnotations(this.advisors.get(), bytes, loader, className);
    ThinClassVisitor accv = new ThinClassVisitor();
    new ClassReader(bytes).accept(accv, ClassReader.SKIP_FRAMES + ClassReader.SKIP_CODE);
    // passing noLongerNeedToWeaveMainMethods=true since not really weaving bytecode here
    ClassAnalyzer classAnalyzer = new ClassAnalyzer(accv.getThinClass(), advisors, shimTypes,
            mixinTypes, loader, this, null, bytes, null, true);
    classAnalyzer.analyzeMethods();
    return classAnalyzer.getAnalyzedClass();
}
 
Example 11
Source File: HBaseIndexingOptionsTest.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvaluateIndexingSpecification_CombinationOfCmdlineAndZk() throws Exception {

    // Create an indexer -- verify INDEXER_ADDED event
    IndexerDefinition indexerDef = new IndexerDefinitionBuilder()
            .name("userindexer")
            .configuration(Resources.toByteArray(Resources.getResource(getClass(), "user_indexer.xml")))
            .connectionParams(ImmutableMap.of(
                    "solr.zk", "myZkHost/solr",
                    "solr.collection", "mycollection"))
            .build();
    addAndWaitForIndexer(indexerDef);

    opts.hbaseIndexerZkHost = "localhost:" + ZK_CLIENT_PORT;
    opts.hbaseIndexerName = "userindexer";
    opts.hbaseTableName = "mytable";
    opts.zkHost = "myOtherZkHost/solr";

    opts.evaluateIndexingSpecification();

    INDEXER_MODEL.deleteIndexerInternal("userindexer");

    IndexingSpecification expectedSpec = new IndexingSpecification(
            "mytable", "userindexer", null,
            Resources.toByteArray(Resources.getResource(getClass(), "user_indexer.xml")), ImmutableMap.of(
                    "solr.zk", "myOtherZkHost/solr",
                    "solr.collection", "mycollection"));

    assertEquals(expectedSpec, opts.getIndexingSpecification());

}
 
Example 12
Source File: SecretResourceTest.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Test
public void backfillExpirationTest() throws Exception {
  byte[] certs = Resources.toByteArray(Resources.getResource("fixtures/expiring-certificates.crt"));
  byte[] pubring = Resources.toByteArray(Resources.getResource("fixtures/expiring-pubring.gpg"));
  byte[] p12 = Resources.toByteArray(Resources.getResource("fixtures/expiring-keystore.p12"));
  byte[] jceks = Resources.toByteArray(Resources.getResource("fixtures/expiring-keystore.jceks"));

  create(CreateSecretRequestV2.builder()
      .name("certificate-chain.crt")
      .content(encoder.encodeToString(certs))
      .build());

  create(CreateSecretRequestV2.builder()
      .name("public-keyring.gpg")
      .content(encoder.encodeToString(pubring))
      .build());

  create(CreateSecretRequestV2.builder()
      .name("keystore.p12")
      .content(encoder.encodeToString(p12))
      .build());

  create(CreateSecretRequestV2.builder()
      .name("keystore.jceks")
      .content(encoder.encodeToString(jceks))
      .build());

  Response response = backfillExpiration("certificate-chain.crt", ImmutableList.of());
  assertThat(response.isSuccessful()).isTrue();

  response = backfillExpiration("public-keyring.gpg", ImmutableList.of());
  assertThat(response.isSuccessful()).isTrue();

  response = backfillExpiration("keystore.p12", ImmutableList.of("password"));
  assertThat(response.isSuccessful()).isTrue();

  response = backfillExpiration("keystore.jceks", ImmutableList.of("password"));
  assertThat(response.isSuccessful()).isTrue();

  SecretDetailResponseV2 details = lookup("certificate-chain.crt");
  assertThat(details.expiry()).isEqualTo(1501533950);

  details = lookup("public-keyring.gpg");
  assertThat(details.expiry()).isEqualTo(1536442365);

  details = lookup("keystore.p12");
  assertThat(details.expiry()).isEqualTo(1681596851);

  details = lookup("keystore.jceks");
  assertThat(details.expiry()).isEqualTo(1681596851);
}
 
Example 13
Source File: LacpCollectorTlvTest.java    From onos with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
     data = Resources.toByteArray(LacpCollectorTlvTest.class.getResource(PACKET_DUMP));
}
 
Example 14
Source File: Dhcp6RelayTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test deserialize relay message with reply message.
 *
 * @throws Exception exception while deserialize the DHCPv6 payload
 */
@Test
public void deserializeReply() throws Exception {
    byte[] data = Resources.toByteArray(getClass().getResource(REPLY));
    Ethernet eth = Ethernet.deserializer().deserialize(data, 0, data.length);
    DHCP6 relayMsg = (DHCP6) eth.getPayload().getPayload().getPayload();
    assertEquals(relayMsg.getMsgType(), DHCP6.MsgType.RELAY_REPL.value());
    assertEquals(relayMsg.getHopCount(), HOP_COUNT);
    assertEquals(relayMsg.getIp6LinkAddress(), LINK_ADDRESS);
    assertEquals(relayMsg.getIp6PeerAddress(), PEER_ADDRESS);

    assertEquals(relayMsg.getOptions().size(), 1);
    Dhcp6Option option = relayMsg.getOptions().get(0);
    assertEquals(option.getCode(), DHCP6.OptionCode.RELAY_MSG.value());
    assertEquals(option.getLength(), 84);
    assertTrue(option.getPayload() instanceof DHCP6);

    DHCP6 relaiedDhcp6 = (DHCP6) option.getPayload();
    assertEquals(relaiedDhcp6.getMsgType(), DHCP6.MsgType.REPLY.value());
    assertEquals(relaiedDhcp6.getTransactionId(), XID_2);
    assertEquals(relaiedDhcp6.getOptions().size(), 3);

    // IA NA
    option = relaiedDhcp6.getOptions().get(0);
    assertTrue(option instanceof Dhcp6IaNaOption);
    Dhcp6IaNaOption iaNaOption = (Dhcp6IaNaOption) option;
    assertEquals(iaNaOption.getCode(), DHCP6.OptionCode.IA_NA.value());
    assertEquals(iaNaOption.getLength(), 40);
    assertEquals(iaNaOption.getIaId(), IA_ID);
    assertEquals(iaNaOption.getT1(), T1_SERVER);
    assertEquals(iaNaOption.getT2(), T2_SERVER);
    assertEquals(iaNaOption.getOptions().size(), 1);

    // IA Address (in IA NA)
    assertTrue(iaNaOption.getOptions().get(0) instanceof Dhcp6IaAddressOption);
    Dhcp6IaAddressOption iaAddressOption =
            (Dhcp6IaAddressOption) iaNaOption.getOptions().get(0);
    assertEquals(iaAddressOption.getIp6Address(), IA_ADDRESS);
    assertEquals(iaAddressOption.getPreferredLifetime(), PREFFERRED_LT_SERVER);
    assertEquals(iaAddressOption.getValidLifetime(), VALID_LT_SERVER);
    assertNull(iaAddressOption.getOptions());

    // Client ID
    option = relaiedDhcp6.getOptions().get(1);
    assertTrue(option instanceof Dhcp6ClientIdOption);
    Dhcp6ClientIdOption clientIdOption = (Dhcp6ClientIdOption) option;
    assertEquals(clientIdOption.getCode(), DHCP6.OptionCode.CLIENTID.value());
    assertEquals(clientIdOption.getLength(), 14);
    assertEquals(clientIdOption.getDuid().getDuidType(), Dhcp6Duid.DuidType.DUID_LLT);
    assertEquals(clientIdOption.getDuid().getHardwareType(), 1);
    assertEquals(clientIdOption.getDuid().getDuidTime(), CLIENT_DUID_TIME);
    assertArrayEquals(clientIdOption.getDuid().getLinkLayerAddress(), CLIENT_MAC.toBytes());

    // Server ID
    option = relaiedDhcp6.getOptions().get(2);
    assertEquals(option.getCode(), DHCP6.OptionCode.SERVERID.value());
    assertEquals(option.getLength(), 14);
    Dhcp6Duid serverDuid =
            Dhcp6Duid.deserializer().deserialize(option.getData(), 0, option.getData().length);
    assertEquals(serverDuid.getDuidType(), Dhcp6Duid.DuidType.DUID_LLT);
    assertEquals(serverDuid.getDuidTime(), 0x211e5340);
    assertEquals(serverDuid.getHardwareType(), 1);
    assertArrayEquals(serverDuid.getLinkLayerAddress(), SERVER_MAC.toBytes());

    assertArrayEquals(data, eth.serialize());
}
 
Example 15
Source File: DocumentMenu_Upload_IntegTest.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Test
public void happy_case() throws Exception {

    // given
    List<Document> incomingDocumentsBefore = repository.findIncomingDocuments();
    assertThat(incomingDocumentsBefore).isEmpty();

    // when
    final String fileName = "3020100123.pdf";
    final byte[] pdfBytes = Resources.toByteArray(
            Resources.getResource(DocumentMenu_Upload_IntegTest.class, fileName));
    final Blob blob = new Blob(fileName, MimeTypeData.APPLICATION_PDF.asStr(), pdfBytes);
    queryResultsCache.resetForNextTransaction(); // workaround: clear MeService#me cache
    final Document uploadedDocument1 = sudoService
            .sudo(Person_enum.DanielOfficeAdministratorFr.getRef().toLowerCase(), () ->
                    wrap(documentMenu).upload(blob));
    transactionService.nextTransaction();

    // then
    List<Document> incomingDocumentsAfter = repository.findAllIncomingDocuments();
    assertThat(incomingDocumentsAfter).hasSize(1);
    final Document document = incomingDocumentsAfter.get(0);
    assertThat(document).isSameAs(uploadedDocument1);

    final Blob documentBlob = uploadedDocument1.getBlob();

    assertThat(ApplicationTenancy_enum.FrBe.getPath()).isEqualTo("/FRA;/BEL");
    assertThat(uploadedDocument1.getAtPath()).isEqualTo("/FRA");
    assertThat(documentBlob.getName()).isEqualTo(blob.getName());
    assertThat(documentBlob.getMimeType().getBaseType()).isEqualTo(blob.getMimeType().getBaseType());
    assertThat(documentBlob.getBytes()).isEqualTo(blob.getBytes());
    assertThat(JDOHelper.getVersion(uploadedDocument1)).isEqualTo(1L);
    assertThat(paperclipRepository.findByDocument(uploadedDocument1).size()).isEqualTo(0);

    // and then also
    final List<IncomingDocumentCategorisationStateTransition> transitions =
            stateTransitionRepository.findByDomainObject(document);

    assertThat(transitions).hasSize(2);
    assertTransition(transitions.get(0),
            NEW, CATEGORISE, null);
    assertTransition(transitions.get(1),
            null, INSTANTIATE, NEW);

    // and when
    final String fileName2 = "3020100123-altered.pdf";
    final byte[] pdfBytes2 = Resources.toByteArray(
            Resources.getResource(DocumentMenu_Upload_IntegTest.class, fileName2));
    final Blob similarNamedBlob = new Blob(fileName, MimeTypeData.APPLICATION_PDF.asStr(), pdfBytes2);
    final Document uploadedDocument2 = wrap(documentMenu).upload(similarNamedBlob);
    transactionService.nextTransaction();


    // then
    assertThat(uploadedDocument1).isNotSameAs(uploadedDocument2);

    incomingDocumentsAfter = repository.findAllIncomingDocuments();
    assertThat(incomingDocumentsAfter).hasSize(2);
    assertThat(incomingDocumentsAfter).contains(uploadedDocument1, uploadedDocument2);

    assertThat(JDOHelper.getVersion(uploadedDocument2)).isEqualTo(1L);
    assertThat(uploadedDocument2.getName()).isEqualTo(fileName);
    assertThat(uploadedDocument2.getBlobBytes()).isEqualTo(similarNamedBlob.getBytes());

    final List<Paperclip> paperclipByAttachedTo = paperclipRepository.findByAttachedTo(uploadedDocument2);
    assertThat(paperclipByAttachedTo.size()).isEqualTo(1);
    final List<Paperclip> paperclipByDocument = paperclipRepository.findByDocument(uploadedDocument1);
    assertThat(paperclipByDocument.size()).isEqualTo(1);
    assertThat(paperclipByDocument.get(0)).isSameAs(paperclipByAttachedTo.get(0));
    assertThat(paperclipRepository.findByAttachedTo(uploadedDocument1)).isEmpty();

    assertThat(JDOHelper.getVersion(uploadedDocument1)).isEqualTo(2L);
    assertThat(uploadedDocument1.getName()).startsWith("arch");
    assertThat(uploadedDocument1.getName()).endsWith(fileName);
    assertThat(uploadedDocument1.getBlobBytes()).isEqualTo(documentBlob.getBytes());

    // and when since ECP-676 atPath derived from filename for France and Belgium
    final String belgianBarCode = "6010012345.pdf";
    final Blob belgianBlob = new Blob(belgianBarCode, MimeTypeData.APPLICATION_PDF.asStr(), pdfBytes2);
    Document belgianDocument = wrap(documentMenu).upload(belgianBlob);

    // then
    assertThat(belgianDocument.getAtPath()).isEqualTo("/BEL");

}
 
Example 16
Source File: NetFlowV9ParserTest.java    From graylog-plugin-netflow with Apache License 2.0 4 votes vote down vote up
@Test
public void testParseIncomplete() throws Exception {
    final byte[] b = Resources.toByteArray(Resources.getResource("netflow-data/netflow-v9-3_incomplete.dat"));
    assertThatExceptionOfType(EmptyTemplateException.class)
            .isThrownBy(() -> NetFlowV9Parser.parsePacket(Unpooled.wrappedBuffer(b), typeRegistry));
}
 
Example 17
Source File: DecryptPioneerPayloadsTest.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
/** Load a private key from a JWK. See the KeyStore for more details. */
private PrivateKey loadPrivateKey(String resourceLocation) throws Exception {
  byte[] data = Resources.toByteArray(Resources.getResource(resourceLocation));
  PublicJsonWebKey key = PublicJsonWebKey.Factory.newPublicJwk(new String(data));
  return key.getPrivateKey();
}
 
Example 18
Source File: DecryptAetIdentifiersTest.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
/** Load a public key from a JWK. See the KeyStore for more details. */
private static PublicJsonWebKey loadPublicKey(String resourceLocation) throws Exception {
  byte[] data = Resources.toByteArray(Resources.getResource(resourceLocation));
  return PublicJsonWebKey.Factory.newPublicJwk(new String(data));
}
 
Example 19
Source File: Dhcp6Test.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test deserialize advertise message.
 *
 * @throws Exception exception while deserialize the DHCPv6 payload
 */
@Test
public void deserializeAdvertise() throws Exception {
    byte[] data = Resources.toByteArray(getClass().getResource(ADVERTISE));
    Ethernet eth = Ethernet.deserializer().deserialize(data, 0, data.length);
    DHCP6 dhcp6 = (DHCP6) eth.getPayload().getPayload().getPayload();
    assertEquals(dhcp6.getMsgType(), DHCP6.MsgType.ADVERTISE.value());
    assertEquals(dhcp6.getTransactionId(), XID_1);
    assertEquals(dhcp6.getOptions().size(), 3);

    // IA NA
    Dhcp6Option option = dhcp6.getOptions().get(0);
    assertTrue(option instanceof Dhcp6IaNaOption);
    Dhcp6IaNaOption iaNaOption = (Dhcp6IaNaOption) option;
    assertEquals(iaNaOption.getCode(), DHCP6.OptionCode.IA_NA.value());
    assertEquals(iaNaOption.getLength(), 40);
    assertEquals(iaNaOption.getIaId(), IA_ID);
    assertEquals(iaNaOption.getT1(), T1_SERVER);
    assertEquals(iaNaOption.getT2(), T2_SERVER);
    assertEquals(iaNaOption.getOptions().size(), 1);

    // IA Address (in IA NA)
    assertTrue(iaNaOption.getOptions().get(0) instanceof Dhcp6IaAddressOption);
    Dhcp6IaAddressOption iaAddressOption =
            (Dhcp6IaAddressOption) iaNaOption.getOptions().get(0);
    assertEquals(iaAddressOption.getIp6Address(), IA_ADDRESS);
    assertEquals(iaAddressOption.getPreferredLifetime(), PREFFERRED_LT_SERVER);
    assertEquals(iaAddressOption.getValidLifetime(), VALID_LT_SERVER);
    assertNull(iaAddressOption.getOptions());

    // Client ID
    option = dhcp6.getOptions().get(1);
    assertTrue(option instanceof Dhcp6ClientIdOption);
    Dhcp6ClientIdOption clientIdOption = (Dhcp6ClientIdOption) option;
    assertEquals(clientIdOption.getCode(), DHCP6.OptionCode.CLIENTID.value());
    assertEquals(clientIdOption.getLength(), 14);
    assertEquals(clientIdOption.getDuid().getDuidType(), Dhcp6Duid.DuidType.DUID_LLT);
    assertEquals(clientIdOption.getDuid().getHardwareType(), 1);
    assertEquals(clientIdOption.getDuid().getDuidTime(), CLIENT_DUID_TIME);
    assertArrayEquals(clientIdOption.getDuid().getLinkLayerAddress(), CLIENT_MAC.toBytes());

    // Server ID
    option = dhcp6.getOptions().get(2);
    assertEquals(option.getCode(), DHCP6.OptionCode.SERVERID.value());
    assertEquals(option.getLength(), 14);
    Dhcp6Duid serverDuid =
            Dhcp6Duid.deserializer().deserialize(option.getData(), 0, option.getData().length);
    assertEquals(serverDuid.getDuidType(), Dhcp6Duid.DuidType.DUID_LLT);
    assertEquals(serverDuid.getDuidTime(), 0x211e5340);
    assertEquals(serverDuid.getHardwareType(), 1);
    assertArrayEquals(serverDuid.getLinkLayerAddress(), SERVER_MAC.toBytes());
    assertArrayEquals(data, eth.serialize());
}
 
Example 20
Source File: ResourceUtils.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static byte[] getBytes(URL resourceUrl) throws IOException {
  return Resources.toByteArray(resourceUrl);
}