Java Code Examples for com.google.common.primitives.Longs

The following examples show how to use com.google.common.primitives.Longs. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ArchUnit   Source File: JavaClassProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example 2
Source Project: intercom-java   Source File: HttpClient.java    License: Apache License 2.0 6 votes vote down vote up
private <T> T throwException(int responseCode, ErrorCollection errors, HttpURLConnection conn) {
    // bind some well known response codes to exceptions
    if (responseCode == 403 || responseCode == 401) {
        throw new AuthorizationException(errors);
    } else if (responseCode == 429) {
        throw new RateLimitException(errors, Ints.tryParse(conn.getHeaderField(RATE_LIMIT_HEADER)),
                Ints.tryParse(conn.getHeaderField(RATE_LIMIT_REMAINING_HEADER)),
                Longs.tryParse(conn.getHeaderField(RATE_LIMIT_RESET_HEADER)));
    } else if (responseCode == 404) {
        throw new NotFoundException(errors);
    } else if (responseCode == 422) {
        throw new InvalidException(errors);
    } else if (responseCode == 400 || responseCode == 405 || responseCode == 406) {
        throw new ClientException(errors);
    } else if (responseCode == 500 || responseCode == 503) {
        throw new ServerException(errors);
    } else {
        throw new IntercomException(errors);
    }
}
 
Example 3
DataChunk(DataBTree.DataChunk delegate) {
  this.delegate = delegate;

  // Check that the chunk length (delegate.size) isn't greater than the maximum array length that we can
  // allocate (MAX_ARRAY_LEN). This condition manifests in two ways.
  // 1) According to the HDF docs (https://www.hdfgroup.org/HDF5/doc/Advanced/Chunking/, "Chunk Maximum Limits"),
  // max chunk length is 4GB (i.e. representable in an unsigned int). Java, however, only has signed ints.
  // So, if we try to store a large unsigned int in a singed int, it'll overflow, and the signed int will come
  // out negative. We're trusting here that the chunk size read from the HDF file is never negative.
  // 2) In most JVM implementations MAX_ARRAY_LEN is actually less than Integer.MAX_VALUE (see note in ArrayList).
  // So, we could have: "MAX_ARRAY_LEN < chunkSize <= Integer.MAX_VALUE".
  if (delegate.size < 0 || delegate.size > MAX_ARRAY_LEN) {
    // We want to report the size of the chunk, but we may be in an arithmetic overflow situation. So to get the
    // correct value, we're going to reinterpet the integer's bytes as long bytes.
    byte[] intBytes = Ints.toByteArray(delegate.size);
    byte[] longBytes = new byte[8];
    System.arraycopy(intBytes, 0, longBytes, 4, 4); // Copy int bytes to the lowest 4 positions.
    long chunkSize = Longs.fromByteArray(longBytes); // Method requires an array of length 8.

    throw new IllegalArgumentException(String.format("Filtered data chunk is %s bytes and we must load it all "
        + "into memory. However the maximum length of a byte array in Java is %s.", chunkSize, MAX_ARRAY_LEN));
  }
}
 
Example 4
Source Project: incubator-gobblin   Source File: SimpleDataWriter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Write a source record to the staging file
 *
 * @param record data record to write
 * @throws java.io.IOException if there is anything wrong writing the record
 */
@Override
public void write(byte[] record) throws IOException {
  Preconditions.checkNotNull(record);

  byte[] toWrite = record;
  if (this.recordDelimiter.isPresent()) {
    toWrite = Arrays.copyOf(record, record.length + 1);
    toWrite[toWrite.length - 1] = this.recordDelimiter.get();
  }
  if (this.prependSize) {
    long recordSize = toWrite.length;
    ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES);
    buf.putLong(recordSize);
    toWrite = ArrayUtils.addAll(buf.array(), toWrite);
  }
  this.stagingFileOutputStream.write(toWrite);
  this.bytesWritten += toWrite.length;
  this.recordsWritten++;
}
 
