JvmOverloads annotation for class primary constructor - constructor

Why is it prohibited to autogenerate many constructors visible to Java from class primary constructor with default params likes this?
#JvmOverloads
class Video(private val id: Long, val ownerId: Long, var title: String? = null, var imgLink: String? = null, var videoLink: String? = null,
var description: String? = null, var created: Date? = null, var accessKey: String? = null, var duration: Long? = null,
var views: Long? = null, var comments: Long? = null) : Entity
This annotation is not applicable to target 'class'

It's not prohibited, you are just applying #JvmOverloads to the wrong target. The proper way to annotate primary constructor is to explicitly specify constructor keyword with #JvmOverloads before:
class Video #JvmOverloads constructor(
private val id: Long,
val ownerId: Long,
var title: String? = null,
var imgLink: String? = null,
var videoLink: String? = null,
var description: String? = null,
var created: Date? = null,
var accessKey: String? = null,
var duration: Long? = null,
var views: Long? = null,
var comments: Long? = null
) : Entity

Related

How to import backend exported public key in frontend

hi i'm trying to import a jwk generated from the server in my flutter app
var signeature =
JsonWebSignature.fromCompactSerialization(response.body);
var payload = signeature.unverifiedPayload;
Map<String, dynamic> key = jsonDecode(payload.jsonContent["jwk"]);
PublicKey rsakey = RsaPublicKey(e: key['e'], n: key['n']);
Jwk jwk = Jwk.fromPublicKey(rsakey);
the problem is that RsaPublicKey requires e and n as List<int> but my keys has no List<int>
{additionalData: {}, alg: null, crv: null, d: null, dp: null, dq: null, e: AQAB, k: null, keyId: null, keyOps: [], kid: null, kty: RSA, n: rnuxgDk-9cWCeehBWotGz2YkXpu6_0wPVlVkip1EHUdpWXpX4vAvOeclNIrEYzMOrBIUvwLptk-FMsOgpdvxjWtHFfanv60xsTLAV6ZXMO-R2Ojzgpv4izFvyduC2MihkoMBL_evo9JltMfX2ZSXIwwZoqPed2v9GI9aIjhhKZqju-anVjt3n6dHxlLyduaoatZbD7tzjo-bPeO8o1rycBQFCncgdQ9ST3C6CmZYOUpCFF9ojb4vZtvmIcbtl9Hyud9dOViufE1vPrpJq0ZjeR_ovtApfaQKsi3YJhn77Uwg_XxzgE-SPq960skNwd0IFpyiuxcOvRRIvL6N_-FCdw, oth: null, p: null, q: null, qi: null, use: null, x: null, x5c: [], x5t: null, x5tS256: null, x5u: null, y: null, keySize: 2048, hasPrivateKey: false, cryptoProviderFactory: {cryptoProviderCache: {}, customCryptoProvider: null, cacheSignatureProviders: true, signatureProviderObjectPoolCacheSize: 4}}
is it possible to convert e and n into a List<int>?
I tried using other defined PublicKey but on the import it asks for bigint instead of list but i still don't know how to convert it into bigint anyway

Unable to insert to Child Table in reference of a Parent Table in node.js

I'm having a hard time figuring out what's wrong with my code base or on my database since i was just trying to insert a device information to a table in reference to the user who owns it. no errors are being thrown but the device registration isn't working.
Here's the database
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`email` varchar(255),
`password` varchar(255),
`firstname` varchar(255),
`lastname` varchar(255),
`dob` varchar(255),
`country` varchar(255),
`farmname` varchar(255),
`acctype` varchar(255),
`firmware` double
);
CREATE TABLE `controlModules` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`deviceowner` int,
`devicename` varchar(255),
`serial#` varchar(255),
`devicestate` varchar(255),
`ipaddress` varchar(255),
`wanaddress` varchar(255),
`firmware` varchar(255)
);
ALTER TABLE `controlModules` ADD FOREIGN KEY (`deviceowner`) REFERENCES `users` (`id`);
Here's the function for react.js where it passes input data to backend
const email = sessionStorage.getItem("email");
const [name, setDeviceName] = useState("");
const [serial, setDeviceSerial] = useState("");
const [lanip, setDeviceLANIP] = useState("");
const [wanip, setDeviceWANIP] = useState("");
const [deviceStatus, setDeviceStatus] = useState("");
Axios.defaults.withCredentials = true;
const registerDevice =()=>{
Axios.post("http://localhost:3020/registerDevice", {
email: email,
name: name,
serial: serial,
lanip: lanip,
wanip: wanip,
}).then((response) => {
if (response) {
setDeviceStatus(response);
} else {
setDeviceStatus("error");
}
});
};
Here's the code for backend on node.js
app.post("/registerDevice", (req, res)=> {
const email = req.body.email;
const name = req.body.name;
const serial = req.body.serial;
const lanip = req.body.lanip;
const wanip = req.body.wanip;
const status = "online"
const firmware = "1.3";
console.log(email);
let stmt = `SELECT * FROM users WHERE id=?`;
let todo = [email];
//getting parentid
db.query(stmt, todo, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
console.log(results)
const userid = results.id;
let statement = `INSERT INTO controlModules(deviceowner, devicename, serial#, devicestate, ipaddress, wanaddress, firmware) VALUES (?,?,?,?,?,?)`;
let task = [userid, name, serial, status, lanip, wanip, firmware];
//inserting to childtable
db.query(statement, task, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
console.log(results);
});
});
Thanks for the help and enlightenment.

