Tomcat add subdomain virtual host

Is there any way how to make a subdomain virtual host on Tomcat (v 8.0.30)?

This works fine so far:

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
</Host>

<Host name="somedomain.com" appBase="webapps2"
            unapckWARs="true" autoDeploy="true">
</Host>

But if I tried to add subdomain it redirects to default one:

<Engine name="Catalina" defaultHost="localhost">

<Host name="sub.somedomain.com" appBase="webapps3"
            unapckWARs="true" autoDeploy="true">
</Host>

what is current subject in Shiro?

I’m new to Shiro and got confused about the current subject concept:

Subject subject = SecurityUtils.getSubject(); // gets the current subject
subject.login(...); // do login
subject.logout(); // do logout

In my application I need to run work from different users concurrently, thus multiple users(subjects) co-exist concurrently, new users login and old users logout on the fly: clients sends work with [username, password] to server, the server do credential check by Shiro with the given [username, password], if [username, password] not exist in database, reject the work, if exist, login and dispatch the work to be processed, in the meanwhile other clients sends their work and login, my question is in a later time when the work for a user is done and I need to logout out the user, how do I get the subject for it?

Java + Operator

I am unable to grasp the idea of either addition operator or short data-type.

It’s said that;

short a = 1;
short b = 2;
short c = a + b;

which will not compile because addition operator always cast short, chart, byte data-types to int and I understand this. But this;

short c = 1 + 2;

works totally fine. So, if addition operator auto converts short to int and then apply the result (where result ofcourse will be an int), why this works fine?

uploading multiple images in a WebVew Using API level below 21

I’m currently converting a website into android application using WebView. One of the requirement in the app is to upload 4-8 images from gallery. I have successfully managed to upload this images in Lollipop and above version of android but i’m stuck in Kitkat and below. I have managed to upload one image in kitkat but the other images are not being uploaded. The Minimum Api level for my app is 18.

here is the main variables used for image uploading:

private WebView browser;

private ValueCallback<Uri[]> uploadedMsgLollipop;
private ValueCallback<Uri> uploadedMsg;

private int  RESULT_CODE_ABOVE_LOLLIPOP = 1;
private int  RESULT_CODE_BELOW_LOLLIPOP = 2;

here is the code i have used WebChromeClient:

    browser.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            uploadedMsgLollipop = filePathCallback; 
            Intent intent = new Intent(); 
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);


            startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_CODE_ABOVE_LOLLIPOP);


            return true;
        }

        void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {

            uploadedMsg = uploadMsg;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            i.setType("image/*");

            Intent chooserIntent = Intent.createChooser(i, "Image Chooser");

            startActivityForResult(chooserIntent, RESULT_CODE_BELOW_LOLLIPOP);
        }


        // openFileChooser for Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        //openFileChooser for other Android versions
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }


    });

here is the code for onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    ClipData clipData = data.getClipData();

    if (clipData != null) {


        Uri[] resultsArray = new Uri[clipData.getItemCount()];

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == RESULT_CODE_ABOVE_LOLLIPOP) {

                if (null == uploadedMsgLollipop) {
                    return;
                }

                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    Uri uri = item.getUri();
                    resultsArray[i] = uri;
                }
                uploadedMsgLollipop.onReceiveValue(resultsArray);

                uploadedMsgLollipop = null;
            }

            if (requestCode == RESULT_CODE_BELOW_LOLLIPOP) {
                if (uploadedMsg == null) {
                    return;
                }
                for (int i = 0; i < clipData.getItemCount(); i++) {

                    ClipData.Item item = clipData.getItemAt(i);

                    Uri uri = item.getUri();

                    uploadedMsg.onReceiveValue(uri);
                }

                uploadedMsg = null;

            }

        }
    } else {
        if (requestCode == RESULT_CODE_BELOW_LOLLIPOP) {
            if (uploadedMsg == null) {
                return;
            }

            uploadedMsg.onReceiveValue(data.getData());
            uploadedMsg = null;
        }
    }
}

