I have a groovy-servlet named query1_action.groovy as:
String sql = "...";
String sql_count = "...";
try {
def ctx = new javax.naming.InitialContext().lookup("java:/comp/env");
def datasource = ctx.lookup("jdbc/tlink");
def executer = Sql.newInstance(datasource);
def rows = executer.rows(sql);
def gson = new com.google.gson.GsonBuilder().setDateFormat("yyyy-MM-dd").create();
def result = gson.toJson(rows);
def rows_count = executer.firstRow(sql_count).num;
int page_count = (rows_count+page_size-1)/page_size;
out << """{"rs": "1", "rows": ${result}, "rows_count": ${rows_count}, "page": {"page_size": ${page_size}, "page_count": ${page_count}, "pn": ${p.pn}}}""";
} catch(Exception e) {
context.log("query1_action.groovy === ${e}");
out << '{"rs": "0"}';
}
I have query1_action.groovy, query2_action.groovy, and so on, all the try-catch parts are the same.
And I want to make a template-methods by this part.
I do not know how to extends some base class in this case, when I extends class, groovy servlet can not run.
How to make that please?
Related
I cannot figure out how to replace setTargetFragment() in the code sample below, which is from my Preferencesfragment obviously:
override fun onPreferenceStartFragment(
caller: PreferenceFragmentCompat,
pref: Preference
): Boolean {
// Instantiate the new Fragment
val args = pref.extras
val fragment = supportFragmentManager.fragmentFactory.instantiate(
classLoader,
pref.fragment
).apply {
arguments = args
setTargetFragment(caller, 0) // <-- DEPRICATED CODE
}
// Replace the existing Fragment with the new Fragment
supportFragmentManager.beginTransaction()
.replace(R.id.settings, fragment)
.addToBackStack(null)
.commit()
title = pref.title
return true
}
Too many unknowns for my level of knowledge of Android Studio! This reference helps, but still confused:
How to replace setTargetFragment() now that it is deprecated
Well, apparently this works, but I'm not sure that I really understand what is going on:
override fun onPreferenceStartFragment(
caller: PreferenceFragmentCompat,
pref: Preference
): Boolean {
// Instantiate the new Fragment
val args = pref.extras
val fragment: Fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, pref.fragment)
fragment.arguments = args
supportFragmentManager.beginTransaction().replace(R.id.settings, fragment).addToBackStack(null).commit()
supportFragmentManager.setFragmentResultListener("requestKey", fragment) { _, _ -> }
return true
}
I'm very new to Kotlin so please bear with me. I want to open a SQLite database or create it if it doesn't exist yet. Afterwards I'd run the appropriate statements to make a table, etc. I'm trying to use SQLiteDatabase. The line of code I'm trying is:
val db = SQLiteDatabase.openOrCreateDatabase("database.db",null, SQLiteDatabase.OPEN_READWRITE)
I get this runtime error when I try the app:
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 1294 SQLITE_CANTOPEN_ENOENT[1294]): Could not open database
I'm not picky about the database, I just want an easy way to read and write to one from within my function.
This is the surrounding code:
package com.google.firebase.codelab.barcode_scanning
// Date/time formatting functions
import android.database.sqlite.SQLiteDatabase
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_row.view.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class QrCodeAdapter(private val qrList: ArrayList<QrCode>) : RecyclerView.Adapter<QrCodeAdapter.QrHolder>() {
//
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QrHolder {
return QrHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false))
}
override fun getItemCount() = qrList.size
override fun onBindViewHolder(holder: QrHolder, position: Int) {
//internal var dbHelper = DatabaseHelper(this)
with(qrList[position]) {
var objname = "Barcode Not Found"
var statustext = ""
// status: 0 = no record, 1 = dirty, 2 = clean, 3 = dwell, 4: dwell done
var status = 0
var lastcleaned = ""
// objcategory: 0 = no record, 1 = contact object, 2 = dwell item
var objcategory = 0
var objcategorytext = ""
// initial setup of current date/time
var unixtime = System.currentTimeMillis()
var currenttime = LocalDateTime.now()
var timeformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
var testtime = currenttime.format(timeformat).toString()
//val db = SQLiteDatabase.openDatabase("//app/maindb.db", null, 0);
val db = SQLiteDatabase.openOrCreateDatabase("database.db",null, null)
//val sql = "SELECT COUNT(*) FROM main"
//val statement = db.compileStatement(sql)
//val result = statement.simpleQueryForLong()
//Convert barcode output to string
var barcodevalue = this.value.toString()
// hide settings
holder.itemView.textSettingsTitle.visibility=View.GONE
holder.itemView.textboxName.visibility=View.GONE
}
Class Carro {
String name
String marca
String matricula
}
Class CarroMovel{
String pro1
String prop2
String prop3
Carro carro
static hasMany = [ carros: Carro]
}
def save2 = {
def carroInstance = new Carro()
def carroMovelInstance = new CarroMovel()
carroInstance.name = params.name
carroInstance.marca = params.marca
carroInstance.matricula = params.matricula
carroMovelInstance.prop1 = params.carroMovel.prop1
carroMovelInstance.prop2 = params.carroMovel.prop2
carroMovelInstance.prop3 = params.carroMovel.prop3
carroInstance.save()
carroMovelInstance.carro = carroInstance
carroMovelInstance.save()
}
The CarroInstance is saving, but the carroMovelInstance isn't. I cannot figure it out. Any help would be apreciated.
You probably have a validation error. Try calling validate() on it and inspecting the errors. Alternatively, try saving it with carroMovelInstance.save(failOnError: true) and you'll get an exception if it doesn't validate.
if ((x == 1 && y == "test") || str.Contains("test"))
...
how to generate condition in the if block by CodeDOM or LinqExpression Dynamiclly with C#?
To allow you to use pure CodeDom for creating the expression you can use the CodeBinaryOperationExpression inside the CodeConditionStatement.
The condition would look like this:
CodeExpression condition = new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("x"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1)),
CodeBinaryOperatorType.BooleanAnd,
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("y"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression("test"))),
CodeBinaryOperatorType.BooleanOr,
new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("str"), "Contains"), new CodePrimitiveExpression("test")));
So then all you need are the true, and optionally false, statements:
CodeStatement[] trueStatements = { new CodeCommentStatement("Do this if true") };
CodeStatement[] falseStatements = { new CodeCommentStatement("Do this is false") };
Then put it all together in the if statement:
CodeConditionStatement ifStatement = new CodeConditionStatement(condition, trueStatements, falseStatements);
The complete sample to create a class with a method that performs the evaluation could look like this:
CodeCompileUnit compileUnit = new CodeCompileUnit();
CodeNamespace exampleNamespace = new CodeNamespace("StackOverflow");
CodeTypeDeclaration exampleClass = new CodeTypeDeclaration("GeneratedClass");
CodeMemberMethod method = new CodeMemberMethod();
method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
method.Name = "EvaluateCondition";
method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "x"));
method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "y"));
method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "str"));
CodeExpression condition = new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("x"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1)),
CodeBinaryOperatorType.BooleanAnd,
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("y"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression("test"))),
CodeBinaryOperatorType.BooleanOr,
new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("str"), "Contains"), new CodePrimitiveExpression("test")));
CodeStatement[] trueStatements = { new CodeCommentStatement("Do this if true") };
CodeStatement[] falseStatements = { new CodeCommentStatement("Do this if false") };
CodeConditionStatement ifStatement = new CodeConditionStatement(condition, trueStatements, falseStatements);
method.Statements.Add(ifStatement);
exampleClass.Members.Add(method);
exampleNamespace.Types.Add(exampleClass);
compileUnit.Namespaces.Add(exampleNamespace);
Generate source output in C# using this code...
string sourceCode;
using (var provider = CodeDomProvider.CreateProvider("csharp"))
using (var stream = new MemoryStream())
using (TextWriter writer = new StreamWriter(stream))
using (IndentedTextWriter indentedWriter = new IndentedTextWriter(writer, " "))
{
provider.GenerateCodeFromCompileUnit(compileUnit, indentedWriter, new CodeGeneratorOptions()
{
BracingStyle = "C"
});
indentedWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
using (TextReader reader = new StreamReader(stream))
{
sourceCode = reader.ReadToEnd();
}
}
...sourceCode will contain:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace StackOverflow
{
public class GeneratedClass
{
public void EvaluateCondition(int x, string y, string str)
{
if ((((x == 1)
&& (y == "test"))
|| str.Contains("test")))
{
// Do this if true
}
else
{
// Do this if false
}
}
}
}
Change the provider from csharp to vb to get this:
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.42000
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
Namespace StackOverflow
Public Class GeneratedClass
Public Sub EvaluateCondition(ByVal x As Integer, ByVal y As String, ByVal str As String)
If (((x = 1) _
AndAlso (y = "test")) _
OrElse str.Contains("test")) Then
'Do this if true
Else
'Do this if false
End If
End Sub
End Class
End Namespace
To create the code above dynamical using codedom you need to do the following:
Create a Method which can be added to a class:
CodeMemberMethod method = new CodeMemberMethod();
method.Name = "TestMethod";
method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
Create a If command including statement inside the brackets eg {Value = 4;}:
CodeConditionStatement codeIf = new CodeConditionStatement(new
CodeSnippetExpression("(x == 1 && y == \"test\")|| str.Contains(\"test\")"), new
CodeSnippetStatement("value = 4;"));
Add the If command to the method which was created above:
method.Statements.Add(codeIf);
Using org.as3commons.reflect I can look-up the class name, and instantiate a class at runtime. I also have (non-working) code which invokes a method. However, I really want to set a property value. I'm not sure if properties are realized as methods internally in Flex.
I have a Metadata class which stores 3 pieces of information: name, value, and type (all are strings). I want to be able to loop through an Array of Metadata objects and set the corresponding properties on the instantiated class.
package com.acme.reporting.builders
{
import com.acme.reporting.model.Metadata;
import mx.core.UIComponent;
import org.as3commons.reflect.ClassUtils;
import org.as3commons.reflect.MethodInvoker;
public class UIComponentBuilder implements IUIComponentBuilder
{
public function build(metadata:Array):UIComponent
{
var typeClass:Class = ClassUtils.forName(getTypeName(metadata));
var result:* = ClassUtils.newInstance(typeClass);
for each (var m:Metadata in metadata)
{
if (m.name == "type")
continue;
// Attempting to invoke as method,
// would really like the property though
var methodInvoker:MethodInvoker = new MethodInvoker();
methodInvoker.target = result;
methodInvoker.method = m.name;
methodInvoker.arguments = [m.value];
var returnValue:* = methodInvoker.invoke(); // Fails!
}
return result;
}
private static function getTypeName(metadata:Array):String
{
if (metadata == null || metadata.length == 0)
throw new ArgumentError("metadata is null or empty");
var typeName:String;
// Type is usually the first entry
if (metadata.length > 1 && metadata[0] != null && metadata[0].name == "type")
{
typeName = metadata[0].value;
}
else
{
var typeMetadata:Array = metadata.filter(
function(element:*, index:int, arr:Array):Boolean
{
return element.name == "type";
}
);
if (typeMetadata == null || typeMetadata.length != 1)
throw new ArgumentError("type entry not found in metadata");
typeName = typeMetadata[0].value;
}
if (typeName == null || typeName.length == 0)
throw new Error("typeName is null or blank");
return typeName;
}
}
}
Here's some usage code:
var metadata:Array = new Array();
metadata[0] = new Metadata("type", "mx.controls.Text", null);
metadata[1] = new Metadata("text", "Hello World!", null);
metadata[2] = new Metadata("x", "77", null);
metadata[3] = new Metadata("y", "593", null);
this.addChild(new UIComponentBuilder().build(metadata));
I realize that I have to declare a dummy variable of the type I was to instantiate, or use the -inculde compiler directive. An unfortunate drawback of Flex.
Also, right now there's code to account for typecasting the value to it's specified type.
Dynamic execution in AS3 is much simpler than in other languages. This code:
var methodInvoker:MethodInvoker = new MethodInvoker();
methodInvoker.target = result;
methodInvoker.method = m.name;
methodInvoker.arguments = [m.value];
var returnValue:* = methodInvoker.invoke(); // Fails!
can be simplified to this:
var returnValue:* = result[method](m.value);
EDIT:
Since it's a property, it would be done like this:
result[method] = m.value;
and there is no return value (well, you can call the getter again but it should just return m.value unless the setter/getter do something funky.