How to decode LONGTEXT/TEXT type in swift

anyone know how to decode a mysql 'LONGTEXT' or 'TEXT' type in swift?
I'm using nodejs get data from mysql and expose it as REST API, and call the API from my swift code. the problem is swift can't decode 'background' and 'notes', it's working if i remove these two columns from the Vote struct
The database table 'vote', the structure is like :
CREATE TABLE `vote` (
`createdAt` bigint(20) DEFAULT NULL,
`updatedAt` bigint(20) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`thumbnail` varchar(255) DEFAULT NULL,
`background` longtext DEFAULT NULL,
`notes` text,
`amount` double DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
`highestScore` double DEFAULT NULL,
`category` int(11) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
the json format is like
[{
"id": 1,
"name": "IQ Test",
"thumbnail": "eddie",
"background": "This is a typical IQ test",
"amount": 33,
"type": "score",
"highestScore": 174
}]
my code in swift is:
struct Vote: Codable {
var id: Int
var name: String
var thumbnail: String
var background: String
var notes: String
var amount: Double
var type: String
var highestScore: Double
enum CodingKeys: String, CodingKey {
case id
case name
case thumbnail
case background
case notes
case amount
case type
case highestScore
}
}
the decode piece is like:
if let data = data {
if let votes = try? jsonDecoder.decode([Vote].self, from: data) {
completion(votes)
}
} else {
completion(nil)
}
Hey Danny, I have run your code and get an optimized way as follows:-
Construct the model structure like this:-
// MARK: - CourseElement
struct VoteElement: Codable {
let id: Int?
let name, thumbnail, background: String?
let amount: Int?
let type: String?
let highestScore: Int?
}
typealias Vote = [VoteElement]
Use the above structure in the network calls like this:-
if let data = data {
if let votes = try? jsonDecoder.decode(Vote.self, from: data) {
completion(votes)
}
} else {
completion(nil)
}

How do I POST multiple JSON objects

I would like to know how to go about posting multiple JSON objects to the server using django-restframework. My datatable model is given below.
class module(models.Model):
uploaded_by=models.ForeignKey(ChangeLog,on_delete=models.CASCADE,null=True)
panel_manufacturer= models.CharField(max_length=100,null=True, blank = True)
panel_model= models.CharField(max_length=100,null=True, blank = True)
panel_serial_number = models.CharField(max_length=100)
label_pmpp=models.FloatField(null=True, blank = True)
label_lower_tolerance=models.FloatField(null=True, blank = True)
label_upper_tolerance=models.FloatField(null=True, blank = True)
label_isc=models.FloatField(null=True, blank = True)
label_voc=models.FloatField(null=True, blank = True)
label_maximum_system_voltage=models.FloatField(null=True, blank = True)
additional_panel_information = JSONField(null=True, blank = True)
def __str__(self):
return self.panel_serial_number
And the corresponding serializer is as such
class module_Serializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="pvlabs_testdata:module-detail")
uploaded_by = ChangeLog_Serializer(required=False)
class Meta:
model = module
fields = '__all__'
validators = [module_validator]
def create(self, validated_data):
uploaded_by_data = {"uploaded_by":self.context['request'].user, "upload_timestamp":datetime.now()}
uploaded_by_instance = ChangeLog.objects.create(**uploaded_by_data)
module_instance=module.objects.create(uploaded_by=uploaded_by_instance, **validated_data)
return module_instance
When I go about posting a JSON like below
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "EFG",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
},
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
},
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
}
I always get an error that says 'Expected dict, got list'.
I managed to create a solution for this using list serializer.
So in my views file, it is coded as below
class module_ViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = module.objects.all()
serializer_class = module_Serializer
permission_classes = [permissions.IsAuthenticated | HasAPIKey]
def get_serializer(self, *args, **kwargs):
if isinstance(kwargs.get("data", {}), list):
kwargs["many"] = True
temp= kwargs.get("data")
for i in range(len(kwargs.get("data"))):
for key, value in temp[i].items():
if " " in key or key.islower()==0:
n_key=str(key).replace(" ", "_").title().lower()
kwargs.get("data")[i][n_key] = kwargs.get("data")[i].pop(key)
return super(module_ViewSet, self).get_serializer(*args, **kwargs)
And for my serializer I have coded as below
from rest_framework import serializers
from django_restql.mixins import DynamicFieldsMixin
class BulkModuleSerializer(DynamicFieldsMixin, serializers.ListSerializer):
def create(self, validated_data):
result=[]
for validated_datas in validated_data:
uploaded_by_data = {"uploaded_by":self.context['request'].user, "upload_timestamp":datetime.now()}
uploaded_by_instance = ChangeLog.objects.create(**uploaded_by_data)
module_instance=module.objects.create(uploaded_by=uploaded_by_instance, **validated_datas)
result.append(module_instance)
return result
class module_Serializer(DynamicFieldsMixin, serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="pvlabs_testdata:module-detail")
uploaded_by = ChangeLog_Serializer(required=False)
class Meta:
model = module
fields = '__all__'
validators = [module_validator]
list_serializer_class = BulkModuleSerializer
def create(self, validated_data):
uploaded_by_data = {"uploaded_by":self.context['request'].user, "upload_timestamp":datetime.now()}
uploaded_by_instance = ChangeLog.objects.create(**uploaded_by_data)
module_instance=module.objects.create(uploaded_by=uploaded_by_instance, **validated_data)
return module_instance
That seems to have worked for me.
You have put your JSON data inside square brackets.
Example:
[
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
},
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
}
]

