Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 5 July 2022

File upload test

 Path to test resources

java.nio.file.Path;=

Path resourceDirectory = Paths.get("src", "test", "resources");

String filePath = resourceDirectory.toFile().getAbsolutePath();

File f = new File(absolutePath);

File[] list = f.listFiles();


InputStream targetStream = new FileInputStream(list[0]);


MockMultipartFile file = new MockMultipartFile("file", "sampletest.xml", MediaType.TEXT_PLAIN_VALUE,

targetStream);


MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

mockMvc.perform(multipart("/uploadFile").file(file).param("filePath", absolutePath)).andExpect(status().isOk());

Monday, 29 November 2021

Print Zero,Even,Odd numbers in this order(0,1,0,2,0,3,0,4...).Threads started at the same time



import java.util.concurrent.Semaphore;

import java.util.function.IntConsumer;


public class ZeroEvenOdd {


private int n, lastPrinted;

private Semaphore oddSem;

private Semaphore zeroSem;

private Semaphore evenSem;


public ZeroEvenOdd(int n) {

this.n = n;

this.lastPrinted = 0;

this.zeroSem = new Semaphore(1);

this.oddSem = new Semaphore(1);

this.evenSem = new Semaphore(1);


try {

this.evenSem.acquire();

this.oddSem.acquire();

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

}


public void zero(IntConsumer printNumber) throws InterruptedException {


int numZeros = n;

while (numZeros-- > 0) {

this.zeroSem.acquire();

printNumber.accept(0);

if (lastPrinted % 2 == 0) {

this.oddSem.release();

} else {

this.evenSem.release();

}

}

}


public void even(IntConsumer printNumber) throws InterruptedException {


int numeven = n / 2;

while (numeven-- > 0) {

this.evenSem.acquire();

printNumber.accept(++lastPrinted);

this.zeroSem.release();

}


}


public void odd(IntConsumer printNumber) throws InterruptedException {

int numOdd = n - n / 2;

while (numOdd-- > 0) {

this.oddSem.acquire();

printNumber.accept(++lastPrinted);

this.zeroSem.release();

}


}


public static void main(String[] args) {

ZeroEvenOdd print = new ZeroEvenOdd(5);

Thread thread = new Thread() {

public void run() {

System.out.println("Thread Running");

IntConsumer ic = (x) -> System.out.println(x);

try {

print.zero(ic);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

Thread thread2 = new Thread() {

public void run() {

System.out.println("Thread Running");

IntConsumer ic = (x) -> System.out.println(x +"\t");

try {

print.odd(ic);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

Thread thread3 = new Thread() {

public void run() {

System.out.println("Thread Running");

IntConsumer ic = (x) -> System.out.println(x);

try {

print.even(ic);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

thread.start();

thread2.start();

thread3.start();


}

}


Three threads started at the same time .Priniting Order should be maintained , it should always print first,second,third

 package printorder;


import java.util.concurrent.Semaphore;

import java.util.function.IntConsumer;


public class PrintOrder {


private Semaphore first;

private Semaphore second;

private Semaphore third;


public PrintOrder() {

this.first = new Semaphore(1);

this.second = new Semaphore(1);

this.third = new Semaphore(1);


try {

this.second.acquire();

this.third.acquire();

} catch (InterruptedException e) {

e.printStackTrace();

}


}


public void first() throws InterruptedException {

this.first.acquire();

print("first");


this.second.release();

}


private void print(String string) {

System.out.println("Print order :" + string);


}


public void second() throws InterruptedException {

this.second.acquire();

print("second");


this.third.release();

}


public void third() throws InterruptedException {

this.third.acquire();

print("third");


this.first.release();

}


public static void main(String[] args) {


PrintOrder order = new PrintOrder();

Thread t1 = new Thread() {

public void run() {

System.out.println("Thread Running t1 "+Thread.currentThread().getName());

try {


order.third();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

Thread t2 = new Thread() {

public void run() {

System.out.println("Thread Running t2 "+Thread.currentThread().getName());

try {


order.second();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

Thread t3 = new Thread() {

public void run() {

System.out.println("Thread Running t3 "+Thread.currentThread().getName());

try {


order.first();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};


t1.start();

t2.start();

t3.start();


}


}


Tuesday, 6 October 2020

Java Map Notes , Immutable objects and its importance,Strategy pattern

 HashMap allows null as a key and so hashcode for this will always be zero , even empty string can be given as a key and it also hols the hash code zero but internally they  are stored in different indexes


Concurrent hashmap does not allow null as a key , Hash table also does not allow null key

Some sample example below


Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo

INFO: HashMap: {NEVADA=Carson City, WASHINGTON=Olympia, NORTH_DAKOTA=Bismark, MONTANA=null, ARIZONA=Phoenix, UTAH=Salt Lake City, OREGON=Salem, COLORADO=Denver, SOUTH_DAKOTA=Pierre, IDAHO=Boise, NEW_MEXICO=Sante Fe, CALIFORNIA=Sacramento, WYOMING=Cheyenne}

Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains

INFO: 

Map of type java.util.HashMap returns null for Map.get() using Montana

Map of type java.util.HashMap returns true for Map.containsKey() using Montana

Map of type java.util.HashMap returns null for Map.get() using Kansas

Map of type java.util.HashMap returns false for Map.containsKey() using Kansas


Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo

INFO: LinkedHashMap: {ARIZONA=Phoenix, CALIFORNIA=Sacramento, COLORADO=Denver, IDAHO=Boise, NEVADA=Carson City, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, OREGON=Salem, SOUTH_DAKOTA=Pierre, UTAH=Salt Lake City, WASHINGTON=Olympia, WYOMING=Cheyenne, MONTANA=null}

Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains

INFO: 

Map of type java.util.LinkedHashMap returns null for Map.get() using Montana

Map of type java.util.LinkedHashMap returns true for Map.containsKey() using Montana

Map of type java.util.LinkedHashMap returns null for Map.get() using Kansas

Map of type java.util.LinkedHashMap returns false for Map.containsKey() using Kansas


Oct 06, 2020 12:39:06 PM MapContainsGet generateStatesMap

SEVERE: java.util.concurrent.ConcurrentHashMap does not allow for null values - java.lang.NullPointerException

Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo

INFO: ConcurrentHashMap: {NEVADA=Carson City, WASHINGTON=Olympia, NORTH_DAKOTA=Bismark, ARIZONA=Phoenix, UTAH=Salt Lake City, OREGON=Salem, COLORADO=Denver, SOUTH_DAKOTA=Pierre, IDAHO=Boise, NEW_MEXICO=Sante Fe, CALIFORNIA=Sacramento, WYOMING=Cheyenne}

Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains

INFO: 

Map of type java.util.concurrent.ConcurrentHashMap returns null for Map.get() using Montana

Map of type java.util.concurrent.ConcurrentHashMap returns false for Map.containsKey() using Montana

Map of type java.util.concurrent.ConcurrentHashMap returns null for Map.get() using Kansas

Map of type java.util.concurrent.ConcurrentHashMap returns false for Map.containsKey() using Kansas


Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo

INFO: EnumMap: {ARIZONA=Phoenix, CALIFORNIA=Sacramento, COLORADO=Denver, IDAHO=Boise, MONTANA=null, NEVADA=Carson City, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, OREGON=Salem, SOUTH_DAKOTA=Pierre, UTAH=Salt Lake City, WASHINGTON=Olympia, WYOMING=Cheyenne}

Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains

INFO: 

Map of type java.util.EnumMap returns null for Map.get() using Montana

Map of type java.util.EnumMap returns true for Map.containsKey() using Montana

Map of type java.util.EnumMap returns null for Map.get() using Kansas

Map of type java.util.EnumMap returns false for Map.containsKey() using Kansas



Best link to read

https://www.devdiaries.net/blog/Java-Recruitment-Questions-HashCode/



Immutable objects are a very important element of application building, which makes applications more legible and consistent, as well as more error-proof. Every developer should know how to use immutable objects and what benefits are associated with their use.


Writing this post I didn’t think about the disadvantages of creating immutable classes. Fortunately, a user potracheno informed about it in the comment. Thanks!

Immutable objects have far more advantages than disadvantages. The only thing that comes to my mind is the cost of memory. With immutability, any time you need to modify data, you need to create a new object. This can be expensive. If you are sure that you will not need immutability (e.g. you are creating a simple single-threaded application) - do not create immutable code.


Advantages of immutable objects

These objects make us avoid accidental changes, often in very inappropriate places. If an object is changeable, there will definitely be someone who wants to change it where it should not.

A good example of such a situation is the object that we pass as a parameter of the method. Such an object can be passed between multiple application layers, between multiple method calls. It can be passed on very deep in the call hierarchy. This makes it very difficult to identify where it was changed. This can lead to many strange and difficult to solve problems.

Using immutable objects we do not have such problems and the design of our application improves.

Invariant objects are also safe for multithreaded use. If an object is not changed, it can be safely transferred between threads without synchronization.

Another advantage is that such objects are ideal as key objects in maps. In a situation where keys are variable, after changing the key object its hashcode changes, making it impossible to find the stored value in HashMap.


How to create immutable objects?

Such objects can be created in three ways. Through the constructor and that is the easiest way. But it has a fundamental disadvantage. The more fields to initiate, the more parameters in the constructor. That’s why you shouldn’t create objects that have more than 2-3 fields.

          
public final class Animal {

    private final String name;
    private final String ownerName;

    public Animal(String name, String ownerName) {
        this.name = name;
        this.ownerName = ownerName;
    }

    public String getName() {
        return name;
    }

    public String getOwnerName() {
        return ownerName;
    }
}

// Creation
Animal animal = new Animal("Tina", "John");

Another way is the factory method. As with the constructor, the more fields, the more parameters. But this approach has such an advantage that we can create several such methods with a different names, with different set of parameters, which improves readability.

A third way to create immutable objects is to use the builder pattern. In order to use the builder, it must be implemented inside the class so that it has access to private class fields.

          
public final class User {
    private int age;
    private String firstName;
    private String lastName;

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private User user = new User();

        public Builder firstName(String firstName) {
            user.firstName = firstName;
            return this;
        }

        public Builder lastName(String lastName) {
            user.lastName = lastName;
            return this;
        }

        public Builder age(int age) {
            user.age = age;
            return this;
        }

        public User build(){
            return user;
        }
    }

// Creation
 User user = User.builder()
                .firstName("John")
                .lastName("People")
                .age(45)
                .build();

We can write such a builder manually or use some kind of IDE plugin to generate it for us. Another option is to use Lombok and @Builder annotation.


What is an immutable object?

An immutable object is one which, after being created and initialized, remains unchanged and, importantly, cannot be changed (in a conventional way, of course). This means that such an object does not provide methods that allow changing its state. And all its fields are private (or public final).

This changeability is a little apparent, because, using reflection, you can change the field values in each class. However, this does not mean that for this reason, we should give up immutable objects.

How to ensure the object’s immutability?

Apart from the fact that all fields should be private, they should be final. And the class itself should be marked as final so that it cannot be inherited. Such an object should not provide methods to modify its internal state, e.g. setters.

But private, final fields are not everything. It is important what types of data we store in these fields. It should also be unchangeable! If the fields in your object are primitives, primitive wrappers or Strings then there is no problem. All these types are immutable. But if you use your own objects, you must ensure that they are unchangeable.


https://www.devdiaries.net/blog/Java-Recruitment-Questions-Immutable-Objects/



Strategy defines a family of interchangeable algorithms (in the form of classes) that are used to solve the same problem in several different ways.


Number converter with the strategy pattern

Imagine that you want to create a system to convert numbers into different Numeral Systems .
As in the previous example, we will start with the interface:

      
public interface ConvertingStrategy {  
    String convert(int number);  
}  

Time for implementation. We will add support to convert number to octal, binary and hex system:

      
public class BinaryConverter implements ConvertingStrategy {  
    public String convert(int number) {  
        return Integer.toBinaryString(number);  
    }  
}  
  
public class HexaConverter implements ConvertingStrategy {  
    public String convert(int number) {  
        return Integer.toHexString(number);  
    }  
}  
  
public class OctaConverter implements ConvertingStrategy {  
    public String convert(int number) {  
        return Integer.toOctalString(number);  
    }  
}  

According to the diagram at the beginning of the post - we will create a class Context that will use our strategies:

      
public class Context {
    private ConvertingStrategy strategy;

    public Context(ConvertingStrategy strategy) {
        this.strategy = strategy;
    }

    public String convert(int number) {
        return strategy.convert(number);
    }
}

An example of how to use a strategy to convert:

      
public class Main {  
    public static void main(String[] args) {  
        Context ctx = new Context(new HexaConverter());  
        System.out.println(ctx.convert(1000));  
//      Result: 3e8  
//      If you change HexaConverter to BinaryConverter, the result will be: 1111101000  
    }  
}  

https://www.devdiaries.net/blog/Java-Strategy-Design-Pattern-By-Examples/

https://www.devdiaries.net/blog/Java-Interview-Questions-Multithreading/

https://www.devdiaries.net/blog/10-Object-oriented-design-principles-everythone-should-know/

Best Practises while using Collections
----------------------------------------

Always use interface type as a reference type.

Always use interface type as a return type

Always use Interface Types as a method argument

Use generic type and diamond operator

You can declare a collection of a generic type like this:
List<Employee> listEmployees = new ArrayList<Employee>();
Since Java 7, the compiler can infer the generic type on the right side from the generic type declared on the left side, so you can write:
List<Employee> listEmployees = new ArrayList<>();

 Prefer isEmpty() over a size()


Return empty collections or arrays, not nulls

Do not use the classic for loop.Use ForEach Loop which uses iterator behind the screen

Overriding equals() and hashCode() properly


Using Arrays and Collections utility classes


Prefer concurrent collections over synchronized wrappers

When you have to use collections in multi-threaded applications, consider using concurrent collections in the java.util.concurrent package instead of using the synchronized collections generated by the Collections.synchronizedXXX() methods.

It’s because the concurrent collections are designed to provide maximum performance in concurrent applications, by implementing different synchronization mechanisms like copy-on-write, compare-and-swap, and special locks. The following list shows you how to choose some concurrent collections (on the right) which are equivalent to the normal ones (on the left):
- HashMap -> ConcurrentHashMap

- ArrayList -> CopyOnWriteArrayList

- TreeMap -> ConcurrentSkipListMap

- PriorityQueue -> PriorityBlockingQueue

Monday, 27 April 2020

Weighted Round Robin Sample Java Example

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.math.IntMath;

public class WeightedRRImpl {
public static void main(String[] args) {
WeightedRRImpl wrr = new WeightedRRImpl();
Map<Integer, Integer> instanceMap = new HashMap<Integer, Integer>();
instanceMap.put(0, 20);
instanceMap.put(1, 28);
instanceMap.put(2, 21);
/*instanceMap.put(3, 4);
instanceMap.put(4, 25);
instanceMap.put(5, 0);*/
/*
* instanceMap.put(3, 4); instanceMap.put(4, 25);
*/

/*
* instanceMap.put(0, 9); instanceMap.put(1, 10); instanceMap.put(2, 8);
* instanceMap.put(3, 7); instanceMap.put(4, 6);
*/
// int gcd = 1;
List<Integer> instanceList = new ArrayList<Integer>(instanceMap.values());
int gcd = wrr.getGCD(instanceList);

System.out.println("**** gcd " + gcd);
/*
* for (int i=0;i<instanceList.size()-1;i++) { BigInteger bigInt = new
* BigInteger(instanceList.get(i).toString()); gcd = bigInt.gcd(new
* BigInteger(instanceList.get(i+1).toString())).intValue(); }
*/

Collections.sort(instanceList);
int max = instanceList.get(instanceList.size() - 1);
int previous = -1;
for (int i = 1; i <= 3; i++) {
// System.out.println("previous "+previous);

Map.Entry<Integer, Integer> entry = wrr.scheduleNext(instanceMap, gcd, max, previous);
if (entry != null) {
previous = entry.getKey();
System.out.println("selected instance:" + previous + " weight:" + entry.getValue());
} else {
System.out.println("Entry is null");
}
}

/*
* System.out.println(gcd); System.out.println(wrr.getGCD(instanceList));
*/

}

private Map.Entry<Integer, Integer> scheduleNext(Map<Integer, Integer> instanceMap, int gcd, int max,
int previous) {
int i = previous;
int cw = (previous == -1) ? 0 : instanceMap.get(previous);
while (true) {
i = (i + 1) % instanceMap.size();
if (i == 0) {
cw = cw - gcd;
if (cw <= 0) {
cw = max;
if (cw == 0)
return null;
}
}
if (instanceMap.get(i) >= cw) {
instanceMap.put(i, cw);
System.out.println("cw " + cw);
// System.out.println("i ==== "+i);
for (Map.Entry<Integer, Integer> entry : instanceMap.entrySet()) {
if (entry.getKey() == i) {
return entry;
}
}
}
}

}


private int getGCD(List<Integer> integerList) {

int result = integerList.get(0);
for (int i = 1; i < integerList.size(); i++) {
result = IntMath.gcd(integerList.get(i), result);

if (result == 1) {
return 1;
}
}

return result;

}

}

Tuesday, 13 August 2019

RestWebService using Java Spring Boot

WebService sample for Sending Token / Some String data to the server



public class FcmToken {

private String content;



public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}



public class FcmTokenReply {

private String content;

String registrationStatus;
int registrationStatusNumber;
public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getRegistrationStatus() {
return registrationStatus;
}

public void setRegistrationStatus(String registrationStatus) {
this.registrationStatus = registrationStatus;
}
public int getRegistrationNumber() {
return registrationStatusNumber;
}

public void setRegistrationStatusNumber(int registrationStatusNumber) {
this.registrationStatusNumber = registrationStatusNumber;
}

}



@RestController
public class FcmRegisterController {
@RequestMapping(method = RequestMethod.POST, value = "/register/token")
@ResponseBody
FcmTokenReply registerStudent(@RequestBody FcmToken fcmregdtoken) {
FcmTokenReply tokenreply = new FcmTokenReply();
//This operation we did so that we can get/fetch this using the get request
FCMGetToken.getInstance().add(fcmregdtoken);

         //We are setting the below value just to reply a message back to the caller

tokenreply.setRegistrationStatusNumber(200);
tokenreply.setRegistrationStatus("Successful");
tokenreply.setContent(fcmregdtoken.getContent());
return tokenreply;
}
}

We test this using POST Man by calling the following URL

http://localhost:8080/register/token and passing the following in the body selecting the content type as application xml/JSON


            "content":"dSSFOk:8OQmsO9W8cTxB3i6ymsjB9I5ngDzmstGsZv0lw6RbGf0tIMcD79nlEQG2hoWgxBqU5r-xK3_zTj7V38UF"
}

we get the response as successful


We will write another URL which will get the token which is registered using the POST URL



public class FCMGetToken {

private static FCMGetToken token = null;

private List<FcmToken> tokenRecords;
private String lastToken;

  private FCMGetToken(){
  tokenRecords = new ArrayList<FcmToken>();
    }
public static FCMGetToken getInstance() {
        if(token == null) {
        token = new FCMGetToken();
              return token;
            }
            else {
                return token;
            }
    }
public void add(FcmToken token) {
tokenRecords.add(token);
lastToken = token.getContent();
    }
public List<FcmToken> getTokenRecords() {
    return tokenRecords;
    }
public String getLastToken() {
    return lastToken;
    }
}



@RestController
public class FCMGetTokenController {


@RequestMapping(method = RequestMethod.GET, value = "/register/alltoken")
/* @ResponseBody
  public List<FcmToken> getAllStudents() {
  return FCMGetToken.getInstance().getTokenRecords();
  }*/
@ResponseBody
  public String getlastToken() {
  return FCMGetToken.getInstance().getLastToken();
  }
}

We can test this using the post man by the following URL

http://localhost:8080/register/alltoken


We Write one more webservice like /sendNotification to send the push notification to client app



@RestController
public class SendNotificationController {

public final static String AUTH_KEY_FCM = "key=FCM Console we can get this under cloud msging tab";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";


@RequestMapping(method = RequestMethod.POST, value = "/sendNotification")
@ResponseBody
private String sendPOST() throws IOException {
String lastToken = FCMGetToken.getInstance().getLastToken();
System.out.println("Inside post "+lastToken);
URL obj = new URL(API_URL_FCM);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// con.setRequestProperty("User-Agent", USER_AGENT);

// For POST only - START
con.setDoOutput(true);

con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");

con.setRequestProperty("Authorization", AUTH_KEY_FCM);

String postJsonData = "{\r\n" +
"  \"notification\": \r\n" +
"  {\r\n" +
"    \"title\": \"Hello Client This is From Server\",\r\n" +
"    \"text\": \"Your Text\",\r\n" +
"    \"sound\": \"default\",\r\n" +
"    \"badge\": \"1\",\r\n" +
"    \r\n" +
"    \"color\": \"#990000\",\r\n" +
"      \r\n" +
"    \r\n" +
"  },\r\n" +
"  \"priority\" : \"high\",\r\n" +
"  \"registration_ids\" : \r\n" +
[\r\n" + "\""+
lastToken+ "\""+ "\r\n" +
"    ]\r\n" +
"}";



OutputStream os = con.getOutputStream();
os.write(postJsonData.getBytes());
os.flush();
os.close();
// For POST only - END
con.connect();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
return "Success";
}

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...