com.google.common.primitives.Bytes Java Examples

The following examples show how to use com.google.common.primitives.Bytes. 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: LsUpdate.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets lsu header.
 *
 * @return lsu header as byte array
 */
public byte[] getLsuHeaderAsByteArray() {
    List<Byte> headerLst = new ArrayList<>();
    try {
        headerLst.add((byte) this.ospfVersion());
        headerLst.add((byte) this.ospfType());
        headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.ospfPacLength())));
        headerLst.addAll(Bytes.asList(this.routerId().toOctets()));
        headerLst.addAll(Bytes.asList(this.areaId().toOctets()));
        headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.checksum())));
        headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.authType())));
        //Authentication is 0 always. Total 8 bytes consist of zero
        byte[] auth = new byte[OspfUtil.EIGHT_BYTES];
        headerLst.addAll(Bytes.asList(auth));
    } catch (Exception e) {
        log.debug("Error::LSUpdate::getLsuHeaderAsByteArray:: {}", e.getMessage());
        return Bytes.toArray(headerLst);
    }

    return Bytes.toArray(headerLst);
}
 
Example #2
Source File: SessionManager.java    From ua-server-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
private SignatureData getServerSignature(ByteString clientNonce,
                                         ByteString clientCertificate,
                                         SecurityPolicy securityPolicy,
                                         KeyPair keyPair) throws UaException {

    if (clientNonce.isNull() || clientCertificate.isNull() || keyPair == null) {
        return new SignatureData(null, null);
    }

    try {
        SecurityAlgorithm algorithm = securityPolicy.getAsymmetricSignatureAlgorithm();

        byte[] data = Bytes.concat(clientCertificate.bytes(), clientNonce.bytes());

        byte[] signature = SignatureUtil.sign(
                algorithm,
                keyPair.getPrivate(),
                ByteBuffer.wrap(data)
        );

        return new SignatureData(algorithm.getUri(), ByteString.of(signature));
    } catch (UaRuntimeException e) {
        throw new UaException(StatusCodes.Bad_SecurityChecksFailed);
    }
}
 
Example #3
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesOutputDirAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${outputDir}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();

    assertThat(Files.exists(Paths.get(stringFromStdout)));
}
 
Example #4
Source File: AbstractTransactionAwareTableTest.java    From phoenix-tephra with Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrates false positives on conflicts due to concatenation of
 * keys for change sets (see TEPHRA-287).
 * @param pre014ChangeSetKey
 */
private void testActionChangeOverlap(boolean pre014ChangeSetKey) {
  long wp = System.currentTimeMillis();
  long rp = wp - 100;
  ConcreteTransactionAwareTable table1 = 
      new ConcreteTransactionAwareTable(ConflictDetection.ROW, false, TABLE_NAME, pre014ChangeSetKey);
  ConcreteTransactionAwareTable table2 = 
      new ConcreteTransactionAwareTable(ConflictDetection.ROW, false, 
          Bytes.concat(TABLE_NAME, ROW_PREFIX.getBytes()), pre014ChangeSetKey);
  Transaction tx = new Transaction(rp, wp, new long[] {}, new long[] {}, wp);
  table1.startTx(tx);
  table2.startTx(tx);
  table1.addToChangeSet(ROW1.getBytes(), FAM1.getBytes(), null);
  table2.addToChangeSet(ROW3.getBytes(), FAM1.getBytes(), null);
  assertNotEquals(table1.getChangeSet(), table2.getChangeSet());
  ConcreteTransactionAwareTable table3 = 
      new ConcreteTransactionAwareTable(ConflictDetection.COLUMN, false, TABLE_NAME, pre014ChangeSetKey);
  table3.startTx(tx);
  table3.addToChangeSet("e".getBytes(), "bc".getBytes(), "d".getBytes());
  table3.addToChangeSet("e".getBytes(), "b".getBytes(), "cd".getBytes());
  assertEquals(pre014ChangeSetKey ? 3 : 2, table3.getTxChanges().size());
}
 