Hibernate error: Could not determine type for: com.mysql.jdbc.Blob

I'm working on a project with Hibernate and MySQL. In one of my model objects, I declared a property "image" whose type is Blob, and I used com.mysql.jdbc.Blob. But when I ran that program, an error occurred: org.hibernate.MappingException: Could not determine type for: com.mysql.jdbc.Blob, at table: SPOT, for columns: [org.hibernate.mapping.Column(image)].
Here is source code of data model:
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "SPOT", catalog = "ar", uniqueConstraints = #UniqueConstraint(columnNames = "name"))
#XmlRootElement(name = "spot")
public class Spot extends BaseIdObject {
private Double axisX;
private Double axisY;
private String address;
private String spotType;
private String description;
private String phoneNumber;
private String website;
private Blob image;
#Column(name = "axis_x", precision = 22, scale = 0)
#NotNull
public Double getAxisX() {
return this.axisX;
}
public void setAxisX(Double axisX) {
this.axisX = axisX;
}
#Column(name = "axis_y", precision = 22, scale = 0)
#NotNull
public Double getAxisY() {
return this.axisY;
}
public void setAxisY(Double axisY) {
this.axisY = axisY;
}
#Column(name = "address", length = 200)
#NotNull
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "spot_type", length = 50)
#NotNull
public String getSpotType() {
return this.spotType;
}
public void setSpotType(String spotType) {
this.spotType = spotType;
}
#Column(name = "description", length = 2000)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "phone_number", length = 30)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
And here is the corresponding DDL of table SPOT:
DROP TABLE IF EXISTS `spot`;
/*!40101 SET #saved_cs_client = ##character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `spot` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(200) DEFAULT NULL,
`AXIS_X` double NOT NULL,
`AXIS_Y` double NOT NULL,
`ADDRESS` varchar(200) DEFAULT NULL,
`SPOT_TYPE` varchar(50) NOT NULL,
`DESCRIPTION` varchar(2000) DEFAULT NULL,
`PHONE_NUMBER` varchar(30) DEFAULT NULL,
`WEBSITE` varchar(200) DEFAULT NULL,
`IMAGE` blob,
PRIMARY KEY (`ID`),
UNIQUE KEY `SPOT_ID_UNIQUE` (`ID`),
UNIQUE KEY `SPOT_NAME_UNIQUE` (`NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = #saved_cs_client */;
I searched on Internet and found a suggestion of using java.sql.Blob. But when I changed to that type, another error occurred, because in my program, I did some processes with XML on that model object, so it cannot handle the interface java.sql.Blob. So what I have to do to keep the data type com.mysql.jdbc.Blob and the program still run normally with Hibernate? Thank you so much.
I'd say that it's not right to depend on the implementation details for the JDBC driver. I would review your dependency, and try to make it a soft dependency. If you really need to keep this hard dependency, you'll need to implement an UserType capable of handling com.mysql.jdbc.Blob. I don't know the details about this implementation, but you can extend Hibernate's BlobType as MySQLBlobType, and annotate your model property with #Type annotation, specifying this MySQLBlobType:
https://github.com/hibernate/hibernate-core/blob/master/hibernate-core/src/main/java/org/hibernate/type/BlobType.java
https://github.com/hibernate/hibernate-core/blob/master/hibernate-core/src/test/java/org/hibernate/test/annotations/type/Dvd.java