Mongotemplate can't rename a collection - mongotemplate

I have a collection named collection_One. I want to rename the collection, but failed. mongotemplate showed me:
executing the 'renameCollection' command on the admin database"
If I run:
db.collection_one.renameCollection("collection_one","collection_two");
in the mongo shell, it works fine.
how to rename a collection by mongotemplate ?
This is the code where I'm trying it:
BasicDBObject basicObject = new BasicDBObject();
basicObject.append("renameCollection","collection_one");
basicObject.append("to","collection_two");
mongoTemplate.executeCommand(basicObject);

String dbName = default;//mongo db name
MongoNamespace mongoNamespace=new MongoNamespace(dbName,"collection_two");
mongoTemplate.getCollection("collection_one").renameCollection(mongoNamespace);
String boot version:2.1.4

If you are using spring's mongo template then try this:
mongoTemplate.getCollection(currName).rename(newName);

Related

SQLDelight: [SQLITE_ERROR] SQL error or missing database (table already exists)

I am trying to build a small POC with JetpackCompose Desktop and SQLDelight. I want that the data is persisted even after the application is restarted (not only in memory as all the tutorial examples I encountered show), so I tried this:
// ArticlesLocalDataSource.kt
class ArticlesLocalDataSource {
private val database: TestDb
init {
val driver: SqlDriver = JdbcSqliteDriver(url = "jdbc:sqlite:database.db")
TestDb.Schema.create(driver)
database = TestDb(driver)
}
// ...
}
When I run the application for the first time this works, i.e: a database.db file in the project root is created and the data is stored successfully.
However, when I try to run the application a second time, then it crashes immediately with:
Exception in thread "main" org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (table ArticleEntity already exists)
at org.sqlite.core.DB.newSQLException(DB.java:1012)
at org.sqlite.core.DB.newSQLException(DB.java:1024)
at org.sqlite.core.DB.throwex(DB.java:989)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.core.CorePreparedStatement.<init>(CorePreparedStatement.java:45)
at org.sqlite.jdbc3.JDBC3PreparedStatement.<init>(JDBC3PreparedStatement.java:30)
at org.sqlite.jdbc4.JDBC4PreparedStatement.<init>(JDBC4PreparedStatement.java:25)
at org.sqlite.jdbc4.JDBC4Connection.prepareStatement(JDBC4Connection.java:35)
at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:241)
at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:205)
at com.squareup.sqldelight.sqlite.driver.JdbcDriver.execute(JdbcDriver.kt:109)
at com.squareup.sqldelight.db.SqlDriver$DefaultImpls.execute$default(SqlDriver.kt:52)
at com.vgrec.TestPlus.TestDbImpl$Schema.create(TestDbImpl.kt:33)
at com.vgrec.data.local.ArticlesLocalDataSource.<init>(ArticlesLocalDataSource.kt:20)
I understand that it's crashing because there's an attempt to create the database again, but the database already exists. What is not clear to me, is how do I connect to the DB if a DB already exists?
For completeness, here's the build file:
// build.gradle
plugins {
kotlin("jvm") version "1.6.10"
id("org.jetbrains.compose") version "1.1.0"
// ...
id("com.squareup.sqldelight") version "1.5.3"
}
sqldelight {
database("TestDb") {
packageName = "com.test"
}
}
dependencies {
implementation(compose.desktop.currentOs)
// ..
implementation("com.squareup.sqldelight:sqlite-driver:1.5.4")
implementation("com.squareup.sqldelight:coroutines-extensions-jvm:1.5.4")
}
OK, so in the end I decided to just check if the database file exists and invoke the creation only if it does not exist.
Something like this:
init {
val driver: SqlDriver = JdbcSqliteDriver("jdbc:sqlite:database.db")
if (!File("database.db").exists()) {
TestDb.Schema.create(driver)
}
// ...
}
From first glance this seems to work as expected, but I am not sure this is the recommended approach as I am very new to SQLDelight, so other suggestions are welcome.

How do I make FreeRADIUS run an SQL query in default site?

What I want to do is to make FreeRADIUS run an SQL statement in a site file:
if(such and such condition is met){
run_some_sql_query
}
How do I do that?
I Assume that you are trying to run the SQL on Unlang. (This file is located on sites-enabled/default or sites-available/default)
First thing first, you should read about freeradius SQL https://wiki.freeradius.org/guide/sql-howto and https://wiki.freeradius.org/modules/Rlm_sql
Later, you can use the SQL Xlat as written there
Assumed that your unlang and sql module configuration is all set (your SQL module name is 'sql'), you can do something like this:
if(such and such condition is met){
"%{sql:SELECT * FROM radcheck WHERE username = '%{User-Name}'}"
"%{sql:INSERT INTO radcheck (username, attribute, op, value) VALUES ('%{User-Name}', 'Cleartext-Password', ':=', 'dummyPassword');}"
}

Grails 3.3 execute H2 script command

I'm running a small, trivial Grails 3.3.0 application using a H2 file based database. For simple backup reasons I would like to dump the current database state to a file using the H2 specific SCRIPT command:
SCRIPT TO /path/to/backup/dir/tempoDb.sql;
Currently I am trying to execute the native SQL command like this.
User.withSession { session ->
NativeSQLQuerySpecification nativeSQLQuerySpecification = new NativeSQLQuerySpecification("SCRIPT TO /path/to/backup/dir/tempoDb.sql;", null, null)
session.executeNativeUpdate(nativeSQLQuerySpecification, new QueryParameters())
}
but this does not work.
You can autowire the dataSource and try to run your sql query using the connection obtained from datasource Without going through Hibernate. The dataSource bean is registered in the Grails Spring context and it is an instance of javax.sql.DataSource.
Here is an example of a Grails service that backup the current H2 database to the file system.
#ReadOnly
class BackupService {
DataSource dataSource
def backup() {
def sql = "SCRIPT DROP TO '${System.properties['java.io.tmpdir']}/backup.sql'"
Statement statement = dataSource.connection.createStatement()
boolean result = statement.execute(sql)
}
}

