下面列出了com.google.common.primitives.Bytes#toArray ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Gets the LSA body as byte array.
*
* @return the lsa body as byte array
* @throws OspfParseException might throws exception while parsing packet
*/
public byte[] getLsaBodyAsByteArray() throws OspfParseException {
List<Byte> bodyLst = new ArrayList<>();
if (this.opaqueId() == 1) {
for (TopLevelTlv tlv : this.topLevelValues) {
//Check the sub type of lsa and build bytes accordingly
if (tlv instanceof RouterTlv) {
RouterTlv routerTlv = (RouterTlv) tlv;
bodyLst.addAll(Bytes.asList(routerTlv.asBytes()));
} else if (tlv instanceof LinkTlv) {
LinkTlv linkTlv = (LinkTlv) tlv;
bodyLst.addAll(Bytes.asList(linkTlv.asBytes()));
}
}
} else {
return opaqueInfo;
}
return Bytes.toArray(bodyLst);
}
@Test
public void testCanHandleStaticRequest() throws Exception {
int availablePort = NetUtils.getAvailablePort();
Map<String, ServletWrapper> mapper = new HashMap<>();
Configuration configuration = new Configuration(availablePort, 3, mapper);
Context context = new Context("sample.jar", configuration);
context.init();
context.start();
HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/favicon.ico");
httpget.setHeader("Sec-Fetch-Dest", "image");
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
int read;
List<Byte> bytes = new ArrayList<>();
while ((read = content.read()) != -1) {
byte read1 = (byte) read;
bytes.add(read1);
}
byte[] actual = Bytes.toArray(bytes);
byte[] except = FileUtils.readBytes(new File("core/src/test/resources/favicon.ico"));
assertArrayEquals(except, actual);
}
/**
* Gets header as byte array.
*
* @return header as byte array
*/
public byte[] getOpaqueLsaHeaderAsByteArray() {
List<Byte> headerLst = new ArrayList<>();
try {
headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.age())));
headerLst.add((byte) this.options());
headerLst.add((byte) this.lsType());
headerLst.add((byte) this.opaqueType());
headerLst.addAll(Bytes.asList(OspfUtil.convertToThreeBytes(this.opaqueId())));
headerLst.addAll(Bytes.asList(this.advertisingRouter().toOctets()));
headerLst.addAll(Bytes.asList(OspfUtil.convertToFourBytes(this.lsSequenceNo())));
headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.lsCheckSum())));
headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.lsPacketLen())));
} catch (Exception e) {
log.debug("Error::getLsaHeaderAsByteArray {}", e.getMessage());
return Bytes.toArray(headerLst);
}
return Bytes.toArray(headerLst);
}
/**
* Gets byte array of local interface ip address.
*
* @return byte array of local interface ip address
* @throws OspfParseException might throws exception while parsing packet
*/
public byte[] getLinkSubTypeTlvBodyAsByteArray() throws OspfParseException {
List<Byte> linkSubTypeBody = new ArrayList<>();
for (String remoteAddress : this.localInterfaceIPAddress) {
try {
linkSubTypeBody.addAll(Bytes.asList(InetAddress.getByName(remoteAddress).getAddress()));
} catch (Exception e) {
log.debug("Error::getLinkSubTypeTlvBodyAsByteArray:: {}", e.getMessage());
throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR,
OspfErrorType.BAD_MESSAGE);
}
}
return Bytes.toArray(linkSubTypeBody);
}
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
if (componentType == boolean.class) {
return Booleans.toArray((Collection) values);
} else if (componentType == byte.class) {
return Bytes.toArray((Collection) values);
} else if (componentType == short.class) {
return Shorts.toArray((Collection) values);
} else if (componentType == int.class) {
return Ints.toArray((Collection) values);
} else if (componentType == long.class) {
return Longs.toArray((Collection) values);
} else if (componentType == float.class) {
return Floats.toArray((Collection) values);
} else if (componentType == double.class) {
return Doubles.toArray((Collection) values);
} else if (componentType == char.class) {
return Chars.toArray((Collection) values);
}
return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
/**
* Gets LsAck body as byte array.
*
* @return byte array
*/
public byte[] getLsAckBodyAsByteArray() {
List<Byte> bodyLst = new ArrayList<>();
try {
for (LsaHeader lsaHeader : linkStateHeaders) {
if (lsaHeader.lsType() == OspfParameters.LINK_LOCAL_OPAQUE_LSA ||
lsaHeader.lsType() == OspfParameters.AREA_LOCAL_OPAQUE_LSA ||
lsaHeader.lsType() == OspfParameters.AS_OPAQUE_LSA) {
OpaqueLsaHeader header = (OpaqueLsaHeader) lsaHeader;
bodyLst.addAll(Bytes.asList(header.getOpaqueLsaHeaderAsByteArray()));
} else {
bodyLst.addAll(Bytes.asList(lsaHeader.getLsaHeaderAsByteArray()));
}
}
} catch (Exception e) {
log.debug("Error::getLsAckBodyAsByteArray {}", e.getMessage());
return Bytes.toArray(bodyLst);
}
return Bytes.toArray(bodyLst);
}
/**
* 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);
}
/**
* Gets DD Header as byte array.
*
* @return dd header as byte array.
*/
public byte[] getDdHeaderAsByteArray() {
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");
}
return Bytes.toArray(headerLst);
}
/**
* Returns TLV body of area address TLV.
*
* @return byteArray TLV body of area address TLV
*/
private byte[] tlvBodyAsBytes() {
List<Byte> bytes = new ArrayList<>();
for (String areaAddress : this.areaAddress) {
bytes.add((byte) (areaAddress.length() / 2));
bytes.addAll(IsisUtil.areaAddressToBytes(areaAddress));
}
return Bytes.toArray(bytes);
}
/**
* Builds ISIS PDU header for complete sequence numbers PDU.
*
* @return isisPduHeader ISIS PDU header
*/
public byte[] isisPduHeader() {
List<Byte> headerList = new ArrayList<>();
headerList.add(this.irpDiscriminator());
headerList.add((byte) IsisUtil.getPduHeaderLength(this.pduType()));
headerList.add(this.version());
headerList.add(this.idLength());
headerList.add((byte) this.pduType());
headerList.add(this.version2());
headerList.add(this.reserved());
headerList.add(this.maximumAreaAddresses());
return Bytes.toArray(headerList);
}
/**
* Builds ISIS PDU header from ISIS message.
*
* @return headerList ISIS PDU header
*/
public byte[] l1l2IsisPduHeader() {
List<Byte> headerList = new ArrayList<>();
headerList.add(this.irpDiscriminator());
headerList.add((byte) IsisUtil.getPduHeaderLength(this.pduType()));
headerList.add(this.version());
headerList.add(this.idLength());
headerList.add((byte) this.pduType());
headerList.add(this.version2());
headerList.add(this.reserved());
headerList.add(this.maximumAreaAddresses());
return Bytes.toArray(headerList);
}
private String headerEntryToString(Byte[] data) {
// since our annotation deserializer has to have the propertys as Byte objects instead of
// byte primative we have to do a wierd little dance to read our strings
byte[] fullName = Bytes.toArray(Arrays.asList(data));
try {
return new String(fullName, "UTF-16");
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* Returns TLV body of IS reachability TLV.
*
* @return byteArray TLV body of area address TLV
*/
private byte[] tlvBodyAsBytes() {
List<Byte> bytes = new ArrayList<>();
bytes.add((byte) this.reserved());
for (MetricsOfReachability metricsOfReachability : this.metricsOfReachabilities) {
bytes.addAll(Bytes.asList(metricsOfReachability.asBytes()));
}
return Bytes.toArray(bytes);
}
/**
* Gets the LSA body as bytes.
*
* @return LSA body as bytes
*/
public byte[] getLsaBodyAsByteArray() {
List<Byte> bodyLst = new ArrayList<>();
try {
int isVirtualEndPointVal = this.isVirtualEndPoint ? 1 : 0;
int isASBoundaryRouterVal = this.isAsBoundaryRouter ? 1 : 0;
int isAreaBorderRouterVal = this.isAreaBorderRouter ? 1 : 0;
StringBuilder sb = new StringBuilder();
sb.append(Integer.toBinaryString(isVirtualEndPointVal));
sb.append(Integer.toBinaryString(isASBoundaryRouterVal));
sb.append(Integer.toBinaryString(isAreaBorderRouterVal));
//added VEB
bodyLst.add((byte) Integer.parseInt(sb.toString(), 2));
//second byte is 0.
bodyLst.add((byte) 0);
//Number of links
bodyLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.noLink())));
//add each link details
for (OspfLsaLink lsaLink : routerLinks) {
bodyLst.addAll(Bytes.asList(InetAddress.getByName(lsaLink.linkId()).getAddress()));
bodyLst.addAll(Bytes.asList(InetAddress.getByName(lsaLink.linkData()).getAddress()));
bodyLst.add((byte) lsaLink.linkType());
bodyLst.add((byte) lsaLink.tos());
bodyLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(lsaLink.metric())));
}
} catch (Exception e) {
log.debug("Error::getLsrBodyAsByteArray {}", e.getMessage());
return Bytes.toArray(bodyLst);
}
return Bytes.toArray(bodyLst);
}
/**
* Returns TLV body of IS extended reachability TLV.
*
* @return byteArray TLV body of IS extended reachability TLV.
*/
private byte[] tlvBodyAsBytes() {
List<Byte> byteList = new ArrayList<>();
for (NeighborForExtendedIs neighbor : this.neighbors) {
byteList.addAll(Bytes.asList(neighbor.neighborBodyAsbytes()));
}
return Bytes.toArray(byteList);
}
/**
* Returns TLV body of LSP entries TLV.
*
* @return byteArray TLV body of LSP entries TLV
*/
private byte[] tlvBodyAsBytes() {
List<Byte> bytes = new ArrayList<>();
for (LspEntry lspEntry : lspEntryList) {
bytes.addAll(Bytes.asList(lspEntry.lspEntryAsBytes()));
}
return Bytes.toArray(bytes);
}
/**
* Builds complete sequence numbers PDU body.
*
* @return bodyList complete sequence numbers PDU body
*/
public byte[] completeSequenceNumberPduBody() {
List<Byte> bodyList = new ArrayList<>();
bodyList.addAll(Bytes.asList(IsisUtil.convertToTwoBytes(this.pduLength())));
bodyList.addAll(IsisUtil.sourceAndLanIdToBytes(this.sourceId()));
bodyList.addAll(IsisUtil.sourceAndLanIdToBytes(this.startLspId()));
bodyList.addAll(IsisUtil.sourceAndLanIdToBytes(this.endLspId()));
for (IsisTlv isisTlv : variableLengths) {
bodyList.addAll(TlvsToBytes.tlvToBytes(isisTlv));
}
return Bytes.toArray(bodyList);
}
/**
* Returns metric of internal reachability values as bytes of metric of internal reachability.
*
* @return byteArray metric of internal reachability values as bytes of metric of internal reachability
*/
public byte[] asBytes() {
List<Byte> bytes = new ArrayList<>();
bytes.add(this.defaultMetric());
int temp = this.delayMetric();
String hsbBits = "";
if (this.isDelayMetricSupported()) {
hsbBits = "0" + hsbBits;
} else {
hsbBits = "1" + hsbBits;
}
if (this.isDelayIsInternal()) {
hsbBits = hsbBits + "0";
} else {
hsbBits = hsbBits + "1";
}
hsbBits = hsbBits + "00";
String binary = hsbBits + IsisUtil.toFourBitBinary(Integer.toBinaryString(temp));
bytes.add((byte) Integer.parseInt(binary, 2));
temp = this.expenseMetric();
hsbBits = "";
if (this.isExpenseMetricSupported()) {
hsbBits = "0" + hsbBits;
} else {
hsbBits = "1" + hsbBits;
}
if (this.isExpenseIsInternal()) {
hsbBits = hsbBits + "0";
} else {
hsbBits = hsbBits + "1";
}
hsbBits = hsbBits + "00";
binary = hsbBits + IsisUtil.toFourBitBinary(Integer.toBinaryString(temp));
bytes.add((byte) Integer.parseInt(binary, 2));
temp = this.errorMetric();
hsbBits = "";
if (this.isErrorMetricSupported()) {
hsbBits = "0" + hsbBits;
} else {
hsbBits = "1" + hsbBits;
}
if (this.isExpenseIsInternal()) {
hsbBits = hsbBits + "0";
} else {
hsbBits = hsbBits + "1";
}
hsbBits = hsbBits + "00";
binary = hsbBits + IsisUtil.toFourBitBinary(Integer.toBinaryString(temp));
bytes.add((byte) Integer.parseInt(binary, 2));
bytes.addAll(Bytes.asList(this.getIpAddress().toOctets()));
bytes.addAll(Bytes.asList(this.getSubnetAddress().toOctets()));
return Bytes.toArray(bytes);
}
private Object toArrayOfType(final Iterable<?> iterable, final Class<?> componentType) {
Collection<?> _xifexpression = null;
if ((iterable instanceof Collection<?>)) {
_xifexpression = ((Collection<?>)iterable);
} else {
_xifexpression = IterableExtensions.toList(iterable);
}
final Collection<?> collection = _xifexpression;
Object _switchResult = null;
boolean _matched = false;
if (Objects.equal(componentType, int.class)) {
_matched=true;
_switchResult = Ints.toArray(((List<Integer>) collection));
}
if (!_matched) {
if (Objects.equal(componentType, long.class)) {
_matched=true;
_switchResult = Longs.toArray(((List<Long>) collection));
}
}
if (!_matched) {
if (Objects.equal(componentType, char.class)) {
_matched=true;
_switchResult = Chars.toArray(((List<Character>) collection));
}
}
if (!_matched) {
if (Objects.equal(componentType, boolean.class)) {
_matched=true;
_switchResult = Booleans.toArray(((List<Boolean>) collection));
}
}
if (!_matched) {
if (Objects.equal(componentType, byte.class)) {
_matched=true;
_switchResult = Bytes.toArray(((List<Byte>) collection));
}
}
if (!_matched) {
if (Objects.equal(componentType, short.class)) {
_matched=true;
_switchResult = Shorts.toArray(((List<Short>) collection));
}
}
if (!_matched) {
if (Objects.equal(componentType, float.class)) {
_matched=true;
_switchResult = Floats.toArray(((List<Float>) collection));
}
}
if (!_matched) {
if (Objects.equal(componentType, double.class)) {
_matched=true;
_switchResult = Doubles.toArray(((List<Double>) collection));
}
}
if (!_matched) {
_switchResult = Iterables.<Object>toArray(collection, ((Class<Object>) componentType));
}
return _switchResult;
}
/**
* Gets byte array of local interface ip address.
*
* @return byte array of local interface ip address
*/
public byte[] tlvBodyAsBytes() {
List<Byte> linkSubTypeBody = new ArrayList<>();
linkSubTypeBody.addAll(Bytes.asList(this.localInterfaceIPAddress.toOctets()));
return Bytes.toArray(linkSubTypeBody);
}