Insert date from Jdatepicker into MS Access

I have a GUI java interface that allows me to open a JDataPicker in order to insert the selected date into a ms-access database.

I tried inserting the date directly from the JDataPicker :
Date date1 =(Date) jdate_picker.getModel().getSelectedValue();
However, the format retrieved returns : java.text.ParseException: Unparseable date: “Tue Apr 26 00:00:00 EDT 2016” (at offset 0).

I attempted several things but nothing seems to work. For instance, I tried retrieving the month, year and day separately through jdate_picker.getModel().getYear () (and getMonth() and getDay()). Then I concatenated the results to get a MM/DD/YYYY format. After that I used DateFormatter to convert the string to a date format but it still, I’m getting date format exceptions. My questions are as follow:

1- Is there a way that I haven’t thought of which would allow me to insert a date from JDatePicker into an Access database?

2- If not, is there another tool that would allow me to select a date and send it to the Access database?

Thank you.

Checking existence of database and a table in it: `java.sql.SQLException: No database selected`

When using jdbc for mysql, I want to first check if an database and a table in it both exist, before inserting some tuple into the table. The following code is my attempt.

  1. Does conn.setCatalog("STUDENTS") set the current database to database STUDENTS?

  2. If I have switch the current database to STUDENTS, why does running st.executeUpdate("CREATE TABLE student") throw java.sql.SQLException: No database selected?

  3. Are my ways of checking existence of database and table correct? Are there better ways?

Thanks.

Class.forName("com.mysql.jdbc.Driver");

//Open a connection                                                                                                                                                    
System.out.println("Connecting to database...");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);                                      

//Execute a query                                                                                                                                                      
Statement st = conn.createStatement();

// check existence of database  STUDENTS                                                                                                                                        
DatabaseMetaData dbm = conn.getMetaData();
ResultSet databases = dbm.getCatalogs();
boolean hasDB = false;
while (databases.next()){
    String databaseName = databases.getString(1);
    if (databaseName.equals("STUDENTS")){
        hasDB = true;
        break;}
}
if (!hasDB){
    st.executeUpdate("CREATE DATABASE STUDENTS");
    System.out.println("Database created successfully...");
}
conn.setCatalog("STUDENTS"); // Can this set the current database to STUDENTS?

// Check existence of table `student` in database `STUDENTS`
ResultSet tables = dbm.getTables(null, null, "student", null);
if (! tables.next()){
    st.executeUpdate("CREATE TABLE student"); // java.sql.SQLException: No database selected
    System.out.println("Table created successfully...");
}

Sychronization block using this and using object as a lock

I want to know the difference between these two pseudo codes:

1.using sychronized(this)

public class Sums{
    int sum1 = 0;
    int sum2 = 0;
    public void add(int val1, int val2){
        synchronized(this){
            this.sum1 += val1;   
            this.sum2 += val2;
        }
    }   
}   

2.using an object as a lock

public class Sums {
    int sum1 = 0;
    int sum2 = 0;

    Integer sum1Lock = new Integer(1);
    Integer sum2Lock = new Integer(2);

    public void add(int val1, int val2){
        synchronized(this.sum1Lock){
            this.sum1 += val1;   
        }
        synchronized(this.sum2Lock){
            this.sum2 += val2;
        }
    }
}

and I have some questions on this example

  1. When using this keyword:

    is lock just for this block and also for the variables inside this block or lock for this block and not for the variables used in this block.

  2. When using an object for the lock:

    a) is the object is locked through out the application or not ?

    b) and is the variables inside the block are also obtain the lock or not ?

Hope somebody help me.Thanks in advance

Any convenient mehtod to check if there are more objects to read with Kryo?

I’m using Kryo to quickly serialize about 1-2M objects concurrently in a bunch of files and then slowly deserialize and further process them in the background. To read objects, I’m using quite a generic way, as follows (simplified):

// for each file
read(File file) throws Exception {
    try (FileInputStream fis = new FileInputStream(file)) {
        Input ois = new Input(fis);
        Entity entry;
        while ( (entry = readEntry(ois)) != null ) {
            // do stuff with entry            
        } 
        ois.close();
    }
}