Example 5
Source Project: presto   Source File: OrcMetadataReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<BloomFilter> readBloomFilterIndexes(InputStream inputStream)
        throws IOException
{
    CodedInputStream input = CodedInputStream.newInstance(inputStream);
    OrcProto.BloomFilterIndex bloomFilter = OrcProto.BloomFilterIndex.parseFrom(input);
    List<OrcProto.BloomFilter> bloomFilterList = bloomFilter.getBloomFilterList();
    ImmutableList.Builder<BloomFilter> builder = ImmutableList.builder();
    for (OrcProto.BloomFilter orcBloomFilter : bloomFilterList) {
        if (orcBloomFilter.hasUtf8Bitset()) {
            ByteString utf8Bitset = orcBloomFilter.getUtf8Bitset();
            long[] bits = new long[utf8Bitset.size() / 8];
            utf8Bitset.asReadOnlyByteBuffer().order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().get(bits);
            builder.add(new BloomFilter(bits, orcBloomFilter.getNumHashFunctions()));
        }
        else {
            builder.add(new BloomFilter(Longs.toArray(orcBloomFilter.getBitsetList()), orcBloomFilter.getNumHashFunctions()));
        }
    }
    return builder.build();
}
 
Example 6
/**
 * Runs the example.
 *
 * @param adManagerServices the services factory.
 * @param session the session.
 * @param lineItemIds the IDs of the line items to get a forecast for. You may pass multiple
 *     values.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(
    AdManagerServices adManagerServices, AdManagerSession session, List<Long> lineItemIds)
    throws RemoteException {
  // Get the ForecastService.
  ForecastServiceInterface forecastService =
      adManagerServices.get(session, ForecastServiceInterface.class);

  DeliveryForecastOptions options = new DeliveryForecastOptions();

  DeliveryForecast forecast =
      forecastService.getDeliveryForecastByIds(Longs.toArray(lineItemIds), options);

  for (LineItemDeliveryForecast lineItemForecast : forecast.getLineItemDeliveryForecasts()) {
    String unitType = lineItemForecast.getUnitType().toString().toLowerCase();
    System.out.printf("Forecast for line item %d:%n", lineItemForecast.getLineItemId());
    System.out.printf("\t%d %s matched%n", lineItemForecast.getMatchedUnits(), unitType);
    System.out.printf("\t%d %s delivered%n", lineItemForecast.getDeliveredUnits(), unitType);
    System.out.printf(
        "\t%d %s predicted%n", lineItemForecast.getPredictedDeliveryUnits(), unitType);
  }
}
 
Example 7
Source Project: emodb   Source File: ConditionEvaluator.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Boolean visit(ComparisonCondition condition, @Nullable Object json) {
    Comparison comparison = condition.getComparison();
    Object value = condition.getValue();

    // Null comparisons are always false.
    if (json == null || value == null) {
        return false;
    }
    if (json instanceof Number && value instanceof Number) {
        Number nLeft = (Number) json;
        Number nRight = (Number) value;
        if (promoteToDouble(nLeft) || promoteToDouble(nRight)) {
            return matchesComparison(comparison, Doubles.compare(nLeft.doubleValue(), nRight.doubleValue()));
        } else {
            return matchesComparison(comparison, Longs.compare(nLeft.longValue(), nRight.longValue()));
        }
    }
    if (json instanceof String && value instanceof String) {
        return matchesComparison(comparison, ((String) json).compareTo((String) value));
    }
    // Everything else is unsupported and therefore does not match.
    return false;
}
 
Example 8
static
public List<?> getValues(Tensor tensor){
	DataType dataType = tensor.dataType();

	switch(dataType){
		case FLOAT:
			return Floats.asList(TensorUtil.toFloatArray(tensor));
		case DOUBLE:
			return Doubles.asList(TensorUtil.toDoubleArray(tensor));
		case INT32:
			return Ints.asList(TensorUtil.toIntArray(tensor));
		case INT64:
			return Longs.asList(TensorUtil.toLongArray(tensor));
		case STRING:
			return Arrays.asList(TensorUtil.toStringArray(tensor));
		case BOOL:
			return Booleans.asList(TensorUtil.toBooleanArray(tensor));
		default:
			throw new IllegalArgumentException();
	}
}
 
Example 9
Source Project: dremio-oss   Source File: ThreadsIterator.java    License: Apache License 2.0 6 votes vote down vote up
public ThreadsIterator(final SabotContext dbContext, final OperatorContext context) {
  this.dbContext = dbContext;
  threadMXBean = ManagementFactory.getThreadMXBean();
  final long[] ids = threadMXBean.getAllThreadIds();

  final Iterator<Long> threadIdIterator = Longs.asList(ids).iterator();

  this.threadInfoIterator = Iterators.filter(
    Iterators.transform(threadIdIterator, new Function<Long, ThreadInfo>() {

      @Override
      public ThreadInfo apply(Long input) {
        return threadMXBean.getThreadInfo(input, 100);
      }
    }),
    Predicates.notNull());

  logger.debug("number of threads = {}, number of cores = {}", ids.length, VM.availableProcessors());

  this.stats = dbContext.getWorkStatsProvider().get();
}
 
Example 10
private String getAAGUID(FIDO2AttestationObject attObject){
    byte[] aaguidbytes = attObject.getAuthData().getAttCredData().getAaguid();
    byte[] aaguidbytes1 = new byte[8];
    byte[] aaguidbytes2 = new byte[8];
    System.arraycopy(aaguidbytes, 0, aaguidbytes1, 0, 8);
    System.arraycopy(aaguidbytes, 8, aaguidbytes2, 0, 8);
    UUID uuid = new UUID(Longs.fromByteArray(aaguidbytes1), Longs.fromByteArray(aaguidbytes2));
    return uuid.toString();
}
 
Example 11
Source Project: vertexium   Source File: StreamingPropertyValueTableData.java    License: Apache License 2.0 5 votes vote down vote up
private boolean loadMoreData() throws IOException {
    if (closed) {
        return false;
    }
    Iterator<Map.Entry<Key, Value>> it = getScannerIterator();
    while (true) {
        if (!it.hasNext()) {
            close();
            return false;
        }
        Map.Entry<Key, Value> column = it.next();
        if (column.getKey().getColumnFamily().equals(METADATA_COLUMN_FAMILY)) {
            if (column.getKey().getColumnQualifier().equals(METADATA_LENGTH_COLUMN_QUALIFIER)) {
                length = Longs.fromByteArray(column.getValue().get());
                continue;
            }

            throw new VertexiumException("unexpected metadata column qualifier: " + column.getKey().getColumnQualifier() + " (row: " + column.getKey().getRow() + ")");
        }

        if (column.getKey().getColumnFamily().equals(DATA_COLUMN_FAMILY)) {
            currentDataRowIndex++;
            currentByteOffsetInRow = 0;

            byte[] data = column.getValue().get();
            if (length == null) {
                throw new VertexiumException("unexpected missing length (row: " + column.getKey().getRow() + ")");
            }
            long len = Math.min(data.length, length - loadedDataLength);
            buffer.write(data, 0, (int) len);
            previousLoadedDataLength = loadedDataLength;
            loadedDataLength += len;
            return true;
        }

        throw new VertexiumException("unexpected column family: " + column.getKey().getColumnFamily() + " (row: " + column.getKey().getRow() + ")");
    }
}
 
Example 12
Source Project: RedisDirectory   Source File: RedisDirectory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param name file name
 * @return Returns the length of a file in the directory.
 * @throws IOException an I/O error
 */