Exception Mapping in Restful Spring boot application

I have a custom Exception class which I want to return as a json when an exception occurs.

SpringCacheException.java

@JsonSerialize
public class SpringCacheException extends Exception{
    private static final long serialVersionUID = 1L;
    private HttpStatus status;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    private LocalDateTime timestamp;
    private String message;
    private String debugMessage;
    public SpringCacheException(HttpStatus status, String message, String debugMessage) {
        super();
        this.setStatus(status);
        this.message = message;
        this.debugMessage = debugMessage;
    }
    public SpringCacheException() {
        timestamp = LocalDateTime.now();
    }

    public SpringCacheException(HttpStatus status) {
        this();
        this.setStatus(status);
    }

    public SpringCacheException(HttpStatus status, Throwable ex) {
        this();
        this.setStatus(status);
        this.setMessage("Unexpected error");
        this.setDebugMessage(ex.getLocalizedMessage());
    }

    public SpringCacheException(HttpStatus status, String message, Throwable ex) {
        this();
        this.setStatus(status);
        this.setMessage(message);
        this.setDebugMessage(ex.getLocalizedMessage());
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getDebugMessage() {
        return debugMessage;
    }

    public void setDebugMessage(String debugMessage) {
        this.debugMessage = debugMessage;
    }
    public HttpStatus getStatus() {
        return status;
    }
    public void setStatus(HttpStatus status) {
        this.status = status;
    }
}

RestExceptionHandler.java

 @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {
        private static final Logger logger= LoggerFactory.getLogger(ContactServiceImpl.class);

         @Override
            protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
                SpringCacheException errorMessage = new SpringCacheException(status.BAD_REQUEST,"My Error",ex);
                return new ResponseEntity<Object>(errorMessage, headers, status);
            }

@ExceptionHandler(SpringCacheException.class)
        ResponseEntity<Object> handleBadRequests(HttpStatus status,String message,SpringCacheException ex) throws IOException  {
            SpringCacheException errorMessage = new SpringCacheException(HttpStatus.BAD_REQUEST,"My Error",ex);
            return new ResponseEntity<Object>(errorMessage,HttpStatus.BAD_REQUEST);
        }
    }

Exception thrown:-

@Override
    public Contact show(int id) throws SpringCacheException  {
        try {
            Contact contact = contactRepository.findOneById(id);
            return contact;
        }
        catch (Exception e) {
            throw new SpringCacheException();
        }
    }

Here I am deleting the contact table from the DB and the exception is thrown and I am getting the below long response.

     Position: 111
2017-10-22 00:37:08.577  WARN 10336 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failed to invoke @ExceptionHandler method: org.springframework.http.ResponseEntity<java.lang.Object> com.myapp.exception.RestExceptionHandler.handleBadRequests(org.springframework.http.HttpStatus,java.lang.String,com.myapp.exception.SpringCacheException) throws java.io.IOException

I just want a son of type SpringCacheException but I am getting this long json with incorrect data. Can any one tell me where I am doing wrong. Thanks !

The Entire code can be found at – https://github.com/iftekharkhan09/SpringCaching

SCrypt – Store and Encrypt

I’am using scrypt (Spongy Castle) for my android application.

I need to store the password for application login and use this password for data encryption. If I store now the scrypt output, I would store the plain password for encryption.

So this is what I am doing:

1.

  • password_scrypt = scrypt(password, salt1) [generate 32 bytes]
  • Store this password with sha3-512(password_scrypt, salt2).
  • Using the password_scrypt for encryption.
  • (Btw is using different salts necessary?)

This is what I thought about:

2.

  • password_scrypt = scrypt(password, salt1) [generate 64 bytes]
  • Store first 32 bytes for password verificaton
  • Use the other 32 bytes for encryption

In fact I can’t find anything about the correct way. Is there a common concept about this issue?

Kotlin error when converting from Java code

I have an ArraysHelper class which looks like this in Java:

