Is there a way to save session keys into mysql 5.5? - java

A company that I'm working now is going to use DB sessions to organize their servers. I have no choice to refuse it :(
The sample php code they were gonna use was
sessioninit.php
<?
/* ------------------------------------------------------------------------
* Create a new database in MySQL called "sessions" like so:
*
* CREATE TABLE ucnovel_session (
* sesskey char(32) not null,
* expiry int(11) unsigned not null,
* value text not null,
* PRIMARY KEY (sesskey)
* );
*/
$SESS_DBH = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
function sess_open($save_path, $session_name)
{
global $SESS_DBH;
$sv = "192.168.0.3";
$SESS_DBH = mysql_pconnect($sv, "ucnovel", "비번") or die("Can't connect to SQL Server");
mysql_select_db("hotdog", $SESS_DBH) or die("Can't connect to SQL Server");
return true;
}
function sess_close()
{
return true;
}
function sess_read($key)
{
global $SESS_DBH, $SESS_LIFE;
//echo $key;
$qry = "SELECT value FROM ucnovel_session WHERE sesskey = '$key' AND expiry > " . time();
$qid = mysql_query($qry, $SESS_DBH);
if (list($value) = mysql_fetch_row($qid)) {
return $value;
}
return false;
}
function sess_write($key, $val)
{
global $SESS_DBH, $SESS_LIFE;
$expiry = time() + $SESS_LIFE;
$value = addslashes($val);
$qry = "SELECT COUNT(*) FROM ucnovel_session WHERE sesskey='$key'";
$qid = mysql_fetch_array(mysql_query($qry, $SESS_DBH));
if($qid[0]>0) {
$qry = "UPDATE ucnovel_session SET expiry = $expiry, value = '$value' WHERE sesskey = '$key'"; // AND expiry > " . time();
$qid = mysql_query($qry, $SESS_DBH);
} else {
$qry = "INSERT INTO ucnovel_session SET expiry = $expiry, value = '$value', sesskey = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
}
return $qid;
}
function sess_destroy($key)
{
global $SESS_DBH;
$qry = "DELETE FROM ucnovel_session WHERE sesskey = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
return $qid;
}
function sess_gc($maxlifetime)
{
global $SESS_DBH;
$qry = "DELETE FROM ucnovel_session WHERE expiry < " . time();
$qid = mysql_query($qry, $SESS_DBH);
return mysql_affected_rows($SESS_DBH);
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_set_cookie_params(0, "/", "ucnovel.com", false, false);
session_start();
?>
sessiontest.php
<?
include "sessioninit.php";
$old = $_COOKIE[test_sess2];
$new = rand()%10000;
$_COOKIE[test_sess2] = $new;
setcookie("test_sess2", $new);
echo "OLD ".$old."<br>"."NEW ".$new;
$old = $_SESSION[test_sess];
$new = rand()%10000;
$_SESSION[test_sess] = $new;
$_SESSION[test_ip] = $REMOTE_ADDR;
echo "<br><br>OLD ".$old."<br>"."NEW ".$new;
?>
I understand that they override the session handler and customized it. But I can't find any references on how to do it in Java.
Some people says that overriding HttpSession is a way. But I still can't understand how to do this. Also, I don't know if DTOs will save in the DB :S
I'm using Spring 3.1 right now, and the server is MySQL 5.5
Is there any samples that I can understand how to do it? or maybe a plugin that helps it?

Related

Can we Replace a portion of String in Java which has symbol in the start and end to Identify?

I have a String SELECT *FROM USERS WHERE ID = '#userid#' AND ROLE = '#role#'
Now i have replace any string between #...# , with a actual value .
Expected output SELECT *FROM USERS WHERE ID = '4' AND ROLE = 'Admin'
This replace will happen from a method , i have written this logic
public String replaceQueryKeyWithValueFromKeyValues(String query, int reportId) {
try {
REPMReportDao repmReportDao = new REPMReportDao();
int Start = 0;
int end;
if (query.contains("#")) {
boolean specialSymbolFound = false;
for (int i = 0; i < query.length(); i++) {
if (query.charAt(i) == '#') {
if (!specialSymbolFound) {
Start = i + 1;
specialSymbolFound = true;
} else {
specialSymbolFound = false;
end = i;
query = query.replace(query.substring(Start - 1, end + 1), repmReportDao.getReportManagerKeyValue(query.substring(Start - 1, end + 1).replaceAll("#", ""), reportId));
}
}
}
return query;
} else {
return query;
}
} catch (Exception e) {
logger.log(Priority.ERROR, e.getMessage());
return e.getMessage();
}
}
It works fine , but in the case if a single '#' symbol exist instead of start and end it will fail.
Like :
SELECT *FROM USERS WHERE emailid = 'xyz#gmail.com' AND ROLE = '#role#'
Here it should replace the only role '#role#' and should left email as it is.
Expected Output => SELECT *FROM USERS WHERE emailid = 'xyz#gmail.com' AND ROLE = 'Admin'
Complete example with mocked data returned by getReportManagerKeyValue:
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StackOverflow54842971 {
private static Map<String, String> map;
public static void main(String[] args) {
// preparing test data
map = new HashMap<>();
map.put("role", "Admin");
map.put("userid", "666");
// original query string
String query = "SELECT * FROM USERS WHERE ID = '#userid#' AND emailid = 'xyz#gmail.com' AND ROLE = '#role#' ";
// regular expression to match everything between '# and #' with capture group
// omitting single quotes
Pattern p = Pattern.compile("'(#[^#]*#)'");
Matcher m = p.matcher(query);
while (m.find()) {
// every match will be replaced with value from getReportManagerKeyValue
query = query.replace(m.group(1), getReportManagerKeyValue(m.group(1).replaceAll("#", "")));
}
System.out.println(query);
}
// you won't need this function
private static String getReportManagerKeyValue(String key) {
System.out.println("getting key " + key);
if (!map.containsKey(key)) {
return "'null'";
}
return map.get(key);
}
}
It's considered very bad practice to use string substitution to generate database queries, because you leave your code open to SQL Injection attacks. I can't tell from the small code sample you've provided, but the vast majority of large-scale Java projects use the Spring Framework, which allows you to use either JdbcTemplate or (my preference) NamedParameterJdbcTemplate. Both will allow you to substitute variables in a safe manner.

Cannot Insert into sqlite

I'm still learning Ionic and programming in general. I followed a link on the internet and I was able to create the white and read the necessary data, but I am not able to insert data in the created table. Can anyone help me with this?
I follow this tutorial: ionic-sqlite
My code:
getRegiao() { // Regiões //
return new Promise<Regiao[]>((resolve, reject) => {
let sql = "SELECT NOM_REGIAO, ID " +
"FROM TB_REGIAO "
this.executeQuery(sql).then(data => {
let regioes = [];
if (data != undefined)
data.forEach(function (row) {
let regiao: Regiao = { nom_regiao: row[0], id: row[1] }
regioes.push(regiao);
});
resolve(regioes);
}).catch(error => {
console.log(error);
});
});
}
addUser() {
let sql = "INSERT INTO TB_USUARIO (EMAIL) VALUES ('BLITCRANK#HOTMAIL.COM')";
// let sql = "SELECT EMAIL FROM TB_USUARIO";
this.executeQuery(sql);
}
executeQuery(sql: string) {
let db: any;
return new Promise<any>((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', this.dbName, true);
xhr.responseType = 'arraybuffer';
xhr.onload = (e) => {
let uInt8Array = new Uint8Array(xhr.response);
db = new SQL.Database(uInt8Array);
let contents = db.exec(sql);
console.log(contents);
if (contents.length > 0)
resolve(contents[0].values);
else
resolve("query executada sem retorno")
};
xhr.send();
});
}
Please use this plugin , this is the plugin that I am using.
Take note in using execute sql like this db.executeSql('create table danceMoves(name VARCHAR(32))', {})
But rather use this db.executeSql('create table danceMoves(name VARCHAR(32))', [])
I dont know why instead of using object '{}' they replace it as array '[]' I think they forgot to update the documentaion

DatabaseMetada.getImportedKey is empty even if foreign are existing

For my project i try to get all foreign key in my table using DatabaseMetada Object form jdbc but when i execute the following code the result set is always empty even if my table contain foreign key ?
ResultSet v_resultPrimaryKey = p_metadata.getImportedKeys(null, Tools.getDBName(), "bookmarks_tags");
if (v_resultPrimaryKey.next()) {
System.out.println("test");
v_resultPrimaryKey.beforeFirst();
v_resultPrimaryKey.beforeFirst();
while (v_resultPrimaryKey.next()) {
if (p_att.equals(v_resultPrimaryKey.getString("FKCOLUMN_NAME"))) {
v_fk = v_resultPrimaryKey.getString("PKTABLE_NAME") + "."
+ v_resultPrimaryKey.getString("PKCOLUMN_NAME");
v_fkName = v_resultPrimaryKey.getString("FK_NAME");
}
}
if(!v_fk.equals("")){
v_foreignKey = new ForeignKey(v_fkName, v_fk);
}
}
stumbled upon this and this may help in case anyone may see it
DatabaseMetaData p_metadata= connection.getMetaData();
ResultSet v_resultPrimaryKey = p_metadata.getImportedKeys(null, Tools.getDBName(), "bookmarks_tags");
if (v_resultPrimaryKey.next()) {
System.out.println("test");
v_resultPrimaryKey.beforeFirst();
v_resultPrimaryKey.beforeFirst();
while (v_resultPrimaryKey.next()) {
if (p_att.equals(v_resultPrimaryKey.getString("FKCOLUMN_NAME"))) {
String v_fk = v_resultPrimaryKey.getString("PKTABLE_NAME") + "."
+ v_resultPrimaryKey.getString("PKCOLUMN_NAME");
String v_fkName = v_resultPrimaryKey.getString("FK_NAME");
}
}
if(!v_fk.equals("")){
v_foreignKey = new ForeignKey(v_fkName, v_fk);
}
}

How to repeat recurring invoice by x amount of days and then it stops

I am trying to update my ( Recurring Invoice ) setup but i am running into a little bit of trouble.
I am trying to make it where i do this...
enter date ( which is the starting date of the recurrence )
enter how it will recur ( weekly.bi-weekly and so on..)
this is where the issue starts for me.... ( enter how many times it will recur for and then stop the invoice recurring)
.. thanks in advance
<?php require 'initapp.php'; $self='invoice-recurring.php'; $rself='all-recurring-invoice.php'; if (isset($_POST['submit'])){
$cid = _post('client');
if ($cid=='' OR $cid=='0'){
conf($self,'e','Client Name is Required.');
}
$idate = _post('date');
$date=date("Y-m-d", strtotime($idate));
if ($date==''){
conf($self,'e','Date is Required.');
}
$item = _post('item');
if ($item==''){
conf($self,'e','Item Name is Required.');
}
$note = _post('note');
$note=html_entity_decode($note);
$recurring = _post('frequency');
if ($recurring==''){
conf($self,'e','Frequency is Required.');
} //starts added on 3-7-2015 //$occurance = _post('occurance'); // if ($occurance==''){ // conf($self,'e','Occurance is Required.'); // } //stops
$price= _post('price');
if ($price==''){
conf($self,'e','Price is Required.');
}
$discount=_post('discount');
$disc_calculate=($discount*$price/100);
$tax=_post('tax'); if ($tax!='0'){ $tax = ORM::for_table('taxes')->find_one($tax); $trate = $tax['rate']; $tname = $tax['name']; $ttype = $tax['type']; if ($ttype=='Excluded'){ $tval = ($price*$trate)/100; $intotal = $price+$tval;
}
else {
$tval = ($price*$trate)/100;
$intotal = $price-$tval;
}
}
else{
$intotal=$price;
$tval='0';
$tname='None';
}
$created = $date;
$add_days =$recurring;
$paiddate = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //add or delete * $occurance added on 3-7-2015 //$emailnotify='Yes'; $emailnotify = $aclient->emailnotify;//added on 2-25-2015
$intotal=$intotal-$disc_calculate; $paymentmethod=_post('paymentmethod');
$d = ORM::for_table('invoices')->create();
$d->userid = $cid;
$d->iteam = $item;
$d->created = $date;
$d->duedate = $date;
$d->nextduedate=$paiddate;
$d->datepaid=$date;
$d->subtotal = $price;
$d->total = $intotal;
$d->discount = $discount;
$d->paymentmethod=$paymentmethod;
$d->note = $note;
$d->tax=$tval;
$d->taxname=$tname;
$d->status = 'Unpaid';
$d->recurring = $recurring;
//$d->occurance = $occurance;//added on 3-7-2015
$d->save();
$invoiceid= $d->id();
if ($emailnotify=='Yes'){
$sysEmail=appconfig('Email');
$sysCompany=appconfig('CompanyName');
$sysUrl= appconfig('sysUrl');
$d= ORM::for_table('email_templates')->where('tplname', 'Customer Invoice Created')->find_one();
$cl = ORM::for_table('accounts')->find_one($cid);
$name = $cl['name'];
$email = $cl['email'];
$template = $d['message'];
$subject = $d['subject'];
$send = $d['send'];
$data = array('name' => $name,
'logo'=> '<img width="61" height="76" border="0" src="'.$sysUrl.'/assets/uploads/logo.jpg">',
'business_name'=> $sysCompany,
'invoice_id'=> $invoiceid,
'invoice_item'=> $item,
'invoice_amount'=> $intotal,
'sys_url' => $sysUrl
);
$message = _render($template,$data);
$mail_subject = _render($subject,$data);
$body = $message;
if ($send=='1'){
$smtp=ORM::for_table('smtp_setting')->find_one('1');
$smtp_status=$smtp['status'];
if($smtp_status!='1'){
require ('../lib/pnp/email/class.phpmailer.php') ;
$mail = new PHPMailer();
$mail->SetFrom($sysEmail, $sysCompany);
$mail->AddReplyTo($sysEmail, $sysCompany);
$mail->AddAddress($email, $name);
$mail->Subject = $mail_subject;
$mail->MsgHTML($body);
$mail->Send();
}else{
require ('../lib/plugin/PHPMailer/PHPMailerAutoload.php');
$host_name=$smtp['host_name'];
$username=$smtp['username'];
$password=$smtp['password'];
$port=$smtp['port'];
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = "$host_name"; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "$username"; // SMTP username
$mail->Password ="$password"; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = "$port";
$mail->SetFrom($sysEmail, $sysCompany);
$mail->AddReplyTo($sysEmail, $sysCompany);
$mail->AddAddress($email, $name);
$mail->Subject = $mail_subject;
$mail->MsgHTML($body);
$mail->Send();
}
}
}
conf("invoice-manage.php?_inid=$invoiceid",'s','Recurring Invoice Add Successfully'); } conf($self,'e','Invoice does not Create Successfully'); ?>
Most likely you need the time and/or lenght/duration of the event. You can use cron for it or send me a PM I have written a php script.

how to encode multiple rows from mysql into json using php

I am trying to encode all the rows of data i get from the DB into JSON and then process it at the client side but i can't seem to get it to work..My code is below
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output['original_title'];
$response['test'] = $output['content'];
return json_encode($response);
//return $output;
}
Then i try to print the var_dump($response) but i get null values.. Although if i var_dump($output) i get all the rows in an array..accessing the array is the problem here now..i think
NB: i am using PDO
The problem is the $output is an array that you need to go through. Like:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response['text'] = $o['original_title'];
$response['test'] = $o['content'];
}
return json_encode($response);
}
}
This is for the last response, but if you want all, do:
function getTopic($conn){
$response = array('error'=>0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response[] = array('text'=>$o['original_title'],'test'=>$o['content']);
}
return json_encode($response);
}
}
If you are only want one row add a limit to your MySQL statement.
$output is array of results. use a loop or if only one row u need do this:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output[0]['original_title'];
$response['test'] = $output[0]['content'];
return json_encode($response);
//return $output;
}

Categories

Resources