How to format SimpleIntegerProperty output - formatting

I do have a SimpleIntegerProperty which contains a number which is the time in 100ms steps like 40 is 4,0 seconds
I do want to display this value to the user with a Label which should display "4,0 s"
I would like to bind the value with the bindings api like
label.textProperty().bind(myobject.secondsProperty().asString());
but how do i create a simple and reusable Converter, i do need only the unidirectional binding.

There is an overloaded form of the asString(...) method that takes a format string as an argument:
String secondsFormat = "%.1f s" ;
label.textProperty().bind(myobject.secondsProperty().asString(secondsFormat));
If you really need a StringConverter, you can do
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
#Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
#Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
and then
label.textProperty().bind(Bindings.createStringBinding(
() -> deciSecondsConverter.toString(myobject.getSeconds()),
myobject.secondsProperty()
));
SSCCE:
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class StopwatchTest extends Application {
#Override
public void start(Stage primaryStage) {
IntegerProperty tenthsOfSeconds = new SimpleIntegerProperty();
Label label = new Label();
StringConverter<Integer> deciSecondsConverter = new StringConverter<Integer>() {
#Override
public String toString(Integer deciSeconds) {
return String.format("%.1f s", deciSeconds.doubleValue()/10);
}
#Override
public Integer fromString(String string) {
// not implemented
return null ;
}
};
label.textProperty().bind(Bindings.createStringBinding(() ->
deciSecondsConverter.toString(tenthsOfSeconds.get()),
tenthsOfSeconds));
new AnimationTimer() {
#Override
public void handle(long now) {
tenthsOfSeconds.set((int)System.currentTimeMillis() % 60000 / 100);
}
}.start();
label.setPadding(new Insets(5, 20, 5, 20));
primaryStage.setScene(new Scene(label, 80, 30));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Related

Jackson-Serialiser: Ignore Field at Serialisation Time

My situation asks for a bit more complex serialisation. I have a class Available (this is a very simplified snippet):
public class Available<T> {
private T value;
private boolean available;
...
}
So a POJO
class Tmp {
private Available<Integer> myInt = Available.of(123);
private Available<Integer> otherInt = Available.clean();
...
}
would normally result in
{"myInt":{available:true,value:123},"otherInt":{available:false,value:null}}
However, I want a serialiser to render the same POJO like this:
{"myInt":123}
What I have now:
public class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
if (available != null && available.isAvailable()) {
jsonGenerator.writeObject(available.getValue());
}
// MISSING: nothing at all should be rendered here for the field
}
#Override
public Class<Available<?>> handledType() {
#SuppressWarnings({ "unchecked", "rawtypes" })
Class<Available<?>> clazz = (Class) Available.class;
return clazz;
}
}
A test
#Test
public void testSerialize() throws Exception {
SimpleModule module = new SimpleModule().addSerializer(new AvailableSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
outputs
{"myInt":123,"otherInt"}
Can anyone tell me how to do the "MISSING"-stuff? Or if I'm doing it all wrong, how do I do it then?
The restriction I have is that I don't want the developers to add #Json...-annotations all the time to fields of type Available. So the Tmp-class above is an example of what a typical using class should look like. If that's possible...
Include.NON_DEFAULT
If we assume that your clean method is implemented in this way:
class Available<T> {
public static final Available<Object> EMPTY = clean();
//....
#SuppressWarnings("unchecked")
static <T> Available<T> clean() {
return (Available<T>) EMPTY;
}
}
You can set serialisation inclusion to JsonInclude.Include.NON_DEFAULT value and it should skip values set to EMPTY (default) values. See below example:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import java.io.IOException;
public class JsonApp {
public static void main(String[] args) throws Exception {
SimpleModule module = new SimpleModule();
module.addSerializer(new AvailableSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
}
class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
jsonGenerator.writeObject(value.getValue());
}
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
public Class<Available<?>> handledType() {
return (Class) Available.class;
}
}
Above code prints:
{"myInt":123}
Custom BeanPropertyWriter
If you do not want to use Include.NON_DEFAULT you can write your custom BeanPropertyWriter and skip all values you want. See below example:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
SimpleModule module = new SimpleModule();
module.addSerializer(new AvailableSerializer());
module.setSerializerModifier(new BeanSerializerModifier() {
#Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
List<BeanPropertyWriter> writers = new ArrayList<>(beanProperties.size());
for (BeanPropertyWriter writer : beanProperties) {
if (writer.getType().getRawClass() == Available.class) {
writer = new SkipNotAvailableBeanPropertyWriter(writer);
}
writers.add(writer);
}
return writers;
}
});
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
}
class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
jsonGenerator.writeObject(value.getValue());
}
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
public Class<Available<?>> handledType() {
return (Class) Available.class;
}
}
class SkipNotAvailableBeanPropertyWriter extends BeanPropertyWriter {
SkipNotAvailableBeanPropertyWriter(BeanPropertyWriter base) {
super(base);
}
#Override
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
// copier from super.serializeAsField(bean, gen, prov);
final Object value = (_accessorMethod == null) ? _field.get(bean) : _accessorMethod.invoke(bean, (Object[]) null);
if (value == null || value instanceof Available && !((Available) value).isAvailable()) {
return;
}
super.serializeAsField(bean, gen, prov);
}
}
Above code prints:
{"myInt":123}
After Michał Ziober's answer I had to look for something regarding Include.NON_DEFAULT and the default object and ran into this answer explaining Include.NON_EMPTY that Google didn't return in my first research (thanks Google).
So things become easier, it's now:
public class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
jsonGenerator.writeObject(available.getValue());
}
#Override
public Class<Available<?>> handledType() {
#SuppressWarnings({ "unchecked", "rawtypes" })
Class<Available<?>> clazz = (Class) Available.class;
return clazz;
}
#Override
public boolean isEmpty(SerializerProvider provider, Available<?> value) {
return value == null || !value.isAvailable();
}
}
with the test
#Test
public void testSerialize() throws Exception {
SimpleModule module = new SimpleModule().addSerializer(availableSerializer);
objectMapper.registerModule(module);
objectMapper.configOverride(Available.class).setInclude(
// the call comes from JavaDoc of objectMapper.setSerializationInclusion(...)
JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, JsonInclude.Include.ALWAYS));
Tmp tmp = new Tmp();
assertThat(objectMapper.writeValueAsString(tmp)).isEqualTo("{\"myInt\":123}");
tmp.otherInt.setValue(123);
assertThat(objectMapper.writeValueAsString(tmp)).isEqualTo("{\"myInt\":123,\"otherInt\":123}");
}
So please, if you upvote my answer please also upvote Michał Ziober's as that's also working with a mildly different approach.

