Categories
discuss

Lombok builder to check non null and not empty

I have a class with variables I don’t want it to be null or empty. Is there a way to use Lombok builder to set the property? I can use @NonNull but I won’t be able to verify if it is empty or not. Obviously the other option is to write my own builder which does all these checks. For example:

class Person {
    @NonNull
    private String firstName;
    @NonNull
    private String lastName;

    public static class PersonBuilder() {
        // .
        // .
        // .
        public Person build() {
            //do checks for empty etc and return object
        }
    }
}

Answer

Maxim Kirilov’s answer is incomplete. It doesn’t check for blank/empty Strings.

I’ve faced the same issue before, and I realized that in addition to using @NonNull and @Builder from Lombok, overload the constructor with a private access modifier, where you can perform the validations. Something like this:

private Person(final String firstName, final String lastName) {
    if(StringUtils.isBlank(firstName)) {
        throw new IllegalArgumentException("First name can't be blank/empty/null"); 
    }
    if(StringUtils.isBlank(lastName)) {
        throw new IllegalArgumentException("Last name can't be blank/empty/null"); 
    }
    this.firstName = firstName;
    this.lastName = lastName;
}

Also, throwing IllegalArgumentException makes more sense (instead of NPE) when String has blank, empty or null values.

Categories
discuss

IE 11 is ignoring appendChild() for dynamically generated html pages

I am trying to create a pseudo report that shows me errors from importing data. to do this I have two functions:

                let createHtmlErrorReport = (err) => {

                    let currentDate = new Date().toLocaleString();
                    let contents = '<!DOCTYPE html> ' +
                        '<html>' +
                        '<head>' +
                        '<title>Import Inventory Import</title>' +
                        '<meta charset="utf-8" />' +
                        '<meta http-equiv="Content-Language" content="en">' +
                        '<style type="text/css">' +
                        ' html { margin:0;  }' +
                        ' body { background-color:#d6d6d6; font: 10pt sans-serif;}' +
                         'ul li{ padding: 3px; font:12pt;}'+
                        ' #header {padding:10px; background-color:#007fcc; color:#ffffff; } ' +
                        '</style>' +
                        '</head>' +
                        '<body>' +
                        '<div id="header">'+
                        '<strong>Import Inventory Import</strong>' +
                        '</div>' +
                        '<p><strong>Imported ' + currentDate + ' by ' + err.username + ' | ' + err.unprocessedItemsCount + ' items not imported | ' + err.processedItemsCount + ' items imported | '+ err.errorMessages.length + ' errors.</strong></p>'+
                        '<p>The following errors occured during import: </p>'+
                        '<div id="errorList" style="padding:5px;"></div>'+
                        '</body>' +
                        '</html>';
                    return contents;

                }

In the above I create a new document, add some basic styling and then create div container where I want a list of errors to be inserted.

<div id="errorList" style="padding:5px;"></div> 

The next function calls this method and builds the error list

            let generateImportErrorReport = (errors) => {
                        let doc = createHtmlErrorReport(errors);
                        let errorReportWindow = window.open('', '_blank');
                        errorReportWindow.document.write(doc);
                        let list = document.createElement('ul');
                        //builds a list of errors 
                        for (let i = 0; i < errors.errorMessages.length; i++) {
                            let item = document.createElement('li');
                            let message = errorReportWindow.document.createTextNode(errors.errorMessages[i]);           
                            item.appendChild(message);
                            list.appendChild(item);;
                        }  
}

The list is nothing more than an array of strings:

errors.errorMessages = [
{'Message 1'},
{'Message 2'}
]

This code works fine in Chrome and Firefox however in IE the new document is generated but the list is never appended to the selected Element. I can see the element generated but it will not add to the newly created document.

Internally the IE dev tools captures a generic message of Error: No such interface supported

I’ve seen other SO postings of similar problems but no solution that fits my scenario as I’m generating the html, and document at the same time vs working with an existing document.

Edit**: This code while standard js is written in typescript as part of an angular application. The TS is generated as ECMA3 and using either arrow functions or standard notation generates the same result.

I’d appreciate any suggestions or pointers on what I am missing.

Answer

To make it work in IE 11, you can follow Mirko Cianfarani’s suggestion: create the dynamic elements with the document object to which these elements will be appended. In your case, that is the document of the new report window, errorReportWindow.document. The report document should also be closed at the end.

