utils -> kt

This commit is contained in:
Milos Kozak 2021-04-13 22:52:40 +02:00
parent f95d4725f1
commit e57c9ea0b8
14 changed files with 189 additions and 231 deletions

View file

@ -2,22 +2,6 @@
<code_scheme name="Project" version="173">
<option name="AUTODETECT_INDENTS" value="false" />
<JetCodeStyleSettings>
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value>
<package name="java.util" alias="false" withSubpackages="false" />
<package name="kotlinx.android.synthetic" alias="false" withSubpackages="true" />
<package name="io.ktor" alias="false" withSubpackages="true" />
</value>
</option>
<option name="PACKAGES_IMPORT_LAYOUT">
<value>
<package name="" alias="false" withSubpackages="true" />
<package name="java" alias="false" withSubpackages="true" />
<package name="javax" alias="false" withSubpackages="true" />
<package name="kotlin" alias="false" withSubpackages="true" />
<package name="" alias="true" withSubpackages="true" />
</value>
</option>
<option name="ALIGN_IN_COLUMNS_CASE_BRANCH" value="true" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="6" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="6" />

View file

@ -795,7 +795,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
// look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
profileSwitch.profileName = PercentageSplitter.INSTANCE.pureName(profileSwitch.profileName);
getDaoProfileSwitch().create(profileSwitch);
aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
openHumansUploader.enqueueProfileSwitch(profileSwitch);

View file

@ -35,6 +35,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var jsonFormatter: JSONFormatter
private var _binding: OpenapsamaFragmentBinding? = null
@ -92,30 +93,30 @@ class OpenAPSAMAFragment : DaggerFragment() {
private fun updateGUI() {
if (_binding == null) return
openAPSAMAPlugin.lastAPSResult?.let { lastAPSResult ->
binding.result.text = JSONFormatter.format(lastAPSResult.json)
binding.result.text = jsonFormatter.format(lastAPSResult.json)
binding.request.text = lastAPSResult.toSpanned()
}
openAPSAMAPlugin.lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS ->
binding.glucosestatus.text = JSONFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam)
binding.currenttemp.text = JSONFormatter.format(determineBasalAdapterAMAJS.currentTempParam)
binding.glucosestatus.text = jsonFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam)
binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterAMAJS.currentTempParam)
try {
val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam)
binding.iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
binding.iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", jsonFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e)
@Suppress("SetTextI18n")
binding.iobdata.text = "JSONException see log for details"
}
binding.profile.text = JSONFormatter.format(determineBasalAdapterAMAJS.profileParam)
binding.mealdata.text = JSONFormatter.format(determineBasalAdapterAMAJS.mealDataParam)
binding.profile.text = jsonFormatter.format(determineBasalAdapterAMAJS.profileParam)
binding.mealdata.text = jsonFormatter.format(determineBasalAdapterAMAJS.mealDataParam)
binding.scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug
}
if (openAPSAMAPlugin.lastAPSRun != 0L) {
binding.lastrun.text = dateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun)
}
openAPSAMAPlugin.lastAutosensResult.let {
binding.autosensdata.text = JSONFormatter.format(it.json())
binding.autosensdata.text = jsonFormatter.format(it.json())
}
}

View file