How to create MAD army base droid?

DBHELPER..........}}}}}}}}}
package com.example.userlap.model2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String Database="Model.db";
public DBHelper(Context context) {
super(context, Database, null, 1);
//SQLiteDatabase db=this.getWritableDatabase() ;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ UserProfile.Users.TableName+" ("+ UserProfile.Users.Col_1+" Integer primary key AUTOINCREMENT,"+ UserProfile.Users.Col_2 +" TEXT,"+ UserProfile.Users.Col_3 +" TEXT,"+ UserProfile.Users.Col_4 +" TEXT,"+ UserProfile.Users.Col_5 +" TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+ UserProfile.Users.TableName);
onCreate(db);
}
public boolean addInfo(String uname,String DOb,String password,String Gender){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(UserProfile.Users.Col_2,uname);
cv.put(UserProfile.Users.Col_3,DOb);
cv.put(UserProfile.Users.Col_4,password);
cv.put(UserProfile.Users.Col_5,Gender);
long ans=db.insert(UserProfile.Users.TableName,null,cv);
if(ans==-1){
return false;
}
else
return true;
}
public boolean updateInfor(int id,String uname,String DOb,String password,String Gender){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(UserProfile.Users.Col_2,uname);
cv.put(UserProfile.Users.Col_3,DOb);
cv.put(UserProfile.Users.Col_4,password);
cv.put(UserProfile.Users.Col_5,Gender);
long ans=db.update(UserProfile.Users.TableName,cv,"UserInfo="+id,null);
if(ans==-1){
return false;
}
else
return true;
}
public List readAllInfor(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
public List readAllInfor(int id){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName+" where _ID="+id,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
public Integer deleteInfo(int id){
SQLiteDatabase db=this.getWritableDatabase();
return db.delete(UserProfile.Users.TableName,"_ID=?"+id,null);
}
}
USERPROFILE-----------------------------------------------------
package com.example.userlap.model2;
import android.provider.BaseColumns;
public class UserProfile {
private UserProfile() {
}
public final static class Users implements BaseColumns{
public static final String Col_1="_ID";
public static final String Col_2="userName";
public static final String Col_3="dateOfBirth";
public static final String Col_4="Password";
public static final String Col_5="Gender";
public static final String TableName="UserInfo";
}
}
HOME---------------------------------------------------
package com.example.userlap.model2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
DBHelper mydb;
Button register,login;
EditText id,pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mydb=new DBHelper(this);
register=(Button)findViewById(R.id.button2);
login=(Button)findViewById(R.id.button) ;
id=(EditText)findViewById(R.id.editText);
pw=(EditText)findViewById(R.id.editText2);
login();
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i1=new Intent(Home.this,ProfileManagement.class);
startActivity(i1);
}
});
}
public void login(){
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<ui> list=(ArrayList<ui>)mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list.isEmpty()){
for(ui u:list){
if(u.getID()==Integer.parseInt(id.getText().toString()) && u.getPasssword().equals(pw.getText().toString())){
Intent i1=new Intent(Home.this,EditProfile.class);
startActivity(i1);
}
}
}
}
});
}
}
ProfileManagement----------------------------
package com.example.userlap.model2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class ProfileManagement extends AppCompatActivity {
Button edit,register;
EditText uname,pass,dob;
DBHelper mydb;
RadioButton type;
RadioGroup gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
mydb=new DBHelper(this);
edit=(Button)findViewById(R.id.button6);
register=(Button)findViewById(R.id.button7);
uname=(EditText)findViewById(R.id.editText6);
pass=(EditText)findViewById(R.id.editText7);
dob=(EditText)findViewById(R.id.editText8);
gender=(RadioGroup)findViewById(R.id.radioGroup2);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2=new Intent(ProfileManagement.this,EditProfile.class);
startActivity(i2);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean res= mydb.addInfo(uname.getText().toString(),dob.getText().toString(),pass.getText().toString(),gtype(gender));
if(res=true){
Toast.makeText(ProfileManagement.this,"Successful",Toast.LENGTH_LONG).show();
}
else
Toast.makeText(ProfileManagement.this,"NOT ",Toast.LENGTH_LONG).show();
}
});
}
public String gtype(View v){
int res=gender.getCheckedRadioButtonId();
type=(RadioButton)findViewById(res);
return type.getText().toString();
}
}
EditProfile-----------------------------------------------------------
package com.example.userlap.model2;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
public class EditProfile extends AppCompatActivity {
Button search,edit,delete;
DBHelper mydb;
RadioButton type,male,female;
RadioGroup gender;
EditText uname,pass,dob,id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mydb=new DBHelper(this);
//ArrayList<ui> list11=new ArrayList<>();
setContentView(R.layout.activity_edit_profile);
search=(Button)findViewById(R.id.button3);
edit=(Button)findViewById(R.id.button4);
delete=(Button)findViewById(R.id.button5);
uname=(EditText)findViewById(R.id.editText3);
pass=(EditText)findViewById(R.id.editText5);
dob=(EditText)findViewById(R.id.editText4);
gender=(RadioGroup)findViewById(R.id.radioGroup);
id=(EditText)findViewById(R.id.editText9);
male=(RadioButton)findViewById(R.id.radioButton);
female=(RadioButton)findViewById(R.id.radioButton2);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
}
}
}
});
}
public String gtype(View v){
int res=gender.getCheckedRadioButtonId();
type=(RadioButton)findViewById(res);
return type.getText().toString();
}
}
ui-----------------------------------------------------------------------------------
package com.example.userlap.model2;
public class ui {
private String usename;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
private int ID;
private String Passsword;
private String DOB;
private String Gender;
public String getUsename() {
return usename;
}
public void setUsename(String usename) {
this.usename = usename;
}
public String getPasssword() {
return Passsword;
}
public void setPasssword(String passsword) {
Passsword = passsword;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
}
selecting a single record
public List readAllInfor(int id){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName+" where _ID="+id,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
-- Calling it
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor(Integer.parseInt(id.getText().toString()));
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
Selecting all records
public List readAllInfor(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor cus=db.rawQuery("Select * from "+ UserProfile.Users.TableName,null);
ArrayList<ui> list=new ArrayList<>();
if(cus.getCount()>0){
while (cus.moveToNext()){
ui ui1=new ui();
ui1.setID(cus.getInt(0));
ui1.setUsename(cus.getString(1));
ui1.setDOB(cus.getString(2));
ui1.setPasssword(cus.getString(3));
ui1.setGender(cus.getString(4));
list.add(ui1);
}
}
return list;
}
--calling it
ArrayList<ui> list11= (ArrayList<ui>) mydb.readAllInfor();
if(!list11.isEmpty()){
for(ui i:list11){
uname.setText(i.getUsename());
pass.setText(i.getPasssword());
dob.setText(i.getDOB());
if(i.getGender().equals("Male")){
male.setChecked(true);
}
else
female.setChecked(true);
-- USING CURSORS --
Selecting a single Record
public MovieDetailsVO getMovie(int movie_id) {
MovieDetailsVO movieDetails = new MovieDetailsVO();
SQLiteDatabase db = this.getReadableDatabase();
//specify the columns to be fetched
String[] columns = {KEY_MOVIE_ID, KEY_MOVIE_NAME, KEY_GENRE, KEY_YEAR, KEY_RATING};
//Select condition
String selection = KEY_MOVIE_ID + " = ?";
//Arguments for selection
String[] selectionArgs = {String.valueOf(movie_id)};
Cursor cursor = db.query(TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
movieDetails.setMovieId(cursor.getInt(0));
movieDetails.setMovieName(cursor.getString(1));
movieDetails.setGenre(cursor.getString(2));
movieDetails.setYear(cursor.getInt(3));
movieDetails.setRating(cursor.getDouble(4));
}
db.close();
return movieDetails;
}
Retrieving all Records
public List getAllMovies() {
List movieDetailsList = new ArrayList();
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " ORDER BY " + KEY_MOVIE_ID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//if TABLE has rows
if (cursor.moveToFirst()) {
//Loop through the table rows
do {
MovieDetailsVO movieDetails = new MovieDetailsVO();
movieDetails.setMovieId(cursor.getInt(0));
movieDetails.setMovieName(cursor.getString(1));
movieDetails.setGenre(cursor.getString(2));
movieDetails.setYear(cursor.getInt(3));
movieDetails.setRating(cursor.getDouble(4));
//Add movie details to list
movieDetailsList.add(movieDetails);
} while (cursor.moveToNext());
}
db.close();
return movieDetailsList;
}

In Eclipse WizardPage - Issues in Navigating between pages

I have written a small program which should navigate from one page to another. But I am unable to do that.
My requirement is
On PageOne, if the user Enters a value it should be validated i.e simple comparison in this case it is "123".
if it matches the proceed to the next page as shown below:
Page One
Page Two
else throw a dialogue box below:
Page One
Page One Code:
package testing.importWizards;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class PageOne extends WizardPage {
private Text text1;
private Composite container;
boolean isVisible=false;
public PageOne() {
super("Page One");
setTitle("Page One");
setDescription("Fake Wizard: Page One");
}
#Override
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
Label label1 = new Label(container, SWT.NONE);
label1.setText("Put a value here.");
text1 = new Text(container, SWT.BORDER | SWT.SINGLE);
text1.setText("");
text1.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if (!text1.getText().isEmpty()) {
setPageComplete(true);
}
}
});
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
text1.setLayoutData(gd);
setControl(container);
setPageComplete(false);
}
#Override
public IWizardPage getNextPage() {
// TODO Auto-generated method stub
Shell shell=getShell();
return super.getNextPage();
}
public String getText1() {
return text1.getText();
}
}
Page Two Code:
package testing.importWizards;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class PageTwo extends WizardPage {
private Text text1;
private Composite container;
public PageTwo() {
super("Page Two");
setTitle("Page Two");
setDescription("Fake Wizard: Page Two");
}
#Override
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
Label label1 = new Label(container, SWT.NONE);
label1.setText("Success");
/*text1 = new Text(container, SWT.BORDER | SWT.SINGLE);
text1.setText("");
text1.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if (!text1.getText().isEmpty()) {
setPageComplete(true);
}
}
});*/
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
//text1.setLayoutData(gd);
setControl(container);
//setPageComplete(false);
setPageComplete(true);
}
public String getText1() {
return text1.getText();
}
}
I have teid overriding setVisible and getNextPage Methods, but I am getting erroneous behaviour. Could someone please explaing me the logic for implementing the validation. Is my entire approach wrong?
Rather than displaying a dialog it is usual for a wizard page to display errors in the top area of the wizard using setErrorMessage or setError.
Usually it is convenient to do the validation every time data on the page is changed. For your example page one something like:
public class PageOne extends WizardPage
{
private Text text1;
public PageOne()
{
super("testWizardPage");
setTitle("Page One");
setDescription("Fake Wizard: Page One");
}
#Override
public void createControl(final Composite parent)
{
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout(2, false));
Label label1 = new Label(container, SWT.NONE);
label1.setText("Put a value here.");
text1 = new Text(container, SWT.BORDER | SWT.SINGLE);
text1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
text1.addModifyListener(this::modifyListener);
setControl(container);
setPageComplete(false);
}
private void modifyListener(final ModifyEvent event)
{
boolean empty = text1.getText().isEmpty();
if (empty)
setErrorMessage("Text must be entered");
else
setErrorMessage(null);
setPageComplete(!empty);
}
}
This is using a 'modify listener' on the text1 field and calling setErrorMessage and setPageComplete each time the field is changed.