Example #5
Source File: RecordFileDownloaderTest.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Exactly 1/3 consensus")
void oneThirdConsensus() throws Exception {
    // Remove last node from current 4 node address book
    byte[] addressBook = Files.readAllBytes(mirrorProperties.getAddressBookPath());
    int index = Bytes.lastIndexOf(addressBook, (byte) '\n');
    addressBook = Arrays.copyOfRange(addressBook, 0, index);
    networkAddressBook.update(addressBook);

    fileCopier.filterDirectories("*0.0.3").copy();
    downloader.download();

    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE, "2019-08-30T18_10_00.419072Z.rcd");
    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE, "2019-08-30T18_10_05.249678Z.rcd");
    verify(applicationStatusRepository, times(2)).updateStatusValue(
            eq(ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE_HASH), any());
    assertValidFiles(List.of("2019-08-30T18_10_05.249678Z.rcd", "2019-08-30T18_10_00.419072Z.rcd"));
}
 
Example #6
Source File: AccountBalancesDownloaderTest.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Exactly 1/3 consensus")
void oneThirdConsensus() throws Exception {
    // Remove last node from current 4 node address book
    byte[] addressBook = Files.readAllBytes(mirrorProperties.getAddressBookPath());
    int index = Bytes.lastIndexOf(addressBook, (byte) '\n');
    addressBook = Arrays.copyOfRange(addressBook, 0, index);
    networkAddressBook.update(addressBook);

    fileCopier.filterDirectories("*0.0.3").copy();
    downloader.download();
    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_BALANCE_FILE, "2019-08-30T18_30_00.010147001Z_Balances" +
                    ".csv");
    assertValidFiles(List
            .of("2019-08-30T18_15_00.016002001Z_Balances.csv", "2019-08-30T18_30_00.010147001Z_Balances.csv"));
}
 
Example #7
Source File: TransformedRecordSerializerTest.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
@Test
public void encryptWhenSerializing() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    TransformedRecordSerializer<Message> serializer = TransformedRecordSerializerJCE.newDefaultBuilder()
            .setEncryptWhenSerializing(true)
            .setEncryptionKey(key)
            .build();

    MySimpleRecord mediumRecord = MySimpleRecord.newBuilder().setRecNo(1066L).setStrValueIndexed(SONNET_108).build();
    assertTrue(Bytes.indexOf(mediumRecord.toByteArray(), "brain".getBytes()) >= 0, "should contain clear text");
    byte[] serialized = serialize(serializer, mediumRecord);
    assertEquals(TransformedRecordSerializer.ENCODING_ENCRYPTED, serialized[0]);
    assertFalse(Bytes.indexOf(serialized, "brain".getBytes()) >= 0, "should not contain clear text");
    Message deserialized = deserialize(serializer, Tuple.from(1066L), serialized);
    assertEquals(mediumRecord, deserialized);
}
 
Example #8
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesJoinAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${join(',', inputs.someList)}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();

    assertThat(stringFromStdout).isEqualTo("a,b,c,d"); // From the input fixture
}
 
Example #9
Source File: NetworkLsa.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets LSA body as byte array.
 *
 * @return LSA body as byte array
 * @throws OspfParseException might throws exception while parsing packet
 */
public byte[] getLsaBodyAsByteArray() throws OspfParseException {
    List<Byte> bodyLst = new ArrayList<>();

    try {
        bodyLst.addAll(Bytes.asList(this.networkMask().toOctets()));
        //add each attachedRouters details
        for (Ip4Address attachedRouter : attachedRouters) {
            //attached router
            bodyLst.addAll(Bytes.asList(attachedRouter.toOctets()));
        }
    } catch (Exception e) {
        log.debug("Error::NetworkLSA::getLsrBodyAsByteArray {}", e.getMessage());
        throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR, OspfErrorType.BAD_MESSAGE);
    }

    return Bytes.toArray(bodyLst);
}
 
