(kohana) Unittest DbUnit foreign key constraint - mysql

I've searched through google/stackoverflow for a solution but failed to find a satisfying solution.
My issue:
[SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a
foreign key constraint (integration.b_node_leafs, CONSTRAINT fk_node_id
FOREIGN KEY (node_id) REFERENCES integration.b_nodes (id))]
And I can't find anywhere in the docs who to solve this issue neither a order for the XmlDataSet (which I use).
This doesn't work.
public function setUp() {
$conn=$this->getConnection();
$conn->getConnection()->query("set foreign_key_checks=0");
parent::setUp();
$conn->getConnection()->query("set foreign_key_checks=1");
}
Results in mysql.log
Connect root#localhost on integration_db
Query set foreign_key_checks=0
Connect root#localhost on integration_db
Query TRUNCATE `table_name`
Quit
Quit
This is my dataset.xml (As you can see I start from the bottom).
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<!-- Meta for node -->
<b_meta id="4321" created_by="###NULL###" deleted="0" />
<!-- Meta for leaf -->
<b_meta id="1010" created_by="###NULL###" deleted="0" />
<!-- Meta for post -->
<b_meta id="1050" created_by="###NULL###" deleted="0" />
<!-- meta for comment -->
<b_meta id="7894" created_by="###NULL###" deleted="0" />
<!-- Add comment -->
<b_comments id="5555" meta_id="7894" text="This is a integrationtest" />
<!-- Add Post -->
<b_posts id="4646" meta_id="1050" title="How to integration" seo_title="how-to-integration" text="Explain why to use integrationtests" />
<!-- Link comment to post -->
<b_post_comments post_id="4646" comment_id="5555" />
<!-- Add Leaf -->
<b_leafs id="3535" meta_id="1010" title="App Testing" seo_title="app-testing" />
<!-- Link leaf to post -->
<b_leaf_posts leaf_id="3535" post_id="4646" />
<!-- Add node -->
<b_nodes id="1234" meta_id="4321" type="forum" title="PHP" />
<!-- Link node to leaf -->
<b_node_leafs node_id="1234" leaf_id="3535" />
</dataset>
PS: I run on PHPUnit 3.7.28

My solution was to save the connection for multiple uses instead of creating new connection for each operation.
In your test setUp function add
public function setUp()
{
$conn = $this->getConnection();
$conn->getConnection()->query("set foreign_key_checks=0");
return parent::setUp();
}
In Kohana_Unittest_Database_TestCase
protected $_connection;
public function getConnection()
{
if ($this->_connection !== NULL)
{
return $this->_connection;
}
// Get the unittesting db connection
$config = Kohana::$config->load('database.'.$this->_database_connection);
if(strtolower($config['type']) !== 'pdo')
{
$config['connection']['dsn'] = strtolower($config['type']).':'.
'host='.$config['connection']['hostname'].';'.
'dbname='.$config['connection']['database'];
}
$pdo = new PDO(
$config['connection']['dsn'],
$config['connection']['username'],
$config['connection']['password']
);
$this->_connection = $this->createDefaultDBConnection($pdo, $config['connection']['database']);
return $this->_connection;
}
See my pull request: https://github.com/kohana/unittest/pull/36

Related

Get SQLexception error before giving the user input in jsp page

