Android QBCustomObject file uploading The resource wasn't found error - file-upload

I am trying to upload file using QBCustomObjectFiles ,uploading starts to show progress in log cat ,but with file field is null and response throws error like this '{"errors":["The resource wasn't found"]}'
I checked My Note Class on Quickblox admin panel,everything seems OK.Also I checked the file (field in method parameter) and it is not null as showing in log cat
public void uploadNote(Note note, File file,
QBEntityCallback<QBCustomObjectFileField> callback, QBProgressCallback
progressCallback) {
QBCustomObject customObject = new QBCustomObject();
customObject.setClassName(Note.Contract.CLASS_NAME_NOTE);
customObject.put(Note.Contract.COURSE_ID,note.getCourseId());
customObject.put(Note.Contract.CATEGORY_ID,note.getCategoryId());
customObject.put(Note.Contract.DESCRIPTION,note.getDescription());
customObject.put(Note.Contract.TOPIC,note.getTopic());
QBCustomObjectsFiles.uploadFile(file, customObject, "noteFile", progressCallback).performAsync(callback);
}
This is my log cat :
REQUEST
POST https://api.quickblox.com/data/Note/null/file.json
HEADERS
QuickBlox-REST-API-Version=0.1.1
QB-SDK=Android 3.9.1
QB-Token=011a2bc55be67185d4d045d8b2d31
PARAMETERS
field_name=noteFile
INLINE
POST https://api.quickblox.com/data/Note/null/file.json?field_name=noteFile
and this is response
'{"errors":["The resource wasn't found"]}'
The Uploading starts and shows progress ,but after progress 100 it throws above error.

You should use QBContent instead of QBCustomObjectsFiles. Example:
QBContent.uploadFileTask(file, isPublic, tags, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progressValue) {
//some code for progress
}
}).performAsync(new QBEntityCallback<QBFile>() {
#Override
public void onSuccess(QBFile qbFile, Bundle params) {
//some code for success upload
}
#Override
public void onError(QBResponseException responseException) {
//some code for error upload
}
});

Related

How to reference resource from Resources file

I have a bunch of messages in a Constants file that I want to convert all string constants for messages displayed to users to be moved to a localized/globalization resource file.
I created a Resources.resx file and I'm trying to figure out how to reference a resource in a controller. For example this resource in my Resources.resx file
internal static string ItemUpdateFailed {
get {
return ResourceManager.GetString("ItemUpdateFailed", resourceCulture);
}
}
I want to reference it in a controller action to replace the bolded reference to the string constant in the method below. How do I reference the resource above in the method below.
public async Task<IActionResult> Index(CancellationToken cancellationToken)
{
var itemIndexViewModel = new ItemIndexViewModel();
try
{
_mapper.Map(await _itemService.GetItemAsync(ItemStatus.Active, cancellationToken).ConfigureAwait(true), itemIndexViewModel.Items);
}
catch
{
**TempData.Put(TempDataKey.Item.UPDATE_MESSAGE, StatusMessageModel.Create(Constants.Item.TO_CREATE_UPDATE_FAIL));**
}
return View(itemIndexViewModel);
}

Using Volley For Spoonacular Api

How to use Volley to fetch recipes from spoonacular API for an android application. I am new to APIs and would like some help in fetching recipes from the spoonacular api for a list of ingredients specified in an android app.
Step 1
dependencies {
...
implementation 'com.android.volley:volley:1.0.0'
}
Step 2
In AndroidManifest file add permission
<uses-permission android:name="android.permission.INTERNET"/>
Step 3 Add following in MyApplication class
private RequestQueue requestQueue;
public RequestQueue getRequestQueue() {
if (requestQueue == null)
requestQueue = Volley.newRequestQueue(getApplicationContext());
return requestQueue;
}
public void addToRequestQueue(Request request, String tag) {
request.setTag(tag);
getRequestQueue().add(request);
}
public void cancelAllRequests(String tag) {
getRequestQueue().cancelAll(tag);
}
Step 4 Final Step
//URL of the request we are sending
String url = "https://api.spoonacular.com/food/products/22347";
/*
JsonObjectRequest takes in five paramaters
Request Type - This specifies the type of the request eg: GET,
URL - This String param specifies the Request URL
JSONObject - This parameter takes in the POST parameters.null in case of
GET request
Listener -This parameter takes in a implementation of Response.Listener()
interface which is invoked if the request is successful
Listener -This parameter takes in a implemention of Error.Listener()
interface which is invoked if any error is encountered while processing
the request
*/
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "getRequest");
Something like that. Let's try. Thanks