Example #10
Source File: MessageDeframerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void deliverIsReentrantSafe() {
  doAnswer(
      new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
          deframer.request(1);
          return null;
        }
      })
      .when(listener)
      .messagesAvailable(ArgumentMatchers.<StreamListener.MessageProducer>any());
  deframer.deframe(buffer(new byte[]{0, 0, 0, 0, 1, 3}));
  deframer.closeWhenComplete();
  verifyNoMoreInteractions(listener);

  deframer.request(1);
  verify(listener).messagesAvailable(producer.capture());
  assertEquals(Bytes.asList(new byte[]{3}), bytes(producer.getValue().next()));
  verify(listener).deframerClosed(false);
  verify(listener, atLeastOnce()).bytesRead(anyInt());
  verifyNoMoreInteractions(listener);
}
 
Example #11
Source File: EOSFormatter.java    From eosio-java with MIT License 6 votes vote down vote up
/**
 * Decompresses a public key based on the algorithm used to generate it.
 *
 * @param compressedPublicKey Compressed public key as byte[]
 * @param algorithmEmployed Algorithm used during key creation
 * @return Decompressed public key as byte[]
 * @throws EOSFormatterError when public key decompression fails.
 */
@NotNull
private static byte[] decompressPublickey(byte[] compressedPublicKey,
        AlgorithmEmployed algorithmEmployed)
        throws EOSFormatterError {
    try {
        ECParameterSpec parameterSpec = ECNamedCurveTable
                .getParameterSpec(algorithmEmployed.getString());
        ECPoint ecPoint = parameterSpec.getCurve().decodePoint(compressedPublicKey);
        byte[] x = ecPoint.getXCoord().getEncoded();
        byte[] y = ecPoint.getYCoord().getEncoded();
        if (y.length > STANDARD_KEY_LENGTH) {
            y = Arrays.copyOfRange(y, 1, y.length);
        }
        return Bytes.concat(new byte[]{UNCOMPRESSED_PUBLIC_KEY_BYTE_INDICATOR}, x, y);
    } catch (Exception e) {
        throw new EOSFormatterError(ErrorConstants.PUBLIC_KEY_DECOMPRESSION_ERROR, e);
    }
}
 
Example #12
Source File: ApplicationThreadDeframerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void messagesAvailableDrainsToMessageReadQueue_returnedByInitializingMessageProducer()
    throws Exception {
  byte[][] messageBytes = {{1, 2, 3}, {4}, {5, 6}};
  Queue<InputStream> messages = new LinkedList<>();
  for (int i = 0; i < messageBytes.length; i++) {
    messages.add(new ByteArrayInputStream(messageBytes[i]));
  }
  MultiMessageProducer messageProducer = new MultiMessageProducer(messages);
  applicationThreadDeframer.getAppListener().messagesAvailable(messageProducer);
  applicationThreadDeframer.request(1 /* value is ignored */);
  for (int i = 0; i < messageBytes.length; i++) {
    InputStream message = listener.storedProducer.next();
    assertNotNull(message);
    assertEquals(Bytes.asList(messageBytes[i]), Bytes.asList(ByteStreams.toByteArray(message)));
  }
  assertNull(listener.storedProducer.next());
}
 
Example #13
Source File: Protocl.java    From wechatbot-xposed with Apache License 2.0 5 votes vote down vote up
public static byte[] Unpack(byte[] buffer,readerData reader){
    ByteBuffer buf = ByteBuffer.allocate(102400);
    long length = buffer.length;
    int biao = 0;
    if (length <= ConstHeaderLength+ConstSaveDataLength+ConstFooterLength) {
        return buffer;
    }
    if (Bytes.indexOf(buffer, ConstHeader.getBytes()) == -1 || Bytes.indexOf(buffer, ConstFooter.getBytes()) == -1){
        return buffer;
    }
    int start = Bytes.indexOf(buffer, ConstHeader.getBytes());
    if (start == -1) {
        return buffer;
    }
    int end =  Bytes.indexOf(Arrays.copyOfRange(buffer,start+ConstHeaderLength,buffer.length), ConstFooter.getBytes());
    if (end == -1) {
        return buffer;
    }
    end += start + ConstHeaderLength;
    biao = start + ConstHeaderLength;
    int messageLength = (int)bytes2int(Arrays.copyOfRange(buffer,biao,biao+ConstSaveDataLength));
    if (end-start-ConstHeaderLength-ConstSaveDataLength != messageLength) {
        return Arrays.copyOfRange(buffer,end+ConstFooterLength,buffer.length);
    }
    biao += ConstSaveDataLength;

    reader.setReader(Arrays.copyOfRange(buffer,biao,biao+messageLength));
    biao += messageLength + ConstFooterLength;
    if (biao == length) {
        return new byte[]{};
    }

    return Arrays.copyOfRange(buffer,biao,buffer.length);
}
 