@Override
public final long fileLength(String name) throws IOException {
    ensureOpen();
    long current = 0;
    byte[] b = inputOutputStream.hget(Constants.DIR_METADATA_BYTES, name.getBytes(), FILE_LENGTH);
    if (b != null) {
        current = Longs.fromByteArray(b);
    }
    return current;
}
 
Example 13
/**
 * Reads a {@code long} as specified by {@link DataInputStream#readLong()}, except using
 * little-endian byte order.
 *
 * @return the next eight bytes of the input stream, interpreted as a {@code long} in
 *     little-endian byte order
 * @throws IOException if an I/O error occurs
 */

@CanIgnoreReturnValue // to skip some bytes
@Override
public long readLong() throws IOException {
  byte b1 = readAndCheckByte();
  byte b2 = readAndCheckByte();
  byte b3 = readAndCheckByte();
  byte b4 = readAndCheckByte();
  byte b5 = readAndCheckByte();
  byte b6 = readAndCheckByte();
  byte b7 = readAndCheckByte();
  byte b8 = readAndCheckByte();
  return Longs.fromBytes(b8, b7, b6, b5, b4, b3, b2, b1);
}
 
Example 14
/**
 * Writes a {@code long} as specified by {@link DataOutputStream#writeLong(long)}, except using
 * little-endian byte order.
 *
 * @throws IOException if an I/O error occurs
 */