Testng - Skip dependent tests for only failed data sets

I am attempting to modify my dependent tests so they are ran in a specific way and have yet find a way possible. For instance, say I have the following two tests and the defined data provider:
#Dataprovider(name = "apiResponses")
Public void queryApi(){
return getApiResponses().entrySet().stream().map(response -> new Object[]{response.getKey(), response.getValue()}).toArray(Object[][]::new);
}
#Test(dataprovider = "apiResponses")
Public void validateApiResponse(Object apiRequest, Object apiResponse){
if(apiResponse.statusCode != 200){
Assert.fail("Api Response must be that of a 200 to continue testing");
}
}
#Test(dataprovider = "apiResponses", dependsOnMethod="validateApiResponse")
Public void validateResponseContent(Object apiRequest, Object apiResponse){
//The following method contains the necessary assertions for validating api repsonse content
validateApiResponseData(apiResponse);
}
Say I have 100 api requests I want to validate, with the above, if a single one of those 100 requests were to return a status code of anything other than 200, then validateResponseContent would be skipped for all 100. What I'm attempting to achieve is that the dependent tests would be skipped for only the api responses that were to return without a status code of 200 and for all tests to be ran for responses that returned WITH a status code of 200.
You should be using a TestNG Factory which creates instances with both the apiRequest and apiResponse in it for each instance. Now each instance would basically first run an assertion on the status code before it moves on to validating the actual api response.
Here's a sample that shows how this would look like:
public class TestClassSample {
private Object apiRequest, apiResponse;
#Factory(dataProvider = "apiResponses")
public TestClassSample(Object apiRequest, Object apiResponse) {
this.apiRequest = apiRequest;
this.apiResponse = apiResponse;
}
#Test
public void validateApiResponse() {
Assert.assertEquals(apiResponse.statusCode, 200, "Api Response must be that of a 200 to continue testing");
}
#Test(dependsOnMethods = "validateApiResponse")
public void validateResponseContent() {
//The following method contains the necessary assertions for validating api repsonse content
validateApiResponseData(apiResponse);
}
#DataProvider(name = "apiResponses")
public static java.lang.Object[][] queryApi() {
return getApiResponses().entrySet()
.stream().map(
response -> new java.lang.Object[]{
response.getKey(), response.getValue()
})
.toArray(Object[][]::new);
}
}
Would'nt adding a if/else block solve this?
#Test(dataprovider = "apiResponses")
Public void validateApiResponse(Object apiRequest, Object apiResponse){
if(apiResponse.statusCode != 200){
Assert.fail("Api Response must be that of a 200 to continue testing");
} else {
validateApiResponseData(apiResponse);
}
}

vaadin: getting user logindata from external page

