How to create a derby user - database-schema

I tried to set the DB schema name by schema.xml but it caused a schema name duplication in the generated SQL statement for ID generators. (Duplicate schema name in sequece generation)
I read the schema is defined by the passed user at connection time. Now I would like to set the schema by this way.
But I don't know how can I create a new Derby user and link it with the desired schema. Can somebody help me?
Environment: NetBeans, Glassfish, Derby
I have found this:
CALL SYSCS_UTIL.SYSCS_CREATE_USER('username', 'password')
But Derby answers:
Error code -1, SQL state 42Y03: 'SYSCS_UTIL.SYSCS_CREATE_USER' is not recognized as a function or procedure.
Why? I have connected to the db as the default admin user.
Or if I try to dispatch this command from a GUI tool, Derby says:
[Error Code: 0, SQL State: 42Y07] : Schema 'SYSCS_UTIL' does not exist

To Create user in Derby :
I am using Command Line Interface and I have already set my System environment variable to Derby.
Otherwise you can write these command into your CLI
java -jar %DERBY_HOME%\lib\derbyrun.jar ij
and hit Enter key to run ij tool, and you will see a prompt like this:
ij>
Now type the following command to create a user (replace sam by the desired username and sampass by the desired password):
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.user.sam','sampass');
Now hit enter. This should give a message like this:
0 rows inserted/updated/deleted.