Example #14
Source File: NulTerminatedStringOption.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] getStringData() {
    byte[] data = super.getStringData();
    int length = Bytes.indexOf(data, (byte) 0);
    if (length >= 0)
        return Arrays.copyOf(data, length);
    return data;
}
 
Example #15
Source File: LedgerDevice.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
public int showAddressSECP256K1(int[] bip32Path, String hrp) throws IOException {
    byte[] pathBytes = LedgerUtils.bipPathToBytes(bip32Path, 3);

    byte[] command = new byte[]{userCLA, userINSPublicKeySECP256K1ShowBech32, 0, 0, 0, 0};
    command[5] = (byte) hrp.length();
    command = Bytes.concat(command, hrp.getBytes());

    command = Bytes.concat(command, pathBytes);
    command[4] = (byte) (command.length - 5);
    byte[] result = device.exchange(command);
    return result.length;
}
 
Example #16
Source File: OutputPublisher.java    From flink-spector with Apache License 2.0 5 votes vote down vote up
/**
 * Send a opening message to the subscriber.
 * Signaling the start of output.
 *
 * @param taskNumber index of the subtask.
 * @param numTasks   number of parallelism.
 * @param serializer serialized serializer.
 */
public void sendOpen(int taskNumber,
                     int numTasks,
                     byte[] serializer) {
    String open = String.format("OPEN %d %d",
            taskNumber,
            numTasks);
    byte[] msg = Bytes.concat((open + " ;").getBytes(), serializer);
    queueMessage(msg);
}
 
Example #17
Source File: FastaReferenceMaker.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void finalizeSequence() {
    final String description = lastPosition.getContig() + ":" + currentSequenceStartPosition + "-" + lastPosition.getEnd();
    try {
        writer.appendSequence(String.valueOf(contigCount), description, basesPerLine, Bytes.toArray(sequence));
    } catch (IOException e) {
        throw new UserException.CouldNotCreateOutputFile("Failed while writing " + output + ".", e);
    }
}
 
Example #18
Source File: GenesisTransaction.java    From Qora with MIT License 5 votes vote down vote up
public boolean isSignatureValid()
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(GENESIS_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(this.timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE RECIPIENT
	data = Bytes.concat(data, Base58.decode(this.recipient.getAddress()));
			
	//WRITE AMOUNT
	byte[] amountBytes = this.amount.unscaledValue().toByteArray();
	byte[] fill = new byte[AMOUNT_LENGTH - amountBytes.length];
	amountBytes = Bytes.concat(fill, amountBytes);
	data = Bytes.concat(data, amountBytes);
	
	//DIGEST
	byte[] digest = Crypto.getInstance().digest(data);
	digest = Bytes.concat(digest, digest);
			
	//CHECK IF EQUAL
	return Arrays.equals(digest, this.signature);
}
 
Example #19
Source File: H264NalUtil.java    From feeyo-hlsserver with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	
	byte[] video_flag = {0x00, 0x00, 0x01, (byte) 0xE0};
	
	byte[] data = TestDataUtil.getTsData();
	int count = 1;
	for(int i=0; i <= data.length - 188; i= i+188 ) {
		byte[] dest = new byte[188]; 
		System.arraycopy(data, i, dest, 0, 188);
		count++;
		if(Bytes.indexOf(dest, video_flag) > 0) {
			System.out.print(count+"--> ");
			int frameType = getPesFrameType(dest);
			switch(frameType) { 
			case FRAME_I:
				System.out.println("I帧");
				break;
			case FRAME_P:
				System.out.println("P帧");
				break;
			case FRAME_B:
				System.out.println("B帧");
				break;
			default :
				System.out.println("Unsupport! " + frameType);
			}
		}
	}
	
}
 