Hadoop Record Reader only reads first line then input stream seems to be closed

I'm trying to implement a hadoop job, that counts how often a object (Click) appears in a dataset.
Therefore i wrote a custom file input format. The record reader seems to read only the first line of the given file and the close the input stream.
Here is the code:
The Pojo class:
package model;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.WritableComparable;
public class Click implements WritableComparable<Click> {
private String user;
private String clickStart;
private String date;
private String clickTarget;
#Override
public void write(DataOutput out) throws IOException {
out.writeUTF(user);
out.writeUTF(clickStart);
out.writeUTF(date);
out.writeUTF(clickTarget);
}
#Override
public void readFields(DataInput in) throws IOException {
user = in.readUTF();
clickStart = in.readUTF();
date = in.readUTF();
clickTarget = in.readUTF();
}
public int compareTo(Click arg0) {
int response = clickTarget.compareTo(arg0.clickTarget);
if (response == 0) {
response = date.compareTo(arg0.date);
}
return response;
}
public String getUser(String user) {
return this.user;
}
public void setUser(String user) {
this.user = user;
}
public String getClickStart() {
return clickStart;
}
public void setClickStart(String clickStart) {
this.clickStart = clickStart;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getClickTarget() {
return clickTarget;
}
public void setClickTarget(String clickTarget) {
this.clickTarget = clickTarget;
}
public String toString() {
return clickStart + "\t" + date;
}
}
Here is the FileInputFormat class:
package ClickAnalysis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import model.Click;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.tools.ant.types.CommandlineJava.SysProperties;
public class ClickAnalysisInputFormat extends FileInputFormat<Click, IntWritable>{
#Override
public RecordReader<Click, IntWritable> createRecordReader(
InputSplit split, TaskAttemptContext context) throws IOException,
InterruptedException {
System.out.println("Creating Record Reader");
return new ClickReader();
}
public static class ClickReader extends RecordReader<Click, IntWritable> {
private BufferedReader in;
private Click key;
private IntWritable value;
#Override
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException {
key = new Click();
value = new IntWritable(1);
System.out.println("Starting to read ...");
FileSplit split = (FileSplit) inputSplit;
Configuration conf = context.getConfiguration();
Path path = split.getPath();
InputStream is = path.getFileSystem(conf).open(path);
in = new BufferedReader(new InputStreamReader(is));
}
#Override
public boolean nextKeyValue() throws IOException, InterruptedException {
String line = in.readLine();
System.out.println("line: " + line);
boolean hasNextKeyValue;
if (line == null) {
System.out.println("line is null");
hasNextKeyValue = false;
} else {
String[] click = StringUtils.split(line, '\\', ';');
System.out.println(click[0].toString());
System.out.println(click[1].toString());
System.out.println(click[2].toString());
key.setClickStart(click[0].toString());
key.setDate(click[1].toString());
key.setClickTarget(click[2].toString());
value.set(1);
System.out.println("done with first line");
hasNextKeyValue = true;
}
System.out.println(hasNextKeyValue);
return hasNextKeyValue;
}
#Override
public Click getCurrentKey() throws IOException, InterruptedException {
return this.key;
}
#Override
public IntWritable getCurrentValue() throws IOException, InterruptedException {
return this.value;
}
#Override
public float getProgress() throws IOException, InterruptedException {
return 0;
}
public void close() throws IOException {
in.close();
System.out.println("in closed");
}
}
}
The Mapper class:
package ClickAnalysis;
import java.io.IOException;
import model.Click;
import model.ClickStartTarget;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Mapper;
import org.jruby.RubyProcess.Sys;
public class ClickAnalysisMapper extends Mapper<Click, IntWritable, Click, IntWritable> {
private static final IntWritable outputValue = new IntWritable();
#Override
protected void map(Click key, IntWritable value, Context context) throws IOException, InterruptedException {
System.out.println("Key: " + key.getClickStart() + " " + key.getDate() + " " + key.getClickTarget() + " Value: " + value);
outputValue.set(value.get());
System.out.println(outputValue.get());
context.write(key, outputValue);
System.out.println("nach context");
}
}
Partitioner class:
package ClickAnalysis;
import model.Click;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Partitioner;
public class ClickAnalysisPartitioner extends Partitioner<Click, IntWritable> {
#Override
public int getPartition(Click key, IntWritable value, int numPartitions) {
System.out.println("in Partitioner drinnen");
int partition = numPartitions;
return partition;
}
}
Hadoop Job, which is triggered via an Restful web service call in a servlet container, but this shouldn't be the problem:
package ClickAnalysis;
import model.Click;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
public class ClickAnalysisJob {
public int run() throws Exception {
// TODO Auto-generated method stub
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "ClickAnalysisJob");
job.setJarByClass(ClickAnalysisJob.class);
// Job Input path
FileInputFormat.setInputPaths(job, "hdfs://localhost:9000/user/hadoop/testdata1.csv");
// Job Output path
Path out = new Path("hdfs://localhost:9000/user/hadoop/clickdataAnalysis_out");
FileOutputFormat.setOutputPath(job, out);
out.getFileSystem(conf).delete(out,true);
job.setMapperClass(ClickAnalysisMapper.class);
job.setReducerClass(Reducer.class);
job.setPartitionerClass(ClickAnalysisPartitioner.class);
//job.setReducerClass(ClickAnalysisReducer.class);
job.setInputFormatClass(ClickAnalysisInputFormat.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setOutputKeyClass(Click.class);
job.setOutputValueClass(IntWritable.class);
job.setMapOutputKeyClass(Click.class);
job.setMapOutputValueClass(IntWritable.class);
System.out.println("in run drinnen");
//job.setGroupingComparatorClass(ClickTargetAnalysisComparator.class);
job.setNumReduceTasks(1);
int result = job.waitForCompletion(true)? 0:1;
return result;
}
}
Next the dataset (example):
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein anderes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein anderes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein drittes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein viertes ziel
/web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
When I run the program the syso's are showing following:
in run drinnen
Creating Record Reader
Starting to read ...
line: /web/big-data-test-site/test-seite-1;2014-07-08;ein ziel
/web/big-data-test-site/test-seite-1
2014-07-08
ein ziel
done with first line
true
Key: /web/big-data-test-site/test-seite-1 2014-07-08 ein ziel Value: 1
1
in closed
analyze Method: 1
From that i conclude that the record reader only reads the first line.
Why is this happening and how is it fixed?

custom colorpicker not working in android

I have made a Simple drawing application in android for the learning purpose..In that i have taken diffrent colorbuttons just like a colorpicker in horizontalscrollview,Now i need is when one of them is clicked that particular color should be chosen and pencolor od drawing pen should be changed..I have tried as below,but its not working..Please help me for the same,Thanx in advance...!
main.java
public void onClick(View v) {
switch (v.getId()) {
case R.id.black:
myplate.setVisibility(View.GONE);
mDrawView.setColor(SingleTouchView.DrawingColors.Black);
break;
case R.id.blue:
myplate.setVisibility(View.GONE);
mDrawView.setColor(SingleTouchView.DrawingColors.Blue);
break;
...so on...for other colors
MyView.java
package com.example.singletouch;
import java.util.AbstractMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import android.R.color;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;
public class SingleTouchView extends View {
public static int width;
public int height;
public Bitmap mBitmap;
public Canvas mCanvas;
public Path mPath;
public Paint mBitmapPaint;
Context context;
public Paint mPaint;
public Paint circlePaint;
public Path circlePath;
public enum DrawingPens {
PEN_1(6), PEN_2(4), PEN_3(2), PEN_4(1);
public Paint mPaint;
private DrawingPens(final int width) {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(width);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
}
Paint getPaint() {
return mPaint;
}
}
public enum DrawingColors{
Black(Color.parseColor("#000000")),Blue(Color.parseColor("#0000FF")),Cofee(Color.parseColor("#D2691E")),Cyan(Color.parseColor("#00FFFF"))
,Fuchiya(Color.parseColor("#FF00FF")),Gray(Color.parseColor("#808080")),Green(Color.parseColor("#00FF00")),Indigo(Color.parseColor("#4B0082")),
Khaki(Color.parseColor("#F0E68C")),Lavendar(Color.parseColor("#E6E6FA")),Magenta(Color.parseColor("#FF00FF")),Mango(Color.parseColor("#FF8C00"))
,Maroon(Color.parseColor("#800000")),Orange(Color.parseColor("#FFA500")),Pink(Color.parseColor("#FFC0CB")),Pista(Color.parseColor("#9ACD32")),
Purple(Color.parseColor("#800080")),Red(Color.parseColor("#FF0000")),Tan(Color.parseColor("#0000A0")),Yellow(Color.parseColor("#FFD801"));
public Paint mPaint;
private DrawingColors(final int color) {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(width);
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
}
Paint getPaint() {
return mPaint;
}
}
public SingleTouchView(final Context context) {
super(context);
init(context);
}
public SingleTouchView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context);
mBitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
}
public SingleTouchView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>> mPaths = new ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>>();
private ConcurrentLinkedQueue<Map.Entry<Path, DrawingColors>> mPaths1 = new ConcurrentLinkedQueue<Map.Entry<Path, DrawingColors>>();
private Path mCurrentPath;
private void init(final Context context) {
setPen(DrawingPens.PEN_1);
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (Map.Entry<Path, DrawingPens> entry : mPaths) {
canvas.drawPath(entry.getKey(), entry.getValue().getPaint());
}
}
#Override
public boolean onTouchEvent(MotionEvent me) {
float eventX = me.getX();
float eventY = me.getY();
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
mCurrentPath.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
mCurrentPath.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
break;
}
invalidate();
return true;
}
public void setPen(final DrawingPens pen) {
mCurrentPath = new Path();
mPaths.add(new AbstractMap.SimpleImmutableEntry<Path, DrawingPens>(
mCurrentPath, pen));
}
public void eraser() {
// TODO Auto-generated method stub
mPaint = new Paint();
/* Toast.makeText(getContext(), "eraser", Toast.LENGTH_LONG).show();
mPaint.setXfermode(null);
mPaint.setAlpha(0x00FFFFFF);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));*/
// invalidate();
}
public void setColor(final DrawingColors color ) {
mCurrentPath = new Path();
mPaths1.add(new AbstractMap.SimpleImmutableEntry<Path, DrawingColors>(
mCurrentPath, color));
}
}
Please help me friends..please...
still a bit unclear but I will try to give you a direction. What happens if you try the below onDraw method? I have a feeling you have not set the colors. The code is a bit messy and not clear to read. Don't worry for now about the performance, creating a new paint every time, just want to make sure it give's you the wanted result.
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
for (Map.Entry<Path, DrawingPens> entry : mPaths) {
canvas.drawPath(entry.getKey(), paint);
}
}