I like to create a registration form where user can register his or her data and the given data will be saved on a database. I created a database HospitalM using mysql workbench 8.0. I ran the project, the jsp file for form creation on Tomcat server. The pid is a primary key in the table called patient in the database HospitalM.
When I run the form on server a form generated but the form did not wait for input data and throw a message SQLException caught: Column 'pid' cannot be null.
I will share my code and the form in the below. Can any one give me some hints why it did not work?
JSP code: (name of the jsp file insert.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
<tr><td>Address</td><td><input type="text" name="patientaddress" ></td></tr>
<tr><td>Phone number</td><td><input type="number" name="Ph" required /></td></tr>
<tr><td>Email</td><td><input type="email" name="email" required /></td></tr>
<tr><td>Type</td><td><input type="text" name="patienttype" ></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="register"></td></tr>
</table>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitalm","root","1234");
out.println ("database successfully opened.");
String sql = "INSERT INTO patient (pid, pname, address, phone, email_id,ptype) values (?, ?, ?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, request.getParameter("pid"));
statement.setString(2, request.getParameter("pname"));
statement.setString(3, request.getParameter("address"));
statement.setString(4, request.getParameter("phone"));
statement.setString(5, request.getParameter("email_id"));
statement.setString(6,request.getParameter("ptype"));
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("One row inserted.");
}
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
%>
</body>
</html>
The sql query for patient table:
create table patient(pid varchar(10),
pname varchar(40) not null,
address varchar(10),
phone numeric(10,0) not null,
email_id varchar(20) not null,
ptype varchar(2),
primary key(pid),
check(email_id like '%_#__%.__%'));
The output that I got
The problem here is that when you first access the page, all of that code gets executed, but there was no request to process.
So, during the first access, all of those request parameters are null.
As suggested by Piotr, you could use the request method to get for whether it's a GET or a POST, and only execute the code on the POST.
The proper answer to that goes much deeper into how these kinds of things are architected along with the page workflow, but that's a much deeper topic that to go in to here.
For now, the simple issue is that on the first access, there are no parameters, so you're essentially trying to do:
statement.setString(1, null);
Which is illegal (to set a column to an explicit SQL NULL value in JDBC, you use the statement.setNull(1) method).

cts:near-query Marklogic on json documents

I am using search:search like below
import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";
let $options :=
<options xmlns="http://marklogic.com/appservices/search">
<concurrency-level>8</concurrency-level>
<search-option>unfiltered</search-option>
<transform-results apply="empty-snippet">
<!-- #apply=snippet : to get snippet-->
<per-match-tokens>30</per-match-tokens>
<max-matches>4</max-matches>
<max-snippet-chars>200</max-snippet-chars>
<preferred-matches/>
</transform-results>
<term>
<term-option>case-insensitive</term-option>
<term-option>wildcarded</term-option>
<term-option>stemmed</term-option>
<term-option>diacritic-insensitive</term-option>
<term-option>punctuation-insensitive</term-option>
</term>
<constraint name="title">
<range collation="http://marklogic.com/collation/codepoint" type="xs:string" facet="false">
<json-property>title</json-property>
</range>
</constraint>
<extract-document-data>
<!-- Full Title -->
<extract-path>/title</extract-path>
</extract-document-data>
<additional-query>
<cts:near-query distance="1" xmlns:cts="http://marklogic.com/cts">
<cts:json-property-word-query>
<cts:property>title</cts:property>
<cts:text xml:lang="en">chemotherapy</cts:text>
<cts:option>case-insensitive</cts:option>
</cts:json-property-word-query>
<cts:json-property-word-query>
<cts:property>title</cts:property>
<cts:text xml:lang="en">hospital</cts:text>
<cts:option>case-insensitive</cts:option>
</cts:json-property-word-query>
<cts:option>ordered</cts:option>
</cts:near-query>
</additional-query>
<additional-query/>
</options>
return
search:search('', $query, 1, 10)
Using this query I am getting the document with title, in the query distance between chemotherapy and hospital in 1
Result with title :{"title":"chemotherapy for cancer patients in the hospital."}
Am I doing something wrong?
Thanks
It worked after enabling the word position index in Db settings

Wildfly with jaas always results in login-error