var generateImportErrorReport = function(errors) {
  let doc = createHtmlErrorReport(errors);
  let errorReportWindow = window.open('', '_blank');
  let errorDoc = errorReportWindow.document; // Get the error report document object
  errorDoc.write(doc);
  let list = errorDoc.createElement('ul'); // Create with errorDoc
  // Builds a list of errors
  for (let i = 0; i < errors.errorMessages.length; i++) {
    let item = errorDoc.createElement('li'); // Create with errorDoc
    let message = errorDoc.createTextNode(errors.errorMessages[i]); // Create with errorDoc
    item.appendChild(message);
    list.appendChild(item);;
  }
  var errorList = errorDoc.getElementById('errorList');
  errorList.appendChild(list);
  errorDoc.close(); // Close the document
}

You can test the code in these two plunkers:

Categories
discuss

Android ndk r15b – Posix_memalign () undeclared identifier

I am new to Android project. For my new task I need to build a project for Android platform. I am able to generate make file successfully​ using cmakelists.txt for Android using Android ndk and it’s corresponding android.toolchain.cmake file. When I tried to run makefile. I am facing:

posix_memalign() undeclared identifier issue.

Here c and c++ compiler are clang which is default toolchain of Android ndk. I don’t know how to fix this issue. Please help me to fix this issue.

I am using Windows os. I generated msys makefile.

Answer

I have fixed this issue. stdlib is the header file needed for posix_memalign() function. Android ndk supports posix_memalign() function for the ANDROID API level above or equal to 16. By adding -DANDROID_NATIVE_API_LEVEL=16 in cmake option , I was able to fix this issue.

Path: /sysroot/usr/include/stdlib.h

#if __ANDROID_API__ >= 16

int posix_memalign(void** memptr, size_t alignment, size_t size)  __INTRODUCED_IN(16);

#endif /* __ANDROID_API__ >= 16 */

Thanks !!!!

Categories
discuss

Cant cancel Axios post request via CancelToken

This code cancel GET requests but cant abort POST calls.
If i send GET requests first and i dont cancel them via abortAll method,they just finish by themselves this token cancel by itself and doesnt work on next requests? What am i missing? Thanks,John

import axios from 'axios'
class RequestHandler {

 constructor(){
  this.cancelToken = axios.CancelToken;
  this.source = this.cancelToken.source();
 }

 get(url,callback){

  axios.get(url,{
   cancelToken:this.source.token,
  }).then(function(response){

        callback(response.data);

    }).catch(function(err){

        console.log(err);

    })

 }

post(url,callbackOnSuccess,callbackOnFail){
 axios.post(url,{

        cancelToken:this.source.token,

    }).then(function(response){

        callbackOnSuccess(response.data);

    }).catch(function(err){

        callbackOnFail()

    })
}

abortAll(){

 this.source.cancel();
    // regenerate cancelToken
 this.source = this.cancelToken.source();

}

}

Answer

I have found out that you can cancel post request this way,i missunderstand this documentation part. In previous code,i have passed cancelToken to the POST data request not as a axios setting.

import axios from 'axios'


var CancelToken = axios.CancelToken;
var cancel;

axios({
  method: 'post',
  url: '/test',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  cancelToken: new CancelToken(function executor(c) {
      // An executor function receives a cancel function as a parameter
      cancel = c;
    })
}).then(()=>console.log('success')).catch(function(err){

  if(axios.isCancel(err)){

    console.log('im canceled');

  }
  else{

    console.log('im server response error');

  }

});
// this cancel the request
cancel()
Categories
discuss

How to import Java packages in Kotlin Native

I’m trying to import Java package for use in Kotlin native as below;

/* main.kt */
import java.util.*

fun main(args: Array<String>) {
    print("Simple program")
}

and compile it with the below command

kotlinc main.kt -o main

I got the error message

main.kt:2:8: error: unresolved reference: java
import java.util.*

obviously I need to show kotlinc where to find java.util, how can I achieve this without using the command line? I’m on Windows 10 64 bit using Kotlin native 0.3.

Answer

You won’t have access to Java packages in Kotlin Native. The whole point of this project is to run Kotlin code without a VM, so you don’t have the Java Virtual Machine (or libraries) to use. You can, however, use native C libraries instead. You can find information about how this works here.

From the announcement post of the first preview of Kotlin/Native:

Note that we do not intend to make arbitrary Kotlin/JVM programs runnable on Kotlin/Native or Kotlin/JS. It would be equivalent to implementing another JVM, which is both a lot of work and a lot of limitations for the runtime. We are going another way: providing a common language for all platforms while enabling creation of common libraries through seamless interoperability with platform code.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..