@Override
public void writeLong(long v) throws IOException {
  byte[] bytes = Longs.toByteArray(Long.reverseBytes(v));
  write(bytes, 0, bytes.length);
}
 
Example 15
Source Project: sofa-lookout   Source File: PollerController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int compare(Slot o1,
                   Slot o2) {
    return Longs.compare(
        o2.getCursor(),
        o1.getCursor());
}
 
Example 16
Source Project: nifi   Source File: OrcFlowFileWriter.java    License: Apache License 2.0 5 votes vote down vote up
void addBloomFilterEntry() {
    if (createBloomFilter) {
        bloomFilterEntry.setNumHashFunctions(bloomFilter.getNumHashFunctions());
        bloomFilterEntry.addAllBitset(Longs.asList(bloomFilter.getBitSet()));
        bloomFilterIndex.addBloomFilter(bloomFilterEntry.build());
        bloomFilter.reset();
        bloomFilterEntry.clear();
    }
}
 
Example 17
Source Project: xtext-lib   Source File: Conversions.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public int lastIndexOf(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return -1;
	}
	if (o instanceof Long) {
		return Longs.lastIndexOf(array, ((Long) o).longValue());
	}
	return -1;
}
 
Example 18
Source Project: hadoop-ozone   Source File: LongCodec.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Long fromPersistedFormat(byte[] rawData) {
  if (rawData != null) {
    return Longs.fromByteArray(rawData);
  } else {
    return null;
  }
}
 
Example 19
Source Project: imhotep   Source File: TestImhotepLocalSession.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test2DMetricRegroup2() throws ImhotepOutOfMemoryException {
    FlamdexReader r = new2DMetricRegroupTestReader();
    ImhotepLocalSession session = new ImhotepLocalSession(r);
    session.pushStat("if1");
    session.pushStat("if2");

    session.metricRegroup2D(0, 4, 8, 2, 1, 2, 4, 2);

    int[] docIdToGroup = new int[10];
    session.exportDocIdToGroupId(docIdToGroup);
    assertEquals(Ints.asList(5, 5, 9, 9, 10, 10, 11, 11, 12, 12), Ints.asList(docIdToGroup));

    session.pushStat("if3");

    long[] if3 = Arrays.copyOf(session.getGroupStats(2), 13);
    long[] expected = { 0, 0, 0, 0, 0, // 1-4
                       5, 0, 0, 0, // 5-8
                       25, 61, 113, 181, // 9-12
    };

    assertEquals(Longs.asList(expected), Longs.asList(if3));

    BucketStats bs = new BucketStats(if3, 4, 3);
    assertEquals(5, bs.getXUnderflow(0));
    assertEquals(25, bs.getXUnderflowYOverflow());
    assertEquals(61, bs.getYOverflow(0));
    assertEquals(113, bs.getYOverflow(1));
    assertEquals(181, bs.getXYOverflow());

    assertEquals(0, bs.getXYUnderflow());
    assertEquals(0, bs.getYUnderflow(0));
    assertEquals(0, bs.getYUnderflow(1));
    assertEquals(0, bs.getXOverflowYUnderflow());
    assertEquals(0, bs.get(0, 0));
    assertEquals(0, bs.get(1, 0));
}
 
Example 20
public List<Long> getAllBlocks(Long containeID) throws IOException {
  List<Long> allBlocks = Lists.newArrayList();
  ReferenceCountedDB meta = getContainerMetadata(containeID);
  List<Map.Entry<byte[], byte[]>> kvs =
      meta.getStore().getRangeKVs(null, Integer.MAX_VALUE,
          MetadataKeyFilters.getNormalKeyFilter());
  kvs.forEach(entry -> {
    allBlocks.add(Longs.fromByteArray(entry.getKey()));
  });
  meta.close();
  return allBlocks;
}
 
