Can you please read through below code and help to let me know if i need to use synchronized keyword with the concurrent hash map in this example?
The main problem is i dont understand when a synchronized keyword needs to be used in compound operations in a concurrent hash map.can someone please help
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
class Pair {
public final Integer x;
public final Integer y;
public Pair(Integer x, Integer y) {
this.x = x;
this.y = y;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
if (y == null) {
if (other.y != null)
return false;
} else if (!y.equals(other.y))
return false;
return true;
}
}
class Order{
int clOrdId;
int origClOrdId;
String symbol;
int qty;
double price;
#Override
public String toString() {
return "Order [clOrdId=" + clOrdId + ", origClOrdId=" + origClOrdId + ", symbol=" + symbol + ", qty=" + qty
+ ", price=" + price + ", side=" + side + "]";
}
char side;
Order(int clOrdId,String symbol,int qty,double price,char side){
this.clOrdId=clOrdId;
this.symbol=symbol;
this.qty=qty;
this.price=price;
this.side=side;
}
Order(int clOrdId,int origClOrdId,String symbol,int qty,double price,char side){
this.clOrdId=clOrdId;
this.origClOrdId=origClOrdId;
this.symbol=symbol;
this.qty=qty;
this.price=price;
this.side=side;
}
}
class Message {
int sessionId;
Order order;
Message(int sessionId, Order order) {
this.sessionId = sessionId;
this.order = order;
}
#Override
public String toString() {
return "Message [sessionId=" + sessionId + ", order=" + order + "]";
}
}
/*
* Different clients can submit different messages 1. Each message has a
* sessionId and a string msg 2. Each of the messages on a particular session
* need to be processed sequentially
*/
public class Concurrency {
private Map<Integer, BlockingDeque<Runnable>> pendingTasks = new ConcurrentHashMap<>();
private Map<Pair,Order> orderMap = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newFixedThreadPool(13);
public void submitMsg(final Message msg) {
submitTask(msg, () -> {
if(msg.order.origClOrdId==0){
print("Received new order msg " + msg);
sleep(1000);
}else{
Pair key = new Pair(msg.sessionId,msg.order.origClOrdId);
if(orderMap.containsKey(key)){
if(isOnlyAggressivePriceMod(msg, key) ){
print("Aggressive price modification "+ msg);
}else if(isOnlyQtyModUp(msg, key)){
print(" Quantity modification up only for "+ msg);
}else if(isOnlyQtyDown(msg, key)){
print(" Quantity modification down only for "+ msg);
}
}
}
orderMap.put(new Pair(msg.sessionId,msg.order.clOrdId), msg.order);
});
}
private boolean isOnlyQtyDown(final Message msg, Pair key) {
return msg.order.qty<orderMap.get(key).qty && Double.compare(msg.order.price,orderMap.get(key).price)==0;
}
private boolean isOnlyQtyModUp(final Message msg, Pair key) {
return msg.order.qty>orderMap.get(key).qty && Double.compare(msg.order.price,orderMap.get(key).price)==0;
}
private boolean isOnlyAggressivePriceMod(final Message msg, Pair key) {
return ((Double.compare(msg.order.price,orderMap.get(key).price)>0 && msg.order.side=='B') ||
(Double.compare(msg.order.price,orderMap.get(key).price)<0 && msg.order.side=='S')) && Double.compare(msg.order.qty,orderMap.get(key).qty)==0;
}
private void sleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void print(String msg){
System.out.println(msg);
}
private void submitTask(final Message msg, Runnable task) {
synchronized(pendingTasks){
if (pendingTasks.containsKey(msg.sessionId)) {
pendingTasks.get(msg.sessionId).add(task);
return;
}
}
BlockingDeque<Runnable> pendingTasksPerSession = new LinkedBlockingDeque<Runnable>();
pendingTasksPerSession.push(task);
pendingTasks.put(msg.sessionId, pendingTasksPerSession);
executorService.submit(new SynchronizedTask(msg, task));
}
public class SynchronizedTask implements Runnable {
Message msg;
Runnable task;
public SynchronizedTask(Message msg, Runnable task) {
this.msg = msg;
this.task = task;
}
public void run() {
task.run();
BlockingDeque<Runnable> pendingTasksForSession = pendingTasks.get(msg.sessionId);
if (!pendingTasksForSession.remove(task)) {
return;
}
if (!pendingTasksForSession.isEmpty())
executorService.submit(new SynchronizedTask(msg, pendingTasksForSession.getFirst()));
}
}
public static void main(String args[]) {
Concurrency c = new Concurrency();
for(int i =1;i<10;i++){
c.submitMsg(new Message(i, new Order(10,"0001.HK",2000*i,200+i,'B')));
c.submitMsg(new Message(i, new Order(11,10,"0001.HK",1000*i,200+i,'B')));
c.submitMsg(new Message(i, new Order(12,11,"0001.HK",2000*i,201+i,'B')));
}
for(int i =1;i<10;i++){
c.submitMsg(new Message(i, new Order(10,"0001.HK",2000*i,200+i,'S')));
c.submitMsg(new Message(i, new Order(11,10,"0001.HK",1000*i,200+i,'S')));
c.submitMsg(new Message(i, new Order(12,11,"0001.HK",2000*i,201+i,'S')));
}
}
}
Related
I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
So I've run into some errors during this code, error is down where the keys are so
first but of code is where the error is, it's saying Syntax error on token "(" Type expected after this token, before I had string without the <> and then keys was underlined and the error was different... so not sure what to do.
Here is where the syntax error is:
for (<String> key : keys) {
Object out = map.get(key);
out = saveObject(out, field, cs, path + "." + key, depth);
subCS.set(key, out);
The whole file:
package me.kalo121;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.util.Vector;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public abstract class ConfigObject
{
protected void onLoad(ConfigurationSection cs)
throws Exception
{
for (Field field : getClass().getDeclaredFields()) {
String path = field.getName().replaceAll("_", ".");
if (!doSkip(field))
{
if (cs.isSet(path))
field.set(this, loadObject(field, cs, path));
else
cs.set(path, saveObject(field.get(this), field, cs, path));
}
}
}
protected void onSave(ConfigurationSection cs) throws Exception {
for (Field field : getClass().getDeclaredFields()) {
String path = field.getName().replaceAll("_", ".");
if (!doSkip(field))
{
cs.set(path, saveObject(field.get(this), field, cs, path));
}
}
}
protected Object loadObject(Field field, ConfigurationSection cs, String path) throws Exception {
return loadObject(field, cs, path, 0);
}
protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path) throws Exception {
return saveObject(obj, field, cs, path, 0);
}
protected Object loadObject(Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
#SuppressWarnings("rawtypes")
Class clazz = getClassAtDepth(field.getGenericType(), depth);
if ((ConfigObject.class.isAssignableFrom(clazz)) && (isConfigurationSection(cs.get(path))))
return getConfigObject(clazz, cs.getConfigurationSection(path));
if ((Location.class.isAssignableFrom(clazz)) && (isJSON(cs.get(path))))
return getLocation((String)cs.get(path));
if ((Vector.class.isAssignableFrom(clazz)) && (isJSON(cs.get(path))))
return getVector((String)cs.get(path));
if ((Map.class.isAssignableFrom(clazz)) && (isConfigurationSection(cs.get(path))))
return getMap(field, cs.getConfigurationSection(path), path, depth);
if ((clazz.isEnum()) && (isString(cs.get(path))))
return getEnum(clazz, (String)cs.get(path));
if ((List.class.isAssignableFrom(clazz)) && (isConfigurationSection(cs.get(path)))) {
#SuppressWarnings("rawtypes")
Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
if ((ConfigObject.class.isAssignableFrom(subClazz)) || (Location.class.isAssignableFrom(subClazz)) || (Vector.class.isAssignableFrom(subClazz)) ||
(Map.class.isAssignableFrom(subClazz)) || (List.class.isAssignableFrom(subClazz)) || (subClazz.isEnum())) {
return getList(field, cs.getConfigurationSection(path), path, depth);
}
return cs.get(path);
}
return cs.get(path);
}
#SuppressWarnings("rawtypes")
protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path, int depth)
throws Exception
{
#SuppressWarnings("rawtypes")
Class clazz = getClassAtDepth(field.getGenericType(), depth);
if ((ConfigObject.class.isAssignableFrom(clazz)) && (isConfigObject(obj)))
return getConfigObject((ConfigObject)obj, path, cs);
if ((Location.class.isAssignableFrom(clazz)) && (isLocation(obj)))
return getLocation((Location)obj);
if ((Vector.class.isAssignableFrom(clazz)) && (isVector(obj)))
return getVector((Vector)obj);
if ((Map.class.isAssignableFrom(clazz)) && (isMap(obj)))
return getMap((Map)obj, field, cs, path, depth);
if ((clazz.isEnum()) && (isEnum(clazz, obj)))
return getEnum((Enum)obj);
if ((List.class.isAssignableFrom(clazz)) && (isList(obj))) {
Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
if ((ConfigObject.class.isAssignableFrom(subClazz)) || (Location.class.isAssignableFrom(subClazz)) || (Vector.class.isAssignableFrom(subClazz)) ||
(Map.class.isAssignableFrom(subClazz)) || (List.class.isAssignableFrom(subClazz)) || (subClazz.isEnum())) {
return getList((List)obj, field, cs, path, depth);
}
return obj;
}
return obj;
}
#SuppressWarnings("rawtypes")
protected Class getClassAtDepth(Type type, int depth)
throws Exception
{
if (depth <= 0) {
String className = type.toString();
if ((className.length() >= 6) && (className.substring(0, 6).equalsIgnoreCase("class "))) {
className = className.substring(6);
}
if (className.indexOf("<") >= 0)
className = className.substring(0, className.indexOf("<"));
try
{
return Class.forName(className);
}
catch (ClassNotFoundException ex) {
if (className.equalsIgnoreCase("byte")) return Byte.class;
if (className.equalsIgnoreCase("short")) return Short.class;
if (className.equalsIgnoreCase("int")) return Integer.class;
if (className.equalsIgnoreCase("long")) return Long.class;
if (className.equalsIgnoreCase("float")) return Float.class;
if (className.equalsIgnoreCase("double")) return Double.class;
if (className.equalsIgnoreCase("char")) return Character.class;
if (className.equalsIgnoreCase("boolean")) return Boolean.class;
throw ex;
}
}
depth--;
ParameterizedType pType = (ParameterizedType)type;
Type[] typeArgs = pType.getActualTypeArguments();
return getClassAtDepth(typeArgs[(typeArgs.length - 1)], depth);
}
protected boolean isString(Object obj) {
if ((obj instanceof String)) {
return true;
}
return false;
}
protected boolean isConfigurationSection(Object o) {
try {
return (ConfigurationSection)o != null; } catch (Exception e) {
}
return false;
}
protected boolean isJSON(Object obj)
{
try {
if ((obj instanceof String)) {
String str = (String)obj;
if (str.startsWith("{")) {
return new JSONParser().parse(str) != null;
}
}
return false; } catch (Exception e) {
}
return false;
}
protected boolean isConfigObject(Object obj)
{
try {
return (ConfigObject)obj != null; } catch (Exception e) {
}
return false;
}
protected boolean isLocation(Object obj)
{
try {
return (Location)obj != null; } catch (Exception e) {
}
return false;
}
protected boolean isVector(Object obj)
{
try {
return (Vector)obj != null; } catch (Exception e) {
}
return false;
}
#SuppressWarnings("rawtypes")
protected boolean isMap(Object obj)
{
try
{
return (Map)obj != null; } catch (Exception e) {
}
return false;
}
#SuppressWarnings("rawtypes")
protected boolean isList(Object obj)
{
try
{
return (List)obj != null; } catch (Exception e) {
}
return false;
}
protected boolean isEnum(#SuppressWarnings("rawtypes") Class clazz, Object obj)
{
if (!clazz.isEnum()) return false;
for (Object constant : clazz.getEnumConstants()) {
if (constant.equals(obj)) {
return true;
}
}
return false;
}
protected ConfigObject getConfigObject(#SuppressWarnings("rawtypes") Class clazz, ConfigurationSection cs)
throws Exception
{
ConfigObject obj = (ConfigObject)clazz.newInstance();
obj.onLoad(cs);
return obj;
}
protected Location getLocation(String json) throws Exception {
JSONObject data = (JSONObject)new JSONParser().parse(json);
World world = Bukkit.getWorld((String)data.get("world"));
double x = Double.parseDouble((String)data.get("x"));
double y = Double.parseDouble((String)data.get("y"));
double z = Double.parseDouble((String)data.get("z"));
float pitch = Float.parseFloat((String)data.get("pitch"));
float yaw = Float.parseFloat((String)data.get("yaw"));
Location loc = new Location(world, x, y, z);
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc;
}
protected Vector getVector(String json) throws Exception {
JSONObject data = (JSONObject)new JSONParser().parse(json);
double x = Double.parseDouble((String)data.get("x"));
double y = Double.parseDouble((String)data.get("y"));
double z = Double.parseDouble((String)data.get("z"));
return new Vector(x, y, z);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
protected Map getMap(Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
Set keys = cs.getKeys(false);
Map map = new HashMap();
if ((keys != null) && (keys.size() > 0)) {
for (<String> key : keys) {
Object in = cs.get(key);
in = loadObject(field, cs, key, depth);
map.put(key, in);
}
}
return map;
}
protected List<String> getList(Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
int listSize = cs.getKeys(false).size();
String key = path;
if (key.lastIndexOf(".") >= 0) {
key = key.substring(key.lastIndexOf("."));
}
List<String> list = new ArrayList<String>();
if (listSize > 0) {
int loaded = 0;
int i = 0;
while (loaded < listSize) {
if (cs.isSet(key + i)) {
Object in = cs.get(key + i);
in = loadObject(field, cs, key + i, depth);
list.add((String) in);
loaded++;
}
i++;
if (i > listSize * 3) loaded = listSize;
}
}
return list;
}
#SuppressWarnings("rawtypes")
protected Enum getEnum(Class clazz, String string) throws Exception
{
if (!clazz.isEnum()) throw new Exception("Class " + clazz.getName() + " is not an enum.");
for (Object constant : clazz.getEnumConstants()) {
if (((Enum)constant).toString().equals(string)) {
return (Enum)constant;
}
}
throw new Exception("String " + string + " not a valid enum constant for " + clazz.getName());
}
protected ConfigurationSection getConfigObject(ConfigObject obj, String path, ConfigurationSection cs)
throws Exception
{
ConfigurationSection subCS = cs.createSection(path);
obj.onSave(subCS);
return subCS;
}
protected String getLocation(Location loc) {
String ret = "{";
ret = ret + "\"world\":\"" + loc.getWorld().getName() + "\"";
ret = ret + ",\"x\":\"" + loc.getX() + "\"";
ret = ret + ",\"y\":\"" + loc.getY() + "\"";
ret = ret + ",\"z\":\"" + loc.getZ() + "\"";
ret = ret + ",\"pitch\":\"" + loc.getPitch() + "\"";
ret = ret + ",\"yaw\":\"" + loc.getYaw() + "\"";
ret = ret + "}";
if (!isJSON(ret)) return getLocationJSON(loc); try
{
getLocation(ret);
} catch (Exception ex) {
return getLocationJSON(loc);
}
return ret;
}
#SuppressWarnings("unchecked")
protected String getLocationJSON(Location loc)
{
JSONObject data = new JSONObject();
data.put("world", loc.getWorld().getName());
data.put("x", String.valueOf(loc.getX()));
data.put("y", String.valueOf(loc.getY()));
data.put("z", String.valueOf(loc.getZ()));
data.put("pitch", String.valueOf(loc.getPitch()));
data.put("yaw", String.valueOf(loc.getYaw()));
return data.toJSONString();
}
protected String getVector(Vector vec) {
String ret = "{";
ret = ret + "\"x\":\"" + vec.getX() + "\"";
ret = ret + ",\"y\":\"" + vec.getY() + "\"";
ret = ret + ",\"z\":\"" + vec.getZ() + "\"";
ret = ret + "}";
if (!isJSON(ret)) return getVectorJSON(vec); try
{
getVector(ret);
} catch (Exception ex) {
return getVectorJSON(vec);
}
return ret;
}
#SuppressWarnings("unchecked")
protected String getVectorJSON(Vector vec)
{
JSONObject data = new JSONObject();
data.put("x", String.valueOf(vec.getX()));
data.put("y", String.valueOf(vec.getY()));
data.put("z", String.valueOf(vec.getZ()));
return data.toJSONString();
}
protected ConfigurationSection getMap(#SuppressWarnings("rawtypes") Map map, Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
ConfigurationSection subCS = cs.createSection(path);
#SuppressWarnings("rawtypes")
Set keys = map.keySet();
if ((keys != null) && (keys.size() > 0)) {
for (<String> key : keys) {
Object out = map.get(key);
out = saveObject(out, field, cs, path + "." + key, depth);
subCS.set(key, out);
}
}
return subCS;
}
protected ConfigurationSection getList(#SuppressWarnings("rawtypes") List list, Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
ConfigurationSection subCS = cs.createSection(path);
String key = path;
if (key.lastIndexOf(".") >= 0) {
key = key.substring(key.lastIndexOf("."));
}
if ((list != null) && (list.size() > 0)) {
for (int i = 0; i < list.size(); i++) {
Object out = list.get(i);
out = saveObject(out, field, cs, path + "." + key + (i + 1), depth);
subCS.set(key + (i + 1), out);
}
}
return subCS;
}
protected String getEnum(#SuppressWarnings("rawtypes") Enum enumObj)
{
return enumObj.toString();
}
protected boolean doSkip(Field field)
{
return (Modifier.isTransient(field.getModifiers())) || (Modifier.isStatic(field.getModifiers())) || (Modifier.isFinal(field.getModifiers())) ||
(Modifier.isPrivate(field.getModifiers()));
}
}
for (<String> key : keys) { is invalid syntax. The reason for (String key : keys) { didn't work either is that the type of your keys variable is the raw Set, which means you can only iterate over it with for (Object key : keys) {.
If you change Set keys = cs.getKeys(false); to
Set<String> keys = cs.getKeys(false); (assuming this Set contains only Strings), the following with work :
for (String key : keys) {
I have an sync Client, how to make this async Client? Client connects properly then it writes to channel, and then it waits (no keys ready because there is nothing to read from channel), now I want it to start writing to channel again, how to achieve this ? Thanks
public class Client {
static class SocketTest implements Runnable {
private Selector selector;
private int sessionID = 0;
int port;
String address;
private List<Message> dummyTypeOneResults = new LinkedList<Message>();
private List<Message> dummyTypeTwoResults = new LinkedList<Message>();
public SocketTest(String address, int port){
this.port = port;
this.address = address;
}
#Override
public void run() {
SocketChannel channel;
try {
selector = Selector.open();
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_CONNECT);
channel.connect(new InetSocketAddress(this.address,this.port));
while (!Thread.interrupted()){
selector.selectNow();
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()){
SelectionKey key = keys.next();
keys.remove();
if (!key.isValid()) continue;
if (key.isConnectable()){
connect(key);
}
if (key.isWritable()){
if(sessionID > 200000){
//force disconnect
System.out.println("sessionID reached limit forcing disconnet");
key.cancel();
//call calculate
calculate();
close();
return;
} else {
write(key);
}
}
if (key.isReadable()){
read(key);
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
close();
}
}
private void calculate() throws IOException{
//open file
File file = new File("results_nio.txt");
// if file doesnt exists, then create it
FileWriter fw = null;
fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
long totalDifferenceSum = 0;
long messageCount = 0;
for (Message message : dummyTypeOneResults) {
long diff = message.getProcessed() - message.getDispatched();
String out = "message with ID: "+message.getSessionID()+" Trip time in seconds %f %n ";
System.out.format(out,diff/1000000000.0);
bw.write(String.format(out,diff/1000000000.0));
totalDifferenceSum +=diff;
messageCount++;
}
for (Message message : dummyTypeTwoResults) {
long diff = message.getProcessed() - message.getDispatched();
String out = "message with ID: "+message.getSessionID()+" Trip time in seconds %f %n ";
System.out.format(out,diff/1000000000.0);
bw.write(String.format(out,diff/1000000000.0));
totalDifferenceSum +=diff;
messageCount++;
}
String totalString = "Total round trip time in seconds %f %n ";
System.out.format(totalString,totalDifferenceSum/1000000000.0);
bw.write(String.format(totalString,totalDifferenceSum/1000000000.0));
double average = messageCount > 0 ? (double)totalDifferenceSum/messageCount : 0;
String averageString = "Average trip time in seconds %f %n ";
System.out.format(averageString,average/1000000000.0);
bw.write(String.format(averageString,average/1000000000.0));
bw.close();
}
private void close(){
try {
selector.close();
} catch (IOException e) {
System.err.println(e);
}
}
private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int length;
try {
length = channel.read(readBuffer);
System.out.println("Bytes read from server: "+length);
if(length != -1){
byte[] bytes;
readBuffer.flip();
bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes, 0, bytes.length);
//create Message
ByteBuffer prepareBuffer = ByteBuffer.wrap(bytes);
int type = prepareBuffer.getInt();
int sessionID = prepareBuffer.getInt();
long dispatched = prepareBuffer.getLong();
Message message = new Message(sessionID, type, dispatched, bytes);
message.setProcessed(System.nanoTime());
if(type == Message.DUMMY_ONE){
dummyTypeOneResults.add(message);
} else if (type == Message.DUMMY_TWO) {
dummyTypeTwoResults.add(message);
}
}
} catch (IOException e) {
System.out.println("Reading problem, closing connection");
key.cancel();
channel.close();
return;
}
if (length == -1) {
System.out.println("Nothing was read from server");
//channel.close();
key.cancel();
System.out.println("Send againg new message ");
key.interestOps(SelectionKey.OP_CONNECT);
return;
}
readBuffer.flip();
byte[] buff = new byte[1024];
readBuffer.get(buff, 0, length);
key.interestOps(SelectionKey.OP_WRITE);
readBuffer.clear();
}
private void write(SelectionKey key) throws IOException {
//Message format |typeID|sessionID|startTime
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer message = ByteBuffer.allocate(16);
if(sessionID % 2 == 0){
message.putInt(Message.DUMMY_ONE);
} else {
message.putInt(Message.DUMMY_TWO);
}
message.putInt(sessionID);
message.putLong(System.nanoTime());
sessionID++;
message.flip();
int bytesWritten = channel.write(message);
System.out.println("client write(): bytesWritten :"+bytesWritten);
// lets get ready to read.
key.interestOps(SelectionKey.OP_READ);
}
private void connect(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
if (channel.isConnectionPending()){
boolean finished = channel.finishConnect();
if (!finished) {
key.cancel();
}
}
channel.configureBlocking(false);
channel.register(selector,SelectionKey.OP_WRITE); // \p was
// channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
}
public static void main(String[] args) {
int DEFAULT_PORT = 9090;
String IP = "127.0.0.1";
if(args.length > 1){
if(args[0]!=null){
IP=args[0];
}
if(args[1]!=null){
DEFAULT_PORT=Integer.valueOf(args[1]);
}
}
new Thread(new SocketTest(IP,DEFAULT_PORT)).start();
}
//and Message class
public class Message implements Serializable {
public static final int DUMMY_ONE = 1;
public static final int DUMMY_TWO = 2;
private static final long serialVersionUID = -555511105603152223L;
// could be message header
protected int sessionID;
protected int type;
protected long created = System.currentTimeMillis();
protected long dispatched;
protected long processed;
protected Object payload;
public Message(int sessionID, int type, long dispatched) {
super();
this.sessionID = sessionID;
this.type = type;
this.dispatched = dispatched;
}
public Message(int sessionID, int type, long dispatched, Object payload) {
super();
this.sessionID = sessionID;
this.type = type;
this.dispatched = dispatched;
this.payload = payload;
}
public int getSessionID() {
return sessionID;
}
public void setSessionID(int sessionID) {
this.sessionID = sessionID;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public long getDispatched() {
return dispatched;
}
public void setDispatched(long dispatched) {
this.dispatched = dispatched;
}
public long getProcessed() {
return processed;
}
public void setProcessed(long processed) {
this.processed = processed;
}
public Object getPayload() {
return payload;
}
public void setPayload(Object payload) {
this.payload = payload;
}
#Override
public String toString() {
return "Message [sessionID=" + sessionID + ", type=" + type
+ ", created=" + created + ", dispatched=" + dispatched + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (created ^ (created >>> 32));
result = prime * result + (int) (dispatched ^ (dispatched >>> 32));
result = prime * result + ((payload == null) ? 0 : payload.hashCode());
result = prime * result + (int) (processed ^ (processed >>> 32));
result = prime * result + sessionID;
result = prime * result + type;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Message other = (Message) obj;
if (created != other.created)
return false;
if (dispatched != other.dispatched)
return false;
if (payload == null) {
if (other.payload != null)
return false;
} else if (!payload.equals(other.payload))
return false;
if (processed != other.processed)
return false;
if (sessionID != other.sessionID)
return false;
if (type != other.type)
return false;
return true;
}
}
You are confused between 'asynchronous' and 'non-blocking'.
You are operating in non-blocking mode, but you're blocking in select(). This is normal.
If you want asynchronous I/O, you need to use an AsynchronousSocketChannel. It is a completely different programming paradigm.
i'm new to design pattern , and now i'm working on an open ware code : so i'm trying to understand the architecture of the code : layers , used design pattern ...
So i found the a package containing classes named EntityWrapper.java here's an example :
The wrapper class :
package org.objectweb.salome_tmf.api.data;
/**
* #author marchemi
*/
public class ActionWrapper extends DataWrapper{
String awaitedResult;
int orderIndex;
int idTest;
/**
* #return Returns the orderIndex.
*/
public int getOrderIndex() {
return orderIndex;
}
/**
* #param orderIndex The orderIndex to set.
*/
public void setOrderIndex(int orderIndex) {
this.orderIndex = orderIndex;
}
/**
* #return Returns the waitedResult.
*/
public String getAwaitedResult() {
return awaitedResult;
}
/**
* #param waitedResult The waitedResult to set.
*/
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
/**
* #return Returns the idTest.
*/
public int getIdTest() {
return idTest;
}
/**
* #param idTest The idTest to set.
*/
public void setIdTest(int idTest) {
this.idTest = idTest;
}
}
The entity class:
package org.objectweb.salome_tmf.data;
import java.io.File;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import org.objectweb.salome_tmf.api.Api;
import org.objectweb.salome_tmf.api.ApiConstants;
import org.objectweb.salome_tmf.api.Util;
import org.objectweb.salome_tmf.api.data.ActionWrapper;
import org.objectweb.salome_tmf.api.data.FileAttachementWrapper;
import org.objectweb.salome_tmf.api.data.ParameterWrapper;
import org.objectweb.salome_tmf.api.data.SalomeFileWrapper;
import org.objectweb.salome_tmf.api.data.UrlAttachementWrapper;
import org.objectweb.salome_tmf.api.sql.ISQLAction;
public class Action extends WithAttachment {
static ISQLAction pISQLAction = null;
private String awaitedResult;
public String getAwaitedResult() {
return awaitedResult;
}
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
private int orderIndex;
private Hashtable parameterHashTable;
private Test pTest = null;
public Action(Test pTest, String name, String description) {
super(name, description);
awaitedResult = "";
orderIndex = 0;
parameterHashTable = new Hashtable();
this.pTest = pTest;
if (pISQLAction == null){
pISQLAction = Api.getISQLObjectFactory().getISQLAction();
}
}
public Action(ActionWrapper pAction, Test pTest) {
this(pTest, pAction.getName(), pAction.getDescription());
awaitedResult = pAction.getAwaitedResult();
orderIndex = pAction.getOrderIndex();
idBdd = pAction.getIdBDD();
}
public Action(Action pAction, Test pTest) {
this(pTest, pAction.getNameFromModel(), pAction.getDescriptionFromModel());
awaitedResult = pAction.getAwaitedResultFromModel();
} // Fin du constructeur Action/1
protected void reloadBaseFromDB() throws Exception {
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
ActionWrapper pActionWrapper = pISQLAction.getActionWrapper(idBdd);
awaitedResult = pActionWrapper.getAwaitedResult();
orderIndex = pActionWrapper.getOrderIndex();
name = pActionWrapper.getName();
description = pActionWrapper.getDescription();
}
public void reloadFromDB(boolean base, Hashtable paramsInModel, boolean attach)
throws Exception {
int transNuber = -1;
try {
transNuber = Api.beginTransaction(101, ApiConstants.LOADING);
if (base){
reloadBaseFromDB();
}
reloadUsedParameterFromDB(paramsInModel);
if (attach){
reloadAttachmentDataFromDB(false);
}
Api.commitTrans(transNuber);
} catch (Exception e){
Api.forceRollBackTrans(transNuber);
throw e;
}
}
public void clearCache() {
/* TODO ClearAttachement */
}
/******************************************************************************/
/** ACCESSEURS ET
MUTATEURS ***/
/******************************************************************************/
public String getAwaitedResultFromModel() {
return awaitedResult;
}
public void setAwaitedResultInModel(String string) {
awaitedResult = string;
}
public int getOrderIndexFromModel() {
return orderIndex;
}
public void setOrderIndex(int i) {
orderIndex = i;
}
public Test getTest(){
return pTest;
}
/////////////////////////////// Basic Operation /////////////////////////
/* Used by Manuel Test */
void addInDB(Test pTest) throws Exception {
//boolean needUpdate = false;
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
if (!pTest.isInBase()){
throw new Exception("Test " + pTest.getNameFromModel() + " is not in BDD");
}
int id = pISQLAction.insert(pTest.getIdBdd(), name, description, awaitedResult);
setIdBdd(id);
orderIndex = pISQLAction.getActionWrapper(id).getOrder();
/*if (orderIndex != rowCount){
needUpdate = true;
}
return needUpdate;*/
Project.pCurrentProject.notifyChanged( ApiConstants.INSERT_ACTION ,this);
}
/* Used by Manuel Test */
void addInModel(Test pTest){
this.pTest = pTest;
}
/* Used by Manuel Test */
void addInDBAndModel(Test pTest)throws Exception {
//boolean res;
addInDB(pTest);
addInModel(pTest);
//return res;
}
public void updateInDB(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.update(idBdd, newActionName, newActionDesc, newActionResAttendu );
Project.pCurrentProject.notifyChanged( ApiConstants.UPDATE_ACTION ,this, new String(name), newActionName);
}
public void updateInModel(String newActionName, String newActionDesc, String newActionResAttendu) {
setNameInModel(newActionName);
updateDescriptionInModel(newActionDesc);
setAwaitedResultInModel(newActionResAttendu);
}
public void updateInDBAndModel(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
updateInDB(newActionName, newActionDesc, newActionResAttendu);
updateInModel(newActionName, newActionDesc, newActionResAttendu);
}
public void updateInDBAndModel(String newName, String newDesc) throws Exception {
updateInDB(newName, newDesc, awaitedResult);
updateInModel(newName, newDesc, awaitedResult);
}
public void updateOrderInDBAndModel(boolean inc) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
orderIndex = pISQLAction.updateOrder(idBdd, inc);
}
/* Used by Manuel Test */
void deleteInDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.delete(idBdd);
Project.pCurrentProject.notifyChanged( ApiConstants.DELETE_ACTION ,this);
}
/* Used by Manuel Test */
void deleteInModel(){
pTest=null;
parameterHashTable.clear();
clearAttachInModel();
}
/* Used by Manuel Test */
void deleteInDBAndModel() throws Exception {
deleteInDB();
deleteInModel();
}
//////////////// PARAMETERS ////////////////////////
public void setParameterHashSetInModel(HashSet set) {
parameterHashTable.clear();
for (Iterator iter = set.iterator(); iter.hasNext();) {
Parameter param = (Parameter)iter.next();
parameterHashTable.put(param.getNameFromModel(), param);
}
}
public void setParameterHashtableInModel(Hashtable table) {
parameterHashTable.clear();
parameterHashTable = table;
}
public Hashtable getCopyOfParameterHashTableFromModel(){
Hashtable copyParameter = new Hashtable();
Enumeration enumKey = parameterHashTable.keys();
while (enumKey.hasMoreElements()){
Object key = enumKey.nextElement();
copyParameter.put(key, parameterHashTable.get(key));
}
return copyParameter;
}
public void reloadUsedParameterFromDB(Hashtable parametersInModel) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] paramActionArray = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < paramActionArray.length; i++) {
Parameter param = null;
ParameterWrapper pParameterWrapper = paramActionArray[i];
if (parametersInModel != null){
param = (Parameter)parametersInModel.get(pParameterWrapper.getName());
if (param == null){
param = new Parameter(pParameterWrapper);
}
}
setUseParamInModel(param);
}
}
public void setUseParamInModel(Parameter pParam) {
parameterHashTable.put(pParam.getNameFromModel(), pParam);
if (pTest != null) {
if (pTest.getUsedParameterFromModel(pParam.getNameFromModel()) == null){
pTest.setUseParamInModel(pParam);
}
}
}
public void setUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.addUseParam(idBdd,paramId);
}
public void setUseParamInDBAndModel(Parameter pParam) throws Exception {
//DB
setUseParamInDB(pParam.getIdBdd());
//model
setUseParamInModel(pParam);
}
public void deleteUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteParamUse(idBdd, paramId);
}
public void deleteUseParamInDBAndModel(Parameter pParam) throws Exception {
deleteUseParamInDB(pParam.getIdBdd());
deleteUseParamInModel(pParam);
}
public void deleteUseParamInModel(Parameter pParam) {
// Clean Action
String newDesc = null ;
if (getDescriptionFromModel()!=null)
newDesc = clearStringOfParameter(getDescriptionFromModel(), pParam);
String newResult = null;
if (getAwaitedResultFromModel()!=null)
newResult = clearStringOfParameter(getAwaitedResultFromModel(), pParam);
description = newDesc;
awaitedResult = newResult;
Object o= parameterHashTable.remove(pParam.getNameFromModel());
Util.log("[Action->deleteUseParamInModel] Delete Use Parameter " + pParam + ", in Action " + name + " res is " +o);
}
public Parameter getParameterFromModel(String name) {
Enumeration paramList = parameterHashTable.elements();
while (paramList.hasMoreElements()){
Parameter param = (Parameter)paramList.nextElement();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public Parameter getParameterFromDB(String name) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = getParameterHashSetFromDB();
for (Iterator iter = result.iterator(); iter.hasNext(); ) {
Parameter param = (Parameter)iter.next();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public HashSet getParameterHashSetFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = new HashSet();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Vector getParameterVectorFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
Vector result = new Vector();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Hashtable getParameterHashSetFromModel() {
return parameterHashTable;
}
////////////// ATTACHEMENT ///////////////////////
public void addAttachementInDB (Attachment attach )throws Exception {
if (attach instanceof FileAttachment) {
addAttachFileInDB((FileAttachment) attach);
} else {
addAttachUrlInDB((UrlAttachment) attach);
}
}
void addAttachFileInDB(FileAttachment file) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
File f = file.getLocalFile();
int id = pISQLAction.addFileAttach(idBdd,new SalomeFileWrapper(f),file.getDescriptionFromModel());
file.setIdBdd(id);
}
void addAttachUrlInDB(UrlAttachment url) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
int id = pISQLAction.addUrlAttach(idBdd, url.getNameFromModel(),url.getDescriptionFromModel());
url.setIdBdd(id);
}
public void deleteAttachementInDB(int attachId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteAttachment(idBdd, attachId);
}
public void deleteAttachementInDBAndModel(Attachment attach)throws Exception {
deleteAttachementInDB(attach.getIdBdd());
deleteAttachmentInModel(attach);
}
public Vector getAttachFilesFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
FileAttachementWrapper[] fawArray = pISQLAction.getAllAttachFile(idBdd);
Vector result = new Vector();
for(int i = 0; i < fawArray.length; i++) {
result.add(fawArray[i]);
}
return result;
}
public Vector getAttachUrlsFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
UrlAttachementWrapper[] uawArray = pISQLAction.getAllAttachUrl(idBdd);
Vector result = new Vector();
for(int i = 0; i < uawArray.length; i++) {
result.add(uawArray[i]);
}
return result;
}
//////// PROTECTED //////////////
protected String clearStringOfParameter(String prtString, Parameter pParam) {
String result = prtString;
result = result.replaceAll("[$]" + pParam.getNameFromModel() + "[$]", "");
return result;
}
public static boolean isInBase(Test pTest, String actionName) {
try {
int id = pISQLAction.getID(pTest.getIdBdd(), actionName);
if (id > 0){
return true;
}
return false;
} catch (Exception e) {
}
return false;
} // Fin de la methode isInBase/1
public boolean existeInBase() throws Exception {
if (!isInBase()) {
return false;
}
return pISQLAction.getID(pTest.getIdBdd(), name) == idBdd;
}
}
So what is the utility of the wrapper class , is it a kind of design pattern ?
I can not see, what ActionWrapper wraps, for me is just implementation of DataWrapper interface.
There 3 "kinds" of wrappers design patterns:
Facade design pattern = take a lot of classes/interfaces, do some logic inside and get out small interface. For example "Car start" encapsulate inside: open car, put key, set DVD, correct chair, ignition.
Decorator design pattern = take some class with behavior and make ability to add behaviors in run time. for example, instead of do class CarWithLCDWithDVDWithTurbo you can do: new LCDDecorator(new DVDDecorator(TurboDecorator(new car)));
Adapter design pattern = take some new interface and adapt it to some known interface.
The fact that something ends with the Wrapper word doesn´t make it a wrapper. To be a wrapper it has to wrap something. This is, it has to encapsulate one or more components, probably a whole third-party API.
There are different types of wrappers as #zzfima says. And yes, proxy could be a wrapper in some cases and also bridges could be.
Your code doesn´t encapsulate any other component and then, it is not a wrapper (at least for me)
call something "wrapper" doesn't make it a wrapper. Basically it needs to encapsulate something or wrap something, whatever you call it
I am working on creating a Java class to map an XML file that has multiple same elements. The following XML is an example of what the file looks like:
<TrackBroadcast>
<DateTime>some date</DateTime>
<From>from someone</From>
<To>to someone</To>
<Classification>some type of classification</Classification>
<Command>some type of command</Command>
<MsgId>some id</MsgId>
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
</TrackBroadcast>
My JAXB class can read in the DateTime, From, To, Classification, Command, and MsgId elements but it cannot read in the Barge elements. I have two classes to try to encapsulate the XML but I know I doing something wrong. The two classes are:
#XmlRootElement(name="TrackBroadcast")
public class TrackBroadcast {
String dataTime;
String from;
String to;
String classification;
String command;
String msgId;
List<Barge> barge = new ArrayList<Barge>();
public String getDataTime() {
return dataTime;
}
#XmlElement(name="DateTime")
public void setDataTime(String dataTime) {
this.dataTime = dataTime;
}
public String getFrom() {
return from;
}
#XmlElement(name="From")
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
#XmlElement(name="To")
public void setTo(String to) {
this.to = to;
}
public String getClassification() {
return classification;
}
#XmlElement(name="Classification")
public void setClassification(String classification) {
this.classification = classification;
}
public String getCommand() {
return command;
}
#XmlElement(name="Command")
public void setCommand(String command) {
this.command = command;
}
public String getMsgId() {
return msgId;
}
#XmlElement(name="MsgId")
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public List<Barge> getBarge() {
return barge;
}
public void setBarge(List<Barge> barge) {
this.barge = barge;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TrackBroadcast other = (TrackBroadcast) obj;
if ((this.dataTime == null) ? (other.dataTime != null) : !this.dataTime.equals(other.dataTime)) {
return false;
}
if ((this.from == null) ? (other.from != null) : !this.from.equals(other.from)) {
return false;
}
if ((this.to == null) ? (other.to != null) : !this.to.equals(other.to)) {
return false;
}
if ((this.command == null) ? (other.command != null) : !this.command.equals(other.command)) {
return false;
}
if ((this.msgId == null) ? (other.msgId != null) : !this.msgId.equals(other.msgId)) {
return false;
}
if (this.barge != other.barge && (this.barge == null || !this.barge.equals(other.barge))) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 7;
hash = 43 * hash + (this.dataTime != null ? this.dataTime.hashCode() : 0);
hash = 43 * hash + (this.from != null ? this.from.hashCode() : 0);
hash = 43 * hash + (this.to != null ? this.to.hashCode() : 0);
hash = 43 * hash + (this.classification != null ? this.classification.hashCode() : 0);
hash = 43 * hash + (this.command != null ? this.command.hashCode() : 0);
hash = 43 * hash + (this.msgId != null ? this.msgId.hashCode() : 0);
hash = 43 * hash + (this.barge != null ? this.barge.hashCode() : 0);
for(int i=0; i<barge.size(); i++){
Barge b = barge.get(i);
System.out.println(b.toString());
}
return hash;
}
#Override
public String toString() {
return "TrackBroadcast{" + "dataTime=" + dataTime + ", from=" + from + ", to=" + to + ", classification=" + classification + ", command=" + command + ", msgId=" + msgId + ", barge=" + barge + '}';
}
}
and
#XmlRootElement(name="Barge")
public class Barge {
String misleBargeVesselId;
String bargeName;
String towingVesselName;
String nonVesselName;
String towingVesselPhoneNo;
String towingVesselCompany;
String positionDate;
double latitude;
double longitude;
String waterwayAbbr;
double waterwayMileMarker;
String bargeDirection;
String bargeCdcType;
double bargeCdcQuantity;
String bargeCdcMeasureUnit;
String bargeLoadStatus;
String nextEta;
public String getMisleBargeVesselId() {
return misleBargeVesselId;
}
#XmlAttribute(name="MISLE_Barge_Vessel_Id")
public void setMisleBargeVesselId(String misleBargeVesselId) {
this.misleBargeVesselId = misleBargeVesselId;
}
public String getBargeName() {
return bargeName;
}
#XmlAttribute(name="Barge_Name")
public void setBargeName(String bargeName) {
this.bargeName = bargeName;
}
public String getTowingVesselName() {
return towingVesselName;
}
#XmlAttribute(name="Towing_Vessel_Name")
public void setTowingVesselName(String towingVesselName) {
this.towingVesselName = towingVesselName;
}
public String getNonVesselName() {
return nonVesselName;
}
#XmlAttribute(name="Non_Vessel_Name")
public void setNonVesselName(String nonVesselName) {
this.nonVesselName = nonVesselName;
}
public String getTowingVesselPhoneNo() {
return towingVesselPhoneNo;
}
#XmlAttribute(name="Towing_Vessel_Phone_No")
public void setTowingVesselPhoneNo(String towingVesselPhoneNo) {
this.towingVesselPhoneNo = towingVesselPhoneNo;
}
public String getTowingVesselCompany() {
return towingVesselCompany;
}
#XmlAttribute(name="Towing_Vessel_Company")
public void setTowingVesselCompany(String towingVesselCompany) {
this.towingVesselCompany = towingVesselCompany;
}
public String getPositionDate() {
return positionDate;
}
#XmlAttribute(name="Position_Date")
public void setPositionDate(String positionDate) {
this.positionDate = positionDate;
}
public double getLatitude() {
return latitude;
}
#XmlAttribute(name="Latitude")
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
#XmlAttribute(name="Longitude")
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getWaterwayAbbr() {
return waterwayAbbr;
}
#XmlAttribute(name="Waterway_Abbr")
public void setWaterwayAbbr(String waterwayAbbr) {
this.waterwayAbbr = waterwayAbbr;
}
public double getWaterwayMileMarker() {
return waterwayMileMarker;
}
#XmlAttribute(name="Waterway_Mile_Marker")
public void setWaterwayMileMarker(double waerwayMileMarker) {
this.waterwayMileMarker = waerwayMileMarker;
}
public String getBargeDirection() {
return bargeDirection;
}
#XmlAttribute(name="Barge_Direction")
public void setBargeDirection(String bargeDirection) {
this.bargeDirection = bargeDirection;
}
public String getBargeCdcType() {
return bargeCdcType;
}
#XmlAttribute(name="Barge_CDC_Type")
public void setBargeCdcType(String bargeCdcType) {
this.bargeCdcType = bargeCdcType;
}
public double getBargeCdcQuantity() {
return bargeCdcQuantity;
}
#XmlAttribute(name="Barge_CDC_Quantity")
public void setBargeCdcQuantity(double bargeCdcQuantity) {
this.bargeCdcQuantity = bargeCdcQuantity;
}
public String getBargeCdcMeasureUnit() {
return bargeCdcMeasureUnit;
}
#XmlAttribute(name="Barge_CDC_Measure_Unit")
public void setBargeCdcMeasureUnit(String bargeCdcMeasureUnit) {
this.bargeCdcMeasureUnit = bargeCdcMeasureUnit;
}
public String getBargeLoadStatus() {
return bargeLoadStatus;
}
#XmlAttribute(name="Barge_Load_Status")
public void setBargeLoadStatus(String bargeLoadStatus) {
this.bargeLoadStatus = bargeLoadStatus;
}
public String getNextEta() {
return nextEta;
}
#XmlAttribute(name="Next_ETA")
public void setNextEta(String nextEta) {
this.nextEta = nextEta;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Barge other = (Barge) obj;
if ((this.misleBargeVesselId == null) ? (other.misleBargeVesselId != null) : !this.misleBargeVesselId.equals(other.misleBargeVesselId)) {
return false;
}
if ((this.bargeName == null) ? (other.bargeName != null) : !this.bargeName.equals(other.bargeName)) {
return false;
}
if ((this.towingVesselName == null) ? (other.towingVesselName != null) : !this.towingVesselName.equals(other.towingVesselName)) {
return false;
}
if ((this.nonVesselName == null) ? (other.nonVesselName != null) : !this.nonVesselName.equals(other.nonVesselName)) {
return false;
}
if ((this.towingVesselPhoneNo == null) ? (other.towingVesselPhoneNo != null) : !this.towingVesselPhoneNo.equals(other.towingVesselPhoneNo)) {
return false;
}
if ((this.towingVesselCompany == null) ? (other.towingVesselCompany != null) : !this.towingVesselCompany.equals(other.towingVesselCompany)) {
return false;
}
if ((this.positionDate == null) ? (other.positionDate != null) : !this.positionDate.equals(other.positionDate)) {
return false;
}
if (Double.doubleToLongBits(this.latitude) != Double.doubleToLongBits(other.latitude)) {
return false;
}
if (Double.doubleToLongBits(this.longitude) != Double.doubleToLongBits(other.longitude)) {
return false;
}
if ((this.waterwayAbbr == null) ? (other.waterwayAbbr != null) : !this.waterwayAbbr.equals(other.waterwayAbbr)) {
return false;
}
if (Double.doubleToLongBits(this.waterwayMileMarker) != Double.doubleToLongBits(other.waterwayMileMarker)) {
return false;
}
if ((this.bargeDirection == null) ? (other.bargeDirection != null) : !this.bargeDirection.equals(other.bargeDirection)) {
return false;
}
if ((this.bargeCdcType == null) ? (other.bargeCdcType != null) : !this.bargeCdcType.equals(other.bargeCdcType)) {
return false;
}
if (Double.doubleToLongBits(this.bargeCdcQuantity) != Double.doubleToLongBits(other.bargeCdcQuantity)) {
return false;
}
if ((this.bargeCdcMeasureUnit == null) ? (other.bargeCdcMeasureUnit != null) : !this.bargeCdcMeasureUnit.equals(other.bargeCdcMeasureUnit)) {
return false;
}
if ((this.bargeLoadStatus == null) ? (other.bargeLoadStatus != null) : !this.bargeLoadStatus.equals(other.bargeLoadStatus)) {
return false;
}
if ((this.nextEta == null) ? (other.nextEta != null) : !this.nextEta.equals(other.nextEta)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + (this.misleBargeVesselId != null ? this.misleBargeVesselId.hashCode() : 0);
hash = 17 * hash + (this.bargeName != null ? this.bargeName.hashCode() : 0);
hash = 17 * hash + (this.towingVesselName != null ? this.towingVesselName.hashCode() : 0);
hash = 17 * hash + (this.nonVesselName != null ? this.nonVesselName.hashCode() : 0);
hash = 17 * hash + (this.towingVesselPhoneNo != null ? this.towingVesselPhoneNo.hashCode() : 0);
hash = 17 * hash + (this.towingVesselCompany != null ? this.towingVesselCompany.hashCode() : 0);
hash = 17 * hash + (this.positionDate != null ? this.positionDate.hashCode() : 0);
hash = 17 * hash + (int) (Double.doubleToLongBits(this.latitude) ^ (Double.doubleToLongBits(this.latitude) >>> 32));
hash = 17 * hash + (int) (Double.doubleToLongBits(this.longitude) ^ (Double.doubleToLongBits(this.longitude) >>> 32));
hash = 17 * hash + (this.waterwayAbbr != null ? this.waterwayAbbr.hashCode() : 0);
hash = 17 * hash + (int) (Double.doubleToLongBits(this.waterwayMileMarker) ^ (Double.doubleToLongBits(this.waterwayMileMarker) >>> 32));
hash = 17 * hash + (this.bargeDirection != null ? this.bargeDirection.hashCode() : 0);
hash = 17 * hash + (this.bargeCdcType != null ? this.bargeCdcType.hashCode() : 0);
hash = 17 * hash + (int) (Double.doubleToLongBits(this.bargeCdcQuantity) ^ (Double.doubleToLongBits(this.bargeCdcQuantity) >>> 32));
hash = 17 * hash + (this.bargeCdcMeasureUnit != null ? this.bargeCdcMeasureUnit.hashCode() : 0);
hash = 17 * hash + (this.bargeLoadStatus != null ? this.bargeLoadStatus.hashCode() : 0);
hash = 17 * hash + (this.nextEta != null ? this.nextEta.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "Barge{" + "misleBargeVesselId=" + misleBargeVesselId + ", bargeName=" + bargeName + ", towingVesselName=" + towingVesselName + ", nonVesselName=" + nonVesselName + ", towingVesselPhoneNo=" + towingVesselPhoneNo + ", towingVesselCompany=" + towingVesselCompany + ", positionDate=" + positionDate + ", latitude=" + latitude + ", longitude=" + longitude + ", waterwayAbbr=" + waterwayAbbr + ", waerwayMileMarker=" + waterwayMileMarker + ", bargeDirection=" + bargeDirection + ", bargeCdcType=" + bargeCdcType + ", bargeCdcQuantity=" + bargeCdcQuantity + ", bargeCdcMeasureUnit=" + bargeCdcMeasureUnit + ", bargeLoadStatus=" + bargeLoadStatus + ", nextEta=" + nextEta + '}';
}
}
When I unmarshall the file I can get everything in the TrackBroadcast except for the Barges. I'm new to JAXB and was wondering if anyone could see what I might be doing wrong or if anyone could nudge me in the right direction.
You should just need to add #XmlElement(name="Barge") as by the JAXB (JSR-222) default naming rules JAXB implementations will look for elements with the name barge instead of Barge:
#XmlElement(name="Barge")
public List<Barge> getBarge() {
return barge;
}
For More Information
http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
Just define JAXB #XmlElement annotation with preferred name over required field setter. Also I think that generating classes from XML Schema is a much better option than manually ensuring mapping contract.