For some reason i can't loggin in my application using Wildfly, primefaces and JAAS. I didn't try it in others versions like JBoss 7 AS because i want to see this working on Wildfly.
After try loggin using admin for j_username and 1234 for j_password, it redirecting to login-error page. I can't understand why.
MD5 hash econding it's right with generated password from postgres
I can acess this JDNI and execute some querys from java code, concluding it's working.
String DATASOURCE_CONTEXT = "java:jboss/datasources/zephyrplace-ds";
Connection result = null;
try {
Context initialContext = new InitialContext();
if ( initialContext == null){
System.out.println("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
if (datasource != null) {
result = datasource.getConnection();
}
else {
System.out.println("Failed to lookup datasource.");
}
}
catch ( NamingException ex ) {
System.out.println("Cannot get connection: " + ex);
}
catch(SQLException ex){
System.out.println("Cannot get connection: " + ex);
}
return result;
login.xhtml (primefaces):
<h:form id="login" onsubmit="document.getElementById('login').action='j_security_check';" prependId="false">
<ul class="nav navbar-nav navbar-right">
<li>
<center>
<p:inputText name="j_username" placeholder="Usuario" style="margin-top:10px;margin-left:10px;" size="15" id="user" value="#{usuarioBean.usuario.usuario}" rendered="#{empty usuarioBean.usuarioLogado}"></p:inputText>
</center>
</li>
<li>
<center>
<p:inputText id="j_password" name="j_password" placeholder="Senha" style="margin-top:10px;margin-left:10px;" size="15" type="password" value="#{usuarioBean.usuario.senha}" rendered="#{empty usuarioBean.usuarioLogado}"></p:inputText>
</center>
</li>
<li>
<center>
<p:commandButton style="margin-top:10px;margin-left:10px;" value="Entrar" rendered="#{empty usuarioBean.usuarioLogado}" ajax="false"></p:commandButton>
</center>
</li>
</ul>
</h:form>
jboss-web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<security-domain>zephyrplace-security-domain</security-domain>
</jboss-web>
standalone.xml:
<security-domains>
<security-domain name="zephyrplace-security-domain" cache-type="default">
<authentication>
<login-module code="Database" flag="required">
<module-option name="dsJndiName" value="java:jboss/datasources/zephyrplace-ds"/>
<module-option name="principalsQuery" value="select pass from users where name=?"/>
<module-option name="rolesQuery" value="select role_name from user_roles where user_name = ?"/>
<module-option name="hashAlgorithm" value="MD5"/>
<module-option name="hashEncoding" value="base16"/>
</login-module>
</authentication>
</security-domain>
</security-domains>
postgres:
CREATE TABLE "users"
(
"name" character varying(50),
pass character varying(50)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "users" OWNER TO postgres;
CREATE TABLE user_roles
(
user_name character varying(50),
role_name character varying
)
WITH (
OIDS=FALSE
);
ALTER TABLE user_roles OWNER TO postgres;
INSERT INTO users("name", pass) VALUES ('admin', MD5('1234'));
INSERT INTO user_roles(user_name, role_name) VALUES ('admin', 'ADMIN');
web.xml:
<!-- Protected Areas -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Only admins</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<web-resource-name>Users and admins</web-resource-name>
<url-pattern>/index/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
<!-- Allowed Roles -->
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
<role-name>USER</role-name>
</security-role>
<!-- Login Prompt -->
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login/login.xhtml</form-login-page>
<form-error-page>/login/login-error.xhtml</form-error-page>
</form-login-config>
</login-config>
In my application i use also wildfly and i configurated the security on the standalone-full.xml. Also on rolesQuery i gave 'Roles' for the name of the result of the query. Sorry for my english. This way is better to explain:
<module-option name="rolesQuery" value="select role_name, 'Roles' from user_roles where user_name = ?"/>
it think it needs that name. those are the differences i see.

Session expired on form submit

There is a scenario in which I am having a form which is shown from my application as a pop up dynamically for various events. I am filling up the form and submitting it which causes session expiry.
I found out that when printing the values of the request headers in the form, i see that the jsession id is missing or sometimes new jseesion id is created.
This is not happening frequently. In working cases I am not missing any jsession id or getting differnt jseesion id's.
Any suggestions?
Below is the code sample.
<HTML>
<HEAD>
</HEAD>
<%
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println("Header Name " +headerName );
System.out.println("headerValue " +headerValue );
}
%>
<body>
Comments </br>
<form name = 'savefrm' action ='save.jsp'>
<textarea name = 'comments' id = 'text' cols=38 rows=8>"+comments.trim()+"</textarea>
<input type="submit" value="ok"/>
</form>
</body>
</html>
You should set your session timeout through web.config like this:
<configuration>
<system.web>
<sessionState timeout="100000"></sessionState>
</system.web>
</configuration>
1000 ms = 1 second
On web.xml file :
<web-app>
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
20 = 20 minutes
Or you can do it inside the code :
HttpSession session = request.getSession();
session.setMaxInactiveInterval(20*60);
20 * 60 = 20 minutes

"Post" XML Data like HTML with Hidden Values using ContentType ="txt/html"

I want to do the same that works previously on HTML but now via .NET Windows Forms.
When I submit this HTML it works :
<html>
<head>
</head>
<body>
<form name="TestForm" action="http://staging.csatravelprotection.com/ws/policyrequest" method="POST">
<input type="hidden" name="xmlrequeststring" value="
<quoterequest>
<aff>COSTAMAR</aff> <!-- required -->
<producer>10527930</producer> <!-- optional -->
<productclass>85FL</productclass> <!-- required -->
<bookingreservno>0123456789AB</bookingreservno> <!-- optional -->
<numinsured>3</numinsured> <!-- required -->
<tripcost>5000.00</tripcost> <!-- required -->
<departdate>2010-11-01</departdate> <!-- required -->
<returndate>2010-11-20</returndate> <!-- required -->
<triptype>Cruise</triptype> <!-- optional -->
<destination>Europe/ Mediterranean</destination> <!-- required -->
<supplier>Carnival Cruise Lines</supplier> <!-- optional -->
<airline>American</airline> <!-- optional-->
<travelers>
<traveler>
<age>45</age> <!-- required -->
</traveler>
<traveler>
<age>43</age> <!-- required -->
</traveler>
<traveler>
<age>15</age> <!-- required -->
</traveler>
</travelers>
</quoterequest>
">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
but when I try to send the XML via POST using .NET it appear to fail cause I dont know how to post via Hidden Input on the URI.
Imports System.IO
Imports System.Text
Imports System.Net
Public Class Form2
Private Shared URL As String = "http://staging.csatravelprotection.com/ws/policyrequest"
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim oHttpWebRequest As WebRequest = WebRequest.Create(New Uri(URL))
oHttpWebRequest.Method = "POST"
oHttpWebRequest.ContentType = "text/xml"
Dim oStream As Stream = oHttpWebRequest.GetRequestStream()
Dim Reader As StreamReader = New StreamReader("C:\TEST.XML", Encoding.Default)
Dim Postdata As String = String.Format("xmlrequeststring={0}", Reader.ReadToEnd)
oStream.Write(Encoding.ASCII.GetBytes(Postdata), 0, Postdata.Length)
oStream.Close()
Dim oHttpWebResponse As HttpWebResponse = CType(oHttpWebRequest.GetResponse(), HttpWebResponse)
Dim oStreamResponse As Stream = oHttpWebResponse.GetResponseStream()
Dim oStreamRead As StreamReader = New StreamReader(oStreamResponse, Encoding.UTF8)
Dim strReturnedXML As String = oStreamRead.ReadToEnd()
MessageBox.Show(strReturnedXML)
oStreamResponse.Close()
oStreamRead.Close()
oHttpWebResponse.Close()
End Sub
End Class
XML :
<quoterequest>
<aff>COSTAMAR</aff>
<producer>10527930</producer>
<productclass>TBD</productclass>
<bookingreservno>0123456789AB</bookingreservno>
<numinsured>3</numinsured>
<tripcost>5000.00</tripcost>
<departdate>2009-11-01</departdate>
<returndate>2009-11-20</returndate>
<initdate>2008-09-30</initdate>
<finalpaymentdate>2008-10-30</finalpaymentdate>
<triptype>Cruise</triptype>
<destination>Europe/ Mediterranean</destination>
<supplier>Carnival Cruise Lines</supplier>
<airline>American</airline>
</quoterequest>
Is there a way to make it work as expected on .NET?
Thanks
It is possible, but you should not post only the xml data, but the original html file with your xml data embedded.
Het recieving page expects the data in that form. It cannot/does not see the difference between a browser or your program posting.
It could be that they have a different url form posting xml format data.
MarcelDevG
Thats impossible, but you can work with POST using ContentType ="txt/xml"