Example 21
Source Project: dhcp4j   Source File: AddressUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testSubtract(byte[] expect, byte[] in, long value) {
    byte[] out = AddressUtils.subtract(C(in), value);
    LOG.info(S(in) + " - " + value + " = " + S(out)
            + " (expected " + S(expect) + ")");
    assertArrayEquals(expect, out);

    byte[] tmp = C(Longs.toByteArray(value), in.length);
    LOG.info(S(in) + " - " + S(tmp) + " = " + S(out) + " (expected " + S(expect) + ")");
    out = AddressUtils.subtract(in, tmp);
    assertArrayEquals(expect, out);
}
 
Example 22
@Override
public int compareTo(TimestampedFilename other) {
  int res = prefix.compareTo(other.getPrefix());
  if (res == 0) {
    res = Longs.compare(timestamp, other.getTimestamp());
  }
  return res;
}
 
Example 23
Source Project: mt-flume   Source File: TestAsyncHBaseSink.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOneEventWithDefaults() throws Exception {
  Map<String,String> ctxMap = new HashMap<String,String>();
  ctxMap.put("table", tableName);
  ctxMap.put("columnFamily", columnFamily);
  ctxMap.put("serializer",
          "org.apache.flume.sink.hbase.SimpleAsyncHbaseEventSerializer");
  ctxMap.put("keep-alive", "0");
  ctxMap.put("timeout", "10000");
  Context tmpctx = new Context();
  tmpctx.putAll(ctxMap);

  testUtility.createTable(tableName.getBytes(), columnFamily.getBytes());
  deleteTable = true;
  AsyncHBaseSink sink = new AsyncHBaseSink(testUtility.getConfiguration());
  Configurables.configure(sink, tmpctx);
  Channel channel = new MemoryChannel();
  Configurables.configure(channel, tmpctx);
  sink.setChannel(channel);
  sink.start();
  Transaction tx = channel.getTransaction();
  tx.begin();
  Event e = EventBuilder.withBody(
          Bytes.toBytes(valBase));
  channel.put(e);
  tx.commit();
  tx.close();
  Assert.assertFalse(sink.isConfNull());
  sink.process();
  sink.stop();
  HTable table = new HTable(testUtility.getConfiguration(), tableName);
  byte[][] results = getResults(table, 1);
  byte[] out = results[0];
  Assert.assertArrayEquals(e.getBody(), out);
  out = results[1];
  Assert.assertArrayEquals(Longs.toByteArray(1), out);
}
 
Example 24
Source Project: warp10-platform   Source File: HHCODEFUNC.java    License: Apache License 2.0 5 votes vote down vote up
private static Object manageFormat(long hh, int res, Object input) {
  Object o;
  if (input instanceof byte[]) {
    o = Longs.toByteArray(hh);
  } else if (input instanceof String) {
    o = HHCodeHelper.toString(hh, res);
  } else {
    o = hh;
  }
  return o;
}
 
Example 25
Source Project: hmftools   Source File: AltContext.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public int hashCode() {
    int h = 5381;
    h += (h << 5) + ref.hashCode();
    h += (h << 5) + alt.hashCode();
    h += (h << 5) + chromosome().hashCode();
    h += (h << 5) + Longs.hashCode(position());
    return h;
}
 
Example 26
Source Project: cloud-search-samples   Source File: FullTraversalSample.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a document for indexing.
 *
 * For this connector sample, the created document is domain public
 *  searchable. The content is a simple text string.
 *
 * @param id unique local id for the document
 * @return the fully formed document ready for indexing
 */
private ApiOperation buildDocument(int id) {
  // [START cloud_search_content_sdk_domain_acl]
  // Make the document publicly readable within the domain
  Acl acl = new Acl.Builder()
      .setReaders(Collections.singletonList(Acl.getCustomerPrincipal()))
      .build();
  // [END cloud_search_content_sdk_domain_acl]

  // [START cloud_search_content_sdk_build_item]
  // Url is required. Use google.com as a placeholder for this sample.
  String viewUrl = "https://www.google.com";

  // Version is required, set to current timestamp.
  byte[] version = Longs.toByteArray(System.currentTimeMillis());

  // Using the SDK item builder class to create the document with appropriate attributes
  // (this can be expanded to include metadata fields etc.)
  Item item = IndexingItemBuilder.fromConfiguration(Integer.toString(id))
      .setItemType(IndexingItemBuilder.ItemType.CONTENT_ITEM)
      .setAcl(acl)
      .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl))
      .setVersion(version)
      .build();
  // [END cloud_search_content_sdk_build_item]

  // [START cloud_search_content_sdk_build_repository_doc]
  // For this sample, content is just plain text
  String content = String.format("Hello world from sample doc %d", id);
  ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content);

  // Create the fully formed document
  RepositoryDoc doc = new RepositoryDoc.Builder()
      .setItem(item)
      .setContent(byteContent, IndexingService.ContentFormat.TEXT)
      .build();
  // [END cloud_search_content_sdk_build_repository_doc]
  return doc;
}
 
