uploading file from backberry to web service = JVM error 104 Uncaught NullPointerException? - web-services

I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!

There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";

Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code

Related

consuming asmx webservice in xamarin forms

I am working on a login page in Xamarin forms and I need to consume an asmx webservice in order to connect to the sql server. I used this example: https://github.com/fabiosilvalima/FSL.ConsummingAsmxServicesInXamarinForms, and tried to apply the same steps for my app. but I got an error.
here's my code:
ILogin.cs:
namespace App33.Models
{
public interface ILogin
{
string Error { get; set; }
bool ValidUser { get; set; }
}
}
ILoginSoapService.cs
public interface ILoginSoapService
{
Task<List<ILogin>> Login(string namee, string passs);
}
in App.xaml.cs
private static ILoginSoapService _loginSoapService;
public static ILoginSoapService LoginSoapService
{
get
{
if (_loginSoapService == null)
{
_loginSoapService = DependencyService.Get<ILoginSoapService>();
}
return _loginSoapService;
}
Main.xaml.cs
public MainPage()
{
InitializeComponent();
}
async void OnButtonClicked(object sender, EventArgs e)
{
var entr_usrname = this.FindByName<Entry>("username");
string usrname = entr_usrname.Text;
var entr_pass = this.FindByName<Entry>("Password");
string pass = entr_pass.Text;
var state = await App.LoginSoapService.Login(usrname,pass);
if (state[0].ValidUser == true)
{
await DisplayAlert("Alert", "You have been alerted", "OK");
}
}
this is for the portable app. my webservice is added to the web reference as LoginWs. it has the following codes:
Result.cs:
public class Result
{
public string Error { get; set; }
public bool ValidUser { get; set; }
}
WebService1.asmx.cs:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Result Login(string userName, string userPass)
{
SqlConnection conn=new SqlConnection (new DBConnection().ConnectionString);
Result result = new Result();
try
{
SqlCommand cmd = new SqlCommand("SELECT userName, password FROM users where CONVERT(VARCHAR, username)=#username and CONVERT(VARCHAR, password)=#password");
cmd.Parameters.AddWithValue("username", userName);
cmd.Parameters.AddWithValue("password", userPass);
cmd.Connection = conn;
if (conn.State==System.Data.ConnectionState.Closed)
{
conn.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
result.ValidUser = true;
return result;
}
else
{
result.ValidUser = false;
}
}
catch(Exception ex)
{
result.Error = ex.ToString();
}
finally
{
conn.Close();
}
return result;
}
}
}
now in App.Android:
Result.cs
namespace App33.Droid.LoginWs
{
public partial class Result : ILogin
{
}
}
LoginSoapService.cs
[assembly: Dependency(typeof(App33.Droid.LoginSoapService))]
namespace App33.Droid
{
public sealed class LoginSoapService :ILoginSoapService
{
LoginWs.WebService1 service;
public LoginSoapService()
{
service = new LoginWs.WebService1()
{
// Url = "http://codefinal.com/FSL.ConsummingAsmxServicesInXamarinForms/Customers.asmx" //remote server
Url = "http://192.168.0.106/site2/WebService1.asmx" //localserver - mobile does not understand "localhost", just that ip address
};
}
public async Task<List<ILogin>> Login( string namee,string pass)
{
return await Task.Run(() =>
{
var result = service.Login(namee,pass);
return new List<ILogin>(result);
});
}
}
}
the error i'm getting is in this line:return new List(result);. it says: Error CS1503 Argument 1: cannot convert from 'App33.Droid.LoginWs.Result' to 'int'. I can't figure out what the peoblem is. sorry for the long question. any help is appreciated.

How to show progress bar while uploading files to amazon s3?