here is a solution (heavily commented):
String setProperty = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(";
String getProperty = "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(";
String requireAuth = "'derby.connection.requireAuthentication'";
String sqlAuthorization = "'derby.database.sqlAuthorization'";
String defaultConnMode = "'derby.database.defaultConnectionMode'";
String fullAccessUsers = "'derby.database.fullAccessUsers'";
String readOnlyAccessUsers = "'derby.database.readOnlyAccessUsers'";
String provider = "'derby.authentication.provider'";
String propertiesOnly = "'derby.database.propertiesOnly'";
System.out.println("Turning on authentication and SQL authorization.");
Statement s = conn.createStatement();
// Set requireAuthentication
s.executeUpdate(setProperty + requireAuth + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.connection.requireAuthentication','true'
// Set sqlAuthorization
s.executeUpdate(setProperty + sqlAuthorization + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.sqlAuthentication','true'
// Retrieve and display property values
ResultSet rs = s.executeQuery(getProperty + requireAuth + ")");
rs.next();
System.out.println("Value of requireAuthentication is " + rs.getString(1));
rs = s.executeQuery(getProperty + sqlAuthorization + ")");
rs.next();
System.out.println("Value of sqlAuthorization is " + rs.getString(1));
// Set authentication scheme to Derby builtin
s.executeUpdate(setProperty + provider + ", 'BUILTIN')");
// Create some sample users
s.executeUpdate(setProperty + "'derby.user." + txtUname.getText() + "', '" + txtPw1.getText() + "')" );
// Define noAccess as default connection mode
s.executeUpdate(setProperty + defaultConnMode + ", 'noAccess')");
// Confirm default connection mode
rs = s.executeQuery(getProperty + defaultConnMode + ")");
rs.next();
System.out.println("Value of defaultConnectionMode is " + rs.getString(1));
// Define read-write users
s.executeUpdate(setProperty + fullAccessUsers + ", '" + txtUname.getText() + "')");
// Define read-only user
// s.executeUpdate(setProperty + readOnlyAccessUsers + ", 'guest')");
// Confirm full-access users
rs = s.executeQuery(getProperty + fullAccessUsers + ")");
rs.next();
System.out.println("Value of fullAccessUsers is " + rs.getString(1));
// Confirm read-only users
rs = s.executeQuery(getProperty + readOnlyAccessUsers + ")");
rs.next();
System.out.println("Value of readOnlyAccessUsers is " + rs.getString(1));
// We would set the following property to TRUE only when we were
// ready to deploy. Setting it to FALSE means that we can always
// override using system properties if we accidentally paint
// ourselves into a corner.
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" + "'derby.database.propertiesOnly', 'false')");
s.close();
Let me know if that works (or not) for you.

Related

JPQL. JPA Query. How to get size of named parameter collection

I'm trying to define custom method in repository interface
public interface RequestRepository extends JpaRepository<Request, Long> {
#Query("SELECT r FROM Request r " +
"LEFT JOIN FETCH r.pathParams pp " +
"WHERE r.responseCode = :code " +
"AND r.requestMethod = :method " +
"AND r.requestPath = :path " +
"AND r.requestBody = :body " +
"AND r.apiDetails = :apidetails " +
"AND (pp IN :pathparams OR r.pathParams IS EMPTY) " +
"AND SIZE(r.pathParams) = :pathparamssize "
)
Optional<Request> findByDetails(
#Param("code") String code,
#Param("method") RequestMethod method,
#Param("path") String path,
#Param("body") RequestBody body,
#Param("apidetails") ApiDetails apidetails,
#Param("pathparams") Set<PathParam> pathparams,
#Param("pathparamssize") Integer pathparamssize
);
}
It works, but I believe it can be done in better way
As you can see I declared redundant parameter "pathparamssize" (IMO)
I tried to do that like "AND SIZE(r.pathParams) = SIZE(:pathparams) " but it doesn't want to work with "SIZE(:pathparams)"
can you please advise something?
many thanks in advance

Bukkit - Displaying null when getting a string from the config file

So I've been working on a custom feature for my minecraft server, one of the things that I need to do is get an integer from the config file that is specific to each player to display how many Packages(keys) they have (Virtual items)
The issue that I am having is that in the GUI it is displaying 'null' instead of how many they have... Could anyone help me please?
Item in the gui
Code for creating the player's instance in the config (Using a custom file class that was provided to me by a friend of mine.)
#EventHandler
public void playerJoin(PlayerJoinEvent event) {
Main main = Main.getPlugin(Main.class);
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
if (!main.getDataFolder().exists())
main.getDataFolder().mkdirs();
File file = new File(main.getDataFolder(), "players.yml");
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
if (!config.contains("Users." + uuid + ".Username")) {
try {
System.out.println("Creating entry for " + player + " (" + uuid + ")");
config.set("Users." + uuid + ".Username", player);
config.set("Users." + uuid + ".Packages.Common", 0);
config.set("Users." + uuid + ".Packages.Rare", 0);
config.set("Users." + uuid + ".Packages.Epic", 0);
config.set("Users." + uuid + ".Packages.Legendary", 0);
config.set("Users." + uuid + ".Packages.Exotic", 0);
config.save(file);
System.out.println("Successfully created the entry for " + " (" + uuid + ")");
} catch (Exception e) {
}
}
}
Code for the creation of the item in the gui:
public static String inventoryname = Utils.chat("&fWhite Backpack");
public static Inventory WhiteBackpack(Player player) {
UUID uuid = player.getUniqueId();
Inventory inv = Bukkit.createInventory(null, 27, (inventoryname));
ItemStack common = new ItemStack(Material.INK_SACK);
common.setDurability((byte) 8);
ItemMeta commonMeta = common.getItemMeta();
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l" + Main.pl.getFileControl().getConfig().getString("Users." + uuid + ".Packages.Common")));
common.setItemMeta(commonMeta);
inv.setItem(10, common);
return inv;
}
There are a couple things wrong with your code.
First, you never account for what happens if the config you are loading does not exist. When you do main.getDataFolder().mkdirs(), you account for if the folder is missing, but not the file.
Second, you are doing the following operation:
config.set("Users." + uuid + ".Username", player);
This is incorrect because the player variable is of the type Player, not of the type String. To fix this, you need to instead do the following:
config.set("Users." + uuid + ".Username", player.getName());
Third, you are attempting to write to a file that might not exist. When you initialize you file, you need to also make sure it exists, and if it does not, you need to create it. Right now you have the following:
File file = new File(main.getDataFolder(), "players.yml");
It must be changed to this block of code:
File file = new File(main.getDataFolder(), "players.yml");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could just have it be created when you attempt to save the file later on, but that is not ideal since it's safer to let Bukkit write to a file that already exists.
Fourth, and I'm not necessarily sure that this is a problem per se, but you are trying to access an Integer value from the config file as if it were a String. Try to replace the following:
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l"
+ Main.pl.getFileControl().getConfig().getString("Users." + uuid + ".Packages.Common")));
with this instead:
commonMeta.setDisplayName(Utils.chat("&fCommon Packages &8» &f&l"
+ Main.pl.getFileControl().getConfig().getInt("Users." + uuid + ".Packages.Common")));
Hope this gets you moving in the right direction!

Making raw SQL safe in Entity Framework