@ -36,6 +36,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var jsonFormatter: JSONFormatter
private var _binding: OpenapsamaFragmentBinding? = null
@ -92,23 +93,23 @@ class OpenAPSSMBFragment : DaggerFragment() {
fun updateGUI() {
if (_binding == null) return
openAPSSMBPlugin.lastAPSResult?.let { lastAPSResult ->
binding.result.text = JSONFormatter.format(lastAPSResult.json)
binding.result.text = jsonFormatter.format(lastAPSResult.json)
binding.request.text = lastAPSResult.toSpanned()
}
openAPSSMBPlugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS ->
binding.glucosestatus.text = JSONFormatter.format(determineBasalAdapterSMBJS.glucoseStatusParam)
binding.currenttemp.text = JSONFormatter.format(determineBasalAdapterSMBJS.currentTempParam)
binding.glucosestatus.text = jsonFormatter.format(determineBasalAdapterSMBJS.glucoseStatusParam)
binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterSMBJS.currentTempParam)
try {
val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam)
binding.iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
binding.iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", jsonFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e)
@SuppressLint("SetTextI18n")
binding.iobdata.text = "JSONException see log for details"
}
binding.profile.text = JSONFormatter.format(determineBasalAdapterSMBJS.profileParam)
binding.mealdata.text = JSONFormatter.format(determineBasalAdapterSMBJS.mealDataParam)
binding.profile.text = jsonFormatter.format(determineBasalAdapterSMBJS.profileParam)
binding.mealdata.text = jsonFormatter.format(determineBasalAdapterSMBJS.mealDataParam)
binding.scriptdebugdata.text = determineBasalAdapterSMBJS.scriptDebug
openAPSSMBPlugin.lastAPSResult?.inputConstraints?.let {
binding.constraints.text = it.getReasons(aapsLogger)
@ -118,7 +119,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
binding.lastrun.text = dateUtil.dateAndTimeString(openAPSSMBPlugin.lastAPSRun)
}
openAPSSMBPlugin.lastAutosensResult.let {
binding.autosensdata.text = JSONFormatter.format(it.json())
binding.autosensdata.text = jsonFormatter.format(it.json())
}
}

View file

@ -1,126 +0,0 @@
package info.nightscout.androidaps.utils;
import android.text.Html;
import android.text.Spanned;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.util.Iterator;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
/**
* Created by mike on 11.07.2016.
*/
public class JSONFormatter {
private static final Logger log = StacktraceLoggerWrapper.getLogger(JSONFormatter.class);
public static Spanned format(final String jsonString) {
final JsonVisitor visitor = new JsonVisitor(1, '\t');
try {
if (jsonString.equals("undefined"))
return HtmlHelper.INSTANCE.fromHtml("undefined");
else if (jsonString.getBytes()[0] == '[')
return HtmlHelper.INSTANCE.fromHtml(visitor.visit(new JSONArray(jsonString), 0));
else
return HtmlHelper.INSTANCE.fromHtml(visitor.visit(new JSONObject(jsonString), 0));
} catch (JSONException e) {
log.error("Unhandled exception", e);
return HtmlHelper.INSTANCE.fromHtml("");
}
}
public static Spanned format(final JSONObject object) {
final JsonVisitor visitor = new JsonVisitor(1, '\t');
try {
return HtmlHelper.INSTANCE.fromHtml(visitor.visit(object, 0));
} catch (JSONException e) {
log.error("Unhandled exception", e);
return HtmlHelper.INSTANCE.fromHtml("");
}
}
private static class JsonVisitor {
private final int indentationSize;
private final char indentationChar;
public JsonVisitor(final int indentationSize, final char indentationChar) {
this.indentationSize = indentationSize;
this.indentationChar = indentationChar;
}
private String visit(final JSONArray array, final int indent) throws JSONException {
String ret = "";
final int length = array.length();
if (length == 0) {
} else {
ret += write("[", indent);
for (int i = 0; i < length; i++) {
ret += visit(array.get(i), indent);
}
ret += write("]", indent);
}
return ret;
}
private String visit(final JSONObject obj, final int indent) throws JSONException {
String ret = "";
final int length = obj.length();
if (length == 0) {
} else {
final Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
final String key = keys.next();
ret += write("<b>" + key + "</b>: ", indent);
ret += visit(obj.get(key), indent + 1);
ret += "<br>";
}
}
return ret;
}
private String visit(final Object object, final int indent) throws JSONException {
String ret = "";
Long n;
if (object instanceof JSONArray) {
ret += visit((JSONArray) object, indent);
} else if (object instanceof JSONObject) {
ret += "<br>" + visit((JSONObject) object, indent);
} else {
if (object instanceof String) {
ret += write("\"" + ((String) object).replace("<", "&lt;").replace(">", "&gt;") + "\"", indent);
} else {
// try to detect Date as milliseconds
if (object instanceof Long) {
n = (Long) object;
if (n > 1580000000000L && n < 2000000000000L) { // from 2020.01.26 to 2033.05.18 it is with high probability a date object
Date date = new Date(n);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ret += write(formatter.format(date), indent);
} else {
ret += write(String.valueOf(object), indent);
}
} else {
ret += write(String.valueOf(object), indent);
}
}
}
return ret;
}
private String write(final String data, final int indent) {
String ret = "";
for (int i = 0; i < (indent * indentationSize); i++) {
ret += indentationChar;
}
ret += data;
return ret;
}
}
}