I am uploading files to Amazon S3 bucket and that is working perfectly fine. Now I want to show the progress while uploading them, I have research everywhere but none of them is working. Below is the code for uploading file to Amazon S3 bucket-
On Spring boot controller-
private static final String UPLOAD_FILE_URL = "/uploadImages.htm";
#RequestMapping(value = UPLOAD_FILE_URL, method = RequestMethod.POST)
public ModelAndView uploadImagesRequest(#RequestParam("file") MultipartFile[] files, #RequestParam("filename") String title, HttpServletRequest request) {
ModelAndView model = new ModelAndView("index");
if(awsUploadImageInterface.uploadImage(filess, title, request)) {
model.addObject("successMsg", "Banner Image Is Added Successfully");
}
return "index";
}
Upload Image Functionality-
#Override
public boolean uploadImage(MultipartFile[] file, String title, HttpServletRequest request) {
boolean result = false;
S3BucketUtility s3client = new S3BucketUtility();
InputStream Is;
String key;
Properties prop = new Properties();
InputStream propstream = getClass().getClassLoader().getResourceAsStream("s3.properties");
try {
prop.load(propstream);
} catch (IOException e) {
System.out.println("Properties File Exception in AWS Connection Class: " + e);
}
try {
for (int j = 0; j < file.length; j++) {
if (file[j].getSize() != 0) {
Is = file[j].getInputStream();
String fileext = FilenameUtils.getExtension(file[j].getOriginalFilename());
AWSCredentials credentials = new BasicAWSCredentials(prop.getProperty("acceskey"), prop.getProperty("scretkey"));
String BucketName = prop.getProperty("bucketName");
key = title.concat(".").concat(fileext);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(Long.valueOf(Is.available()));
metadata.setContentType("image".concat("/").concat(fileext));
s3client.uploadfile(credentials, BucketName, key, Is, metadata);
}
}
}catch (AmazonClientException e) {
return result;
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
Hope anyone can help me how to show the progress as I am unable to do. Thanks in advance.

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

how to get contacts list from google glass using GDK

I'm implement Google Glass app.
I want to get contacts list from google glass using GDK.
I already tried contacts Api v3 (ContactsService)
but i failed because -
i can't scrolling & tapping(click) pop-up (OK Button) after glass update XE16
-> run to android phone is ok.
i tried
mirror api. device OAuth.... -> no example.. i don't know how...
if you have sample code, As it is also upload. Would you? I'd appreciate that.
here is my code.
public class MainActivity extends Activity
{
private Account[] accounts;
private AccountManager mManager;
private ContactsService mService;
private URL feedUrl;
private final String url = "https://www.google.com/m8/feeds/contacts/default/full";
private final String ACCOUNTS_TYPE = "com.google";
private final String AUTH_TOKEN_TYPE = "cp";
private String mToken;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mManager = AccountManager.get(this);
accounts = mManager.getAccountsByType(ACCOUNTS_TYPE);
Log.d("account", ""+accounts[0]);
mManager.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>()
{
public void run(AccountManagerFuture<Bundle> future)
{
try
{
mToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
GetTask task = new GetTask();
task.execute(mToken);
}
catch (OperationCanceledException e)
{
e.printStackTrace();
}
catch (AuthenticatorException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}, null);
}
public void createService(String token) throws IOException, ServiceException
{
mService = new ContactsService("contacts_list");
mService.setUserToken(token);
feedUrl = new URL(url);
ContactFeed resultFeed = (ContactFeed)mService.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) getContacts(entry);
}
private class GetTask extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params)
{
try
{
String token = "";
if(params != null)
{
for(String s : params) token += s;
}
createService(token);
}
catch (ServiceException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
public void getContacts(ContactEntry entry) throws ServiceException, IOException
{
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullName = name.getFullName().getValue();
Log.d("name", fullName);
}
}
else Log.d("name", "no name");
if (entry.hasPhoneNumbers())
{
for (PhoneNumber phone : entry.getPhoneNumbers())
{
String phoneNum = phone.getPhoneNumber();
Log.d("phone", phoneNum);
}
}
else Log.d("phone", "no phone");
}
}

JMockit - mock CXF webservice port object