public class ArraysHelper<T> {

public final Iterable<T> iterable;

private ArraysHelper(Iterable<T> iterable) {
    this.iterable = iterable;
}

public static <T> T[] concat(T[] array, @Nullable T element) {
    T[] result = Arrays.copyOf(array, array.length + 1);
    result[array.length] = element;
    return result;
}

public final ArraysHelper<T> filter(Prediction<T> prediction) {
    return from(filter(iterable, prediction));
}

private static <T> List<T> filter(Iterable<T> iterable, Prediction<T> predicate) {
    ArrayList<T> list = new ArrayList<>();
    for (T object : iterable) {
        if (predicate.apply(object)) {
            list.add(object);
        }
    }

    return list;
}

public final List<T> toList() {
    List<T> list = new ArrayList<>();
    for (T item : iterable) {
        list.add(item);
    }
    return list;
}

public static <T> ArraysHelper<T> from(final Iterable<T> iterable) {
    return new ArraysHelper<>(iterable);
    }
}

I converted it to Kotlin like this:

class ArraysHelper<T> private constructor(val iterable: Iterable<T>) {

fun filter(prediction: Prediction<T>): ArraysHelper<T> {
    return from(filter(iterable, prediction))
}

fun toList(): ArrayList<T> {
    val list = ArrayList<T>()
    for (item in iterable) {
        list.add(item)
    }
    return list
}

companion object {

    fun <T> concat(array: Array<T>, element: T?): Array<T> {
        val result = Arrays.copyOf(array, array.size + 1)
        result[array.size] = element
        return result
    }

    private fun <T> filter(iterable: Iterable<T>, predicate: Prediction<T>): ArrayList<T> {
        val list = ArrayList<T>()
        for (`object` in iterable) {
            if (predicate.apply(`object`)) {
                list.add(`object`)
            }
        }

        return list
    }


    fun <T> from(iterable: Iterable<T>): ArraysHelper<T> {
        return ArraysHelper(iterable)
    }
  }
}

I am also converted one interface which i am using. In java:

public interface Prediction<T> {

boolean apply(@Nullable T input);

@Override
boolean equals(@Nullable Object object);

}

In Kotlin:

interface Prediction<T> {

fun apply(input: T?): Boolean

override fun equals(`object`: Any?): Boolean
}

Now to the point – I want to use those here:

 val cleanedGeoEvents = ArraysHelper.from<LocationGeoEvent>(locationGeoEvents).filter(object : Prediction<LocationGeoEvent> {
            override fun apply(input: LocationGeoEvent): Boolean {
                return Math.abs(input.timestamp - latestRSSIEvent.timestamp) < maxTimeDifferenceSeconds * 1000
            }
        }).toList()

But in IDE(Android Studio 3.0) underlines the filter method:

object : Prediction<LocationGeoEvent>

and it says:

Required: Prediction LocationGeoEvent Found:

So what exatcly is wrong with it?

gradle: Java API for JSON Processing (JSR 374)

How are the dependencies for JSON Processing, JSR 374, handled from gradle? Working examples would be greatly appreciated.

context: below is what I have with maven; looking to migrate this to gradle.

build is ok, even if there are duplicates:

