On client side I created 3 attachments in the following way:
public String sendMessage(MMSMessage mmsMessage, String formatCDR, FlowSessionData flowSessionData)
throws IOException, ServiceException, PolicyException {
SendMessage sendMessage = sendMessageService.getSendMessage();
int index = 1;
List<Attachment> atts = new ArrayList<Attachment>();
BufferedImage image = ImageIO.read(new URL(mmsMessage.getImgPath()));
atts.add(createAttachmentPart(mmsMessage.getImgMimeType(), image, index));
if (mmsMessage.getPrerollText() != null) {
atts.add(createAttachmentPart("text/plain", mmsMessage.getPrerollText(), index++));
}
if (mmsMessage.getPostrollText() != null) {
atts.add(createAttachmentPart("text/plain", mmsMessage.getPostrollText(), index++));
}
setServiceParams((BindingProvider) sendMessage, atts, configService.getSendMessageEndpointAddress());
String value = null;
validateURI(configService.getParlayxCallbackEndpointService() + "/" + NOTOFICATION_MMS_INTERFACE);
SimpleReference correlator = new SimpleReference();
correlator.setCorrelator(formatCDR);
correlator.setInterfaceName(NOTOFICATION_MMS_INTERFACE);
correlator.setEndpoint(configService.getParlayxCallbackEndpointService() + "/" + NOTOFICATION_MMS_INTERFACE);
String toNumber = mmsMessage.getSmsServiceActivationNumber().get(0);
if (!toNumber.startsWith(MSGConstants.PHONE_URI_PREFIX)) {
if (!toNumber.startsWith("+")) {
toNumber = "+" + toNumber;
}
toNumber = MSGConstants.PHONE_URI_PREFIX + toNumber;
}
validateURI(toNumber);
List<String> addr = new ArrayList<String>();
addr.add(toNumber);
value = sendMessage.sendMessage(addr, mmsMessage.getSenderAddress(), mmsMessage.getSubject(), null, null,
correlator);
LOGGER.info(value);
return value;
}
private Attachment createAttachmentPart(String mimeType, Object data, int index) {
return new AttachmentImpl(String.valueOf(index), new DataHandler(data, mimeType));
}
private void setServiceParams(BindingProvider serviceInf, Collection<Attachment> attachments, String endPoint) {
Map<String, Object> requestContext = serviceInf.getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endPoint);
requestContext.put(BindingProvider.USERNAME_PROPERTY, configService.getParlayxEndPointUserName());
requestContext.put(BindingProvider.PASSWORD_PROPERTY, configService.getParlayxEndPointPassword());
final Client client = ClientProxy.getClient(serviceInf);
final HTTPConduit http = (HTTPConduit) client.getConduit();
final HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setReceiveTimeout(configService.getParlayxEndPointTimeOut());
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setConnectionTimeout(configService.getParlayxEndPointTimeOut());
http.setClient(httpClientPolicy);
if (attachments != null && !attachments.isEmpty()) {
requestContext.put(org.apache.cxf.message.Message.ATTACHMENTS, attachments);
}
}
And I receive the exception below, what causes it and how can I fix it?
WARNING: Interceptor for
{http://www.csapi.org/wsdl/parlayx/multimedia_messaging/send/v2_4/service}SendMessageService#{http://www.csapi.org/wsdl/parlayx/multimedia_messaging/send/v2_4/interface}sendMessage
has thrown exception, unwinding now
org.apache.cxf.binding.soap.SoapFault:
Error reading XMLStreamReader. at
org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:222)
at
org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:60)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255)
at
org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:755)
at
org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2335)
at
org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2193)
at
org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:2037)
at
org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
at
org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:697)
at
org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255)
at
org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:516)
at
org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at
org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:265)
at
org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at
org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
at $Proxy92.sendMessage(Unknown
Source) at
com.amobee.common.sms.ParlayxMessagingService.sendMessage(ParlayxMessagingService.java:105)
at
com.amobee.nc.protocol.msg.MMSResponseBuilder.buildResponseMessage(MMSResponseBuilder.java:96)
at
com.amobee.nc.protocol.msg.BaseMSGResponseWriter.getResponse(BaseMSGResponseWriter.java:59)
at
com.amobee.nc.protocol.AbstractResponseWriter.write(AbstractResponseWriter.java:75)
at
com.amobee.frontend.servlets.AbstractBaseServlet.runCommand(AbstractBaseServlet.java:124)
at
com.amobee.frontend.servlets.AbstractBaseServlet.doGet(AbstractBaseServlet.java:64)
at
javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at
javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at
org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at
org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390)
at
org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at
org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at
org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at
org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at
org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at
org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at
org.mortbay.jetty.Server.handle(Server.java:326)
at
org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at
org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at
org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
at
org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at
org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at
org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at
org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by:
com.ctc.wstx.exc.WstxEOFException:
Unexpected EOF in prolog at [row,col
{unknown-source}]: [1,0] at
com.ctc.wstx.sr.StreamScanner.throwUnexpectedEOF(StreamScanner.java:682)
at
com.ctc.wstx.sr.BasicStreamReader.handleEOF(BasicStreamReader.java:2090)
at
com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:1996)
at
com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1100)
at
com.ctc.wstx.sr.BasicStreamReader.nextTag(BasicStreamReader.java:1123)
at
org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:122)
... 40 more
Thanks, Daniela
This exception means that you have End of file character within the XML message, you should use Base64bit type to use attachments in Web services to avoid such error like that.
Related
I'm trying to call the https API from the WPF application but i'm getting this error:
InnerException = {"The underlying connection was closed: An unexpected
error occurred on a send."} Message = "An error occurred while sending
the request."
Can anyone help me what exactly the problem is?
private static readonly string apiURL =
"https://api.totalsynergy.com/api/v2/Profile/Index";
private async Task<bool> GetAuth(string accessToken)
{
try
{
HttpClient hc = new HttpClient();
HttpResponseMessage hpm = await hc.GetAsync(apiURL);
if (hpm.IsSuccessStatusCode)
{
var res = await hpm.Content.ReadAsAsync<Organization>();
}
return boolValue;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
return boolValue;
}
}
When is HTTPS, connection requires some protocols.
In my example I have a API URL that I call and can send some information and receive the response in JSON. You can adapt this to your problem:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//get OS version
var query = "SELECT version FROM Win32_OperatingSystem";
var searcher = new ManagementObjectSearcher(query);
var info = searcher.Get().Cast<ManagementObject>().FirstOrDefault();
string version = info.Properties["Version"].Value.ToString();
int majorVersion = Int32.Parse(version.Substring(0, version.IndexOf(".")));
//OS version is windows xp or older
if (majorVersion < 6)
{
//tls 1.0
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192;
}
else
{
//tls 1.1 or tls 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
}
//url to send data
string url = **YOUR URL**
//create request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = 240000;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = **REQUEST METHOd GET/POST**;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
//convert to byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(**Text to send or empty**);
//specify content of request - this example is in JSON
request.ContentType = "application/json";
if (requestMethod != RequestMethods.GET)
{
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
//send
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (var readers = new StreamReader(response.GetResponseStream()))
{
return result = readers.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
finally
{
request.Abort();
}
While updating data in database through spring jdbcTemplate, Please advise is there is any way so that I need not to hardcode the parameter Index,I am getting below error:
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.ClientPreparedStatement.checkBounds(ClientPreparedStatement.java:1408)
at com.mysql.cj.jdbc.ClientPreparedStatement.getCoreParameterIndex(ClientPreparedStatement.java:1421)
at com.mysql.cj.jdbc.ClientPreparedStatement.setNull(ClientPreparedStatement.java:1686)
at org.springframework.jdbc.core.StatementCreatorUtils.setNull(StatementCreatorUtils.java:308)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:232)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:166)
at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.doSetValue(ArgumentPreparedStatementSetter.java:66)
at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.setValues(ArgumentPreparedStatementSetter.java:47)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:875)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:931)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:941)
at com.ganeshTrading.riceAppService.dao.impl.JdbcPurchaseDAO.updateStock(JdbcPurchaseDAO.java:151)
at com.ganeshTrading.riceAppService.controller.PurchaseController.updateStock(PurchaseController.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Here, is my code:
public void updateStock(Stock stock) {
String sql = "update stock_details set ";
Object[] obj = new Object[3];
if(stock.getRemainingStock() != null) {
sql+= "remaining_stock = ? ";
obj[0] = stock.getRemainingStock();
if(stock.getCommodityPricePerKg() != null) {
sql+= ", commodityPricePerKg = ? ";
obj[1] = stock.getCommodityPricePerKg();
sql += " where commodity_id = ? ";
obj[2] = stock.getCommodityId();
}
else {
sql += " where commodity_id = ? ";
obj[1] = stock.getCommodityId();
}
}
else if(stock.getCommodityPricePerKg() != null) {
sql+= " commodityPricePerKg = ? ";
obj[0] = stock.getCommodityPricePerKg();
sql += " where commodity_id = ? ";
obj[1] = stock.getCommodityId();
}
if(jdbcTemplate == null)
jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println(obj.length);
jdbcTemplate.update(sql, obj);
}
Please advise what is wrong in my code or there is some other way to do this through jdbcTemplate. Thanks in advance.
The problem is that the number of parameters in the SQL statement doesn't match with the number of provided arguments. It is not obvious by looking at the code, but
Object[] obj = new Object[3];
obj[0] = "Duke";
jdbcTemplate.update(sql, obj);
is basically the same as
jdbcTemplate.update(sql, new Object[] { "Duke", null, null });
JdbcTemplate assumes that the number of parameters in the SQL statement and in provided arguments array is the same.
To handle different number of arguments you can change from arrays to lists
List<Object> args = new ArrayList<>();
// some logic with args.add(...)
jdbcTemplate.update(sql, args.toArray());
An alternative is the NamedParameterJdbcTemplate:
Map<String, Object> args = new HashMap<>();
args.put("name", "Duke");
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
jdbcTemplate.update("UPDATE user SET name = :name", args);
In:
sql+= " commodityPricePerKg = ? "
And:
sql+= ", commodityPricePerKg = ? ";
Are you sure your field in db is named like that? Maybe it is named "commodity_price_per_kg"?
I've searched for hours and tried everything to fix this code. I've been working with the example below and after updating appropriate variables this works fine through till the end of processing the first email. It seems to pause indefinitely. I had to alter code at (//check if the content is an inline image) as variables appear to need declaration before they were used but have not changed anything apart from that. Any help before I loose my mind will be much appreciated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original code at https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My code below... (output below that)
package com.mail.coder;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class FetchingEmail2 {
public static void fetch(String pop3Host, String storeType, String user,
String password) {
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// emailSession.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect("mail.DOMAIN.com", "USERNAME#DOMAIN.com", "PASS");
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
writePart(message);
String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username =
"abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
//Call method fetch
fetch(host, mailStoreType, username, password);
}
/*
* This method checks for content-type
* based on which, it processes and
* fetches the content of the message
*/
public static void writePart(Part p) throws Exception {
if (p instanceof Message)
//Call method writeEnvelope
writeEnvelope((Message) p);
System.out.println("----------------------------");
System.out.println("CONTENT-TYPE: " + p.getContentType());
//check if the content is plain text
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
System.out.println((String) p.getContent());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
**int i;
byte[] bArray = new byte[x.available()];**
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
i = 0;
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
}
/*
* This method would print FROM,TO and SUBJECT of the message
*/
public static void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
System.out.println("SUBJECT: " + m.getSubject());
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Output
messages.length---5
---------------------------------
This is the message envelope
---------------------------
FROM: Jack Frost <sender#gmail.com>
TO: recipient#domain.com
SUBJECT: another email
----------------------------
CONTENT-TYPE: multipart/alternative; boundary="000000000000096c73056991868c"
This is a Multipart
---------------------------
----------------------------
CONTENT-TYPE: text/plain; charset="UTF-8"
This is plain text
---------------------------
testing
----------------------------
CONTENT-TYPE: text/html; charset="UTF-8"
This is a string
---------------------------
<div dir="ltr">testing</div>
This is the error that I get:
Error:
Execution failed for task ':passenger:transformClassesWithRealmTransformerForDebug'.
javassist.CannotCompileException: updateVehicle (Landroid/content/Context;Ljava/lang/Integer;Lnl/hgrams/passenger/model/Vehicle;Ljava/lang/Integer;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Lnl/hgrams/passenger/interfaces/JsonCallback;)V in nl.hgrams.passenger.model.UserVehicle: failed to resolve types
Now I seen that the latest versions of Realm do support having functions inside the realmObject.
I have this function inside that causes the crash:
public void updateVehicle(Context context, Integer userID, Vehicle newVehicle, Integer vclass, String newCountry, String newLicense, String newImage, List<MileageRates> mileageRates, final JsonCallback jsonCallback) {
try{
JSONObject params = createJsonForUpdate(context,newVehicle, vclass, newCountry, newLicense, newImage, mileageRates);
Log.i("","vehicle params is:" + params.toString());
WSCalls.sendData(Request.Method.POST, Constants.API_ENDPOINT + "/users/" + userID + "/vehicles/" + id + "/update", params , context, null, true, new JsonCallback() {
#Override
public void onResponse(JSONObject jsonObject, VolleyError error, String errorMsg) {
if(jsonCallback != null)
jsonCallback.onResponse(jsonObject,error,errorMsg);
}
});
}catch (Exception e){
Log.e("","error updating vehicle:" + e.getMessage());
}
}
IF I comment out WScall.sendData, then it will work.
This is the method:
public static void sendData(final Integer type , final String url, final JSONObject params, final Context context, final View loader, boolean hasAllURL , final JsonCallback listener){
String URL = Constants.API_ENDPOINT + url;
if(hasAllURL){
URL = url;
}
final String URL2 = URL;
Log.i(TAG, "test offline sendData - url:: " + URL);
if(params != null) {
Log.i(TAG, "test offline sendData - params: " + params.toString());
}
JsonObjectRequest jr = new JsonObjectRequest(type, URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "sendData Response: " + response.toString());
Utils.logWSResponse("POST", URL2, 200, response.toString(), header);
try{
if(Utils.WSValidator(response)){
if(loader!= null)
loader.setVisibility(View.GONE);
if(listener != null)
listener.onResponse(response, null, null);
}else{
if(listener != null)
listener.onResponse(response,null, null);
Log.i("","test offline data:" + response.toString());
Utils.appendLog("send data response not VALID",true);
}
}catch (Exception e){
Utils.appendLog("send data error: " + e.getMessage(),true);
Log.e(TAG, "JsonException: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
if(loader!= null)
loader.setVisibility(View.GONE);
if(error != null && error.networkResponse != null) {
Utils.appendLog("WSCALL send data done, ERROR stop STATUS CODE" + error.networkResponse.statusCode, true);
json = new String(error.networkResponse.data);
json = trimMessage(json, "message");
if (json != null) {
Utils.logWSResponse("POST", URL2, error.networkResponse.statusCode, json, header);
}
Log.i(TAG, "checkout valid send data Volley error response: " + json);
if(error.networkResponse.statusCode == 401 && PSLocationCenter.getInstance().pref.getAuthenticationToken() != null){
PSLocationCenter.getInstance().pref.setFbConnected(context, false);
if(PSSocialService.getInstance().fbSession != null){
PSSocialService.getInstance().fbSession.closeAndClearTokenInformation();
}
PSUserService.getInstance(context).finishLogOut();
return;
}
}
if(listener != null)
listener.onResponse(null, error, json);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
PassengerPreferencesManager pref = new PassengerPreferencesManager(context);
if(pref.getAuthenticationToken() != null){
return getHeaderData(pref, context);
}else{
return super.getHeaders();
}
}
};
if (Utils.networkIsAvailable( context)) {
try{
header = jr.getHeaders().toString();
Utils.logWSRequest("POST", URL, params.toString() ,header);
}catch (Exception e){
Log.e("","error volley: " + e.getMessage());
}
jr.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, 1));
PSLocationCenter.getInstance().mRequestQueue.add(jr);
}
else {
if(loader!= null)
loader.setVisibility(View.GONE);
Log.i(TAG, "sendData - no internet");
AlertDialog.show(context, "", context.getString(R.string.no_internet), context.getString(R.string.OK), null);
}
}
Can this be fixed? or it does not support that method cause of nonrealm objects in it? I tried to add a nonrealm object inside and it worked.
Also, Another question. can I add inside my realmObject Integers that I don't want to be added to the db. Values that I use in functions, so that I do not need to call a realm transaction every time I use them?
I have the URL like this:
Constants.API_ENDPOINT + "/users/" + userID + "/vehicles/" + id + "/update"
If I set getId() instead of simply the variable, it works
I have been reading about how to handle AJAX in Selenium webdriver. There are a lot of solutions. Is there one best and correct solution?
The solutions I have read about so far are:
1) Using thread sleep
2) waitFor method
3) ExpectedCondition
4) FluentWait
5) PresenceOfElementLocated
Thanks!
The reliable solution to handle ajax components(as used in my case) is to wait for the element to be visible on the page using waitUntil() API call of webdriver.
Otherwise threadsleep() like solution is not at all recommended to handle Ajax.
I have used this and it itself waits works fine.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thanks try it.
If you're using jQuery, this is what I recommend. You can control exactly how often polling happens.
// poll every 1/3 second for 3 seconds
int timeout = 3; // seconds
int pollFreq = 3; // times per second
WebDriverWait wait = new WebDriverWait(driver, timeout, 1000/pollFreq);
// to be safe, test (driver instanceof JavascriptExecutor) here
JavascriptExecutor executor = ((JavascriptExecutor) driver);
// Check to see if jQuery is available first
Boolean hasJquery = (Boolean) executor.executeScript("return !!window.jQuery");
Boolean hasActive = (Boolean) executor.executeScript("return typeof window.jQuery.active === \"number\"");
if (hasJquery && hasActive) {
// Wait for JS AJAX calls to complete...
wait.until((ExpectedCondition<Boolean>) driver -> (Boolean) executor
.executeScript("return window.jQuery.active === 0"));
// JS AJAX calls completed.
// Good idea to add a timing report here for troubleshooting.
}
// else jQuery/active-prop not available, continue
You might want to try the Apache Http Client if you want to perform make ajax requests from your test. Here is some Groovy code that does this. Chances are not high that you are using Groovy, but this should still be informative regarding Get & Post in general with the client.
import groovy.util.Expando
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.methods.GetMethod
import java.io.BufferedReader
import java.io.InputStreamReader
import org.apache.commons.httpclient.Header
import java.net.URLDecoder
import com.auto.utils.crypto.Crypto
class ClientHttps {
private HttpClient client = null
private BufferedReader br = null
private String cookieString = ""
private crypto = new Crypto()
def log
public ClientHttps(log) {
this.log = log
client = new HttpClient();
client.getParams().setParameter("http.useragent", "Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2")
}
public Expando get(String url) {
def startTime = System.nanoTime()
GetMethod method = new GetMethod(url)
Expando returnData = new Expando()
try {
log.info("cookieString = " + cookieString)
method.addRequestHeader("Cookie", cookieString)
method.addRequestHeader("Accept", "application/json")
int returnCode = client.executeMethod(method)
log.info("returnCode = " + returnCode)
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error("The Get method is not implemented by this URI")
} else {
if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_PERMANENTLY))
assert false, "Bad Response Code"
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
String readLine;
while(((readLine = br.readLine()) != null)) {
log.info(readLine)
}
Header [] respHeaders = method.getResponseHeaders()
respHeaders.each () {
log.info(it.getName() + " = " + it.getValue())
returnData.setProperty(it.getName(), it.getValue())
}
}
def endTime = System.nanoTime()
def duration = endTime - startTime;
def seconds = (double)duration / 1000000000.0;
log.info("Get took = " + seconds + " seconds (Get url = " + url + ")")
return returnData;
} catch (Exception e) {
log.error(e.message, e)
return null
} finally {
method.releaseConnection()
if(br != null) try {
br.close()
} catch (Exception fe) {
log.info(fe.message, fe)
}
}
}
public Expando post(Expando postData) {
def startTime = System.nanoTime()
PostMethod method = new PostMethod(postData.getProperty("url"))
postData.getProperty("params").each() {method.addParameter(it.key, it.value)}
Expando returnData = new Expando()
try {
int returnCode = client.executeMethod(method)
log.info(returnCode)
if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error("The Post method is not implemented by this URI")
} else {
if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_TEMPORARILY))
assert false, "Bad Response Code"
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
String readLine
while(((readLine = br.readLine()) != null)) {
log.info("Response Data = " + readLine)
}
Header [] respHeaders = method.getResponseHeaders()
respHeaders.each () {
log.info(it.getName() + " = " + it.getValue())
try {
returnData.setProperty(it.value.split("=")[0], it.value.split("=")[1])
}
catch (Exception exc) {
log.info("Could not split on equals sign = " + it.value)
}
}
}
def endTime = System.nanoTime()
def duration = endTime - startTime;
def seconds = (double)duration / 1000000000.0;
log.info("Post took = " + seconds + " seconds (Post url = " + postData.getProperty("url") + ")")
return returnData
} catch (Exception exc) {
log.info(exc.message, exc)
return null
} finally {
method.releaseConnection()
if(br != null) try {
br.close()
} catch (Exception fe) {
log.info(fe.message, fe)
}
}
}
}