var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");
// normally when using parameters I would do something like this:
var valueParam = SqlParameter("aValue", passedInValues);
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE Column1 = #aValue", valueParam);
// NOTE: I would not do this at all. I know to use LINQ. But for this question, I'm concentrating on the issue of passing variables to a raw sql string.
But since both the column and value are "parameters" in:
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");
, is there to prevent sql injection for both?
First: whilelist aColumn: this has to be added via string concatenation but you know what columns are in your database (or you can check using schema views).
Second: In entity framework – as you show – you can use parameters for values in the query. However, rather than creating SqlParameter instances you can pass the values and use #p0, #p1, ….
Right way to prevent SQL injection is to use SqlParameter and SqlQuery<T>:
var parameter = new SqlParameter("#title", value);
var result = context.Database.SqlQuery<Book>("SELECT * FROM Books WHERE Title LIKE #title", parameter);
http://ignoringthevoices.blogspot.ru/2013/07/sql-injection-with-entity-framework-5.html

Conversion failed when converting the varchar value to data type

i search a lot but didn't find what i want this question is ask by many users here but i didn't find my solution so i ask this question.
i have page in which i have Assign and withdraw button which
is used to Assign and withdraw device id for the selected group
id (group id fetch from dropdownlist) from one list-box to another
that part is completed
Now when i add another device id for the same group id i need to
append that updated record and show it in listbox2.
here is my code:
string queryString1 = "select device_id from device_group_master where group_id='" + ddlGroupName.SelectedValue.ToString() +"'";
SqlDataAdapter newdataAdapter = new SqlDataAdapter(queryString1, con);
SqlCommandBuilder newcommandBuilder = new SqlCommandBuilder(newdataAdapter);
newdataAdapter.Fill(ds1, "table");
if (ds1.Tables["table"].Rows.Count != 0)
{
if (ds1.Tables["table"].Rows[0][0].ToString() == "0")
{
string queryString2 = "update DEVICE_GROUP_MASTER set DEVICE_ID='" + device.ToString() + "', NOT_EXCLUDE_DEVICE_ID='" + enable + "' where GROUP_ID='" + ddlGroupName.SelectedValue.ToString() + "'";
SqlCommand update = new SqlCommand(queryString2, con);
update.CommandType = CommandType.Text;
update.ExecuteNonQuery();
}
else
{
string append;
append = ds1.Tables["table"].Rows[0][0].ToString();
append += ","+ device;
string queryString2 = "update DEVICE_GROUP_MASTER set DEVICE_ID='" + append.ToString() + "' where GROUP_ID='" + ddlGroupName.SelectedValue.ToString() + "'";
SqlCommand update = new SqlCommand(queryString2, con);
update.CommandType = CommandType.Text;
update.ExecuteNonQuery();
}
}

DbCommand , Must Declare a variable error

This is my code. I have added the db parameter too but it still shows me error (on execution). Must declare a scalar variable
DbCommand command;
StringBuilder query = new StringBuilder(
#"SELECT isnull(UpsellService_OID,'') UpsellService_OID," + Environment.NewLine +
" isnull(ServiceName,'') ServiceName," + Environment.NewLine +
" isnull(ServiceDescription,'') ServiceDescription," + Environment.NewLine +
" isnull(Create_By,'') Create_By," + Environment.NewLine +
" isnull(Create_Date,'') Create_Date," + Environment.NewLine +
" isnull(Modify_By,'') Modify_By," + Environment.NewLine +
" isnull(Modify_Date,'') Modify_Date," + Environment.NewLine +
" isnull(Active_f,'') Active_f" + Environment.NewLine +
"FROM TRGPAYROLL.ZONG.UPSELLSERVICES " + Environment.NewLine +
"WHERE 1 = 1");
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
query.Append(" AND ServiceName like '%' #ServiceName '%'");
}
command = db.GetSqlStringCommand(query.ToString());
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
db.AddInParameter(command, "ServiceName", DbType.String, idObject.ServiceName);
}
return command;
I would rewrite the last part of your code in this way
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
query.Append(" AND ServiceName like #ServiceName");
}
command = db.GetSqlStringCommand(query.ToString());
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
db.AddInParameter(command, "#ServiceName", DbType.String, "%" + idObject.ServiceName + "%");
}
The wildcard are added directly to the value of the parameter, while the placeholder of the parameter should be free from any string concatenations. However there are many details missing to be sure of the correctness of this answer. In particular Ican only assume the inner workings of the methods GetSqlStringCommand and AddInParameter
#ServiceName variable is not declared in your SQL statement. Append to beggining of it something like
DECLARE #ServiceName AS nchar(32)
SET #ServiceName = ....