View file

@ -0,0 +1,113 @@
package info.nightscout.androidaps.utils
import android.text.Spanned
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.utils.HtmlHelper.fromHtml
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class JSONFormatter @Inject constructor(
private val aapsLogger: AAPSLogger
) {
fun format(jsonString: String?): Spanned {
jsonString ?: return fromHtml("")
val visitor = JsonVisitor(1, '\t')
return try {
when {
jsonString == "undefined" -> fromHtml("undefined")
jsonString.toByteArray()[0] == '['.toByte() -> fromHtml(visitor.visit(JSONArray(jsonString), 0))
else -> fromHtml(visitor.visit(JSONObject(jsonString), 0))
}
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
fromHtml("")
}
}
fun format(jsonObject: JSONObject?): Spanned {
jsonObject ?: return fromHtml("")
val visitor = JsonVisitor(1, '\t')
return try {
fromHtml(visitor.visit(jsonObject, 0))
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
fromHtml("")
}
}
private class JsonVisitor(private val indentationSize: Int, private val indentationChar: Char) {
fun visit(array: JSONArray, indent: Int): String {
var ret = ""
val length = array.length()
if (length != 0) {
ret += write("[", indent)
for (i in 0 until length) {
ret += visit(array[i], indent)
}
ret += write("]", indent)
}
return ret
}
fun visit(obj: JSONObject, indent: Int): String {
var ret = ""
val length = obj.length()
if (length != 0) {
val keys = obj.keys()
while (keys.hasNext()) {
val key = keys.next()
ret += write("<b>$key</b>: ", indent)
ret += visit(obj[key], indent + 1)
ret += "<br>"
}
}
return ret
}
private fun visit(any: Any, indent: Int): String {
var ret = ""
val n: Long
if (any is JSONArray) {
ret += visit(any, indent)
} else if (any is JSONObject) {
ret += "<br>" + visit(any, indent)
} else {
if (any is String) {
ret += write("\"" + any.replace("<", "&lt;").replace(">", "&gt;") + "\"", indent)
} else {
// try to detect Date as milliseconds
if (any is Long) {
n = any
ret += if (n in 1580000000001..1999999999999) { // from 2020.01.26 to 2033.05.18 it is with high probability a date object
val formatter: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
write(formatter.format(Date(n)), indent)
} else {
write(any.toString(), indent)
}
} else {
ret += write(any.toString(), indent)
}
}
}
return ret
}
private fun write(data: String, indent: Int): String {
var ret = ""
for (i in 0 until indent * indentationSize) {
ret += indentationChar
}
ret += data
return ret
}
}
}

View file

@ -1,26 +0,0 @@
package info.nightscout.androidaps.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.ui.NumberPicker;
/**
* Created by mike on 28.06.2016.
*/
public class NumberPickerVertical extends NumberPicker {
public NumberPickerVertical(Context context) {
super(context);
}
public NumberPickerVertical(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void inflate(Context context) {
LayoutInflater.from(context).inflate(R.layout.number_picker_layout_vertical, this, true);
}
}

View file

@ -0,0 +1,17 @@
package info.nightscout.androidaps.utils
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.ui.NumberPicker
class NumberPickerVertical : NumberPicker {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
override fun inflate(context: Context) {
LayoutInflater.from(context).inflate(R.layout.number_picker_layout_vertical, this, true)
}
}

View file

@ -1,22 +0,0 @@
package info.nightscout.androidaps.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by mike on 22.12.2017.
*/
public class PercentageSplitter {
// Matches "Profile name (200%,-2h)", "Profile name (50%)
private static final Pattern splitPattern = Pattern.compile("(.+)\\(\\d+%(,-?\\d+h)?\\)");
/** Removes the suffix for percentage and timeshift from a profile name. This is the inverse of what
* {@link info.nightscout.androidaps.db.ProfileSwitch#getCustomizedName()} does.
* Since the customized name is used for the PS upload to NS, this is needed get the original profile name
* when retrieving the PS from NS again. */
public static String pureName(String name) {
Matcher percentageMatch = splitPattern.matcher(name);
return percentageMatch.find() ? percentageMatch.group(1).trim() : name;
}
}

View file

@ -0,0 +1,21 @@
package info.nightscout.androidaps.utils
import info.nightscout.androidaps.utils.PercentageSplitter
import java.util.regex.Pattern
object PercentageSplitter {
// Matches "Profile name (200%,-2h)", "Profile name (50%)
private val splitPattern = Pattern.compile("(.+)\\(\\d+%(,-?\\d+h)?\\)")
/**
* Removes the suffix for percentage and timeshift from a profile name. This is the inverse of what
* [info.nightscout.androidaps.db.ProfileSwitch.getCustomizedName] does.
* Since the customized name is used for the PS upload to NS, this is needed get the original profile name
* when retrieving the PS from NS again.
*/
fun pureName(name: String): String {
val percentageMatch = splitPattern.matcher(name)
return if (percentageMatch.find()) percentageMatch.group(1).trim { it <= ' ' } else name
}
}

View file

@ -1,17 +0,0 @@
package info.nightscout.androidaps.utils;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
public class SPBackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
// API 24
final String PREFS = getApplicationContext().getPackageName() + "_preferences";
final String PREFS_BACKUP_KEY = "SP";
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}

