Interface with general or special methods?

At the moment I need to save four types of files, movie pictures, movie posters, movie trailers, and user avatars. I want to put photos and posters in the images folder, avatars I want to put in the avatars folder, and trailers in the trailers folder.

My current interface looks like this

public interface StorageService {
    String save (
            final File file,
            final String contentType
    ) throws IOException;
...
}

to customize the save method to place different files I wonder which way to use.

The first way is to add a new parameter String folder

 public interface StorageService {
    String save (
            final File file,
            final String contentType,
            final String folder
    ) throws IOException;
...
}

and in the variable folder, enter the name of the folder to which the file will be added.

The second way is to create three separate methods

public interface StorageService {
    String saveImage (
            final File file,
            final String contentType
    ) throws IOException;
    String saveAvatar (
            final File file,
            final String contentType
    ) throws IOException;
    String saveTrailer (
            final File file,
            final String contentType
    ) throws IOException;
...
}

What do you think? Which idea is better?

what deos new () instruction deos

i came across this code

public class b {

private String msg = null;
static private int n;

b() {
    n = 1;
    if (msg == null)
        msg = "Rouge";
    affiche();
}

private void affiche() {
    System.out.println(n + msg);
    if (!msg.equals("Vert")) {
        msg = "Vert";
    new b();
    }
}

public static void main(String[] args) {
    b x = new b();
    n++;
    x.affiche();
    b y = new b();
    n++;
    x.affiche();
    y.affiche();
}}

first time i run it with msg being static and it worked normaly and i thought

new b();

which is inside the methode affiche was just calling the constructor
and then i tried running it after removing static of msg but it didn’t work it writes 1Rouge like a hundred time and i didn’t understand iis that an infinte loop or what and it also writes Exception in thread "main" java.lang.StackOverflowError
i just want to know what

new b();

exactly does ?

Modeling many-to-many relationships in mongodb using embedded documents to achieve better search performance

Background:

I am trying to model a many-to-many relationship using the embedded document model.

The reason behind choosing mongodb is because the schema is dynamic as the platform deals with various products and services.

The application when logged in by an user bootstraps all the information of a user. But, all the queries such as update,search are majorly done on the products and services associated with users on the platform.

Problem Statement:

@Getter
@Setter
@ToString(exclude = { "id", "password" })
@Document(collection = "users")
public class User implements Serializable {

    @Id
    private ObjectId id;
    @Indexed(unique = true)
    private String username;
    private String password;
    private String email;
    private String mobile;
    private Sex sex;
    private List<String> tags;

}

public class Product {

    @Id
    private String id;
    private String name;
    private double price;
    private List<User> users;
}

public class Service{

    @Id
    private String id;
    private String name;
    private double price;
    private List<User> users;
}

Initially i thought of making users as embedded documents within products and services. The reason behind choosing the embedded document design is to avoid multiple queries during the search.

But, I also realized that when a user logs in to the application i need to have all the user related information which needs to be bootstrapped. The design seems to be getting complicated.

I would like to understand if this scenario could be handled in a better way. Anyone who has already solved this situation?

Run JAR which will trigger Chrome driver from PHP

I have written a JAVA program which will trigger Chrome driver and open google.com the program works fine in eclipse so I created a JAR file.
Even the JAR file is working fine independently. It will open google.com in google chrome then its closing the chrome driver.
But I am trying to trigger this JAR through PHP now for some reason this is not working.

The PHP is not triggering the JAR file at all.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Chrome_Test {

    public static void main(String[] args) {
        // Telling the system where to find the Chrome driver
        System.getProperty("user.dir" + "\chromedriver.exe");
        WebDriver webDriver = new ChromeDriver();
        // Open google.com
        webDriver.navigate().to("http://www.google.com");
        // Printing result here.
        WebDriverWait wait = new WebDriverWait(webDriver, 10);
        webDriver.close();
        webDriver.quit();

    }

}

Android library missing dependency appcompat

I’m writing a library(module) in android studio 3.0 with gradle 4.1 minsdk version is 21 target is 26. My problem is that my module(.jar file) doesn’t contain appcomat dependency (I opened the jar file it isnt there I also tried retrofit2 same result). I’ve tried with implementation and with compile. I’m building a Unity plugin btw. The module works fine if I call basic methods (return a number, screen density etc).

