I'm getting the following error when I tried to processing the data from hazelcast jet.
Caused by: java.lang.IllegalArgumentException: Invalid lambda deserialization
at com.example.LearnJet.joins.LeftJoins.$deserializeLambda$(LeftJoins.java:1)
... 59 more
Here is the code:-
AddToCart1 instance
public class AddToCart1 implements Serializable {
private int number;
private String cart;
public AddToCart1() {
super();
// TODO Auto-generated constructor stub
}
public int getNumber() {
return number;
}
public AddToCart1(int number, String cart) {
super();
this.number = number;
this.cart = cart;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cart == null) ? 0 : cart.hashCode());
result = prime * result + number;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddToCart1 other = (AddToCart1) obj;
if (cart == null) {
if (other.cart != null)
return false;
} else if (!cart.equals(other.cart))
return false;
if (number != other.number)
return false;
return true;
}
public void setNumber(int number) {
this.number = number;
}
public String getCart() {
return cart;
}
public void setCart(String cart) {
this.cart = cart;
}
}
PageVisit1 instance
public class PageVisit1 implements Serializable {
/**
*
*/
private int number;
private String pageName;
public PageVisit1() {
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + number;
result = prime * result + ((pageName == null) ? 0 : pageName.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;
PageVisit1 other = (PageVisit1) obj;
if (number != other.number)
return false;
if (pageName == null) {
if (other.pageName != null)
return false;
} else if (!pageName.equals(other.pageName))
return false;
return true;
}
public PageVisit1(int number, String pageName) {
super();
this.number = number;
this.pageName = pageName;
}
/**
* #return the number
*/
public int getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number) {
this.number = number;
}
/**
* #return the pageName
*/
public String getPageName() {
return pageName;
}
/**
* #param pageName the pageName to set
*/
public void setPageName(String pageName) {
this.pageName = pageName;
}
}
Here is the main class
public class LeftJoins {
public static void main(String[] args) throws InvocationTargetException {
JetInstance jet = Jet.bootstrappedInstance();
IList<AddToCart1> addToCartList = jet.getList("cart");
IList<PageVisit1> paymentList = jet.getList("page");
// AddToCartData
AddToCart1 ad1 = new AddToCart1();
ad1.setNumber(1);
ad1.setCart("lulu bazar");
AddToCart1 ad2 = new AddToCart1();
ad2.setNumber(2);
ad2.setCart("krishna bazar");
AddToCart1 ad3 = new AddToCart1();
ad3.setNumber(3);
ad3.setCart("ram bazar");
addToCartList.add(ad1);
addToCartList.add(ad2);
addToCartList.add(ad3);
// Page Data
PageVisit1 pg1 = new PageVisit1();
pg1.setNumber(1);
pg1.setPageName("k login");
PageVisit1 pg2 = new PageVisit1();
pg2.setNumber(2);
pg2.setPageName("plogin");
paymentList.add(pg1);
paymentList.add(pg2);
// creating a piple-line here
Pipeline p = Pipeline.create();
BatchStageWithKey<AddToCart1, Object> cart = p.readFrom(Sources.<AddToCart1>list("cart"))
.groupingKey(cart1 -> cart1.getNumber());
BatchStageWithKey<PageVisit1, Object> page = p.readFrom(Sources.<PageVisit1>list("page"))
.groupingKey(page1 -> page1.getNumber());
BatchStage<Tuple2<List<PageVisit1>, List<AddToCart1>>> joinedLists1 = page.aggregate2(toList(), cart, toList())
.map(Entry::getValue);
BatchStage<Tuple2<List<PageVisit1>, List<AddToCart1>>> m = joinedLists1.filter(pair -> !pair.f0().isEmpty());
m.writeTo(Sinks.logger());
jet.newJob(p).join();
// joinedLists.filter(pair -> !pair.isEmpty());
}
The code is obviously incomplete, because there's no page variable so that page.aggregate2(...) shouldn't compile.
For this reason, I'm unable to point you to the exact line where the issue occurs. However, the error message tells you're using a "standard" lambda from the JDK that isn't Serializable, whereas you should use the ones from Jet, which are.
Please check this package.
EDIT:
I've created a dedicated GitHub project with the above code.
Everything works as expected. The 2 tuples are displayed correctly in the log:
09:33:59.974 [ INFO] [c.h.j.i.c.WriteLoggerP] [05d8-7d0a-e3c0-0001/loggerSink#0] ([ch.frankel.so.PageVisit1#c544b8f8], [ch.frankel.so.AddToCart1#41c722ed])
09:33:59.974 [ INFO] [c.h.j.i.c.WriteLoggerP] [05d8-7d0a-e3c0-0001/loggerSink#0] ([ch.frankel.so.PageVisit1#58fbcb54], [ch.frankel.so.AddToCart1#c666a2c4])
Related
I'm currently in need of some guidance. Instead of making a huge constructor class with gets/sets. Is it possible to simplify this task?
Trying to avoid having a huge constructor with gets/sets. So I'm assuming what's a good way to avoid doing something like this. How can this sort of thing be simplified significantly?
public User(int id, String name, long skillPoints) {
this.id = id;
this.name = name;
this.skillPoints = skillPoints;
this.level = 0;
// So on so forth
}
Have you heard of Project Lombok?
By adding the annotation #Data you will get a shortcut for #ToString, #EqualsAndHashCode, #Getter on all fields, #Setter on all non-final fields, and #RequiredArgsConstructor. And there are plenty more annotations you can check out!
With Lombok
import lombok.AccessLevel;
import lombok.Setter;
import lombok.Data;
import lombok.ToString;
#Data public class DataExample {
private final String name;
#Setter(AccessLevel.PACKAGE) private int age;
private double score;
private String[] tags;
#ToString(includeFieldNames=true)
#Data(staticConstructor="of")
public static class Exercise<T> {
private final String name;
private final T value;
}
}
Vanilla Java
import java.util.Arrays;
public class DataExample {
private final String name;
private int age;
private double score;
private String[] tags;
public DataExample(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setScore(double score) {
this.score = score;
}
public double getScore() {
return this.score;
}
public String[] getTags() {
return this.tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#Override public String toString() {
return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
}
protected boolean canEqual(Object other) {
return other instanceof DataExample;
}
#Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof DataExample)) return false;
DataExample other = (DataExample) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
if (this.getAge() != other.getAge()) return false;
if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
return true;
}
#Override public int hashCode() {
final int PRIME = 59;
int result = 1;
final long temp1 = Double.doubleToLongBits(this.getScore());
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + this.getAge();
result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
return result;
}
public static class Exercise<T> {
private final String name;
private final T value;
private Exercise(String name, T value) {
this.name = name;
this.value = value;
}
public static <T> Exercise<T> of(String name, T value) {
return new Exercise<T>(name, value);
}
public String getName() {
return this.name;
}
public T getValue() {
return this.value;
}
#Override public String toString() {
return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
}
protected boolean canEqual(Object other) {
return other instanceof Exercise;
}
#Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Exercise)) return false;
Exercise<?> other = (Exercise<?>) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
return true;
}
#Override public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
return result;
}
}
}
Add Kotlin to your project, is becoming the standard, solves your problem as a charm, and as is officially supported by Google, you do not have any problem if you go in production, instead to use other libraries( that could have bugs).
Do not think that you cannot manage to transform all the project from Java to Kotlin, because Kotlin is 100 per cent compatible. One of the K features of Kotlin is just to solve your problem: avoiding to have constructor linked to instance variables and getter and setter, is a lot of boiler plate code.
you just add Kotlin to your project, will take less than 3 minutes, then you can change only the POJO classes, this is the name/acronym of the plain classes you are referring with constructors, getter and setters.
After you installed Kotlin, use Data Classes
in this way a class with 86 lines like the following will become one line. Is worthy to do it, even if you are not going to implement Kotlin to the rest of your project
public class Movie {
private String name;
private String studio;
private float rating;
public Movie(String name, String studio, float rating) {
this.name = name;
this.studio = studio;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudio() {
return studio;
}
public void setStudio(String studio) {
this.studio = studio;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(rating);
result = prime * result + ((studio == null) ? 0 : studio.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;
Movie other = (Movie) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(rating) != Float.floatToIntBits(other.rating))
return false;
if (studio == null) {
if (other.studio != null)
return false;
} else if (!studio.equals(other.studio))
return false;
return true;
}
#Override
public String toString() {
return "Movie [name=" + name + ", studio=" + studio + ", rating=" + rating + "]";
}
}
will become just
this and will get for free also toHash and toString:
data class Movie(var name: String, var studio: String, var rating: Float)
Hello folks this may be dumb question but as a beginner am struggling with this how to group values based on id in list, Now let me clarify you briefly am having set of objects like this :
ID:1,UserID:330
ID:2,UserID:303
ID:3,UserID:090
ID:1,UserID:302
ID:2,UserID:306
How my list should look like is(Json Format):
[{"ID":1,"UserID":[330,302]},{"ID":2,"UserID":[303,306]},{"ID":3,"UserID":[090]}]
Now let me post what i have tried so far:
final List<Integer>list=new ArrayList<>();
final List<SpareReturnModel>lisobj=new ArrayList<>();
int duplicate=0;
for(int i=0;i<tView.getSelected().size();i++){
Object o= tView.getSelected().get(i).getValue();
SpareReturnModel asset=(SpareReturnModel) o;
int flag=asset.getFlag();
if(flag==2) {
int warehouseid = asset.getWareHouseID();
asset.setWareHouseID(warehouseid);
int partid = asset.getSerialNoID();
list.add(partid);
}
else {
Log.d("s","no value for header");
}
if(duplicate!=asset.getWareHouseID()){
asset.setParlist(list);
asset.setWareHouseID(asset.getWareHouseID());
lisobj.add(asset);
list.clear();
}
duplicate=asset.getWareHouseID();
}
Gson gson=new Gson();
//this will convert list to json
String value=gson.toJson(listobj);
SpareReturn Model Class:
public class SpareReturnModel {
private Integer SerialNoID;
private String SerialNumber;
private List<Integer>parlist;
public List<Integer> getParlist() {
return parlist;
}
public void setParlist(List<Integer> parlist) {
this.parlist = parlist;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
private Integer flag;
public Integer getWareHouseID() {
return WareHouseID;
}
public void setWareHouseID(Integer wareHouseID) {
WareHouseID = wareHouseID;
}
private Integer WareHouseID;
public Integer getSerialNoID() {
return SerialNoID;
}
public void setSerialNoID(Integer serialNoID) {
SerialNoID = serialNoID;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
}
Can someone let me know how to achieve this am struggling with this.
I simplify your class to make solution clearer:
public class SpareReturnModel implements Comparable<SpareReturnModel> {
private Integer id;
private String userId;
public SpareReturnModel(Integer id, String userId) {
this.id = id;
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public int compareTo(SpareReturnModel other) {
return this.getId().compareTo(other.getId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpareReturnModel model = (SpareReturnModel) o;
if (id != null ? !id.equals(model.id) : model.id != null) return false;
return userId != null ? userId.equals(model.userId) : model.userId == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
}
and add JsonSpareReturnModel
public class JsonSpareRuturnModel implements Comparable<JsonSpareRuturnModel> {
private final List<SpareReturnModel> modelList;
private final Integer id;
public JsonSpareRuturnModel(List<SpareReturnModel> modelList) {
this.modelList = modelList;
this.id = modelList.get(0).getId();
}
private final String toJson() {
return String.format("{\"ID\":%s,\"UserID\":%s}", id, formatUserIdList());
}
private String formatUserIdList() {
StringBuilder builder = new StringBuilder("[");
Iterator<SpareReturnModel> modelIterator = modelList.iterator();
while (modelIterator.hasNext()) {
builder.append(modelIterator.next().getUserId());
if (modelIterator.hasNext()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JsonSpareRuturnModel that = (JsonSpareRuturnModel) o;
return id != null ? id.equals(that.id) : that.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public int compareTo(JsonSpareRuturnModel other) {
return this.id.compareTo(other.id);
}
#Override
public String toString() {
return toJson();
}
if you need to group by user id you need to sort your models according to id's
and place them to json format model:
public class Main {
public static void main(String[] args) {
List<SpareReturnModel> models = new ArrayList<>(Arrays.asList(
new SpareReturnModel(1, "330"),
new SpareReturnModel(2, "303"),
new SpareReturnModel(3, "090"),
new SpareReturnModel(1, "302"),
new SpareReturnModel(2, "306")
));
Map<Integer, List<SpareReturnModel>> groupById = new HashMap<>();
for (SpareReturnModel model : models) {
List<SpareReturnModel> listById = groupById.get(model.getId());
if (listById == null) {
groupById.put(model.getId(), new ArrayList<>(Arrays.asList(model)));
} else {
listById.add(model);
}
}
List<JsonSpareRuturnModel> jsonList = new ArrayList<>();
for (Map.Entry<Integer, List<SpareReturnModel>> pair : groupById.entrySet()) {
jsonList.add(new JsonSpareRuturnModel(pair.getValue()));
}
System.out.println(jsonList);
final String expected = "[{\"ID\":1,\"UserID\":[330,302]}, {\"ID\":2,\"UserID\":[303,306]}, {\"ID\":3,\"UserID\":[090]}]";
System.out.println(jsonList.toString().equals(expected));
}
}
I am a beginner in android.I am calling a webservice from my android project which returns a json string as response which contain a xml formatted string as one entry.
String jsoncontent=restTemplate.getForObject(constr+"getAssetdata/{Id}", String.class, curAcct.getiD());
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Assets.class, new AssetDeserialiser());
final Gson gson = gsonBuilder.create();
Assets assetAcc = gson.fromJson(jsoncontent, Assets.class);
Toast.makeText(getApplicationContext(), assetAcc.getKeyValueData(), 68000).show();
Below is the json string that i got as webservice response
jsoncontent={"id":39,"name":"ICICI Bank","purchaseValue":6000.0,"purchaseDate":1402403751000,"keyValueData":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><root><Description><Name>Tax and other payments</Name><Value>433</Value></Description><Description><Name>Add more details...</Name><Value></Value></Description></root>"}
But i am getting a null value for assetAcc.getKeyValueData() after deserialization,there is no isue with other fields in assets.How to solve this issue? Please help me.
AssetDeserialiser.java:
public class AssetDeserialiser implements JsonDeserializer<Assets> {
#Override
public Assets deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
JsonObject jobject =arg0.getAsJsonObject();
final Assets asset = new Assets();
try{
asset.setId(jobject.get("id").getAsInt());
asset.setName(jobject.get("name").getAsString());
asset.setPurchaseValue(jobject.get("purchaseValue").getAsFloat());
asset.setPurchaseDate(new Timestamp(jobject.get("purchaseDate").getAsLong()));
asset.setKeyValueData(jobject.get("keyValueData").isJsonNull() ? "" : jobject.get("keyValueData").getAsString());
}catch(Exception es){
System.out.println("es "+es);
}
return asset;
}
}
Assets.java:
public class Assets implements Serializable{
private Integer id;
private String name;
private Float purchaseValue;
private Timestamp purchaseDate;
private String keyValueData;
public Assets() {
super();
// TODO Auto-generated constructor stub
}
public Assets(Integer id, String name, Float purchaseValue, Timestamp purchaseDate, String keyValueData) {
super();
this.id = id;
this.name = name;
this.purchaseValue = purchaseValue;
this.purchaseDate = purchaseDate;
this.keyValueData = keyValueData;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getPurchaseValue() {
return purchaseValue;
}
public void setPurchaseValue(Float purchaseValue) {
this.purchaseValue = purchaseValue;
}
public Timestamp getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Timestamp purchaseDate) {
this.purchaseDate = purchaseDate;
}
public String getKeyValueData() {
return keyValueData;
}
public void setKeyValueData(String keyValueData) {
this.keyValueData = keyValueData;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((keyValueData == null) ? 0 : keyValueData.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((purchaseDate == null) ? 0 : purchaseDate.hashCode());
result = prime * result
+ ((purchaseValue == null) ? 0 : purchaseValue.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;
Assets other = (Assets) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (keyValueData == null) {
if (other.keyValueData != null)
return false;
} else if (!keyValueData.equals(other.keyValueData))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (purchaseDate == null) {
if (other.purchaseDate != null)
return false;
} else if (!purchaseDate.equals(other.purchaseDate))
return false;
if (purchaseValue == null) {
if (other.purchaseValue != null)
return false;
} else if (!purchaseValue.equals(other.purchaseValue))
return false;
return true;
}
#Override
public String toString() {
return name;
}
}
You can set this keyValueData after deserialisation from your json string that contain the xml string as below
String jsoncontent=restTemplate.getForObject(constr+"getAssetdata/{Id}", String.class, curAcct.getiD());
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Assets.class, new AssetDeserialiser());
final Gson gson = gsonBuilder.create();
Assets assetAcc = gson.fromJson(jsoncontent, Assets.class);
JSONObject jsonObj=new JSONObject(jsoncontent);
assetAcc.setKeyValueData(jsonObj.getString("keyValueData"));
1.Use Parcelable -its much faster.
2.Timestamp change to long. (Then can parce this value like this):
private String parceDate(data long){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
try {
retrun df.format(your long from Assets.class);
}catch (Exception e){
return "";
}
}
UPDATE:
Y can change your getter and setter for use Timestamp object from Assets class like this:
public void setPurchaseDate(long purchaseDate){
this.purchaseDate=purchaseDate
}
public Timestamp getPurchaseDate(){
return new Timestamp(purchaseDate); //from java.sql.Timestamp;
}
You can use jackson for deserialization.
public class AssetDeserialiser extends JsonDeserializer<Asset> {
#Override
public Asset deserialize(JsonParser arg0, DeserializationContext arg1)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(arg0);
final Asset asset = new Asset();
try{
asset.setId(mapper.readValue(node.get("id"),Integer.class));
asset.setName(mapper.readValue(node.get("name"),String.class));
asset.setPurchaseDate(mapper.readValue(node.get("purchaseDate"),Timestamp.class));
asset.setPurchaseValue(mapper.readValue(node.get("purchaseValue"),Float.class));
asset.setKeyValueData(mapper.readValue(node.get("keyValueData"), String.class));
}catch(Exception es){
System.out.println("es "+es);
}
return asset;
}
}
This may help you.
Also you will have to add "#JsonDeserialize(using=AssetDeserialiser.class)" at the beginning of your asset class. It is done like this:
#JsonDeserialize(using=AssetDeserialiser.class)
public class Asset implements Serializable{
I have created simple web application with JAAS auth, all works fine, but I need get user's roles list in the servlet, I get subject but it is not return any roles list and related principals. It return only first added principal? Why so?How get roles?
here my sources:
AccLoginModule.java
public class AccLoginModule implements LoginModule {
public Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
private AccPrincipal principal;
private boolean committed = false;
#Override
public boolean abort() throws LoginException {
System.out.println("abort");
if (!committed)
return false;
if (principal != null) {
logout();
principal = null;
}
return true;
}
#Override
public boolean commit() throws LoginException {
try {
if (subject.getPrincipals().size() == 0) {
subject.getPrincipals().add(new AccPrincipal("principal 1"));
subject.getPrincipals().add(new AccPrincipal("principal 2"));
subject.getPrincipals().add(new AccRole("Acc User"));
subject.getPrincipals().add(new AccRole("Acc User1"));
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean login() throws LoginException {
// System.out.println("login");
if (callbackHandler == null)
throw new LoginException("No CallbackHandler specified");
Callback callbacks[] = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
// Interact with the user to retrieve the username and password
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = ((NameCallback) callbacks[0]).getName();
password = new String(((PasswordCallback) callbacks[1]).getPassword());
return true;
} catch (Exception e) {
throw new LoginException(e.toString());
}
}
#Override
public boolean logout() throws LoginException {
System.out.println("logout");
committed = false;
subject.getPrincipals().remove(principal);
return false;
}
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
AccPrincipal
public class AccPrincipal implements Principal, Serializable {
/**
*
*/
private static final long serialVersionUID = 5002820876845306935L;
private final String loginResponse;
public AccPrincipal(String lr) {
this.loginResponse=lr;
}
#Override
public String getName() {
return loginResponse;
}
public String getLoginResponse() {
return loginResponse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((loginResponse == null) ? 0 : loginResponse.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;
AccPrincipal other = (AccPrincipal) obj;
if (loginResponse == null) {
if (other.loginResponse != null)
return false;
} else if (!loginResponse.equals(other.loginResponse))
return false;
return true;
}
}
AccRole
public class AccRole implements Principal, Serializable {
/**
*
*/
private static final long serialVersionUID = 2764250372647034496L;
private String name;
public AccRole(String name){
this.name = name;
}
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.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;
AccRole other = (AccRole) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
context.xml
<Context>
<Realm className="org.apache.catalina.realm.JAASRealm" appName="acczk"
userClassNames="com.laws.acc.jaas.AccPrincipal"
roleClassNames="com.laws.acc.jaas.AccRole">
</Realm>
</Context>
MyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final Subject subject = Subject.getSubject(AccessController.getContext());
for (Principal princ : subject.getPrincipals()) {
System.out.println(princ.getName());
}
}
Console:
09.04.2012 17:11:29 org.apache.catalina.startup.Catalina start
INFO: Server startup in 1385 ms
principal 1
How I can get all entity principals (principals+roles)? What I am doing wrong?
Tomcat and Java EE in general doesn't work like that. You can't access the Subject in the way you are doing it.
See this answer for a full explanation: Tomcat-Jaas - How to retrieve subject?
I have a DropDownChoice :
DropDownChoice timePeriod = new DropDownChoice("timePeriod", Arrays.asList(new TimePeriod(1, "Weekly"), new TimePeriod(2, "Bi-Weekly"), new TimePeriod(3, "Semi-Monthly"), new TimePeriod(4, "Monthly"), new TimePeriod(5, "Yearly")), new IChoiceRenderer() {
private static final long serialVersionUID = 10102L;
#Override
public String getIdValue(Object object, int index) {
return ((TimePeriod) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
return ((TimePeriod) object).getPeriodType();
}
});
timePeriod.setNullValid(false);
My question is:
How to set the selected index to 2 or any other?
How to remove first default blank option?
Thank you.
You should be able to set the selected index by using a PropertyModel instead of hard-coding the values of the dropdown. I can't test at the moment, but it would be something like
String timePeriodValue = "Bi-Weekly";
DropDownChoice timePeriod = new DropDownChoice("timePeriod",
new PropertyModel(this, "timePeriodValue"),
Arrays.asList(/* your options */),
new IChoiceRenderer() {
// ...
// Again, this is pseudocode only
As a bonus, the very act of setting a default value should eliminate the blank option problem.
DropDownChoice has a constructor which accepts the default value.
Or in your code you can add timePeriod.setModel(Model.of(new TimePeriod(2, "Bi-Weekly")))
I guess TimePeriod has proper #equals() and #hashCode() implementations.
About the blank option: see org.apache.wicket.markup.html.form.AbstractSingleSelectChoice.isNullValid()
Lord Torgamus and martin-g thank you both of you. I did a small test. And it is working perfectly. As Lord Torgamus indicated,
#SuppressWarnings({ "unchecked", "rawtypes", "serial" })
public class MyPage extends WebPage {
public MyPage() {
add(new MyForm("form"));
}
private class MyForm extends Form {
public MyForm(String id) {
super(id);
setOutputMarkupPlaceholderTag(true);
setModel(new Model(new FormModel()));
final DropDownChoice timePeriod = new DropDownChoice("timePeriod", new PropertyModel(getModel(), "timePeriod"), Arrays.asList(new TimePeriod(1, "Weekly"), new TimePeriod(2, "Bi-Weekly"), new TimePeriod(3, "Semi-Monthly"), new TimePeriod(4, "Monthly"), new TimePeriod(5, "Yearly")), new IChoiceRenderer() {
private static final long serialVersionUID = 10102L;
#Override
public String getIdValue(Object object, int index) {
return ((TimePeriod) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
return ((TimePeriod) object).getPeriodType();
}
});
timePeriod.setNullValid(false);
add(timePeriod);
timePeriod.setOutputMarkupPlaceholderTag(true);
timePeriod.add(new AjaxFormComponentUpdatingBehavior("onChange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
MyForm form = (MyForm) timePeriod.getParent();
FormModel formModel = (FormModel) form.getModelObject();
formModel.setTimePeriod(new TimePeriod(4, "Monthly"));
form.setModel(new Model(formModel));
target.addComponent(form);
}
});
}
#Override
public void onSubmit() {
System.out.println(getModelObject());
}
}
private class FormModel implements Serializable {
private TimePeriod timePeriod = new TimePeriod(2, "Bi-Weekly");
public FormModel() {
}
public TimePeriod getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(TimePeriod timePeriod) {
this.timePeriod = timePeriod;
}
#Override
public String toString() {
return "FormModel [timePeriod=" + timePeriod + "]";
}
}
private class TimePeriod implements Serializable {
private int id;
private String periodType;
public TimePeriod(int id, String periodType) {
super();
this.id = id;
this.periodType = periodType;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPeriodType() {
return periodType;
}
public void setPeriodType(String periodType) {
this.periodType = periodType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + id;
result = prime * result + ((periodType == null) ? 0 : periodType.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;
TimePeriod other = (TimePeriod) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (id != other.id)
return false;
if (periodType == null) {
if (other.periodType != null)
return false;
} else if (!periodType.equals(other.periodType))
return false;
return true;
}
private LoginPage getOuterType() {
return LoginPage.this;
}
#Override
public String toString() {
return "TimePeriod [id=" + id + ", periodType=" + periodType + "]";
}
}
}
The above code is provided for other users as it might be helpful and I wrote it for testing purpose so all the classes are written in one .java file although it is not advisable.
Thank you.