I'm trying to unit test a webservice wrapper class which attempts to hide all the webservice implementation details. It's called from a scripting platform so all interfaces are simple String or integers. The class provides a static initialise method which takes the hostname and port number and uses this to create a private static Apache CXF IRemote port instance (generated from CXF wsdl2java). Subsequent calls to a static business method delegate to the port instance.
How can I use JMockit to mock the CXF port stub when unit testing the static wrapper class?
public class WebServiceWrapper {
private static final QName SERVICE_NAME = new QName("http://www.gwl.org/example/service",
"ExampleService");
private static IRemoteExample _port = null;
public static final String initialise(String url) {
if(_port != null) return STATUS_SUCCESS;
try {
URL wsdlURL = new URL(url);
ExampleService svc = new ExampleService(wsdlURL, SERVICE_NAME);
_port = svc.getIRemoteExamplePort();
BindingProvider bp = (BindingProvider)_port;
Map<String, Object> context = bp.getRequestContext();
context.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
return STATUS_SUCCESS;
}
catch(MalformedURLException ex) {
return STATUS_ERROR_PREFIX + ex.getMessage();
}
catch(WebServiceException ex) {
return STATUS_ERROR_PREFIX + ex.getMessage();
}
}
public static final String businessMethod(String arg) {
if(_port == null) {
return STATUS_ERROR_PREFIX + "Attempted to call businessMethod before connection is initialised. Pease call initialise first.";
}
try {
BusinessMethodRequest request = new BusinessMethodRequest ();
BusinessThing thing = new BusinessThing();
thing.setValue(arg);
request.setThing(thing);
BusinessMethodResponse response = _port.businessMethod(request);
String result = response.getResult();
if(result == null) {
return STATUS_ERROR_PREFIX + "Null returned!";
}
return STATUS_SUCCESS;
}
catch(MyBusinessException_Exception ex) {
return STATUS_ERROR_PREFIX + ex.getFaultInfo().getReason();
}
catch(WebServiceException ex) {
return STATUS_ERROR_PREFIX + ex.getMessage();
}
}
Example behaviour of the webservice would be, if I pass the value "OK" then it returns a success message, but if I call with a value of "DUPLICATE" then the webservice would throw a MyBusinessException_Exception.
I think I have managed to mock the _port object, but the business call always returns a null Response object so I suspect that my Expectations does not define the "BusinessThing" object correctly. My Test method so far.
#Test
public void testBusinessMethod(#Mocked final IRemoteExample port) {
new NonStrictExpectations() {
#Capturing IRemoteExample port2;
{
BusinessThing thing = new BusinessThing();
thing.setValue("OK");
BusinessMethodRequest req = new BusinessMeothdRequest();
req.setThing(thing);
BusinessMethodResponse resp = new BusinessMethodResponse ();
resp.setResult("SUCCESS");
try {
port.businessMethod(req);
returns(resp);
}
catch(MyBusinessException_Exception ex) {
returns(null);
}
Deencapsulation.setField(WebServiceWrapper.class, "_port", port);
}
};
String actual = WebServiceWrapper.businessMethod("OK");
assertEquals(WebServiceWrapper.STATUS_SUCCESS, actual);
}
Seems to be working as follows.
Added a custom Matcher class for my BusinessMethodRequest
class BusinessMethodRequestMatcher extends TypeSafeMatcher<BusinessMethodRequest> {
private final BusinessMethodRequestexpected;
public BusinessMethodRequestMatcher(BusinessMethodRequest expected) {
this.expected. = expected;
}
#Override
public boolean matchesSafely(BusinessMethodRequest actual) {
// could improve with null checks
return expected.getThing().getValue().equals(actual.getThing().getValue());
}
#Override
public void describeTo(Description description) {
description.appendText(expected == null ? null : expected.toString());
}
}
Then use "with" in my Expectation.
try {
port.createResource(with(req, new BusinessMethodRequestMatcher(req)));
returns(resp);
}
The mock object now recognises the business method call with the correct parameter and returns the expected response object.