Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add UnitUtil class #66

Merged
merged 3 commits into from
Mar 19, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.baidu.hugegraph</groupId>
<artifactId>hugegraph-common</artifactId>
<version>1.8.5</version>
<version>1.8.6</version>

<name>hugegraph-common</name>
<url>https://github.com/hugegraph/hugegraph-common</url>
Expand Down Expand Up @@ -266,7 +266,7 @@
<manifestEntries>
<!-- Must be on one line, otherwise the automatic
upgrade script cannot replace the version number -->
<Implementation-Version>1.8.5.0</Implementation-Version>
<Implementation-Version>1.8.6.0</Implementation-Version>
</manifestEntries>
</archive>
</configuration>
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/baidu/hugegraph/util/Bytes.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ public final class Bytes {
public static final long KB = BASE;
public static final long MB = KB * BASE;
public static final long GB = MB * BASE;
public static final long TB = GB * KB;
public static final long PB = GB * MB;
public static final long EB = GB * GB;

private static final Comparator<byte[]> CMP =
UnsignedBytes.lexicographicalComparator();
Expand Down
182 changes: 182 additions & 0 deletions src/main/java/com/baidu/hugegraph/util/UnitUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/*
* Copyright 2017 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.util;

import java.math.BigDecimal;
import java.time.Duration;

public final class UnitUtil {

public static double bytesToMB(long bytes) {
return doubleWith2Scale(bytes / (double) Bytes.MB);
}

public static double bytesToGB(long bytes) {
return doubleWith2Scale(bytes / (double) Bytes.GB);
}

public static double doubleWith2Scale(double value) {
BigDecimal decimal = new BigDecimal(value);
return decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}

public static String bytesToReadableString(long bytes) {
// NOTE: FileUtils.byteCountToDisplaySize() lost decimal precision
final String[] units = {"B", "KB", "MB", "GB", "TB", "PB", "EB"};
if (bytes <= 0L) {
return "0 B";
}
int i = (int) (Math.log(bytes) / Math.log(1024));
E.checkArgument(i < units.length,
"The bytes parameter is out of %s unit: %s",
units[units.length - 1], bytes);
double value = bytes / Math.pow(1024, i);
if (value % 1L == 0L) {
return ((long) value) + " " + units[i];
} else {
return doubleWith2Scale(value) + " " + units[i];
}
}

public static long bytesFromReadableString(String valueWithUnit) {
int spacePos = valueWithUnit.indexOf(" ");
E.checkArgument(spacePos >= 0,
"Invalid readable bytes '%s', " +
"expect format like '10 MB'", valueWithUnit);
String unit = valueWithUnit.substring(spacePos + 1);

long factor = 0L;
switch (unit.trim().toUpperCase()) {
case "B":
case "BYTE":
case "BYTES":
factor = 1L;
break;
case "KB":
case "KIB":
factor = Bytes.KB;
break;
case "MB":
case "MIB":
factor = Bytes.MB;
break;
case "GB":
case "GIB":
factor = Bytes.GB;
break;
case "TB":
case "TIB":
factor = Bytes.TB;
break;
case "PB":
case "PIB":
factor = Bytes.PB;
break;
case "EB":
case "EIB":
factor = Bytes.EB;
break;
default:
throw new IllegalArgumentException("Unrecognized unit " + unit);
}

double value;
try {
value = Double.parseDouble(valueWithUnit.substring(0, spacePos));
} catch (Exception e) {
throw new IllegalArgumentException(String.format(
"Invalid parameter(not number): '%s'", valueWithUnit), e);
}
value = value * factor;
E.checkArgument(value <= Long.MAX_VALUE,
"The value %s from parameter '%s' is out of range",
value, valueWithUnit);
return (long) value;
}

public static String timestampToReadableString(long time) {
Duration duration = Duration.ofMillis(time);
long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long seconds = duration.getSeconds();

if (days > 0) {
return String.format("%dd%dh%dm%ds",
days,
hours % 24,
minutes % 60,
seconds % 60);
} else if (hours > 0) {
return String.format("%dh%dm%ds",
hours,
minutes % 60,
seconds % 60);
} else if (minutes > 0) {
return String.format("%dm%ds",
minutes,
seconds % 60);
} else if (seconds > 0) {
long ms = duration.toMillis() % 1000L;
if (ms > 0L) {
return String.format("%ds%dms", seconds, ms);
} else {
return String.format("%ds", seconds);
}
} else {
return String.format("%dms", duration.toMillis());
}
}

public static long timestampFromReadableString(String valueWithUnit) {
long ms = 0L;
// Adapt format 'nDnHnMnS' to 'PnYnMnDTnHnMnS'
String formatDuration = valueWithUnit.toUpperCase();
if (formatDuration.indexOf('D') >= 0) {
// Contains days
assert !formatDuration.contains("MS");
formatDuration = "P" + formatDuration.replace("D", "DT");
} else {
// Not exists days
int msPos = formatDuration.indexOf("MS");
// If contains ms, rmove the ms part
if (msPos >= 0) {
int sPos = formatDuration.indexOf("S");
if (0 <= sPos && sPos < msPos) {
// If contains second part
sPos += 1;
ms = Long.parseLong(formatDuration.substring(sPos, msPos));
ms %= 1000L;
formatDuration = formatDuration.substring(0, sPos);
} else {
// Not contains second part, only exists ms
ms = Long.parseLong(formatDuration.substring(0, msPos));
return ms;
}
} else {
assert formatDuration.endsWith("S");
}
formatDuration = "PT" + formatDuration;
}

Duration duration = Duration.parse(formatDuration);
return duration.toMillis() + ms;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ public class CommonVersion {

// The second parameter of Version.of() is for all-in-one JAR
public static final Version VERSION = Version.of(CommonVersion.class,
"1.8.5");
"1.8.6");
}
4 changes: 3 additions & 1 deletion src/test/java/com/baidu/hugegraph/unit/UnitTestSuite.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import com.baidu.hugegraph.unit.concurrent.KeyLockTest;
import com.baidu.hugegraph.unit.concurrent.LockGroupTest;
import com.baidu.hugegraph.unit.concurrent.LockManagerTest;
import com.baidu.hugegraph.unit.concurrent.PausableScheduledThreadPoolTest;
import com.baidu.hugegraph.unit.concurrent.RowLockTest;
import com.baidu.hugegraph.unit.config.HugeConfigTest;
import com.baidu.hugegraph.unit.config.OptionSpaceTest;
Expand All @@ -50,7 +51,6 @@
import com.baidu.hugegraph.unit.perf.PerfUtilTest;
import com.baidu.hugegraph.unit.rest.RestClientTest;
import com.baidu.hugegraph.unit.rest.RestResultTest;
import com.baidu.hugegraph.unit.concurrent.PausableScheduledThreadPoolTest;
import com.baidu.hugegraph.unit.util.BytesTest;
import com.baidu.hugegraph.unit.util.CollectionUtilTest;
import com.baidu.hugegraph.unit.util.DateUtilTest;
Expand All @@ -62,6 +62,7 @@
import com.baidu.hugegraph.unit.util.ReflectionUtilTest;
import com.baidu.hugegraph.unit.util.StringUtilTest;
import com.baidu.hugegraph.unit.util.TimeUtilTest;
import com.baidu.hugegraph.unit.util.UnitUtilTest;
import com.baidu.hugegraph.unit.util.VersionUtilTest;
import com.baidu.hugegraph.unit.version.VersionTest;

Expand Down Expand Up @@ -105,6 +106,7 @@
LongEncodingTest.class,
OrderLimitMapTest.class,
DateUtilTest.class,
UnitUtilTest.class,

ExtraParamTest.class,
LicenseCreateParamTest.class,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void testClasses() throws IOException {
@SuppressWarnings("unchecked")
List<ClassInfo> classes = IteratorUtils.toList(ReflectionUtil.classes(
"com.baidu.hugegraph.util"));
Assert.assertEquals(16, classes.size());
Assert.assertEquals(17, classes.size());
classes.sort((c1, c2) -> c1.getName().compareTo(c2.getName()));
Assert.assertEquals("com.baidu.hugegraph.util.Bytes",
classes.get(0).getName());
Expand All @@ -100,7 +100,7 @@ public void testClasses() throws IOException {
Assert.assertEquals("com.baidu.hugegraph.util.CollectionUtil",
classes.get(2).getName());
Assert.assertEquals("com.baidu.hugegraph.util.VersionUtil",
classes.get(15).getName());
classes.get(16).getName());
}

@Test
Expand Down
Loading