View file

@ -0,0 +1,16 @@
package info.nightscout.androidaps.utils
import android.app.backup.BackupAgentHelper
import android.app.backup.SharedPreferencesBackupHelper
@Suppress("LocalVariableName")
class SPBackupAgent : BackupAgentHelper() {
override fun onCreate() {
// API 24
val PREFS = applicationContext.packageName + "_preferences"
val PREFS_BACKUP_KEY = "SP"
val helper = SharedPreferencesBackupHelper(this, PREFS)
addHelper(PREFS_BACKUP_KEY, helper)
}
}

View file

@ -32,10 +32,6 @@ class StacktraceLoggerWrapper(private val delegate: Logger) : Logger by delegate
// all other methods will be implemented by delegate
companion object {
@JvmStatic
@Deprecated("please inject AAPSLogger")
fun getLogger(ltag: LTag) = StacktraceLoggerWrapper(LoggerFactory.getLogger(ltag.name))
@JvmStatic
@Deprecated("please inject AAPSLogger")
fun getLogger(clazz: Class<*>) = StacktraceLoggerWrapper(LoggerFactory.getLogger(clazz))

View file

@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDeco
public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHistoryEntry> {
private static final Logger LOG = StacktraceLoggerWrapper.getLogger(LTag.PUMPCOMM);
//private static final Logger LOG = StacktraceLoggerWrapper.getLogger(LTag.PUMPCOMM);
// CGMSValuesWriter cgmsValuesWriter = null;
@ -35,7 +35,7 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
try {
return decodeRecord(record, false);
} catch (Exception ex) {
LOG.error(" Error decoding: type={}, ex={}", record.getEntryType().name(), ex.getMessage(), ex);
//LOG.error(" Error decoding: type={}, ex={}", record.getEntryType().name(), ex.getMessage(), ex);
return RecordDecodeStatus.Error;
}
}
@ -144,7 +144,7 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
if (entryType == CGMSHistoryEntryType.None) {
this.unknownOpCodes.put(opCode, opCode);
LOG.warn("GlucoseHistoryEntry with unknown code: " + opCode);
//LOG.warn("GlucoseHistoryEntry with unknown code: " + opCode);
CGMSHistoryEntry pe = new CGMSHistoryEntry();
pe.setEntryType(CGMSHistoryEntryType.None);
@ -208,7 +208,7 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
entry.setDateTime(dateTime, getIndex);
}
LOG.debug("Record: {}", entry);
//LOG.debug("Record: {}", entry);
}
return reversedOutList;
@ -274,7 +274,7 @@ public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder<CGMSHis
return atechDateTime;
} else if (entry.getEntryType().getDateType() == CGMSHistoryEntryType.DateType.SecondSpecific) {
LOG.warn("parseDate for SecondSpecific type is not implemented.");
//LOG.warn("parseDate for SecondSpecific type is not implemented.");
throw new RuntimeException();
// return null;
} else