thufir@dur:~/NetBeansProjects/HelloJsonMaven$ 
thufir@dur:~/NetBeansProjects/HelloJsonMaven$ mvn clean package
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building HelloJsonMaven 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ HelloJsonMaven ---
[INFO] Deleting /home/thufir/NetBeansProjects/HelloJsonMaven/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ HelloJsonMaven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 3 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ HelloJsonMaven ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /home/thufir/NetBeansProjects/HelloJsonMaven/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ HelloJsonMaven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/thufir/NetBeansProjects/HelloJsonMaven/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ HelloJsonMaven ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ HelloJsonMaven ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ HelloJsonMaven ---
[INFO] Building jar: /home/thufir/NetBeansProjects/HelloJsonMaven/target/HelloJsonMaven-1.0-SNAPSHOT.jar
[INFO] 
[INFO] --- maven-shade-plugin:3.1.0:shade (default) @ HelloJsonMaven ---
[INFO] Including javax.json:javax.json-api:jar:1.1 in the shaded jar.
[INFO] Including org.glassfish:javax.json:jar:1.0.4 in the shaded jar.
[WARNING] Discovered module-info.class. Shading will break its strong encapsulation.
[WARNING] javax.json-1.0.4.jar, javax.json-api-1.1.jar define 25 overlapping classes: 
[WARNING]   - javax.json.stream.JsonParser
[WARNING]   - javax.json.stream.JsonParserFactory
[WARNING]   - javax.json.JsonString
[WARNING]   - javax.json.JsonValue
[WARNING]   - javax.json.stream.JsonLocation
[WARNING]   - javax.json.Json
[WARNING]   - javax.json.stream.JsonParsingException
[WARNING]   - javax.json.stream.JsonParser$Event
[WARNING]   - javax.json.JsonWriter
[WARNING]   - javax.json.JsonValue$ValueType
[WARNING]   - 15 more...
[WARNING] maven-shade-plugin has detected that some class files are
[WARNING] present in two or more JARs. When this happens, only one
[WARNING] single version of the class is copied to the uber jar.
[WARNING] Usually this is not harmful and you can skip these warnings,
[WARNING] otherwise try to manually exclude artifacts based on
[WARNING] mvn dependency:tree -Ddetail=true and the above output.
[WARNING] See http://maven.apache.org/plugins/maven-shade-plugin/
[INFO] Replacing original artifact with shaded artifact.
[INFO] Replacing /home/thufir/NetBeansProjects/HelloJsonMaven/target/HelloJsonMaven-1.0-SNAPSHOT.jar with /home/thufir/NetBeansProjects/HelloJsonMaven/target/HelloJsonMaven-1.0-SNAPSHOT-shaded.jar
[INFO] Dependency-reduced POM written at: /home/thufir/NetBeansProjects/HelloJsonMaven/dependency-reduced-pom.xml
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.616 s
[INFO] Finished at: 2017-10-21T12:15:07-07:00
[INFO] Final Memory: 18M/61M
[INFO] ------------------------------------------------------------------------
thufir@dur:~/NetBeansProjects/HelloJsonMaven$ 
thufir@dur:~/NetBeansProjects/HelloJsonMaven$ 

and the JAR actually runs:

thufir@dur:~/NetBeansProjects/HelloJsonMaven$ 
thufir@dur:~/NetBeansProjects/HelloJsonMaven$ java -jar target/HelloJsonMaven-1.0-SNAPSHOT.jar 
Oct 21, 2017 12:15:19 PM net.bounceme.dur.hello_json_maven.Main props
INFO: {foo=bar}
Oct 21, 2017 12:15:20 PM net.bounceme.dur.hello_json_maven.JsonOperations createJsonObject
INFO: creating..
Oct 21, 2017 12:15:20 PM net.bounceme.dur.hello_json_maven.Main json
INFO: {"name":"Falco","age":3,"biteable":false}
thufir@dur:~/NetBeansProjects/HelloJsonMaven$ 

sample code:

package net.bounceme.dur.hello_json_maven;

import java.math.BigDecimal;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObject;

public class JsonOperations {

    private static final Logger log = Logger.getLogger(JsonOperations.class.getName());

    public void loadJsonFromFile(String jsonFileName) {
        log.info(jsonFileName);
    }

    public JsonObject createJsonObject() {
        // Create Json and serialize
        log.info("creating..");
        JsonObject json = Json.createObjectBuilder()
                .add("name", "Falco")
                .add("age", BigDecimal.valueOf(3))
                .add("biteable", Boolean.FALSE).build();
        String result = json.toString();
        log.fine(json.toString());
        return json;
    }

}

Having been down this road before, seems prudent to ask before going too far down any false paths.