Use MongoDB createIndex in Java

private MongoCollection<Document> createCollection(String collectionName) {
    String indexFieldName1 = "itemId";
    String indexFieldName2 = "time";
    MongoCollection<Document> mongoCollection = this.database.getCollection(collectionName);

    if (mongoCollection == null) {
        this.database.createCollection(collectionName);
        mongoCollection = this.database.getCollection(collectionName);
    }

    IndexOptions indexOptions1 = new IndexOptions().unique(false)
            .background(false).name(indexFieldName1);
    Bson keys1 = new Document(indexFieldName1, Integer.valueOf(1));
    mongoCollection.createIndex(keys1, indexOptions1);

    IndexOptions indexOptions2 = new IndexOptions().unique(false)
            .background(false).name(indexFieldName2);
    Bson keys2 = new Document(indexFieldName2, Integer.valueOf(1));
    mongoCollection.createIndex(keys2, indexOptions2);

    return mongoCollection;
}

References
https://www.programcreek.com/java-api-examples/?class=com.mongodb.client.MongoCollection&method=createIndex

Convert Joda-Time `DateTime` with timezone

DateTime dateTimePlus2 = DateTime.parse("2015-07-09T05:10:00+02:00");
System.out.println(dateTimePlus2);

DateTime dateTimeUTC = dateTimePlus2.withZone(DateTimeZone.UTC);
System.out.println(dateTimeUTC);

LocalDateTime localDateTimeUTC = dateTimeUTC.toLocalDateTime();
System.out.println(localDateTimeUTC);

References
https://stackoverflow.com/questions/27381626/convert-joda-time-datetime-with-timezone-to-datetime-without-timezone
https://stackoverflow.com/questions/23939576/how-to-specify-a-timezone-for-a-joda-datetime-object

Returning Image/Media Data with Spring

@RequestMapping(value = "/image-manual-response", method = RequestMethod.GET)
public void getImageAsByteArray(HttpServletResponse response) throws IOException {
    InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    IOUtils.copy(in, response.getOutputStream());
}

or

@GetMapping(
  value = "/get-image-with-media-type",
  produces = MediaType.IMAGE_JPEG_VALUE
)
public @ResponseBody byte[] getImageWithMediaType() throws IOException {
    InputStream in = getClass()
      .getResourceAsStream("/com/baeldung/produceimage/image.jpg");
    return IOUtils.toByteArray(in);
}

References
https://www.baeldung.com/spring-mvc-image-media-data
https://www.baeldung.com/spring-controller-return-image-file

Subjects in RxJava

  • PublishSubject
  • BehaviorSubject
  • AsyncSubject
  • ReplaySubject
  • UnicastSubject
  • SingleSubject

A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by re-emitting them, and it can also emit new items.

Publish Subject

It emits all the subsequent items of the source Observable at the time of subscription.

Here, if a student entered late into the classroom, he just wants to listen from that point of time when he entered the classroom.

PublishSubject<Integer> source = PublishSubject.create();

// It will get 1, 2, 3, 4 and onComplete
source.subscribe(getFirstObserver()); 

source.onNext(1);
source.onNext(2);
source.onNext(3);

// It will get 4 and onComplete for second observer also.
source.subscribe(getSecondObserver());

source.onNext(4);
source.onComplete();

Replay Subject

It emits all the items of the source Observable, regardless of when the subscriber subscribes.

Here, if a student entered late into the classroom, he wants to listen from the beginning.

ReplaySubject<Integer> source = ReplaySubject.create();
// It will get 1, 2, 3, 4
source.subscribe(getFirstObserver());
source.onNext(1);
source.onNext(2);
source.onNext(3);
source.onNext(4);
source.onComplete();
// It will also get 1, 2, 3, 4 as we have used replay Subject
source.subscribe(getSecondObserver());

Behavior Subject

It emits the most recently emitted item and all the subsequent items of the source Observable when an observer subscribes to it.

Here, if a student entered late into the classroom, he wants to listen the most recent things(not from the beginning) being taught by the professor so that he gets the idea of the context.

BehaviorSubject<Integer> source = BehaviorSubject.create();
// It will get 1, 2, 3, 4 and onComplete
source.subscribe(getFirstObserver());
source.onNext(1);
source.onNext(2);
source.onNext(3);
// It will get 3(last emitted)and 4(subsequent item) and onComplete
source.subscribe(getSecondObserver());
source.onNext(4);
source.onComplete();

Async Subject

It only emits the last value of the source Observable(and only the last value) only after that source Observable completes.

Here, if a student entered at any point of time into the classroom, and he wants to listen only about the last thing(and only the last thing) being taught, after class is over.

AsyncSubject<Integer> source = AsyncSubject.create();
// It will get only 4 and onComplete
source.subscribe(getFirstObserver());
source.onNext(1);
source.onNext(2);
source.onNext(3);
// It will also get only get 4 and onComplete
source.subscribe(getSecondObserver());
source.onNext(4);
source.onComplete();

References
http://reactivex.io/documentation/subject.html
https://blog.mindorks.com/understanding-rxjava-subject-publish-replay-behavior-and-async-subject-224d663d452f
https://www.journaldev.com/22573/rxjava-subject

Create Observable using empty method in RxJava

This type of source signals completion immediately upon subscription.

Observable<String> empty = Observable.empty();

empty.subscribe(new DefaultObserver<String>() {
    @Override
    public void onNext(String s) {
        System.out.println("This should never be printed!");
    }

    @Override
    public void onError(Throwable e) {
        System.out.println("Or this!");
    }

    @Override
    public void onComplete() {
        System.out.println("Done will be printed.");
    }
});

References
https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#empty