diff --git a/api/src/main/java/org/apache/cloudstack/api/response/StatsResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/StatsResponse.java index 232daa4f4a9a..e477f1ac8635 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/StatsResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/StatsResponse.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @@ -90,6 +91,10 @@ public void setCpuUsed(String cpuUsed) { this.cpuUsed = cpuUsed; } + public String getCpuUsed() { + return cpuUsed; + } + public void setDiskIORead(Long diskIORead) { this.diskIORead = diskIORead; accumulateDiskIopsTotal(diskIORead); @@ -123,14 +128,14 @@ public void setMemoryTargetKBs(Long memoryTargetKBs) { public void setNetworkKbsRead(Long networkKbsRead) { this.networkKbsRead = networkKbsRead; if (networkKbsRead != null) { - this.networkRead = String.format("%.2f MiB", networkKbsRead / 1024.0); + this.networkRead = NumberFormatUtils.format("%.2f MiB", networkKbsRead / 1024.0); } } public void setNetworkKbsWrite(Long networkKbsWrite) { this.networkKbsWrite = networkKbsWrite; if (networkKbsWrite != null) { - this.networkWrite = String.format("%.2f MiB", networkKbsWrite / 1024.0); + this.networkWrite = NumberFormatUtils.format("%.2f MiB", networkKbsWrite / 1024.0); } } diff --git a/api/src/test/java/org/apache/cloudstack/api/response/StatsResponseTest.java b/api/src/test/java/org/apache/cloudstack/api/response/StatsResponseTest.java index 938488e2a11f..b65329e208c1 100644 --- a/api/src/test/java/org/apache/cloudstack/api/response/StatsResponseTest.java +++ b/api/src/test/java/org/apache/cloudstack/api/response/StatsResponseTest.java @@ -16,7 +16,7 @@ // under the License. package org.apache.cloudstack.api.response; -import java.text.DecimalFormat; +import java.util.Locale; import org.junit.Assert; import org.junit.Test; @@ -31,8 +31,6 @@ public class StatsResponseTest { @Spy StatsResponse statsResponseMock; - final char decimalSeparator = ((DecimalFormat) DecimalFormat.getInstance()).getDecimalFormatSymbols().getDecimalSeparator(); - @Test public void setDiskIOReadTestWithAnyInput() { statsResponseMock.setDiskIORead(1L); @@ -106,7 +104,7 @@ public void setNetworkKbsReadTestWithNullInput() { @Test public void setNetworkKbsReadTestWithInputNotNull() { Long expectedNetworkKbsRead = Long.valueOf("100"); - String expectedNetworkRead = String.format("0%s10 MiB", decimalSeparator); // the actual result is 0.097 but the value is rounded to 0.10 + String expectedNetworkRead = "0.10 MiB"; // the actual result is 0.097 but the value is rounded to 0.10 statsResponseMock.setNetworkKbsRead(expectedNetworkKbsRead); @@ -125,11 +123,26 @@ public void setNetworkKbsWriteTestWithNullInput() { @Test public void setNetworkKbsWriteTestWithInputNotNull() { Long expectedNetworkKbsWrite = Long.valueOf("100"); - String expectedNetworkWrite = String.format("0%s10 MiB", decimalSeparator); // the actual result is 0.097 but the value is rounded to 0.10 + String expectedNetworkWrite = "0.10 MiB"; // the actual result is 0.097 but the value is rounded to 0.10 statsResponseMock.setNetworkKbsWrite(expectedNetworkKbsWrite); Assert.assertEquals(expectedNetworkKbsWrite, statsResponseMock.networkKbsWrite); Assert.assertEquals(expectedNetworkWrite, statsResponseMock.networkWrite); } + + @Test + public void setNetworkKbsUsesDotAsDecimalSeparatorRegardlessOfDefaultLocale() { + Locale originalLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.GERMANY); + statsResponseMock.setNetworkKbsRead(100L); + statsResponseMock.setNetworkKbsWrite(100L); + + Assert.assertEquals("0.10 MiB", statsResponseMock.networkRead); + Assert.assertEquals("0.10 MiB", statsResponseMock.networkWrite); + } finally { + Locale.setDefault(originalLocale); + } + } } diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/metrics/MetricsServiceImpl.java b/plugins/metrics/src/main/java/org/apache/cloudstack/metrics/MetricsServiceImpl.java index 0321d7c08d9e..04af33279682 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/metrics/MetricsServiceImpl.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/metrics/MetricsServiceImpl.java @@ -26,6 +26,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; @@ -81,6 +82,7 @@ import org.apache.cloudstack.storage.datastore.db.ObjectStoreDao; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.utils.NumberFormatUtils; import org.apache.cloudstack.utils.bytescale.ByteScaleUtils; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.collections.CollectionUtils; @@ -540,14 +542,14 @@ protected ListResponse createVmMetricsStatsResponse(List /** - * Creates a {@code Set} from a given {@code List}. + * Creates a {@code List} from a given {@code List}. * * @param vmStatsList the list of VM stats. - * @return the set of responses that was created. + * @return the list of responses that was created. */ protected List createStatsResponse(List vmStatsList) { - List statsResponseList = new ArrayList(); - DecimalFormat decimalFormat = new DecimalFormat("#.##"); + List statsResponseList = new ArrayList<>(); + DecimalFormat decimalFormat = NumberFormatUtils.decimalFormat("#.##"); for (VmStatsVO vmStats : vmStatsList) { StatsResponse response = new StatsResponse(); response.setTimestamp(vmStats.getTimestamp()); @@ -995,10 +997,10 @@ private void copyManagementServerStatusToResponse(ManagementServerMetricsRespons metricsResponse.setThreadsTerminatedCount(status.getThreadsTerminatedCount()); metricsResponse.setThreadsTotalCount(status.getThreadsTotalCount()); metricsResponse.setThreadsWaitingCount(status.getThreadsWaitingCount()); - metricsResponse.setSystemMemoryTotal(toReadableSize(status.getSystemMemoryTotal())); - metricsResponse.setSystemMemoryFree(toReadableSize(status.getSystemMemoryFree())); + metricsResponse.setSystemMemoryTotal(toReadableSize(status.getSystemMemoryTotal(), Locale.ROOT)); + metricsResponse.setSystemMemoryFree(toReadableSize(status.getSystemMemoryFree(), Locale.ROOT)); // we are not adding metricsResponse.setSystemMemoryUsed(toReadableSize(status.getSystemMemoryUsed())); as the value is confusing and arguably wrong - metricsResponse.setSystemMemoryVirtualSize(toReadableSize(status.getSystemMemoryVirtualSize())); + metricsResponse.setSystemMemoryVirtualSize(toReadableSize(status.getSystemMemoryVirtualSize(), Locale.ROOT)); metricsResponse.setLogInfo(status.getLogInfo()); metricsResponse.setSystemTotalCpuCycles(status.getSystemTotalCpuCycles()); metricsResponse.setSystemLoadAverages(status.getSystemLoadAverages()); diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/ClusterMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/ClusterMetricsResponse.java index cfaaa5ce4a77..d64a8124f7be 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/ClusterMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/ClusterMetricsResponse.java @@ -20,6 +20,7 @@ import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; public class ClusterMetricsResponse extends ClusterResponse implements HostMetricsSummary { @SerializedName("state") @@ -116,51 +117,51 @@ public void setResources(final Long upResources, final Long totalResources) { public void setCpuTotal(final Long cpuTotal) { if (cpuTotal != null) { - this.cpuTotal = String.format("%.2f Ghz", cpuTotal / 1000.0); + this.cpuTotal = NumberFormatUtils.format("%.2f Ghz", cpuTotal / 1000.0); } } public void setCpuUsed(final Double cpuUsedPercentage, final Long totalHosts) { if (cpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { - this.cpuUsed = String.format("%.2f%%", 1.0 * cpuUsedPercentage / totalHosts); + this.cpuUsed = NumberFormatUtils.format("%.2f%%", 1.0 * cpuUsedPercentage / totalHosts); } } public void setCpuAllocated(final Long cpuAllocated, final Long cpuTotal) { if (cpuAllocated != null && cpuTotal != null && cpuTotal != 0) { - this.cpuAllocated = String.format("%.2f%%", cpuAllocated * 100.0 / cpuTotal); + this.cpuAllocated = NumberFormatUtils.format("%.2f%%", cpuAllocated * 100.0 / cpuTotal); } } public void setCpuMaxDeviation(final Double maxCpuUsagePercentage, final Double totalCpuUsedPercentage, final Long totalHosts) { if (maxCpuUsagePercentage != null && totalCpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { final Double averageCpuUsagePercentage = totalCpuUsedPercentage / totalHosts; - this.cpuMaxDeviation = String.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) / averageCpuUsagePercentage); + this.cpuMaxDeviation = NumberFormatUtils.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) / averageCpuUsagePercentage); } } public void setMemTotal(final Long memTotal) { if (memTotal != null) { - this.memTotal = String.format("%.2f GB", memTotal / (1024.0 * 1024.0 * 1024.0)); + this.memTotal = NumberFormatUtils.format("%.2f GB", memTotal / (1024.0 * 1024.0 * 1024.0)); } } public void setMemUsed( final Long memUsed, final Long memTotal) { if (memUsed != null && memTotal != null && memTotal != 0) { - this.memUsed = String.format("%.2f%%", memUsed * 100.0 / memTotal); + this.memUsed = NumberFormatUtils.format("%.2f%%", memUsed * 100.0 / memTotal); } } public void setMemAllocated(final Long memAllocated, final Long memTotal) { if (memAllocated != null && memTotal != null && memTotal != 0) { - this.memAllocated = String.format("%.2f%%", memAllocated * 100.0 / memTotal); + this.memAllocated = NumberFormatUtils.format("%.2f%%", memAllocated * 100.0 / memTotal); } } public void setMemMaxDeviation(final Long maxMemoryUsage, final Long totalMemory, final Long totalHosts) { if (maxMemoryUsage != null && totalMemory != null && totalHosts != null && totalHosts != 0) { final Double averageMemoryUsage = 1.0 * totalMemory / totalHosts; - this.memMaxDeviation = String.format("%.2f%%", (maxMemoryUsage - averageMemoryUsage) * 100.0 / averageMemoryUsage); + this.memMaxDeviation = NumberFormatUtils.format("%.2f%%", (maxMemoryUsage - averageMemoryUsage) * 100.0 / averageMemoryUsage); } } @@ -215,7 +216,7 @@ public void setMemoryAllocatedDisableThreshold(final Long memAllocated, final Lo public void setDrsImbalance(Double drsImbalance) { if (drsImbalance != null) { - this.drsImbalance = String.format("%.2f%%", drsImbalance); + this.drsImbalance = NumberFormatUtils.format("%.2f%%", drsImbalance); } else { this.drsImbalance = null; } diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/HostMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/HostMetricsResponse.java index 3e48cd4280f0..f6ef931e738b 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/HostMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/HostMetricsResponse.java @@ -22,6 +22,7 @@ import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.outofbandmanagement.OutOfBandManagement; +import org.apache.cloudstack.utils.NumberFormatUtils; import com.cloud.serializer.Param; import com.cloud.utils.exception.CloudRuntimeException; @@ -118,19 +119,19 @@ public void setInstances(final long running, final long total) { public void setCpuTotal(final Integer cpuNumber, final Long cpuSpeed) { if (cpuNumber != null && cpuSpeed != null) { - this.cpuTotal = String.format("%.2f Ghz", cpuNumber * cpuSpeed / 1000.0); + this.cpuTotal = NumberFormatUtils.format("%.2f Ghz", cpuNumber * cpuSpeed / 1000.0); } } public void setCpuUsed(final String cpuUsed, final Integer cpuNumber, final Long cpuSpeed) { if (cpuUsed != null && cpuNumber != null && cpuSpeed != null) { - this.cpuUsed = String.format("%.2f Ghz", parseCPU(cpuUsed) * cpuNumber * cpuSpeed / (100.0 * 1000.0)); + this.cpuUsed = NumberFormatUtils.format("%.2f Ghz", parseCPU(cpuUsed) * cpuNumber * cpuSpeed / (100.0 * 1000.0)); } } public void setCpuAllocated(final String cpuAllocated, final Integer cpuNumber, final Long cpuSpeed) { if (cpuAllocated != null && cpuNumber != null && cpuSpeed != null) { - this.cpuAllocated = String.format("%.2f Ghz", parseCPU(cpuAllocated) * cpuNumber * cpuSpeed / (100.0 * 1000.0)); + this.cpuAllocated = NumberFormatUtils.format("%.2f Ghz", parseCPU(cpuAllocated) * cpuNumber * cpuSpeed / (100.0 * 1000.0)); } } @@ -140,31 +141,31 @@ public String getCpuAllocatedGhz() { public void setMemTotal(final Long memTotal) { if (memTotal != null) { - this.memTotal = String.format("%.2f GB", memTotal / (1024.0 * 1024.0 * 1024.0)); + this.memTotal = NumberFormatUtils.format("%.2f GB", memTotal / (1024.0 * 1024.0 * 1024.0)); } } public void setMemUsed(final Long memUsed) { if (memUsed != null) { - this.memUsed = String.format("%.2f GB", memUsed / (1024.0 * 1024.0 * 1024.0)); + this.memUsed = NumberFormatUtils.format("%.2f GB", memUsed / (1024.0 * 1024.0 * 1024.0)); } } public void setMemAllocated(final Long memAllocated) { if (memAllocated != null) { - this.memAllocated = String.format("%.2f GB", memAllocated / (1024.0 * 1024.0 * 1024.0)); + this.memAllocated = NumberFormatUtils.format("%.2f GB", memAllocated / (1024.0 * 1024.0 * 1024.0)); } } public void setNetworkRead(final Long networkReadKbs) { if (networkReadKbs != null) { - this.networkRead = String.format("%.2f GB", networkReadKbs / (1024.0 * 1024.0)); + this.networkRead = NumberFormatUtils.format("%.2f GB", networkReadKbs / (1024.0 * 1024.0)); } } public void setNetworkWrite(final Long networkWriteKbs) { if (networkWriteKbs != null) { - this.networkWrite = String.format("%.2f GB", networkWriteKbs / (1024.0 * 1024.0)); + this.networkWrite = NumberFormatUtils.format("%.2f GB", networkWriteKbs / (1024.0 * 1024.0)); } } @@ -217,7 +218,7 @@ public void setMemoryAllocatedDisableThreshold(final Long memAllocated, final Lo } private Double parseCPU(String cpu) { - DecimalFormat decimalFormat = new DecimalFormat("#.##"); + DecimalFormat decimalFormat = NumberFormatUtils.decimalFormat("#.##"); try { return decimalFormat.parse(cpu).doubleValue(); } catch (ParseException e) { diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/ManagementServerMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/ManagementServerMetricsResponse.java index 3c5093d69a37..a1064057b98a 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/ManagementServerMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/ManagementServerMetricsResponse.java @@ -20,6 +20,7 @@ import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.MetricConstants; import org.apache.cloudstack.api.response.ManagementServerResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; import java.util.Date; @@ -206,6 +207,6 @@ public void setCollectionTime(Date collectionTime) { } public void setCpuLoad(double cpuLoad) { - this.cpuLoad = String.format("%.2f %%",cpuLoad); + this.cpuLoad = NumberFormatUtils.format("%.2f %%",cpuLoad); } } diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/StoragePoolMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/StoragePoolMetricsResponse.java index 6902761643e2..18065ed7fd42 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/StoragePoolMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/StoragePoolMetricsResponse.java @@ -20,6 +20,7 @@ import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; public class StoragePoolMetricsResponse extends StoragePoolResponse { @SerializedName("disksizeusedgb") @@ -56,26 +57,26 @@ public class StoragePoolMetricsResponse extends StoragePoolResponse { public void setDiskSizeUsedGB(final Long diskSizeUsed) { if (diskSizeUsed != null) { - this.diskSizeUsedGB = String.format("%.2f GB", diskSizeUsed / (1024.0 * 1024.0 * 1024.0)); + this.diskSizeUsedGB = NumberFormatUtils.format("%.2f GB", diskSizeUsed / (1024.0 * 1024.0 * 1024.0)); } } public void setDiskSizeTotalGB(final Long totalDiskSize, final String overProvisionFactor) { if (totalDiskSize != null && overProvisionFactor != null) { - this.diskSizeTotalGB = String.format("%.2f GB (x%s)", totalDiskSize / (1024.0 * 1024.0 * 1024.0), overProvisionFactor); + this.diskSizeTotalGB = NumberFormatUtils.format("%.2f GB (x%s)", totalDiskSize / (1024.0 * 1024.0 * 1024.0), overProvisionFactor); } } public void setDiskSizeAllocatedGB(final Long diskSizeAllocated) { if (diskSizeAllocated != null) { - this.diskSizeAllocatedGB = String.format("%.2f GB", diskSizeAllocated / (1024.0 * 1024.0 * 1024.0)); + this.diskSizeAllocatedGB = NumberFormatUtils.format("%.2f GB", diskSizeAllocated / (1024.0 * 1024.0 * 1024.0)); } } public void setDiskSizeUnallocatedGB(final Long totalDiskSize, final Long diskSizeAllocated, final String overProvisionFactor) { if (totalDiskSize != null && diskSizeAllocated != null && overProvisionFactor != null) { - this.diskSizeUnallocatedGB = String.format("%.2f GB", ((Double.valueOf(overProvisionFactor) * totalDiskSize) - diskSizeAllocated) / (1024.0 * 1024.0 * 1024.0)); + this.diskSizeUnallocatedGB = NumberFormatUtils.format("%.2f GB", ((Double.valueOf(overProvisionFactor) * totalDiskSize) - diskSizeAllocated) / (1024.0 * 1024.0 * 1024.0)); } } diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/VmMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/VmMetricsResponse.java index 6de8e5e0ecbb..dc1031134e52 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/VmMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/VmMetricsResponse.java @@ -19,6 +19,7 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @@ -56,37 +57,37 @@ public class VmMetricsResponse extends UserVmResponse { public void setCpuTotal(final Integer cpuNumber, final Integer cpuSpeed) { if (cpuNumber != null && cpuSpeed != null) { - this.cpuTotal = String.format("%.1f Ghz", cpuNumber * cpuSpeed / 1000.0); + this.cpuTotal = NumberFormatUtils.format("%.1f Ghz", cpuNumber * cpuSpeed / 1000.0); } } public void setMemTotal(final Integer memory) { if (memory != null) { - this.memTotal = String.format("%.2f GiB", memory / 1024.0); + this.memTotal = NumberFormatUtils.format("%.2f GiB", memory / 1024.0); } } public void setNetworkRead(final Long networkReadKbs) { if (networkReadKbs != null) { - this.networkRead = String.format("%.2f MiB", networkReadKbs / 1024.0); + this.networkRead = NumberFormatUtils.format("%.2f MiB", networkReadKbs / 1024.0); } } public void setNetworkWrite(final Long networkWriteKbs) { if (networkWriteKbs != null) { - this.networkWrite = String.format("%.2f MiB", networkWriteKbs / 1024.0); + this.networkWrite = NumberFormatUtils.format("%.2f MiB", networkWriteKbs / 1024.0); } } public void setDiskRead(final Long diskReadKbs) { if (diskReadKbs != null) { - this.diskRead = String.format("%.2f MiB", diskReadKbs / 1024.0); + this.diskRead = NumberFormatUtils.format("%.2f MiB", diskReadKbs / 1024.0); } } public void setDiskWrite(final Long diskWriteKbs) { if (diskWriteKbs != null) { - this.diskWrite = String.format("%.2f MiB", diskWriteKbs / 1024.0); + this.diskWrite = NumberFormatUtils.format("%.2f MiB", diskWriteKbs / 1024.0); } } diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/VolumeMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/VolumeMetricsResponse.java index 8622eea89e97..c45e6e99b719 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/VolumeMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/VolumeMetricsResponse.java @@ -19,6 +19,7 @@ import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; import com.cloud.serializer.Param; import org.apache.commons.lang3.StringUtils; @@ -41,7 +42,7 @@ public void setStorageType(final String storageType, final String volumeType) { public void setDiskSizeGB(final Long size) { if (size != null) { - this.diskSizeGB = String.format("%.2f GiB", size / (1024.0 * 1024.0 * 1024.0)); + this.diskSizeGB = NumberFormatUtils.format("%.2f GiB", size / (1024.0 * 1024.0 * 1024.0)); } } diff --git a/plugins/metrics/src/main/java/org/apache/cloudstack/response/ZoneMetricsResponse.java b/plugins/metrics/src/main/java/org/apache/cloudstack/response/ZoneMetricsResponse.java index f8770399628c..d51f174f2f8a 100644 --- a/plugins/metrics/src/main/java/org/apache/cloudstack/response/ZoneMetricsResponse.java +++ b/plugins/metrics/src/main/java/org/apache/cloudstack/response/ZoneMetricsResponse.java @@ -20,6 +20,7 @@ import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.utils.NumberFormatUtils; public class ZoneMetricsResponse extends ZoneResponse implements HostMetricsSummary { @SerializedName("state") @@ -107,51 +108,51 @@ public void setResource(final Long upResources, final Long totalResources) { public void setCpuTotal(final Long cpuTotal) { if (cpuTotal != null) { - this.cpuTotal = String.format("%.2f Ghz", cpuTotal / 1000.0); + this.cpuTotal = NumberFormatUtils.format("%.2f Ghz", cpuTotal / 1000.0); } } public void setCpuUsed(final Double cpuUsedPercentage, final Long totalHosts) { if (cpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { - this.cpuUsed = String.format("%.2f%%", 1.0 * cpuUsedPercentage / totalHosts); + this.cpuUsed = NumberFormatUtils.format("%.2f%%", 1.0 * cpuUsedPercentage / totalHosts); } } public void setCpuAllocated(final Long cpuAllocated, final Long cpuTotal) { if (cpuAllocated != null && cpuTotal != null && cpuTotal != 0) { - this.cpuAllocated = String.format("%.2f%%", cpuAllocated * 100.0 / cpuTotal); + this.cpuAllocated = NumberFormatUtils.format("%.2f%%", cpuAllocated * 100.0 / cpuTotal); } } public void setCpuMaxDeviation(final Double maxCpuUsagePercentage, final Double totalCpuUsedPercentage, final Long totalHosts) { if (maxCpuUsagePercentage != null && totalCpuUsedPercentage != null && totalHosts != null && totalHosts != 0) { final Double averageCpuUsagePercentage = totalCpuUsedPercentage / totalHosts; - this.cpuMaxDeviation = String.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) / averageCpuUsagePercentage); + this.cpuMaxDeviation = NumberFormatUtils.format("%.2f%%", (maxCpuUsagePercentage - averageCpuUsagePercentage) / averageCpuUsagePercentage); } } public void setMemTotal(final Long memTotal) { if (memTotal != null) { - this.memTotal = String.format("%.2f GB", memTotal / (1024.0 * 1024.0 * 1024.0)); + this.memTotal = NumberFormatUtils.format("%.2f GB", memTotal / (1024.0 * 1024.0 * 1024.0)); } } public void setMemUsed( final Long memUsed, final Long memTotal) { if (memUsed != null && memTotal != null) { - this.memUsed = String.format("%.2f%%", memUsed * 100.0 / memTotal); + this.memUsed = NumberFormatUtils.format("%.2f%%", memUsed * 100.0 / memTotal); } } public void setMemAllocated(final Long memAllocated, final Long memTotal) { if (memAllocated != null && memTotal != null && memTotal != 0) { - this.memAllocated = String.format("%.2f%%", memAllocated * 100.0 / memTotal); + this.memAllocated = NumberFormatUtils.format("%.2f%%", memAllocated * 100.0 / memTotal); } } public void setMemMaxDeviation(final Long maxMemoryUsage, final Long totalMemory, final Long totalHosts) { if (maxMemoryUsage != null && totalMemory != null && totalHosts != null && totalHosts != 0) { final Long averageMemoryUsage = totalMemory / totalHosts; - this.memMaxDeviation = String.format("%.2f%%", (maxMemoryUsage - averageMemoryUsage) * 100.0 / averageMemoryUsage); + this.memMaxDeviation = NumberFormatUtils.format("%.2f%%", (maxMemoryUsage - averageMemoryUsage) * 100.0 / averageMemoryUsage); } } diff --git a/plugins/metrics/src/test/java/org/apache/cloudstack/metrics/MetricsServiceImplTest.java b/plugins/metrics/src/test/java/org/apache/cloudstack/metrics/MetricsServiceImplTest.java index 9184d7444105..0a7444f3ed3d 100644 --- a/plugins/metrics/src/test/java/org/apache/cloudstack/metrics/MetricsServiceImplTest.java +++ b/plugins/metrics/src/test/java/org/apache/cloudstack/metrics/MetricsServiceImplTest.java @@ -23,11 +23,13 @@ import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import org.apache.cloudstack.api.ListVMsUsageHistoryCmd; import org.apache.cloudstack.api.ListVolumesUsageHistoryCmd; import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.StatsResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.response.VmMetricsStatsResponse; import org.apache.commons.lang3.time.DateUtils; @@ -368,6 +370,26 @@ public void createStatsResponseTestWithValidStatsData() { spy.createStatsResponse(Arrays.asList(vmStatsVOMock)); } + @Test + public void createStatsResponseUsesDotAsDecimalSeparatorRegardlessOfDefaultLocale() { + Locale originalLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.GERMANY); + final String fakeVmStatsData = "{\"vmId\":1,\"cpuUtilization\":15.615905273486222,\"networkReadKBs\":1024.0," + + "\"networkWriteKBs\":2048.0,\"diskReadIOs\":0.1,\"diskWriteIOs\":0.2,\"diskReadKBs\":1.1," + + "\"diskWriteKBs\":2.1,\"memoryKBs\":262144.0,\"intfreememoryKBs\":262144.0,\"targetmemoryKBs\":262144.0," + + "\"numCPUs\":1,\"entityType\":\"vm\"}"; + Mockito.doReturn(new Date()).when(vmStatsVOMock).getTimestamp(); + Mockito.doReturn(fakeVmStatsData).when(vmStatsVOMock).getVmStatsData(); + + List statsResponseList = spy.createStatsResponse(Arrays.asList(vmStatsVOMock)); + + Assert.assertEquals("15.62%", statsResponseList.get(0).getCpuUsed()); + } finally { + Locale.setDefault(originalLocale); + } + } + @Test public void searchForVolumesInternalWithValidParameters() { Mockito.doReturn(null).when(listVolumesUsageHistoryCmdMock).getId(); @@ -419,5 +441,4 @@ public void searchForVolumesInternalWithValidParametersNoItem() { Assert.assertEquals(0, result.second().intValue()); } } - } diff --git a/plugins/metrics/src/test/java/org/apache/cloudstack/response/HostMetricsResponseTest.java b/plugins/metrics/src/test/java/org/apache/cloudstack/response/HostMetricsResponseTest.java index d81d6f6dadbf..799ddb8d1f1c 100644 --- a/plugins/metrics/src/test/java/org/apache/cloudstack/response/HostMetricsResponseTest.java +++ b/plugins/metrics/src/test/java/org/apache/cloudstack/response/HostMetricsResponseTest.java @@ -17,7 +17,7 @@ package org.apache.cloudstack.response; -import java.text.DecimalFormat; +import java.util.Locale; import org.junit.Assert; import org.junit.Test; @@ -26,13 +26,11 @@ public class HostMetricsResponseTest { - final char decimalSeparator = ((DecimalFormat) DecimalFormat.getInstance()).getDecimalFormatSymbols().getDecimalSeparator(); - @Test public void testSetCpuAllocatedWithZeroCpu() { final HostMetricsResponse hostResponse = new HostMetricsResponse(); - hostResponse.setCpuAllocated(String.format("50%s25%%", decimalSeparator), 0, 1000L); - Assert.assertEquals(String.format("0%s00 Ghz", decimalSeparator), hostResponse.getCpuAllocatedGhz()); + hostResponse.setCpuAllocated("50.25%", 0, 1000L); + Assert.assertEquals("0.00 Ghz", hostResponse.getCpuAllocatedGhz()); } @Test @@ -50,10 +48,22 @@ public void testSetCpuAllocatedWithInvalidCpu() { @Test public void testSetCpuAllocatedWithValidCpu() { - String expected = String.format("5%s03 Ghz", decimalSeparator); final HostMetricsResponse hostResponse = new HostMetricsResponse(); - hostResponse.setCpuAllocated(String.format("50%s25%%", decimalSeparator), 10, 1000L); - Assert.assertEquals(expected, hostResponse.getCpuAllocatedGhz()); + hostResponse.setCpuAllocated("50.25%", 10, 1000L); + Assert.assertEquals("5.03 Ghz", hostResponse.getCpuAllocatedGhz()); + } + + @Test + public void testSetCpuAllocatedUsesDotAsDecimalSeparatorRegardlessOfDefaultLocale() { + Locale originalLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.GERMANY); + final HostMetricsResponse hostResponse = new HostMetricsResponse(); + hostResponse.setCpuAllocated("50.25%", 10, 1000L); + Assert.assertEquals("5.03 Ghz", hostResponse.getCpuAllocatedGhz()); + } finally { + Locale.setDefault(originalLocale); + } } @Test @@ -68,7 +78,7 @@ public void testSetCpuAllocatedWithNullCpu() { public void testSetCpuAllocatedWithNullCpuNumber() { String expected = null; final HostMetricsResponse hostResponse = new HostMetricsResponse(); - hostResponse.setCpuAllocated(String.format("50%s25%%", decimalSeparator), null, 1000L); + hostResponse.setCpuAllocated("50.25%", null, 1000L); Assert.assertEquals(expected, hostResponse.getCpuAllocatedGhz()); } @@ -76,7 +86,7 @@ public void testSetCpuAllocatedWithNullCpuNumber() { public void testSetCpuAllocatedWithNullCpuSpeed() { String expected = null; final HostMetricsResponse hostResponse = new HostMetricsResponse(); - hostResponse.setCpuAllocated(String.format("50%s25%%", decimalSeparator), 10, null); + hostResponse.setCpuAllocated("50.25%", 10, null); Assert.assertEquals(expected, hostResponse.getCpuAllocatedGhz()); } } diff --git a/server/src/main/java/com/cloud/api/query/dao/HostJoinDaoImpl.java b/server/src/main/java/com/cloud/api/query/dao/HostJoinDaoImpl.java index f942a38746c6..b91444414c6f 100644 --- a/server/src/main/java/com/cloud/api/query/dao/HostJoinDaoImpl.java +++ b/server/src/main/java/com/cloud/api/query/dao/HostJoinDaoImpl.java @@ -41,6 +41,7 @@ import org.apache.cloudstack.ha.HAResource; import org.apache.cloudstack.ha.dao.HAConfigDao; import org.apache.cloudstack.outofbandmanagement.dao.OutOfBandManagementDao; +import org.apache.cloudstack.utils.NumberFormatUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; @@ -209,7 +210,7 @@ private void setNewHostResponseBase(HostJoinVO host, EnumSet detail } } - DecimalFormat decimalFormat = new DecimalFormat("#.##"); + DecimalFormat decimalFormat = NumberFormatUtils.decimalFormat("#.##"); if (host.getType() == Host.Type.Routing) { if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) || details.contains(HostDetails.core)) { String hostTags = host.getTag(); @@ -448,7 +449,7 @@ private String calculateResourceAllocatedPercentage(float resource, float resour if (resource == 0 || resourceWithOverProvision == 0) { return "0.00%"; } - DecimalFormat decimalFormat = new DecimalFormat("#.##"); + DecimalFormat decimalFormat = NumberFormatUtils.decimalFormat("#.##"); return decimalFormat.format(((float)resource / resourceWithOverProvision * 100.0f)) + "%"; } diff --git a/server/src/main/java/com/cloud/api/query/dao/UserVmJoinDaoImpl.java b/server/src/main/java/com/cloud/api/query/dao/UserVmJoinDaoImpl.java index 1836ed41b090..b5cb66fa2d42 100644 --- a/server/src/main/java/com/cloud/api/query/dao/UserVmJoinDaoImpl.java +++ b/server/src/main/java/com/cloud/api/query/dao/UserVmJoinDaoImpl.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.api.query.dao; -import java.text.DecimalFormat; import java.time.LocalDate; import java.time.ZoneId; import java.time.temporal.ChronoUnit; @@ -51,6 +50,7 @@ import org.apache.cloudstack.extension.ExtensionHelper; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.query.QueryService; +import org.apache.cloudstack.utils.NumberFormatUtils; import org.apache.cloudstack.vm.lease.VMLeaseManager; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.BooleanUtils; @@ -355,7 +355,7 @@ public UserVmResponse newUserVmResponse(ResponseView view, String objectName, Us // stats calculation VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId(), accumulateStats); if (vmStats != null) { - userVmResponse.setCpuUsed(new DecimalFormat("#.##").format(vmStats.getCPUUtilization()) + "%"); + userVmResponse.setCpuUsed(NumberFormatUtils.decimalFormat("#.##").format(vmStats.getCPUUtilization()) + "%"); userVmResponse.setNetworkKbsRead((long)vmStats.getNetworkReadKBs()); userVmResponse.setNetworkKbsWrite((long)vmStats.getNetworkWriteKBs()); userVmResponse.setDiskKbsRead((long)vmStats.getDiskReadKBs()); diff --git a/utils/src/main/java/com/cloud/utils/NumbersUtil.java b/utils/src/main/java/com/cloud/utils/NumbersUtil.java index f1a2e8632479..2d1fe1aba1d4 100644 --- a/utils/src/main/java/com/cloud/utils/NumbersUtil.java +++ b/utils/src/main/java/com/cloud/utils/NumbersUtil.java @@ -79,6 +79,10 @@ public static String bytesToString(byte[] data, int start, int end) { protected static final long TB = 1024 * GB; public static String toReadableSize(Long bytes) { + return toReadableSize(bytes, Locale.getDefault()); + } + + public static String toReadableSize(Long bytes, Locale locale) { if (bytes == null){ return "null"; @@ -88,7 +92,7 @@ public static String toReadableSize(Long bytes) { return Long.toString(bytes) + " bytes"; } StringBuilder builder = new StringBuilder(); - Formatter format = new Formatter(builder, Locale.getDefault()); + Formatter format = new Formatter(builder, locale); if (bytes < MB) { format.format("%.2f KB", (float)bytes / (float)KB); } else if (bytes < GB) { diff --git a/utils/src/main/java/org/apache/cloudstack/utils/NumberFormatUtils.java b/utils/src/main/java/org/apache/cloudstack/utils/NumberFormatUtils.java new file mode 100644 index 000000000000..df03f775a6fe --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/NumberFormatUtils.java @@ -0,0 +1,46 @@ +// 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 org.apache.cloudstack.utils; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +/** + * Locale-independent number formatting helpers. API responses must not depend on the Management + * Server's default locale, so decimal separators are always formatted as a dot. + */ +public final class NumberFormatUtils { + + private NumberFormatUtils() { + } + + /** + * Formats the given format string using {@link Locale#ROOT}. + */ + public static String format(String format, Object... args) { + return String.format(Locale.ROOT, format, args); + } + + /** + * Creates a {@link DecimalFormat} for the given pattern that always uses a dot as decimal separator. + */ + public static DecimalFormat decimalFormat(String pattern) { + return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.ROOT)); + } +} diff --git a/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java index 55dfaab25884..cb17ca466fb0 100644 --- a/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java +++ b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java @@ -37,6 +37,17 @@ public void toReadableSize() { assertEquals("1023 bytes", NumbersUtil.toReadableSize((1023L))); } + @Test + public void toReadableSizeWithLocaleUsesGivenLocale() { + Locale originalLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.GERMANY); + assertEquals("1.00 GB", NumbersUtil.toReadableSize(1024L * 1024 * 1024, Locale.ROOT)); + } finally { + Locale.setDefault(originalLocale); + } + } + @Test public void bytesToLong() { assertEquals(0, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 0})); diff --git a/utils/src/test/java/org/apache/cloudstack/utils/NumberFormatUtilsTest.java b/utils/src/test/java/org/apache/cloudstack/utils/NumberFormatUtilsTest.java new file mode 100644 index 000000000000..a3ec4f5e3524 --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/NumberFormatUtilsTest.java @@ -0,0 +1,51 @@ +// 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 org.apache.cloudstack.utils; + +import java.util.Locale; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class NumberFormatUtilsTest { + + private Locale originalLocale; + + @Before + public void setUp() { + originalLocale = Locale.getDefault(); + Locale.setDefault(Locale.GERMANY); + } + + @After + public void tearDown() { + Locale.setDefault(originalLocale); + } + + @Test + public void formatUsesDotAsDecimalSeparatorRegardlessOfDefaultLocale() { + Assert.assertEquals("15.50%", NumberFormatUtils.format("%.2f%%", 15.5)); + } + + @Test + public void decimalFormatUsesDotAsDecimalSeparatorRegardlessOfDefaultLocale() { + Assert.assertEquals("15.5", NumberFormatUtils.decimalFormat("#.##").format(15.5)); + } +}