Example #20
Source File: PredicateIndexBuilder.java    From vespa with Apache License 2.0 5 votes vote down vote up
public PredicateIndex build() {
    return new PredicateIndex(
            config,
            Ints.toArray(seenIds),
            Bytes.toArray(minFeatureIndexBuilder),
            Shorts.toArray(intervalEndsBuilder),
            highestIntervalEnd,
            intervalIndexBuilder.build(),
            boundsIndexBuilder.build(),
            conjunctionIntervalIndexBuilder.build(),
            intervalStoreBuilder.build(),
            conjunctionIndexBuilder.build(),
            Ints.toArray(zeroConstraintDocuments)
    );
}
 
Example #21
Source File: IcebergEncoder.java    From iceberg with Apache License 2.0 5 votes vote down vote up
private static byte[] getWriteHeader(org.apache.avro.Schema schema) {
  try {
    byte[] fp = SchemaNormalization.parsingFingerprint("CRC-64-AVRO", schema);
    return Bytes.concat(V1_HEADER, fp);
  } catch (NoSuchAlgorithmException e) {
    throw new AvroRuntimeException(e);
  }
}
 
Example #22
Source File: TestDelimitedLengthFieldBasedFrameDecoder.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void writeStringAndAssert(
    EmbeddedChannel channel,
    String value,
    Charset charset,
    boolean randomlyPartition,
    boolean expectFrameTooLarge
) {
  String frame = makeFrame(value, charset);

  try {
    if (randomlyPartition) {
      for (List<Byte> chunk : getRandomByteSlices(frame.getBytes())) {
        channel.writeInbound(Unpooled.copiedBuffer(Bytes.toArray(chunk)));
      }
    } else {
      channel.writeInbound(Unpooled.copiedBuffer(frame, charset));
    }
  } catch (TooLongFrameException e) {
    if (!expectFrameTooLarge) {
      Assert.fail("TooLongFrameException unexpectedly thrown");
    } else {
      Assert.assertNull(channel.readInbound());
    }
  }
  if (!expectFrameTooLarge) {
    ByteBuf in = (ByteBuf) channel.readInbound();
    Assert.assertEquals(value, in.toString(charset));
    in.release();
  }
}
 
Example #23
Source File: FileBasedMap.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static byte[] readData(Path path) throws IOException {
  LinkedList<Integer> bytes = new LinkedList<>();
  try (BufferedReader br = new BufferedReader(
      new InputStreamReader(Files.newInputStream(path)))) {
    int ch;
    while ((ch = br.read()) != -1) {
      if (ch == 0) {
        break;
      } else {
        bytes.add(ch);
      }
    }
  }
  return Bytes.toArray(bytes);
}
 
Example #24
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException {
    final byte[] challenge = AttestationProtocol.getChallenge();
    pendingChallenges.put(ByteBuffer.wrap(challenge), true);

    final byte[] challengeMessage =
            Bytes.concat(new byte[]{AttestationProtocol.PROTOCOL_VERSION},
                    new byte[AttestationProtocol.CHALLENGE_LENGTH], challenge);

    exchange.sendResponseHeaders(200, challengeMessage.length);
    try (final OutputStream output = exchange.getResponseBody()) {
        output.write(challengeMessage);
    }
}
 
Example #25
Source File: IpInternalReachabilityTlv.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] asBytes() {
    byte[] bytes = null;
    byte[] tlvHeader = tlvHeaderAsByteArray();
    byte[] tlvBody = tlvBodyAsBytes();
    tlvHeader[1] = (byte) tlvBody.length;
    bytes = Bytes.concat(tlvHeader, tlvBody);
    return bytes;
}
 
