Invalid identifier results from an sql statement in php
hello there, i'm trying to access data from an oracle 11g database via oci and php 5.3.8.
i'm getting the ORA-00904 (invalid identifier) error when executing the following statement:
$stid = oci_parse($conn, 'select * from table1 where column1 = "XYZ"');
when i do this:
$searchstring = "XYZ";
$stid = oci_parse($conn, 'select * from table1 where column1 = '.$searchstring.'');
i'm getting this error:
ORA-00933: SQL command not properly ended
column1 is varchar2, the entries are either letters and numbers (never only numbers) or empty.
when i do this:
$stid = oci_parse($conn, 'select * from table1');
i'm getting the data and there are entries in column1 with XYZ.
has anyone an idea, what i do wrong?
regards j
The PHP forum for questions like this is at http://www.oracle.com/technetwork/forums/php/index.html
You really need to be using a bind variable here. Otherwise you will likely suffer from poor DB performance, and also open yourself to SQL Injection security attacks. Try:
$stid = oci_parse($conn, 'select * from table1 where column1 = :bv');
oci_bind_by_name($stid, ":bv", $searchstring);Regarding quoting of your example try:
$searchstring = "XYZ";
echo 'select * from table1 where column1 = '.$searchstring.'';Then run that SQL in SQL*Plus and watch it fail. What you need is given with:
echo 'select * from table1 where column1 = \''.$searchstring.'\'';See the bottom of p 126 of The Underground PHP and Oracle Manual
Note that with the bind variable example you didn't need quotes around :bv.
Similar Messages
-
How to export the result from executing sql statement to excel file ?
HI all,
Great with Oracle SQL Developer, but I have have a trouble as follwing :
I want to export the result from executing sql statement to excel file . I do easily like that in TOAD ,
anyone can help me to do that ? Thanks so much
SigmasvnHello Sue,
I just tried to export to excel with the esdev extension and got java.lang.NumberFormatException. I found the workaround at Re: Windows Multi-language env, - how do I set English for application lang?
open the file sqldeveloper\jdev\bin\sqldeveloper.conf and add the following two lines:
AddVMOption -Duser.language=en
AddVMOption -Duser.country=USyet now my date formats in excel are 'american-style' instead of german. For example 01-DEC-01 so excel does not recognize it as date and therefore I can not simply change the format.
When export to excel will be native to 1.1 perhaps someone can have a look at this 'feature'
Regards
Marcus -
Different result from same SQL statement
The following SQL statement brings back records using query
analyzer on the SQL server. However when I run it in a cold fusion
page it comes back with no results. Any idea why????????
SELECT COUNT(h.userID) AS hits, u.OCD
FROM dbo.tbl_hits h INNER JOIN
dbo.tlkp_users u ON h.userID = u.PIN
WHERE (h.appName LIKE 'OPwiz%') AND (h.lu_date BETWEEN
'05/01/07' AND '06/01/07')
GROUP BY u.OCD
ORDER BY u.OCDAnthony Spears wrote:
> That didn't work either.
>
> But here is something interesting. If we use the dates
05/01/2007 and
> 06/01/2007 we get results in SQL Server Query Analyzer
but not using a cold
> fusion page. But if we use the dates 05/01/2007 and
09/01/2007 both get back
> the same results.
>
Are you absolutely, 100% sure that you are connecting to the
same
database instance with both CF and Query Analyzer? That kind
of symptom
is 9 out of 10 times because the user is looking at different
data. One
is looking at production and the other development or an
backup or
recent copy or something different. -
Count the number of rows resulting from a select statement
Hi,
Is there any way of counting the number of rows resulting from a select statement. i.e I have a select distinct statement and I then want to perform an IF statement on the number of rows resulting from the select statement.
Any help appreciated
Thanks
GaryDeclare
var1 number;
Begin
select count(distinct column_name) into
var1 from table_name;
If var1 > x Then
End IF;
End;
Hope I understood the problem correctly
null -
High Database server load from expensive SQL statements
Dear all,
I am facing problem in the production sever there is high Database server load from expensive SQL statements as per EVA report
Buffer Load [%] Disk Load [%] CPU Load [%]
55 69 0
Analysis of DB SQL CACHE
EXPENSIVE SQL STATEMENTS OVERVIEW
Object Name CPU Load [%] I/O Load [%] Elapsed Time [%] Executions Records Processed
BSIS 1 9 0 22 90462
CDEF$ 6 6 0 2131113 2575694
BSAD 1 3 0 21 408576
MKPF 1 32 0 180 3899
ICOL$ 9 1 0 2575694 8703798
OBJ$ 6 1 0 3405254 3400023
COL$ 12 0 0 2138793 22919657
MKPF 1 13 0 75 396
MCHB 7 0 0 366543 41708
Please suggest the step by step to reduce the expensive SQL from these table.
RegardsHi,
In tx code ST05 i have find the following deatails.
Duration |Obj. name |Op. |Recs.|RC |Statement
4 TSP03A REOPEN 0 SELECT WHERE "NAME" = 'LOCL' AND "P" = 'S_CLIENTS' 344 TSP03A FETCH 1 0 42 ZRIN DECLARE 0 SELECT WHERE "MANDT" = :A0 AND "BCQ" = :A1 442 ZRIN PREPARE 0 SELECT WHERE "MANDT" = :A0 AND "BCQ" = :A1 3 ZRIN OPEN 0 SELECT WHERE "MANDT" = '600' AND "BCQ" = 'BCQ'
2,181,565 ZRIN FETCH 4 1403
706,267 DBA_SEGME FETCH 99 0 8,248 DBA_SEGME FETCH 99 0 44,994 DBA_SEGME FETCH 99 0 67,713 DBA_SEGME FETCH 99 0
1,367,923 DBA_SEGME FETCH 99 0
16,735|TADIR |FETCH | 1| 1403| |
5
TADIR
REOPEN
0
SELECT WHERE "PGMID" = 'R3TR' AND "OBJECT" = 'TABL' AND "OBJ_NAME" = 'CME__TEXT'
22,415
TADIR
FETCH
1
1403
4
TADIR
REOPEN
0
SELECT WHERE "PGMID" = 'R3TR' AND "OBJECT" = 'TABL' AND "OBJ_NAME" = 'CME_PATTERN_SIGN'
232
TADIR
FETCH
1
1403
4
TADIR
REOPEN
0
SELECT WHERE "PGMID" = 'R3TR' AND "OBJECT" = 'TABL' AND "OBJ_NAME" = 'CML_ARC_DEADLINE'
19,189
TADIR
FETCH
1
1403
4
TADIR
REOPEN
706,267
DBA_SEGME
FETCH
99
0
|
44,994
DBA_SEGME
FETCH
99
0
67,713
DBA_SEGME
FETCH
99
0
Please suggest how to reduce it.
Regards, -
How to processing the results from the select statement in SQL query?
Hi
This might be too simple, but my knowledge of the SQL is very limited...
I have table where I do have details from calls (Lync QoE).
I can take all calls from the table, but I would like to count the concurrent calls on the table. This is how I got it work on the Excel to work (but I would like to do that on the SQL statement to get it more dynamic use):
Table have these line and this is what I get out from the Select):
[callid],[start],[end]
1ABC,1.1.2014 01:00:15, 1.1.2014 01:01:00
5DEF,1.1.2014 01:00:45, 1.1.2014 01:05:00
FDE2,1.1.2014 01:03:15, 1.1.2014 01:04:00
KDJ8,1.1.2014 01:04:15, 1.1.2014 01:06:00
FDJ8,2.1.2014 01:04:15, 2.1.2014 01:06:00
KDSE,3.1.2014 01:04:15, 3.1.2014 01:06:00
The information I would like to get, is what is the maximum amount of the concurrent calls per day.
On the excel I basically count line by line how many concurrent calls each line have had, and then pickup the highest one. On above example the calls 5DEF, FDE2 and FDE2 have been active at the same time which gives 3 for the first day.
The table is ordered by the start. So let say the code is on the third line (FDE2). I need to count calls from before which end time is after the start time (of FDE2), but also I need to count calls after (FDE2) which are started before the current
call has ended.
PetriUnfortunately your post is off topic as it's not specific to SQL Server Samples and Community Projects.
This is a standard response I’ve written in advance to help the many people who post their question in this forum in error, but please don’t ignore it. The links I provide below will help you determine the right forum to ask your question in.
For technical issues with Microsoft products that you would run into as an end user, please visit the Microsoft Answers forum ( http://answers.microsoft.com ) which has sections for Windows, Hotmail,
Office, IE, and other products.
For Technical issues with Microsoft products that you might have as an IT professional (like technical installation issues, or other IT issues), please head to the TechNet Discussion forums at http://social.technet.microsoft.com/forums/en-us, and
search for your product name.
For issues with products you might have as a Developer (like how to talk to APIs, what version of software do what, or other developer issues), please head to the MSDN discussion forums at http://social.msdn.microsoft.com/forums/en-us, and
search for your product or issue.
If you’re asking a question particularly about one of the Microsoft Dynamics products, a great place to start is here: http://community.dynamics.com/
If you think your issue is related to SQL Server Samples and Community Projects and I've flagged it as Off-topic, I apologise. Please repost your question and include as much detail as possible about your problem so that someone can assist you further.
If you really have no idea where to post your question please visit the Where is the forum for…? forum http://social.msdn.microsoft.com/forums/en-us/whatforum/
When you see answers and helpful posts, please click Vote As Helpful,
Propose As Answer, and/or Mark As Answer
Jeff Wharton
MSysDev (C.Sturt), MDbDsgnMgt (C.Sturt), MCT, MCPD, MCSD, MCSA, MCITP, MCDBA
Blog: Mr. Wharty's Ramblings
Twitter: @Mr_Wharty
MC ID:
Microsoft Transcript -
Refering alias of a function result in an sql statement
Dear Sir,
How to refer an alias of a function result in sql statement?
eg.(new_name is the alias)
select myfunction(name) new_name
from mytable
where new_name = '#vincent#';
I can't refer new_name in the above statement coz it gives an error "invalid column name".
But I don't want to put the myfunction(name) again in the where clause which will double the job. So, how should I refer to it?
Please advise.
Thanks.
nullYou can not refer to the alias like you are talking. You will have to use myfunction(name) as you have said. Or you can try creating a view with query:
select myfunction(name) new_name
from mytable
and then refer to "new_name".
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by guest2000:
Dear Sir,
How to refer an alias of a function result in sql statement?
eg.(new_name is the alias)
select myfunction(name) new_name
from mytable
where new_name = '#vincent#';
I can't refer new_name in the above statement coz it gives an error "invalid column name".
But I don't want to put the myfunction(name) again in the where clause which will double the job. So, how should I refer to it?
Please advise.
Thanks.<HR></BLOCKQUOTE>
null -
Two statements, get results from the first statement?
Ok maybe I made it sound a little harder than it is, but this is what I am trying to do. I have a result set from from a database call when I pass in the username and password . In the 1st call I get the Users info: User_ID, first_name, lastname, etc...
But I either need to get info from the first statement, and pass it to the 2nd statement or just do two statement calls calling the same info and passing it to my user object? I dont know which if any is faster, or better. The only thing I need from the first statement is the user_id. In the 2nd statement I need the user_id to find out the user permissions.
Here is the original code when It was getting the user info and permissions from the same table. try
dba = new DbAccess();
java.sql.Connection con = dba.getConnection();
java.sql.DriverManager.getConnection("jdbc:oracle:thin:@kares:1523:appd","user","pass");
ps = con.prepareStatement("SELECT USER_ID, LAST_NAME, FIRST_NAME, LOGIN, PASSWORD," +
"X, Y, Z FROM RD_USERS WHERE LOGIN=? and PASSWORD=?");
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
// set the user attributes
if ( rs.next() )
loginValid = true;
setUserId(rs.getInt("USER_ID"));
setLastName(rs.getString("LAST_NAME"));
setFirstName(rs.getString("FIRST_NAME"));
setLoginName(rs.getString("LOGIN"));
setPassword(rs.getString("PASSWORD"));
X = rs.getBoolean("X");
setX(X);
Y = rs.getBoolean("Y");
setY(Y);
Z = rs.getBoolean("Z");
setZ(Z);
else
setLastName(null);
setFirstName(null);
setLoginName(null);
setPassword(null);
setX(false);
setY(false);
setZ(false);
rs.close(); rs = null;
ps.close(); ps = null;
//dba.close(); dba = null;
} The code above gets the info from one table, I now need to get the X, Y, and Z from a different table, but I need the USER_ID first. So, the first table is set up with the user_id and user info, and the 2nd table is set up with the user_id and user permissionsThanks DrClap I started on the the query and I did it a little differently, but it should hopefull do the same thing. my tables are constructed as so:
USER
USER_ID
FIRST_NAME
LAST_NAME
USER_NAME
PASSWORD
ETC....
USER_PERMISSIONS
USER_ID
PERMISSION X
PERMISSION Y
PERMISSION Z
ETC....
My Select looks something like this
ps = con.prepareStatement("SELECT a.USER_ID, a.LAST_NAME, a.FIRST_NAME, a.USER_NAME, a.USER_PASSWORD," +
"b.X, b.Y, b.Z FROM RD_USERS a, RD_PERMISSIONS b WHERE USER_NAME=? and USER_PASSWORD=?");
This is where I come to a crossroads, Can I add on another AND to say "WHERE a.USER_ID = b.USER_ID
and do I use the =, or is it ==, or .equals(). Thanks in advance.
orozcom -
This SQL statement will give me the results listed in the first table
SELECT Count([Accepts 2].Queue) AS CountOfQueue, Date.Date
FROM [Accepts 2] INNER JOIN [Date] ON FORMAT(Date.Date,"hh")=format([Accepts 2].TimeOfAccept,"hh")
WHERE ((([Accepts 2].TimeOfAccept) Between (#1/1/2002#) And ((#12/30/2002#))))
GROUP BY Date.Date;
I set up a table where I put in the 24 hours
And this query will give you the number of cases per hour per the time specified like this
CountOfQueue Date
1 12:00:00
10 15:00:00
2 16:00:00
1 17:00:00
2 18:00:00
But I want it to give me something like this
Count Of Queue Date
1 12:00:00
0 13:00:00
0 14:00:00
10 15:00:00
2 16:00:00
and so on and so forth all the way up to 23 hundred hours
Do you know the way to modify the query to do this
or how to parse the query resultset to populate the array. For hours that are not returned simply pop a zero into the relevant array position.
THanking you in advance
STEVEHere's something that I hope will get you started:Map map = new HashMap (); // you could use a tree map if you want to sort the results
for (int i = 0; i < 24; i ++) {
map.put (i + ":00:00", new Integer (0));
ResultSet rs = ...; // your result set
while (rs.next ()) {
map.put (rs.getString ("date"), new Integer (rs.getInt ("count")));
} -
Spooling Extracts from Multiple SQL statements in 1 File
Hi all,
I am trying to spool extract results of 3 separate SQL statements into one single file. I wrote a SQL block similar to the one below. However, the result of the statements overwrite each other: 3 overwrote 2 and overwrote 1. Any suggestion how to combined there extracted results in one file?
spool c:\test.txt
<SQL statement 1>
<SQL statement 2>
<SQL statement 3>
/spool OFF
Thanks in advance
JasonPlease paste you SQL file here. These is no way one should overwrite another.
Eric -
Identifying most recently failed SQL statement
Hi,
We are using Forms 6i
Is there anyway to identify what the most recently failed SQL statement was?
We occasionally have Unhandled Exceptions for which we would like to identify the cause of.
To help do this quickly is there anyway to get Forms to report the SQL statement that failed.
I am sure I saw a demo many years ago where someone simply used Forms to report on the failure rather than writing custom exception code to identify the problem(May have had something to do with the Help button)
Thanks in advance.
NavThank you for your prompt reply.
I am encountering a "FRM-40735 Unhandled Exception"
When I press Shft+Ctrl+E(Display Error) I simply get a FRM-42100( No errors encountered recently)
This seems to contradict the FRM-40735 error.
Currently my fmrweb.res does not map anything to the Shift+F1 key.
What kind of function do I need to map it to? -
Output fields dynamically from an SQL statement
I'm trying to build an SQL statement that uses the values from one table to form the field names to output in the select statement. I have two tables, pjl_test contains the field names and bp_objects contains the data I want the sql to return... the tables look like this:
pjl_test table:
field_name
OBJECT_TYPE
SHORT_DESCRIPTION
OBJECT_ID
bp_objects table:
object_id, object_type, short_description
275 TS Establish Contract
276 TS Enter contract details
277 TS Review & amend Contract details as required
278 TS Enter/update contractor details
The select statement I'm toying with looks like this:
SELECT (
SELECT field_name
from (SELECT ROWNUM as MyNo, field_name from pjl_test)
where myno = 1) as Name FROM BP_OBJECTS
The problem is that the sql is using the returned field name as a display value instead of a column name and thus outputs the following:
OBJECT_TYPE
OBJECT_TYPE
OBJECT_TYPE
OBJECT_TYPE
I'm sure there must be a way to do this in an single sql statement, is anyone able to advise.
Thanks in advanceI'm sure there must be a way to do this in an single sql statement, is anyone able to advise.No, there is no simple way to get the column name then select those ones in one statement.
Dynamic sql will do that. But not a single statement.
Or maybe some XML package. Then you have to tell about your db vwersion.
Nicolas. -
From 10g, "SQL Statement Length" description disappeared....
http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10755/limits003.htm#sthref3594
From 10g, on the above 'Logical Database Limits' section of 'Reference' document, the description for 'SQL Statement Length' limitation (64K) has been dropped.
Is this mean there is NO limitation on 10g or just mistake?Hi Tadaaki,
Apologies for the delay in responding to you.
Unfortunately I cannot answer this question. Although my group maintains the Documentation pages on OTN, we are not part of OTN, nor do we have input with regard to the content of documentation. We merely provide links to the documentation at: http://www.oracle.com/technology/documentation/index.html
Please try the Members Feedback Forum at: Community Feedback (No Product Questions)
Thanks and regards,
Les -
SQL check result of the sql statement
hello gurus, i have this sql statement:
select MyTableColumn_PDF_File
from Database.dbo.MyTableName
where coalesce( MyTableColumn_PDF_File,' ') is null;
so basically, it works fine on sql management studio.
But what if I used this command on vb.net, how do I check whether the column is null or not?
Any help is greatly appreciated.
Thanks. :)
Every second counts..make use of it. Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.
IT Stuff Quick BytesDim con As New SqlClient.SqlConnection("connectionstring")
Dim DR As SqlClient.SqlDataReader = Nothing
Try
con.Open()
Dim cmd As New SqlClient.SqlCommand("select COUNT(*) AS TotalNull " & _
"from Database.dbo.MyTableName " & _
"where MyTableColumn_PDF_File is null", mSQLConnection)
DR = cmd.ExecuteReader()
If DR.Read Then
'' found rows
If CInt(DR.Item("TotalNull")) <> 0 Then
'' We have more than 1 row that is not null
End If
Else
'' not found nows
End If
Catch ex As Exception
''' oops
Finally
If Not IsNothing(DR) Then
If Not DR.IsClosed Then DR.Close()
DR = Nothing
End If
If Not IsNothing(con) Then
If con.State = ConnectionState.Open Then con.Close()
con = Nothing
End If
End Try
This is a more complete example -
Get result from PL/SQL function through XDBUri (10g)
Hi!
I have to call a PL/SQL function that takes two parameters and return one parameter. (I will do this from Oracle Service Bus).
It is possible to get relational data as xml through an XDBUri type over http by using the XML DB functionality. But is it possible to get the result of a PL/SQL function as XML as well?
I have tried to wrap the PL/SQL procedure inside a view, but cant get the variable to be bound into the sql.
I have tried with stuff like this:
create or replace view test (a, b)
as
select function(a, b) from dual
But since I dont have a table returning the values i cant get it work.
If I can make this view, I can call it through the XDMUri type.
Sombody that can help me to manage this?
/Helge
Edited by: user3169245 on 03.apr.2009 12:06Here's a code snippet that may help
package com.oracle.st.xmldb.pm.xfiles;
import com.oracle.st.xmldb.pm.multipart.InputStreamProcessor;
import com.oracle.st.xmldb.pm.multipart.MultipartInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
import oracle.jdbc.OracleCallableStatement;
import com.oracle.st.xmldb.pm.multipart.MultipartProcessor;
import com.oracle.st.xmldb.pm.multipart.MultipartProcessorImpl;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import oracle.jdbc.OraclePreparedStatement;
import oracle.jdbc.OracleResultSet;
import oracle.jdbc.OracleTypes;
import oracle.sql.BLOB;
import oracle.sql.CLOB;
import oracle.xdb.XMLType;
import oracle.xml.parser.v2.XMLDocument;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class XFilesServlet extends HttpServlet implements InputStreamProcessor {
public static String TARGET_PATH = "target";
public static String STYLESHEET_PATH = "stylesheet";
private static String CREATE_RESOURCE_SQL =
"begin " +
" XFILES_SOAP_SERVICES.UPLOADRESOURCE" +
" ( " +
" P_RESOURCE_PATH => :1, " +
" P_CONTENT => :2, " +
" P_CONTENT_TYPE => :3," +
" P_DESCRIPTION => :4," +
" P_LANGUAGE => :5," +
" P_CHARACTER_SET => :6," +
" P_DUPLICATE_POLICY => :7" +
" );" +
"end;";
private static String GET_FOLDER_HTML_PAGE_SQL =
"select xdburitype('/XFILES/lite/Folder.html').getClob() from dual";
private static String WRITE_LOG_RECORD_SQL =
"begin xfiles_logging.enqueue_log_record(:1); end;";
private OracleConnection dbConnection;
private OracleCallableStatement createResource;
private OracleCallableStatement writeLogRecord;
private DatabaseMetaData dbMetadata;
private static final int FILE_UPLOAD = 1;
private static final int PUBLISH_RSS = 2;
private static final int DB_REST_SERVICE = 3;
private static final int FORCE_AUTHENTICATION = 4;
private static final int SET_PASSWORD = 5;
private static final int DISPLAY_XML = 6;
private static final int ENABLE_RSS = 7;
public static final int XDB_ACCESS_DENIED = 31050;
private static String SERVLET_ROOT = "/sys/servlets/XFILES";
private static final String FILE_UPLOAD_PATH = "fileUpload";
private static final String PUBLISH_RSS_PATH = "publishRSS";
private static final String SET_PASSWORD_PATH = "setPassword";
private static final String DB_REST_SERVICE_PATH = "dbRestService";
private static final String FORCE_AUTHENTICATION_PATH = "doAuthentication";
private static final String DISPLAY_XML_PATH = "displayXML";
private static final String ENABLE_RSS_PATH = "enableRSS";
public static String POST_UPLOAD_URL = "postUploadRedirect";
public static String DULPLICATE_POLICY = "duplicatePolicy";
public static String SOURCE_FILE_PATH = "sourceFilePath";
public static String RESOURCE_FILENAME = "targetFileName";
public static String RESOURCE_DESCRIPTION = "description";
public static String UPLOAD_LANGUAGE = "UploadLanguage";
public static String UPLOAD_CHARACTERSET = "UploadCharset";
public static String PASSWORD = "password";
public static String XML_DOCUMENT = "content";
public static String XML_CHUNK = "chunk";
public static String RESOURCE_ID = "resid";
public static String DATABASE_SCHEMA = "DatabaseSchema";
public static String PACKAGE = "Package";
public static String METHOD = "Method";
public static String SQL_CALL = "SqlOperation";
protected XMLDocument logRecord;
protected Element parameterList;
protected Element timings;
protected int currentOperation;
public String xmlContent;
public static String XML_TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS000";
public static String LOG_TIMESTAMP_FORMAT = "HH:mm:ss.SSS000";
protected SimpleDateFormat xmlDateFormatter = new SimpleDateFormat(XML_TIMESTAMP_FORMAT);
private String postUploadURL;
private String targetFolder;
private String onDuplicateAction;
private String sourceFile;
private BLOB resourceContent;
private String contentType;
private String resourceName;
private String resourceComment;
private String uploadLanguage;
private String uploadCharacterSet;
public XFilesServlet() {
private void logParameter(Document doc)
this.parameterList.appendChild(logRecord.importNode(doc.getDocumentElement().cloneNode(true),true));
private void logParameter(String parameterName, String[] values)
Element e = this.logRecord.createElement(parameterName);
this.parameterList.appendChild(e);
if (values != null)
Attr a = this.logRecord.createAttribute("Length");
e.setAttributeNode(a);
a.setValue(Integer.toString(values.length));
for (int i = 0; i < values.length; i++)
Element v = this.logRecord.createElement("parameterValue");
e.appendChild(v);
Text t = this.logRecord.createTextNode(values);
v.appendChild(t);
a = this.logRecord.createAttribute("Index");
v.setAttributeNode(a);
a.setValue(Integer.toString(i));
public void logParameter(String parameterName,String value)
Element e = this.logRecord.createElement(parameterName);
this.parameterList.appendChild(e);
if (value != null)
Text t = this.logRecord.createTextNode(value);
e.appendChild(t);
private void logParameterCDATA(String parameterName,String value)
Element e = this.logRecord.createElement(parameterName);
this.parameterList.appendChild(e);
if (value != null)
CDATASection c = this.logRecord.createCDATASection(value);
e.appendChild(c);
private void logException(Exception e) {
Element stackTrace = this.logRecord.createElement("StackTrace");
this.logRecord.getDocumentElement().appendChild(stackTrace);
this.appendException(stackTrace,e);
private void appendException(Element stackTrace, Throwable error)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
error.printStackTrace(pw);
pw.flush();
pw.close();
Text t = this.logRecord.createCDATASection(sw.toString());
stackTrace.appendChild(t);
if (error.getCause() != null)
Element causedBy = this.logRecord.createElement("CausedBy");
stackTrace.appendChild(causedBy);
appendException(causedBy,error.getCause());
else {
if (error instanceof ServletException) {
ServletException se = (ServletException) error;
if (se.getRootCause() != null) {
Element causedBy = this.logRecord.createElement("CausedBy");
stackTrace.appendChild(causedBy);
appendException(causedBy,se.getRootCause());
private void logTimestamp(String eventName)
Timestamp ts = new Timestamp(System.currentTimeMillis());
Element element = logRecord.createElement(eventName);
this.timings.appendChild(element);
Text text = logRecord.createTextNode(this.xmlDateFormatter.format(ts));
element.appendChild(text);
protected void initiateLogging(HttpServletRequest request)
throws IOException
this.logRecord = new XMLDocument();
Element root = this.logRecord.createElement("XFilesLogRecord");
this.logRecord.appendChild(root);
Element e = this.logRecord.createElement("HttpRequest");
root.appendChild(e);
Element e1 = this.logRecord.createElement("ServletName");
Text t = this.logRecord.createTextNode(this.getClass().getName());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("HttpMethod");
t = this.logRecord.createTextNode(request.getMethod());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("RequestURI");
t = this.logRecord.createTextNode(request.getRequestURI());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("PathTranslated");
t = this.logRecord.createTextNode(request.getPathTranslated());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("RequestURL");
t = this.logRecord.createTextNode(new String(request.getRequestURL()));
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("Protocol");
t = this.logRecord.createTextNode(request.getProtocol());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("ServerName");
t = this.logRecord.createTextNode(request.getServerName());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("ContentType");
t = this.logRecord.createTextNode(request.getContentType());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("LocalAddr");
t = this.logRecord.createTextNode(request.getLocalAddr());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("LocalName");
t = this.logRecord.createTextNode(request.getLocalName());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("LocalPort");
t = this.logRecord.createTextNode(Integer.toString(request.getLocalPort()));
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("Port");
t = this.logRecord.createTextNode(Integer.toString(request.getServerPort()));
e1.appendChild(t);
e.appendChild(e1);
this.timings = this.logRecord.createElement("Timestamps");
root.appendChild(this.timings);
logTimestamp("Init");
e = this.logRecord.createElement("Remote");
root.appendChild(e);
e1 = this.logRecord.createElement("RemoteHost");
t = this.logRecord.createTextNode(request.getRemoteHost());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("RemoteAddress");
t = this.logRecord.createTextNode(request.getRemoteAddr());
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("RemotePort");
t = this.logRecord.createTextNode(Integer.toString(request.getRemotePort()));
e1.appendChild(t);
e.appendChild(e1);
e1 = this.logRecord.createElement("RemoteUser");
t = this.logRecord.createTextNode(request.getRemoteUser());
e1.appendChild(t);
e.appendChild(e1);
e = this.logRecord.createElement("RequestHeaders");
root.appendChild(e);
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements())
String headerName = (String) headerNames.nextElement();
e1 = this.logRecord.createElement(headerName);
t = this.logRecord.createTextNode(request.getHeader(headerName));
e1.appendChild(t);
e.appendChild(e1);
this.parameterList = this.logRecord.createElement("ServletParameters");
root.appendChild(parameterList);
public void writeLogRecord(XMLDocument logRecord) throws SQLException , IOException {
XMLType xml = new XMLType(this.dbConnection, logRecord);
this.writeLogRecord.setObject(1, xml);
this.writeLogRecord.execute();
this.dbConnection.commit();
protected String readParameter(HttpServletRequest request,String parameterName,String defaultValue)
String value = request.getParameter(parameterName);
if (value != null)
if (value.length() == 0) {
value = null;
if (value == null) {
value = defaultValue;
logParameter(parameterName,value);
return value;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException
try {
try {
initiateLogging(request);
initializeDatabaseConnection();
String requestURI = request.getRequestURI();
this.currentOperation = getOperation(requestURI);
switch (this.currentOperation) {
case DB_REST_SERVICE:
restResponse(request,response);
break;
default:
response.sendError(HttpServletResponse.SC_NOT_FOUND);
logTimestamp("Complete");
writeLogRecord(this.logRecord);
this.dbConnection.commit();
catch (Exception e) {
try {
this.dbConnection.rollback();
logTimestamp("Exception");
logException(e);
writeLogRecord(this.logRecord);
catch (Exception wle) {
System.out.println("XFilesServlet : Fatal error while logging Error : ");
e.printStackTrace(System.out);
System.out.flush();
wle.printStackTrace(System.out);
System.out.flush();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
finally {
try {
this.createResource.close();
this.writeLogRecord.close();
catch (SQLException e) {
System.out.println("XFilesServlet : Fatal error while closing statements : ");
e.printStackTrace(System.out);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (IOException ioe) {
System.out.println("XFilesServlet : Fatal error while Sending Error Status : ");
ioe.printStackTrace(System.out);
System.out.flush();
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
doGet(req, res);
private void initializeDatabaseConnection() throws SQLException {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
OracleDriver ora = new OracleDriver();
this.dbConnection = (OracleConnection) ora.defaultConnection();
this.createResource = (OracleCallableStatement) this.dbConnection.prepareCall(this.CREATE_RESOURCE_SQL);
this.writeLogRecord = (OracleCallableStatement) this.dbConnection.prepareCall(this.WRITE_LOG_RECORD_SQL);
this.dbMetadata = this.dbConnection.getMetaData();
private int getOperation(String requestURI) {
String servletTarget = requestURI.substring(this.SERVLET_ROOT.length()+1);
if (servletTarget.indexOf('/') > -1) {
servletTarget = servletTarget.substring(0,servletTarget.indexOf("/"));
if (servletTarget.equals(this.FILE_UPLOAD_PATH)) return FILE_UPLOAD;
if (servletTarget.equals(this.FORCE_AUTHENTICATION_PATH)) return this.FORCE_AUTHENTICATION;
if (servletTarget.equals(this.PUBLISH_RSS_PATH)) return this.PUBLISH_RSS;
if (servletTarget.equals(this.DB_REST_SERVICE_PATH)) return this.DB_REST_SERVICE;
if (servletTarget.equals(this.SET_PASSWORD_PATH)) return this.SET_PASSWORD;
if (servletTarget.equals(this.DISPLAY_XML_PATH)) return this.DISPLAY_XML;
if (servletTarget.equals(this.ENABLE_RSS_PATH)) return this.ENABLE_RSS;
return 0;
public void processParameter(String name, String value)
throws SQLException {
logParameter(name,value);
if (name.equals(this.TARGET_PATH)) {
this.targetFolder = value;
if (name.equals(this.POST_UPLOAD_URL)) {
this.postUploadURL = value;
if (name.equals(this.UPLOAD_LANGUAGE)) {
this.uploadLanguage = value;
if (name.equals(this.UPLOAD_CHARACTERSET)) {
this.uploadCharacterSet = value;
if (name.equals(this.DULPLICATE_POLICY)) {
this.onDuplicateAction = value;
if (name.equals(this.SOURCE_FILE_PATH)) {
this.sourceFile = value;
if (name.equals(MultipartProcessor.MULTIPART_CONTENT_TYPE)) {
this.contentType = value;
if (name.equals(this.RESOURCE_FILENAME)) {
this.resourceName = value;
if (name.equals(this.RESOURCE_DESCRIPTION)) {
this.resourceComment = value;
createNewResource();
private void restResponse(HttpServletRequest request, HttpServletResponse response)
throws IOException, SQLException, ServletException {
String requestURI = request.getRequestURI();
String restTarget = requestURI.substring(this.SERVLET_ROOT.length() + this.DB_REST_SERVICE_PATH.length()+1);
if (restTarget.contains("//")) {
// Cannot have // in URL
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
if (restTarget.length() < 4) {
// URL is too short to be valid - Minumum is /A/B
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
if (!restTarget.startsWith("/")) {
// Invalid URL
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
if (!restTarget.substring(1).contains("/")) {
// URL must contain /Schema/Method, may Contain /Schema/Package/Method
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
String schemaName = restTarget.substring(1,restTarget.substring(1).indexOf("/")+1);
restTarget = restTarget.substring(schemaName.length()+1);
logParameter(this.DATABASE_SCHEMA,schemaName);
String packageName = null;
if (restTarget.substring(1).contains("/")) {
// URL contains /Schema/Package/Method
packageName = restTarget.substring(1,restTarget.substring(1).indexOf("/")+1);
restTarget = restTarget.substring(packageName.length()+1);
logParameter(this.PACKAGE,packageName);
if (restTarget.substring(1).contains("/")) {
// URL must be /Schema/Method or /Schema/Package/Method, anything else is junk
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
String methodName = restTarget.substring(1);
logParameter(this.METHOD,methodName);
int responseCode = verifyTarget(request,schemaName,packageName,methodName);
if (responseCode != HttpServletResponse.SC_OK) {
System.out.println("Status Code = " + responseCode);
response.sendError(responseCode);
return;
String target = "\"" + schemaName + "\".";
if (packageName != null) {
target = target + "\"" + packageName + "\".";
target = target + "\"" + methodName + "\"";
int index;
Enumeration parmNames;
String sqlStatementText =
"begin" + "\n" +
" :1 := " + target + "(" + "\n";
index = 1;
parmNames = request.getParameterNames();
while (parmNames.hasMoreElements()) {
index++;
sqlStatementText = sqlStatementText + "\"" + parmNames.nextElement() + "\" => :" + index + " ";
if (parmNames.hasMoreElements()) {
sqlStatementText = sqlStatementText + ",\n";
sqlStatementText = sqlStatementText + ");\nend;";
logParameterCDATA(this.SQL_CALL,sqlStatementText);
OracleCallableStatement statement = (OracleCallableStatement) this.dbConnection.prepareCall(sqlStatementText);
index = 1;
parmNames = request.getParameterNames();
while (parmNames.hasMoreElements()) {
index++;
String parameterName = (String) parmNames.nextElement();
String parameterValue = (String) request.getParameter(parameterName);
logParameter(parameterName,parameterValue);
statement.setString(index,parameterValue);
XMLType xml = null;
try {
statement.registerOutParameter(1,OracleTypes.OPAQUE,"SYS.XMLTYPE");
statement.execute();
xml = (XMLType) statement.getObject(1);
statement.close();
catch (SQLException sqle) {
statement.close();
if (xml != null) xml.close();
if (sqle.getErrorCode() == this.XDB_ACCESS_DENIED) {
logTimestamp("RequestAuthorization");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
ServletException se = new ServletException("Unexpected SQL Error",sqle);
throw se;
response.setContentLength(0);
response.setContentType("text/xml");
xml.writeToOutputStream(response.getOutputStream());
xml.close();
response.getOutputStream().flush();
response.getOutputStream().write( new byte[] {'\r','\n'} );
// response.getOutputStream().flush();
response.getOutputStream().close();
response.setStatus(HttpServletResponse.SC_OK);
private int verifyTarget(HttpServletRequest request, String schemaName, String packageName, String methodName)
throws SQLException {
int response = HttpServletResponse.SC_NOT_FOUND;
boolean parameterValid = false;
ResultSet procedure = null;
procedure = this.dbMetadata.getProcedures(packageName,schemaName,methodName);
while (procedure.next()) {
response = HttpServletResponse.SC_OK;
response = verifyMandatoryParameters(request,schemaName,packageName,methodName);
if (response == HttpServletResponse.SC_OK) {
response = verifyOptionalParameters(request,schemaName,packageName,methodName);
return response;
private int verifyMandatoryParameters(HttpServletRequest request, String schemaName, String packageName, String methodName) throws SQLException {
// Check Mandatory Parameters are present.
ResultSet columns = null;
columns = this.dbMetadata.getProcedureColumns(packageName,schemaName,methodName,"%");
while (columns.next()) {
short nullable = columns.getShort(12);
String columnName = columns.getString(4);
if (nullable == DatabaseMetaData.procedureNoNulls) {
if (request.getParameter(columnName) == null) {
columns.close();
return HttpServletResponse.SC_BAD_REQUEST;
return HttpServletResponse.SC_OK;
private int verifyOptionalParameters(HttpServletRequest request, String schemaName, String packageName, String methodName) throws SQLException {
// Check Optional Parameters are valid
Enumeration parms = request.getParameterNames();
ResultSet column = null;
while (parms.hasMoreElements()) {
String columnName = (String) parms.nextElement();
column = this.dbMetadata.getProcedureColumns(packageName,schemaName,methodName,columnName);
if (!column.next()) {
column.close();
return HttpServletResponse.SC_BAD_REQUEST;
column.close();
return HttpServletResponse.SC_OK;
Maybe you are looking for
-
How to let two programs access the same BDB data
I want to use two programs to access data in one BDB database, but get this error multiple databases specified but not supported by file db open failed:Invalid argument I do not know how to deal with it..... anyone can help? thank you first
-
Where can I get a Thunderbolt SPLITTER? (Thunderbolt to Thunderbolt & Thunderbolt.) I cannot daisy chain because of no Thunderbolt OUTPUT on the chassis.
-
Indesign keeps crashing on instalation of trial creative cloud
I have downloaded the trial vertion of creative cloud fine but when i try to try indesign cs6 the download compleats but when it is installed about 50 % it keeps crashing and freezing my comp... Am i doing somthing wrong.?
-
Exchange 2013 SP1 OWA the page can't be displayed issue
OWA the page can't be displayed Hi, i've Exchange topology (upgraded from 2007 one server) 2 CAS servers NLB with VIP 172.16.0.98 2 MBX Servers DAG with DAG using Cisco ASA NAT public IP for example 9.9.9.9 ....> 172.16.0.98 i've created split DNS z
-
For some reason I can not upload Quicktime, in which I can not upload Itunes. Every time I try to download Itunes, it always says Quicktime is not installed. I went back and tried to download Quicktime separately from Itunes. This did not prove to he