i wrote a normal html login form, that forwards to a vaadin project, where i want to receive the username and password and check if its valid. but i have problems getting this request.
when i add a requesthandler in the init() method of my UI class, i can only get the request data after the second call of the vaadin page (because at the first call of init, the hander ist not added yet)
#Override
protected void init(VaadinRequest vaadinRequest) {
setContent(new MainComponent());
VaadinSession.getCurrent().addRequestHandler(
new RequestHandler() {
#Override
public boolean handleRequest(VaadinSession vaadinSession, VaadinRequest vaadinRequest, VaadinResponse vaadinResponse) throws IOException {
String username = vaadinRequest.getParameter("username");
return false;
}
});
so i tried to overwrite the VaadinServlet method doPost, but it does not get triggered. when i overwrite the methode service(HttpServletRequest request, HttpServletResponse response), this method is triggered a serval times for each request, so also not a good place to get just the userdata.
so whats the right way to solve this problem?
i dont't know if this is the best solution, but at least it works. maybe this helps someone.
here a short explanation what i do. i retrieve the posted username and password from the post values of my plain html login formular from another url and see if it is existing in the database. if it exists, it returns the result, otherwise the value ERROR.
i extended the VaadinServlet and overwrote the method service like this
#Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.service(request, response);
String username = request.getParameter("username");
if(username != null) { // called several times, only set when username is returned, otherwise the value remains "error"
String password = request.getParameter("password");
this.result = getResult(username, Encrypter.encryp(password));
}
}
and this is inside my class extended from UI
#Override
protected void init(VaadinRequest vaadinRequest) {
MyServlet myServlet = (MyServlet) VaadinServlet.getCurrent();
String result = myServlet.getResult();
if(result .equals(MyServlet.ERROR)){ // check if the result set in the servlet is valid, otherwise forward to the loginpage
goToLogin();
myServlet.resetResult();
return;
}
myServlet.resetResult();
...
}
To whom it may concern - obtaining request and response in Vaadin 8 (which might be also available in Vaadin 7):
VaadinServletRequest vsRequest = (VaadinServletRequest) VaadinService.getCurrentRequest ();
HttpServletRequest httpServletRequest = vsRequest.getHttpServletRequest ();
VaadinServletResponse vsResponse = (VaadinServletResponse) VaadinService.getCurrentResponse ();
HttpServletResponse httpServletResponse = vsResponse.getHttpServletResponse ();
You can read the request parameter directly through the VaadinRequest object that's passed into init():
#Override
protected void init(VaadinRequest vaadinRequest) {
setContent(new MainComponent());
String username = vaadinRequest.getParameter("username");
}
It work for me perfect:
User is my simple class with username, name etc.
setting logged user in session:
public void setLoggedUser(User loggedUser) {
this.loggedUser = loggedUser;
getUI().getSession().getSession().setAttribute("loggedUser", loggedUser);
}
reading user:
loggedUser = (User) getUI().getSession().getSession().getAttribute("loggedUser"); //return null if not logged in

GWT code-splitting pattern for ClientBundle image resources

In my GWT large project, I have a ClientBundle for my image resources. I defined about 40 GIF files inside it. (size of each file is about 5KB)
Then I create a class with a static method to set the proper image to the obj that get as parameters:
public static void setImageFromId (String id,final Image img) {
//for 1.gif
if (id.equals("1")) {
GWT.runAsync(new RunAsyncCallback() {
#Override
public void onFailure(Throwable reason) {}
#Override
public void onSuccess() {
img.setResource(MyImages.INSTANCE.img1()); //MyImages is the ClientBundle
}
});
}
}
//for 2.gif
if (id.equals("2")) {
GWT.runAsync(new RunAsyncCallback() {
#Override
public void onFailure(Throwable reason) {}
#Override
public void onSuccess() {
img.setResource(MyImages.INSTANCE.img2()); //MyImages is the ClientBundle
}
});
}
//etc. for other images 3, 4, 5, ...
//...
}
I want to know is it good pattern for code-splitting? because if I don't do it all the 40 files will be cached to client browser in first call, but it is not necessary.
RGDS
So you're trying to avoid downloading each image when your page loads. That's good, if you don't know ahead of time whether every image will be needed.
But, what your code is doing is using code-splitting to only download the code to display your images when the image is needed, which as you can see, is only one line of code per image.
Try this code:
if (id.equals("1")) {
img.setSrc(MyImages.INSTANCE.img1().getUrl());
} else if (id.equals("2")) {
//.. and so on.
}
Your images will only be downloaded and displayed when the relevant image is needed. You can use Firebug or Chrome's Developer Tools to see when your images are being downloaded, they should only be requested when needed.
If you have any more questions or find that all your images are being downloaded on page load, let me know and I'll edit my answer again to help you out.