readEntry(Input ois) {
    try {
        return (Entity) kryo.readClassAndObject(ois);
    } catch (KryoException e) {
        log.info("EOF")
        return null;
    }
}

Obviously, using exception handling to find EOF isn’t the best idea, so I wonder if there’s any way to check that current stream (created from the upstream file) has no more data to read?

MongoDB run command replSetGetStatus from Java driver

I want to retrieve the detailed status of each member of a replica set in Java driver as a BSON document and then process that document. However, I am having problem with the retrieving step. My code is as following:

MongoClient shard = new MongoClient(new MongoClientURI("mongodb://" + shardUri));

BasicDBObject replStatCmd = new BasicDBObject("replSetGetStatus", 1);
Document replStatus = shard.getDatabase("admin").runCommand(replStatCmd);

System.out.println(replStatus);

I can run this command in the admin database of Mongo shell. But my implementation in Java returns nothing as document and the code never gets to the line println(). Can anyone give me some suggestions ?

Creating object in onTouchEvent

I’ve ran into a problem regarding onTouchEvent().

I am trying to create an object(draw a circle) when MotionEvent.ACTION_POINTER_DOWN and when MotionEvent.ACTION_POINTER_UP – gather it’s area.
Circle is successfully drawn but its’ area is 0. I have a feeling that it gets area after MotionEvent.ACTION_POINTER_UP because when I try to draw next circle it gets area of the previous one. I have no idea how to fix that, could you help me?

This is my onTouchEvent method.

@Override
public boolean onTouchEvent(MotionEvent event) {
    this.gestureDetector.onTouchEvent(event);

    int action = event.getActionMasked();
    int index = event.getActionIndex();
    float xPos;
    float yPos;

    if (event.getPointerCount() > 1) {
        Log.d("MULTI", "Multitouch event");
        xPos = (int) MotionEventCompat.getX(event, index);
        yPos = (int) MotionEventCompat.getY(event, index);
        circleRadius = getDistance(xPos, yPos, event);


        switch (action) {
            case MotionEvent.ACTION_POINTER_DOWN:
                circle = generateCircle();
                drawPoint(circle);
                return false;

            case MotionEvent.ACTION_POINTER_UP:
                circleArea = circle.getFigArea();
                Log.i("circleS", circleS + "");
                break;
        }

    } else {
        Log.d("SINGLE", "Single touch event");
        xPos = (int) MotionEventCompat.getX(event, index);
        yPos = (int) MotionEventCompat.getY(event, index);

    }

    return super.onTouchEvent(event);
}

IDE is wanting to convert my Int into a boolean? and one of my methods says it cannot be applied

I am having issues. it’s wanting to change int len into a boolean? And there is some issue with addNode method.
Not Quite sure what else to add there is this little box yelling at me about adding some more details.
I have all the imports needed.

