My web service based application occur lexical error. How to fix this? Please help me.
#WebMethod(operationName = "operation")
public String operation(#WebParam(name = "username") String username, #WebParam(name = "password") String password){
String message = "";
Connection myConObj = null;
Statement myStatObj = null;
PreparedStatement ps;
ResultSet myresObj = null;
String query = "SELECT `USERNAME`, `PASSWORD` FROM HIRUNA.BANKLOGIN WHERE `USERNAME`=? AND `PASSWORD`=?";
try{
myConObj = mybank.getConnection();
ps = myConObj.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
ResultSet result = ps.executeQuery();
result.next();
message = "Success!";
result.close();
myConObj.close();
return message;
}catch(SQLException ex){
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
return message;
}
}
Here is the error..
Severe: java.sql.SQLSyntaxErrorException: Lexical error at line 1,
column 8. Encountered: "`" (96), after : "".
Remove the back ticks:
String query = "SELECT USERNAME, PASSWORD FROM HIRUNA.BANKLOGIN WHERE USERNAME=? AND PASSWORD=?";
Related
I am trying to send an XML soap request to a dynamics nav web service. This is the XML from the WSDL. I have created a web access key and its the one in the key parameter of the XML.
<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
<s11:Body>
<ns1:Create xmlns:ns1='urn:microsoft-dynamics-schemas/page/customerws'>
<ns1:CustomerWS>
<ns1:Key>+gn8Nu4i7iW7D/g9vCaI8HZE5IEi1NBkTBqDp5QfXe4=</ns1:Key>
<ns1:Shipping_Advice></ns1:Shipping_Advice>
<ns1:Shipment_Method_Code></ns1:Shipment_Method_Code>
<ns1:Shipping_Agent_Code></ns1:Shipping_Agent_Code>
<ns1:Shipping_Agent_Service_Code></ns1:Shipping_Agent_Service_Code>
<ns1:Shipping_Time></ns1:Shipping_Time>
<ns1:Base_Calendar_Code></ns1:Base_Calendar_Code>
<ns1:Customized_Calendar></ns1:Customized_Calendar>
<ns1:Currency_Code></ns1:Currency_Code>
<ns1:Language_Code></ns1:Language_Code>
<ns1:VAT_Registration_No></ns1:VAT_Registration_No>
</ns1:CustomerWS>
</ns1:Create>
</s11:Body>
</s11:Envelope>
And this is the code that am using to send this request:
Console.WriteLine("We have started");
string pageName = "http://hrp-dmu.uganda.hrpsolutions.co.ug:9047/DynamicsNAV80/WS/Uganda%20Management%20Institute/Page/CustomerWS";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pageName);
req.Method = "POST";
req.ContentType = "text/xml;charset=UTF-8";
req.ProtocolVersion = new Version(1, 1);
req.Headers.Add("SOAPAction", #"urn:microsoftdynamicsschemas/page/customerws:Create");
Console.WriteLine("After preparing request object");
string xmlRequest = GetTextFromXMLFile("E:\\tst3.xml");
Console.WriteLine("xml request : "+xmlRequest);
byte[] reqBytes = new UTF8Encoding().GetBytes(xmlRequest);
req.ContentLength = reqBytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(reqBytes, 0, reqBytes.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("GetRequestStreamException : " + ex.Message);
}
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
Console.WriteLine("GetResponseException : " + exc.Message);
}
string xmlResponse = null;
if (resp == null)
{
Console.WriteLine("Null response");
}
else
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
xmlResponse = sr.ReadToEnd();
}
Console.WriteLine("The response");
Console.WriteLine(xmlResponse);
}
Console.ReadKey();
when using NavUserPassword Authentication you'll need a certificate.
See here on MSDN
Cheers!
I have an Email Web Service - working ok - and now I need to add attachment.
1.How do I write the #FormParam in my post method to receive byte[] ?
2.How do I write my bean the addParam to add the file?
My bean is like this:
public String sendEmail() throws IOException{
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
String ip = req.getRemoteAddr();
String conteudo = "é ô ç $ & / { [";
List<byte[]> att = new ArrayList<byte[]>();
String request = "myURI";
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(request);
method.getParams().setContentCharset("utf-8");
method.addParameter("conteudo", conteudo);
method.addParameter("ip", ip);
return "sendEmail ok";
}
My POST Method is like this:
#POST
#Path("/sendEmail")
#Consumes({"application/json","application/x-www-form-urlencoded",})
public String sEmail(#FormParam("conteudo") String conteudo, #FormParam("ip") String ip)throws MessagingException {
String de = "de#mail.com.br";
String para = "para#rmail.com.br";
String cc = "";
String cco = "";
String titulo = "Email test";
String conteudo = "conteudo";
try {
Email email = new SimpleEmail();
email.setHostName("smtp....");
email.setSmtpPort(25);
email.setStartTLSEnabled(true);
email.setFrom(de);
email.addTo(para);
email.setSubject(titulo);
email.setMsg(conteudo);
if (!cc.equals("")){
email.addCc(cc);
}
if (!cco.equals("")){
email.addBcc(cco);
}
email.send();
} catch (EmailException e) {
Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, e.getMessage());
}
I use JavaMail 1.4.
I encoded to base64, then I put all the files into a String separated with ;
In the web service first I split the String and then I decoded from base64.
my code for gcm:
[WebMethod]
public void SendNotificationToAndroid()
{
string DeviceTokenID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// string deviceId = notificationId;
const string tickerText = "Text";
const string contentTitle = "Title";
string message = "Hello world";
string postData =
"{ \"registration_ids\": [ \"" + DeviceTokenID + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
SendGcmNotification("xxxxxxxxxxxxxxxxx", postData, "application/json");
}
private void SendGcmNotification(string apiKey, string postData, string postDataContentType)
{
// ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertificate;
var byteArray = Encoding.UTF8.GetBytes(postData);
var request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = postDataContentType;
request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
request.ContentLength = byteArray.Length;
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
var response = request.GetResponse();
var responseCode = ((HttpWebResponse)response).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
const string text = "Unauthorized - need new token";
Context.Response.Write(text);
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
const string text = "Response from web service isn't OK";
Context.Response.Write(text);
}
// ReSharper disable AssignNullToNotNullAttribute
var reader = new StreamReader(response.GetResponseStream());
// ReSharper restore AssignNullToNotNullAttribute
reader.ReadToEnd();
reader.Close();
//Context.Response.Write();
}
catch (Exception e)
{
Context.Response.Write(e.ToString());
}
}
this is my push notification code at server side.The response i am getting error "System.Net.WebException: The remote server returned an error: (401) Unauthorized.
please any one one help. Thank yOu in advance.
Try unsing session on your web method
[WebMethod(true)]
I am receiving the following error from a class that invokes a webservice.
"You have uncommitted work pending. Please commit or rollback before calling out"
Here is the class that is calling the webservice:
global class myWS
{
WebService static string invokeExternalWs(string childValue, string parentValue)
{
HttpRequest req = new HttpRequest();
req.setEndpoint('https://externalURL/Services');
req.setMethod('POST');
req.setHeader('Content-Type', 'text/xml; charset=utf-8');
req.setHeader('SOAPAction', 'http://externalService/externalMethod');
string b = '--soap request goes here--';
req.setBody(b);
Http http = new Http();
try {
//Execute web service call here
String xObjectID ='';
HTTPResponse res = http.send(req);
Dom.Document doc = res.getBodyDocument();
String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
Dom.XmlNode root = doc.getRootElement();
for(dom.XmlNode node1 : root.getChildElements()) {
for(dom.XmlNode node2 : node1.getChildElements()) {
for(dom.XmlNode node3 : node2.getChildElements()) {
for(dom.XmlNode node4 : node3.getChildElements()) {
xObjectID = node4.getText();
}
}
}
}
return xObjectID;
} catch(System.CalloutException e){
return 'ERROR:' + e;
}
}
}
UPDATE: Here is my class that is executing myWS
public void applyURLString(ID ArgBuildID) {
Builder__c current_build = [SELECT id, name, LLURL__c, column1, column2, Opportunity__c
FROM Builder__c
WHERE id = :ArgBuildID];
if(current_build.LLURL__c == null || current_build.LLURL__c.trim().length() == 0)
{
String tmpFolderName = current_build.column1 + ' - ' + current_build.column2;
String LLWSResultPattern = '[0-9]{2,}';
String myWSXMLResult = myWS.invokeExternalWs(tmpFolderName,'test');
Boolean LLWSPatternMatched = pattern.matches(LLWSResultPattern,myWSXMLResult);
if(LLWSPatternMatched)
{
Opportunity oppt = [SELECT Id,Name
FROM Opportunity
WHERE Id = :current_build.Opportunity__c
LIMIT 1];
oppt.LLURL__c = 'https://someService/' + myWSXMLResult;
update oppt;
}
}
}
UPDATE #2 - Here is where applyURLString() is executed. This is the only place that DML is executed prior to my HTTP request. Yet I need the ID of the new Builder record.
Builder__c insertBuild = new Builder__c();
insertBuild.Opportunity__c = opportunityId;
insertBuild.Product_Group__c = selectedBuild.Product_Group__c;
insertBuild.Manual_Build_Product__c = selectedBuild.Manual_Build_Product__c;
insert insertBuild;
applyURLString(insertBuild.Id);
Any ideas why this error would occur?
#JCD's suggestion to use an #future annotation solved my problem. Thanks again!
I'm writing one of my very first web-service, as far as now it was more than ok, but when I'm trying to create sperate class:
public class Workers {
private String name;
private String surname;
private boolean type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public boolean isType() {
return type;
}
public void setType(boolean type) {
this.type = type;
}
public Workers(String name, String surname, boolean type) {
this.name = name;
this.surname = surname;
this.type = type;
}
}
and than to use it in webservice like this:
#WebMethod(operationName = "SelectWorker")
public Pracownicy SelectWorker(#WebParam(name = "username") String username, #WebParam(name = "password") String password) {
ResultSet rs = null;
String name = null;
String surname = null;
boolean type = false;
PreparedStatement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("db_address", "login", "password");
System.out.println("connection status: " +con);
st = con.prepareStatement("select name, surname from clients where login = ? and passwd= ?");
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if (rs.next()) {
name = rs.getString(2);
surname=rs.getString(3);
type = rs.getBoolean(5);
Workers pr = new Workers(name, surname, type);
return pr;
}
} catch (Exception e) {
System.out.println("error: " + e.toString());
}
return null;
}
the body of method can be empty or filled with code, it doesn't matter - I'm getting the same error:
Error occurred during deployment: Exception while loading the app
:java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: java.lang.RuntimeException: Servlet web
service endpoint '' failure.
Are the int, string, boolean etc only allowed as return type?
there is by no means enough information given in your post... How are you creating the web service (I guess with an #WebService), your're telling it does not matter if method SelectWorker (which btw should be called selectWorker by proper naming conventions) is empty or not, but with an empty body your source would not even compile...
what I can tell you: int, String, boolean are not the only allowed return types. You can of course also return instances of your classes from a web service.
For future googlers :
I've had the same error, and checked the server log and got the error :
Two classes have the same XML type name
Which I found wierd but adding this :
#XmlType(namespace="someName")
To my class I was trying to return ( I chose the same name of the class) fixed the problem.
I had this problem, the glassfish was on Linux environment. check your $JAVA_HOME
it should be set in to jdk
export JAVA_HOME=/usr/java/jdk1.7.0_55
/opt/glassfish4/glassfish/bin # echo $JAVA_HOME
/usr/java/jdk1.7.0_55
then problem was solved..