Example #26
Source File: ParserTest.java    From elastic-load-balancing-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAddresses_unix() throws IOException {
    AddressFamily addressFamily = AddressFamily.AF_UNIX;
    TransportProtocol transportProtocol = TransportProtocol.DGRAM;
    Command command = Command.PROXY;
    int addressSize = addressFamily.getAddressSize();

    byte[] srcAddress = new byte[] {1,2,3,4};
    byte[] srcPadding = new byte[addressSize - srcAddress.length];
    byte[] dstAddress = new byte[] {6,7,8,9,10};
    byte[] dstPadding = new byte[addressSize - dstAddress.length];

    byte[] stream = Bytes.concat(srcAddress, srcPadding, dstAddress, dstPadding);
    assertEquals(addressSize * 2, stream.length);


    Parser parser = newParser(stream);
    Header header = new Header();
    header.setCommand(command);
    header.setAddressFamily(addressFamily);
    header.setTransportProtocol(transportProtocol);
    parser.readAddresses(header);

    assertEquals(0, header.getSrcPort());
    assertEquals(0, header.getDstPort());
    assertArrayEquals(srcAddress, header.getSrcAddress());
    assertArrayEquals(dstAddress, header.getDstAddress());
}
 
Example #27
Source File: LsPdu.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] asBytes() {
    byte[] lspMessage = null;
    byte[] helloHeader = l1l2IsisPduHeader();
    byte[] lspBody = l1l2LsPduBody();
    lspMessage = Bytes.concat(helloHeader, lspBody);
    return lspMessage;
}
 
Example #28
Source File: CancelSellNameTransaction.java    From Qora with MIT License 5 votes vote down vote up
@Override
public boolean isSignatureValid() 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(CANCEL_SELL_NAME_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(this.timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, this.reference);
	
	//WRITE OWNER
	data = Bytes.concat(data, this.owner.getPublicKey());
	
	//WRITE NAME SIZE
	byte[] nameBytes = this.name.getBytes(StandardCharsets.UTF_8);
	int nameLength = nameBytes.length;
	byte[] nameLengthBytes = Ints.toByteArray(nameLength);
	data = Bytes.concat(data, nameLengthBytes);
			
	//WRITE NAME
	data = Bytes.concat(data, nameBytes);
	
	//WRITE FEE
	byte[] feeBytes = this.fee.unscaledValue().toByteArray();
	byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);
	
	return Crypto.getInstance().verify(this.owner.getPublicKey(), this.signature, data);
}
 
Example #29
Source File: NioServer.java    From Geisha with GNU General Public License v3.0 5 votes vote down vote up
private void read(SocketChannel channel) throws Exception {
    LinkedList<Byte> list = new LinkedList<>();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    int bytesRead = channel.read(buf);
    // 如果读取到-1,则说明客户端关闭了该链接
    if (bytesRead == -1) {
        log.info("Close channel {}", channel.getRemoteAddress());
        channel.close();
        return;
    }
    // 非阻塞IO可以读取0个字节,这种数据应该手动丢弃
    if (bytesRead == 0) return;

    // 读取所有的数据
    while (bytesRead > 0) {
        buf.flip();
        while (buf.hasRemaining()) {
            list.add(buf.get());
        }
        buf.clear();
        bytesRead = channel.read(buf);
    }
    String request = new String(Bytes.toArray(list), Constants.DEFAULT_ENCODING);
    try {
        // 写回响应
        response(request, channel);
    } catch (Exception e) {
        e.printStackTrace();
        // 返回错误信息
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        serverError(stringWriter.toString(), channel);
    }
}
 
Example #30
Source File: DebugTest.java    From Recaf with MIT License 5 votes vote down vote up
@Test
@Timeout(FAIL_TIMEOUT_SECONDS)
public void testClassRedefinition() {
	// Intercept the preparation of the "AddAndSub" class, force it to multiply instead of add
	vm.prepare("calc.AddAndSub", e -> {
		// Replace the "DADD" instruction with "DMUL"
		byte[] code = resource.getClasses().get("calc/AddAndSub");
		// 0x63 = DADD
		// 0x39 = DSTORE
		int daddIndex = Bytes.indexOf(code, new byte[]{ 0x63, 0x39 });
		// 0x6b = DMUL
		code[daddIndex] = 0x6b;
		// Redefine the class
		try {
			assertTrue(vm.redefine("calc.AddAndSub", code));
		} catch(JdiRedefineException ex) {
			fail(ex);
		}
	}).enable();
	// Send commands that normally would yield "6.0" but now will be "9.0"
	queue(() -> {
		sendInput("3+3\n");
		close();
	});
	execute();
	// Assertions: 3+3 = 9
	out.assertContains("COMPUTED: 9.0");
}