public class CustomClassLoader extends ClassLoader {


private HashMap<String, ClassNode> classes = new HashMap<String, ClassNode>();


@Override

public Class<?> loadClass(String name) throws ClassNotFoundException {

    return findClass(name);

}


@Override

protected Class<?> findClass(String name) throws ClassNotFoundException {

    ClassNode node = classes.get(name.replace('.', '/'));

    if (node != null)

        return nodeToClass(node);

    else

        return super.findClass(name);

}


public final void addNode(String name, ClassNode node) {

    classes.put(node.name, node);

}


private final Class<?> nodeToClass(ClassNode node) {

    if (super.findLoadedClass(node.name) != null)

        return findLoadedClass(node.name);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

    node.accept(cw);

    byte[] b = cw.toByteArray();

    return defineClass(node.name.replace('/', '.'), b, 0, b.length,

            getDomain());

}


private final ProtectionDomain getDomain() {

    CodeSource code = new CodeSource(null, (Certificate[]) null);

    return new ProtectionDomain(code, getPermissions());

}


private final Permissions getPermissions() {

    Permissions permissions = new Permissions();

    permissions.add(new AllPermission());

    return permissions;

}
private HashMap<String,URL> resources = new HashMap<String,URL>();
public final void addResource(String name,URL url){

    resources.put(name, url);

}
protected URL findResource(String name) {

    if (getSystemResource(name) == null){

        if (resources.containsKey(name))

            return resources.get(name);

        else

            return null;

    }else

        return getSystemResource(name);

}

public void loadClassesFromJar(File jar) throws IOException {

    ZipFile jf = new ZipFile(jar);

    ZipEntry e;

    Enumeration<? extends ZipEntry> entries = jf.entries();

    while (entries.hasMoreElements()) {

        e = entries.nextElement();

        if(e.isDirectory())

            continue; //skip directories, as the file names contain the slashes

        InputStream in = jf.getInputStream(e);

        if (e.getName().endsWith(".class")) {

// reads the class

            ClassReader reader = new ClassReader(in);

            ClassNode cn = new ClassNode();

            reader.accept(cn, ClassReader.SKIP_DEBUG

                    | ClassReader.SKIP_FRAMES);

//add the class to our node list

            addNode(e.getName(), cn);

        } else {

//write the resource to a temporary file

            File tmp = File.createTempFile("06loader", "dat");

            FileOutputStream fout = new FileOutputStream(tmp);

            byte[] b = new byte[1024];

            int len;

            while (len = in.read() >= 0) {

                fout.write(b, 0, len);

            }

            fout.close(); // flushes and closes the file output stream

            addResource(e.getName(),tmp.toURI().toURL());

            tmp.deleteOnExit(); // delete the file once java closes

        }

    }

    jf.close(); // close the jar file

}

}

Meaning of the bold blue font in eclipse

I am new to programming and Java. I am trying to learn it by doing. I am studying the open source library where I found 1 unit test. I created a “sandbox”, where I copied this unit test and I try to put all the code into the main method.
I have the following question: why does the double and int type of variables have blue bold font in the unit test and they are brown in my sandbox. Does that mean that these variables changed somehow? If yes, how did they change ( Should I worry about different behavior of the code than in Unit tests?)
For example,

see the original screenshot of the test file:
original,

see screenshot of my file my_file

and see how I played with Eclipse IDE suggestion to remove the warnings: Eclipse suggestion

It is written that Name ‘TOLERANCE_ROOT’ and ‘STEP_MAX’ must match pattern ‘^[a-z][a-zA-Z0-9]*$’. I believe that it is problem with conventions that my types of the variables in main method are different from the same types of variables in the test class.

Mock/stub Arguments.createMap during testing

In the React Native library theres a class https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/bridge/Arguments.java that is used for Bundles. I’m using PowerMockito to mock the Arguments.createMap() method and return an object with the following snippet:

PowerMockito.when(Arguments.createMap()).thenAnswer(
            new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    return new JavaOnlyMap();
                }
            });

The method I’m testing errors with the following message when the test is ran:

java.lang.UnsatisfiedLinkError: no reactnativejni in java.library.path

when executing this line:

WritableMap map = Arguments.createMap();

Any ideas?

OpenCSV does not write bean records

I just start using OpenCSV for my project. After runing this code, created “test.csv” file on my Desktop but its empty. Where am i doing wrong?

public class test {
    List<MockBean> testData = new ArrayList<MockBean>();

    public static void main(String[] args) {
        try {
            List<MockBean> testData = new ArrayList<MockBean>();
            MockBean mb = new MockBean();
            mb.setName("kyle");
            mb.setOrderNumber("abc123456");
            mb.setNum(123);
            testData.add(mb);
            mb = new MockBean();
            mb.setName("jimmy");
            mb.setOrderNumber("def098765");
            mb.setNum(456);
            testData.add(mb);

            Writer writer = new FileWriter("C:\Users\ali.gumusoglu\Desktop\New folder\test.csv");

            ColumnPositionMappingStrategy mappingStrategy = 
                    new ColumnPositionMappingStrategy();
            mappingStrategy.setType(MockBean.class);

            StatefulBeanToCsvBuilder<MockBean> builder = new StatefulBeanToCsvBuilder(writer);

            StatefulBeanToCsv beanWriter = builder
                    .withMappingStrategy(mappingStrategy)
                    .withSeparator('#')
                    .withQuotechar(''')
                    .build();
            beanWriter.write(testData);
            System.out.println("CSV File written successfully!!!");


        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}

Thanks you for your help.