Change a java string to date

Well I tried to look for many questions but couldn’t find something relevant. I have a string that has the following data:

String sDate = "2018-01-17 00:00:00";

This comes from an application and I need to convert it into a Date format that results

17-01-2018

I went through this link but could not relate.

Can someone help..?

Is it possible to store a string using sun.misc.Unsafe from a class and retrieve it from another class?

Hi I am storing a string using sun.misc.Unsafe using following code:

package com.util.OffHeapStorage;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class OffHeapStorage {
    static Unsafe unsafe = getUnsafe();

    static Unsafe getUnsafe() {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (Unsafe) f.get(null);
        } catch (Exception x) {
            x.printStackTrace();
        }

        return null;
    }

    static long storeString(String str){
        long bytes = 2;
        long startAddress = unsafe.allocateMemory(bytes);
        int strlength = str.length();

        for(long i=0;i<strlength;i++){
            char ch = str.charAt((int)i);
            unsafe.putChar(startAddress + i*2, ch);
            System.out.println("Stored "+ch+" to address "+(startAddress+i*2));
        }

        return startAddress;
    }

    static String fetchString(long startAddress, int strlength){
        StringBuilder strOut = new StringBuilder();

        for(long i = startAddress; i < startAddress + strlength * 2; i += 2 ){
            strOut.append(unsafe.getChar(i));
        }

        return strOut.toString();
    }

    static void freeStringMemory(long startAddress, int strlength ){
        for(long i = startAddress; i < startAddress + strlength * 2; i += 2 ){
            unsafe.freeMemory(i);
        }
    }


    public static void main(String [] args){
        String message = "Hello World";

        long stringAddress = storeString(message);
        System.out.println(fetchString(stringAddress, message.length()));
        //freeStringMemory(stringAddress, message.length());
    }


}

As you can see I am not freeing the memory.

Output of this code will tell me the start-address of the string that was stored which I want to check if I will be able to use in an another class to obtain the string value.

So my other class looks like:

public static void main(String [] args){
        String message = "Hello World";

        long stringAddress = 413100824;
        System.out.println(fetchString(stringAddress, message.length()));
        freeStringMemory(stringAddress, message.length());
    }

However on executing this class I get this error:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6ce8d1b3, pid=11624, tid=0x000025c0
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) Client VM (25.131-b11 mixed mode windows-x86 )
# Problematic frame:
# V  [jvm.dll+0x13d1b3]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:localeclipseworkspaceOffHeapStoragehs_err_pid11624.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#

I’ve just tried Java Unsafe and maybe I got the whole concept wrong. In-essence I am trying to check if I can store data in OS memory and not burden my JVM.

Any help would be very appreciated.

SpringSecurity select authentication provider by prefix

I have a Spring REST-API which is secured by SpringSecurity.

I have different ways to authenticate in that application.

  • Customer (db)
  • Employees (ldap)
  • Other Applications/Services (inMemory)

Each of these are covered by a different authentication provider, which properly assigns the access roles. (Works)

However I need to know which authentication provider was used to authenticate the user, so I can write it to the logs, history…

User CUSTOMER/max.pain created a new entry.

I considered adding a special role based on the authentication provider used, but extracting that information over and over is annoying and probably has bad performance and might cause problems in the future. (user.getGrantedAuthorities().findStartingWith("AP_"))

I also tried using org.springframework.security.config.annotation.SecurityConfigurerAdapter.addObjectPostProcessor(ObjectPostProcessor<?>) but i cannot use it to wrap the AuthenticationProvider with a custom AuthenticationProvider class, because it requires the use the same class for whatever reason.

Is there an inbuild method I could use to achieve that or do I have to use a custom implementation/configuration?


Prozess steps:

  1. Login: EMPLOYEE/always.calm
  2. Don’t check CUSTOMER AuthenticationProvider
  3. Check EMPLOYEE AuthenticationProvider
  4. Don’t check SERVICE AuthenticationProvider
  5. authentication.getPrincipal().getAP() = EMPLOYEE