Jira custom script validator: check if input textbox exists

I am totally new to Jira. In fact I don't even know where to start. I went to the jira atlassian website but got nothing solid enough to help me. I would like to validate if the information entered into a textbox already exists. I clicked around jira and ended up on the screen below:
Now I would like to find out the following:
Which programming language should be used for validation ? Is it Java
If the name of the custom field(of type Textbox) is XYZ and I wanna if check if value entered into XYZ already exist, how do I go about doing that ? Can I just write conditional statements in Java ?
I wrote some stuff and nothing worked.
That's a screenshot from the Script Runner add-on.
There are some documentation and examples for custom validators here.
You can also find an example here that shows how to query the JIRA (or an external) database from a groovy script. Ie.:
import com.atlassian.jira.component.ComponentAccessor
import groovy.sql.Sql
import org.ofbiz.core.entity.ConnectionFactory
import org.ofbiz.core.entity.DelegatorInterface
import java.sql.Connection
def delegator = (DelegatorInterface) ComponentAccessor.getComponent(DelegatorInterface)
String helperName = delegator.getGroupHelperName("default");
def sqlStmt = """
SELECT project.pname, COUNT(*) AS kount
FROM project
INNER JOIN jiraissue ON project.ID = jiraissue.PROJECT
GROUP BY project.pname
ORDER BY kount DESC
"""
Connection conn = ConnectionFactory.getConnection(helperName);
Sql sql = new Sql(conn)
try {
StringBuffer sb = new StringBuffer()
sql.eachRow(sqlStmt) {
sb << "${it.pname}\t${it.kount}\n"
}
log.debug sb.toString()
}
finally {
sql.close()
}
For anything that gets a bit complex it's easier to implement your script in a groovy file and make it available to Script Runner via the file system. That also allows you use a vcs like git to easily push/pull your changes. More info about how to go about that, is here.

How to execute a Groovy Script from my Grails app?

Well, it seems a simple task but I didn't manage to make it run.
I have a groovy script that runs fine under Windows Vista when calling from prompt:
> cd MY_GAILS_PROJECT_DIR
> groovy cp src/groovy scripts/myscript.groovy
Now, I want to execute this script (and passing to it some input arguments) through my my Maintenance Service Class (called from a controller) as below,
class MaintenanceService {
def executeMyScript() {
"groovy cp src/groovy scripts/myscript.groovy".execute()
}
}
It does not work at all! I don't even manage to have the execute() method recognizing any command (like "cd .".execute()) throwing exception:
Error 500: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
1- How can I execute a groovy script from my grails application?
2- What are the best practices here? For instance, should I use the QuartzPlugin and then the triggerNow method for executing a script? should I use a Gant Task? If yes, how to do it?
Thank you.
If you don't mind your script running asynchronously (in a separate process to the service method), the following should work assuming groovy is on your PATH variable:
def cmd = ['groovy.bat', 'cp', 'src/groovy scripts/myscript.groovy']
cmd.execute()
If you want to view the output of the process in the application console, you should try something like this instead
// Helper class for redirecting output of process
class StreamPrinter extends Thread {
InputStream inputStream
StreamPrinter(InputStream is) {
this.inputStream = is
}
public void run() {
new BufferedReader(new InputStreamReader(inputStream)).withReader {reader ->
String line
while ((line = reader.readLine()) != null) {
println(line)
}
}
}
}
// Execute the script
def cmd = ['groovy', 'cp', 'src/groovy scripts/myscript.groovy']
Process executingProcess = cmd.execute()
// Read process output and print on console
def errorStreamPrinter = new StreamPrinter(executingProcess.err)
def outputStreamPrinter = new StreamPrinter(executingProcess.in)
[errorStreamPrinter, outputStreamPrinter]*.start()
Update:
In response to your comment below, try the following (which assumes you're on Windows):
1: Create the file C:\tmp\foo.groovy. The content of this file should be simply:
println 'it works!'
2: In the groovy console, run the following:
cmd = ['groovy.bat', 'C:\\tmp\\foo.groovy']
cmd.execute().text
3: You should see the result of the script (the text 'it works!') shown in the Groovy console
If you can't get this simple example working, there's something wrong with your environment, e.g. 'groovy.bat' is not on your PATH. If you can get this example working, then you should be able to work forward from it to achieve your objective.
As of grails 1.3.6 the run-script command is built in to let you run
grails run-script myScript.groovy
For earlier versions of grails, check out my updated blog post from what Carlos posted above.
Easiest Way:
Generate an Groovy Class and place at in your /src/groovy Folder of your Grails Project.
Import that Class in your Domain Class and use the Functions you defined.
My 2 Cents...
This might help as well:
http://naleid.com/blog/2008/03/31/using-gant-to-execute-a-groovy-script-within-the-grails-context-updated/
Carlos
Another decision you can use GroovyScriptEngine for example:
file MyScript.groovy:
static String showMessage() {
println("Message from showMessage")
}
file BootStrap.groovy:
class BootStrap {
def init = { servletContext ->
new GroovyScriptEngine("scripts")
.loadScriptByName("MyScript.groovy")
.showMessage()
}
def destroy = {
}
}

Resources