Example 27
Source Project: dhcp4j   Source File: AddressUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testSubtract(byte[] expect, byte[] in, long value) {
    byte[] out = AddressUtils.subtract(C(in), value);
    LOG.info(S(in) + " - " + value + " = " + S(out)
            + " (expected " + S(expect) + ")");
    assertArrayEquals(expect, out);

    byte[] tmp = C(Longs.toByteArray(value), in.length);
    LOG.info(S(in) + " - " + S(tmp) + " = " + S(out) + " (expected " + S(expect) + ")");
    out = AddressUtils.subtract(in, tmp);
    assertArrayEquals(expect, out);
}
 
Example 28
Source Project: presto   Source File: ParquetTimestampUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns GMT timestamp from binary encoded parquet timestamp (12 bytes - julian date + time of day nanos).
 *
 * @param timestampBinary INT96 parquet timestamp
 * @return timestamp in millis, GMT timezone
 */
public static long getTimestampMillis(Binary timestampBinary)
{
    if (timestampBinary.length() != 12) {
        throw new PrestoException(NOT_SUPPORTED, "Parquet timestamp must be 12 bytes, actual " + timestampBinary.length());
    }
    byte[] bytes = timestampBinary.getBytes();

    // little endian encoding - need to invert byte order
    long timeOfDayNanos = Longs.fromBytes(bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
    int julianDay = Ints.fromBytes(bytes[11], bytes[10], bytes[9], bytes[8]);

    return julianDayToMillis(julianDay) + (timeOfDayNanos / NANOS_PER_MILLISECOND);
}
 
Example 29
Source Project: glowroot   Source File: Weaver.java    License: Apache License 2.0 5 votes vote down vote up
private void checkForDeadlockedActiveWeaving(List<Long> activeWeavingThreadIds) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long[] deadlockedThreadIds = threadBean.findDeadlockedThreads();
    if (deadlockedThreadIds == null || Collections.disjoint(Longs.asList(deadlockedThreadIds),
            activeWeavingThreadIds)) {
        return;
    }
    // need to disable weaving, otherwise getThreadInfo can trigger class loading and itself get
    // blocked by the deadlocked threads
    weavingDisabledForLoggingDeadlock = true;
    try {
        @Nullable
        ThreadInfo[] threadInfos = threadBean.getThreadInfo(deadlockedThreadIds,
                threadBean.isObjectMonitorUsageSupported(), false);
        StringBuilder sb = new StringBuilder();
        for (ThreadInfo threadInfo : threadInfos) {
            if (threadInfo != null) {
                sb.append('\n');
                appendThreadInfo(sb, threadInfo);
            }
        }
        logger.error("deadlock detected in class weaving, please report to the Glowroot"
                + " project:\n{}", sb);
        // no need to keep checking for (and logging) deadlocked active weaving
        throw new TerminateSubsequentExecutionsException();
    } finally {
        weavingDisabledForLoggingDeadlock = false;
    }
}
 
Example 30
Source Project: phoenix   Source File: PLong.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(Object lhs, Object rhs, PDataType rhsType) {
  if (rhsType == PDecimal.INSTANCE) {
    return -((BigDecimal) rhs).compareTo(BigDecimal.valueOf(((Number) lhs).longValue()));
  } else if (equalsAny(rhsType, PDouble.INSTANCE, PFloat.INSTANCE, PUnsignedDouble.INSTANCE, PUnsignedFloat.INSTANCE)) {
    return Doubles.compare(((Number) lhs).doubleValue(), ((Number) rhs).doubleValue());
  }
  return Longs.compare(((Number) lhs).longValue(), ((Number) rhs).longValue());
}