jeudi 13 août 2015

Establish connection between app server and oracle database using java

I have been given a task to write a script in java, to connect oracle database from an app server. Scheduling tool will be used to schedule the job every 10 minutes.

If connection exists, the script will do nothing and just disconnect it. (and will be run again after 10 minutes). If cannot connect after 10 secs, the program will send an email notification.

The whole thing is to ensure connection can be established between the app server and the oracle db.

Really have no clue on this. Could you please advise what are the steps to do this and what Java APIs I'll need??

Many many thanks in advance!



via Chebli Mohamed

Full screen mode in java application

I would like to make an app that have a button that make the app full screen when clicked and then change to normal when the button is clicked second time. The JDK is 1.7 and I know it support application in full screen mode. I tried in many ways but not succeed. Please, is there someone who could help me?



via Chebli Mohamed

DateFormat return null java

I'm confused. I've tried, well I can not assign a null value to projects which have no date. What am i doing wrong?

 private static String projectDate = null;
    public static void main(String[] args) throws Exception {
        DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
            List<Project> projects;
            if (projects == null || projects.size() == 0) {
            } else {
                for (Project project : projects) {
                    try {
                        projectDate = formatter.format(project.getLastAnalyzedDate().getTime());
                    }catch (Exception e) {
                        System.err.println("Last Analyzed failed");
                    }
                    outFile.println("<LastAnalyzed>" + projectDate + "</LastAnalyzed>");



via Chebli Mohamed

Simple upload to S3 from android

I've searched the web for ways to upload a simple file to s3 from android but couldn't find anything that work and I think it is because lack of concrete steps.

1.) http://ift.tt/1PaB2FW

That is the best guide I found but it does not tell what libraries to include. I downloaded the aws sdk for android and inside there were many jars. So intuitively, I included the aws-android-sdk-s3-2.2.5.jar however that is not complete. It does not have the class BasicAWSCredentials.

2.)I've looked at the more at the sample but it is not straightforward as #1 and I couldn't get the core upload functionality with credentials.

I appreciate your help



via Chebli Mohamed

Crosswalk project how to keep view alive

My app works with regular webview but it's very slow under Android 4.0 - 4.2 and just slow on 4.3 and 4.4.

I've already done lot of optimalizations in html/js/css, but still is too slow. So decided to take a look at Crosswalk project.

It's almost all great even with +20mb size for apk, except for one thing..

You cannot create XWalkView (equivalent of WebView) with Service context (like you can do with regular WebView) only Activity context is an option for Crosswalk view.

Why it's bad?

The website that I load into WebView/XWalkView uses WebSockets, it has to be always alive! But Android likes to kill apps, especially on older devices with Android 4.0-4.2.

Solution is to create WebView with Service context and keep reference to it in Service (Service is in foreground mode so hard to kill!).

Then if Activity will crash or will be garbage-collected, simply user taps to it, Activity recreates himself and gets reference to WebView (from Service class) to add it to his hierarchy again. :) (and in the meantime when activity didn't exist, webview was still working along with websocket connection)

All works, but with WebView and WebView is slow..

Why I am writing it? Need advice from you what to do or maybe solution how to force CrossWalk view to works with Service context.

Is it other way to keep XWalkView "always" alive?

Thanks!



via Chebli Mohamed

Java: PrintWriter object does not output the text on my file?

I'm trying to print out the usernames of a certain program into a file but PrintWriter is not printing anything on my file. I've tried everything mentioned on stackOverFlow none of them worked.

Users Class

private File usersListFile;
private PrintWriter usersListPrintWriter;
private Scanner usersListScanner;

Constructor:

Users(){
    try {
        this.usersListFile = new File("D:\\Dairy\\usersList.txt");
        if(usersListFile.exists()){
            this.usersListPrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("D:\\Dairy\\usersList.txt", true)));
            this.usersListScanner = new Scanner("D:\\Dairy\\usersList.txt");
        }
        else
            System.err.println("File does not exist !");
    }
    catch(Exception e){
        System.err.println("Error: Users Class!");                   
    }
}

Method:

public void addToUsersList(String username){
        usersListPrintWriter.print(username);           
    }

Main Method:

public static void main(String[] args) {

    Users usersObject = new Users();
    usersObject.addToUsersList("USERNAME");

    }



via Chebli Mohamed

Android eclipse xml formatting issue

Hello i have a xml file which doesent seem to work, i am trying to reach it with a listpreference.

Here is the listpreference code:

<PreferenceCategory android:name="@string/yo_category">

<ListPreference
    android:title="YOYO"
    android:key="YOYOYO"
    android:summary="YODOBO"
    android:entries="@+arrays/yoyo"
    android:entryValues="@+arrays/yoyoValues"
></ListPreference>

</PreferenceCategory>  

And here is the xml file:

<string-array name="yoyo">
    <item>1 yoyo</item>
    <item>2 yoyos</item>
    <item>3 yoyos</item>
</string-array>
<string-array name="yoyoValues">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

PreferenceActivity class:

public class PreferenceHandler extends PreferenceActivity

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefFragment()).commit();
}

public static class PrefFragment extends PreferenceFragment
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences);
}
}   

} And i cannot seem to find the issue here, i get no errors in eclipse but when i try to run it i cant see the items in the listpreference.

Thanks for any help!



via Chebli Mohamed

how to retrieve data from database in servlet

im beginners in java servlet... i working on curd operation... ...data not displaying please tell me where im wrong....

DAO.java

public void select(){

        try{
            Class.forName(jdbcDriver);
            Connection conn = DriverManager .getConnection(connectionString,username,password);
        PreparedStatement create = conn.prepareStatement("select * from student.users");

            ResultSet rs;
            rs = create.executeQuery();
            while(rs.next()){
                int id =rs.getInt("id");
                String name = rs.getString("fname");

            }
            }
            catch(Exception e){
                e.printStackTrace();
            }

    }

servlet.java

DAO user = new DAO();   /// i create object of DAO
user.select();  //calling select method

out.write("<td>");
                    out.write("<p>"+user.id+"</p>");    ///tried many from different way
            out.write("</td>");
            out.write("<td>"); 
                    out.write("<p>"+user.name+"</p>");    ///
            out.write("</td>"); 

i tried many from different way but no luck.... can you tell me where I'm wrong



via Chebli Mohamed

parse initialization is making the app crash

I am trying to use parse but parse told me to include the first code into the project to check if the data is transfered.... my app crashes...

I then followed a solution on stack overflow that explained how you have to initialize the parse in separate class and include it into manifest file... but after I followed it... my app still doesn't work... It crashes every single time..

Android manifest

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
    package="com.example.parseexample"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21" />

    <application
        android:name=".Initializeparse"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.example.parseexample;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        ParseObject testObject = new ParseObject("TestObject");
        testObject.put("foo", "bar");
        testObject.saveInBackground();

    }


}

And this is my parseexample.java

    package com.example.parseexample;

    import com.parse.Parse;

    import android.app.Application;

    public class Initializeparse extends Application{

        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();

            Parse.enableLocalDatastore(getApplicationContext());

            Parse.initialize(getApplicationContext(), "lUdLAC7d7HXQfdv1g7SO0T70jcc6vIMIHJRlYEvE", "ObFeYoJE3dqJmxMSfMkCQx37MvAqQfrNvnXHr38v");

        }



    }

Logcat

    08-14 05:07:48.569: D/HyLog(3996): I : /data/font/config/sfconfig.dat, No such file or directory (2)
08-14 05:07:48.569: D/HyLog(3996): I : /data/font/config/dfactpre.dat, No such file or directory (2)
08-14 05:07:48.569: D/HyLog(3996): I : /data/font/config/sfconfig.dat, No such file or directory (2)
08-14 05:07:48.579: I/dalvikvm(3996): Could not find method com.parse.Parse.initialize, referenced from method com.example.parseexample.Initializeparse.onCreate
08-14 05:07:48.579: W/dalvikvm(3996): VFY: unable to resolve static method 19: Lcom/parse/Parse;.initialize (Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
08-14 05:07:48.579: D/dalvikvm(3996): VFY: replacing opcode 0x71 at 0x0007
08-14 05:07:48.579: D/AndroidRuntime(3996): Shutting down VM
08-14 05:07:48.579: W/dalvikvm(3996): threadid=1: thread exiting with uncaught exception (group=0x41a00e48)
08-14 05:07:48.579: E/AndroidRuntime(3996): FATAL EXCEPTION: main
08-14 05:07:48.579: E/AndroidRuntime(3996): Process: com.example.parseexample, PID: 3996
08-14 05:07:48.579: E/AndroidRuntime(3996): java.lang.NoClassDefFoundError: com.parse.Parse
08-14 05:07:48.579: E/AndroidRuntime(3996):     at com.example.parseexample.Initializeparse.onCreate(Initializeparse.java:14)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4432)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread.access$1500(ActivityThread.java:142)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1263)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.os.Looper.loop(Looper.java:136)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread.main(ActivityThread.java:5120)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at java.lang.reflect.Method.invoke(Method.java:515)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at dalvik.system.NativeStart.main(Native Method)



via Chebli Mohamed

Parse Json into a Map in Java

I have a json whose structure can vary in terms of number of nested levels. Like some of the key might have a json object, some of the key might have json object inside a json object. So any key can have a json object (of different depth) or a String as its value. For example,

{
 k1: v1,
 k2: {
      k21: {
           k211: v211,
           k212: v212
           },
      k22: {
           k221: v221,
           k222: v222
           }
     },
 k3: {
      k31: v31
     }
}

Note that k1, k2, k3 have value different levels of json objects (depth of json objects vary) as their values.

I need to parse the above json into a map of key and values like below,

<k1, v1>,
<k211, v211>,
<k212, v212>,
<k221, v221>,
<k222, v222>,
<k31, v31>

How can we parse them like that in java?



via Chebli Mohamed

Java if statement issue? [duplicate]

This question already has an answer here:

I am working on a code that takes what you input into a window's text box, and answers you accordingly. Currently I am trying to say that if the user enters the word "yes", two windows will display, one saying "k, lets talk", and one saying "you typed in yes". Right now only the second window is opening, and the first two if statements aren't even executing. How can I make this work?

class hear implements ActionListener{

    public void actionPerformed(ActionEvent event){

        String string = "";
        if (event.getActionCommand() == "yes"  || event.getActionCommand() =="Yes" || event.getActionCommand() =="YES")
             JOptionPane.showMessageDialog(null, "k, lets talk");
         if (event.getActionCommand() == "no"  || event.getActionCommand() =="NO" || event.getActionCommand() == "NO")   
             JOptionPane.showMessageDialog(null, "k bye!");
        if(event.getSource()==textfield)
            string = String.format("You typed in %s", event.getActionCommand());


         JOptionPane.showMessageDialog(null, string); //Open a new window that displays String string, which has changed based on which field you hit enter on.



via Chebli Mohamed

Hibernate Session Issue

I am facing an hibernate session issue. In the DAO class am using Hibernate template to get the data which returns 2 rows. These 2 entities have same foreign key. The issue is first record is retreived successfully where as second record throw "collection is not associated with any session" . I tried adding @Transactional but that didnt help. pls suggest

(List<EntityName>) hibernateTemplate.findByCriteria(detachedCriteria,searchCriteria.getFirstResult(),searchCriteria.getMaxResults());

Collection

    <set name="entites" lazy="false" cascade="all" inverse="true">
     <key column="Key" not-null="true" property-ref="xxx"/>
     <one-to-many class="EntityClass"/>
    </set>



via Chebli Mohamed

JSP servlet include tuncated

I am trying to include the response from a servlet in a jsp page using:

<li><jsp:include page="/icr/TasksServlet.html"/></li>

The servlet gives back one word:

try (PrintWriter out = response.getWriter()) {
        out.println("OOps");
        out.flush();
        out.close();
    }

And the result is that my page is truncated directly after the "OOps"

    <ul class="navList">
    <li>ICR Open Tasks</li>
    <li>
        <ul>
    <li>OOps

The tomcat throws this error:

org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet 
[validateUser] in context with path [/CAS] threw exception
[java.lang.IllegalStateException: Exception occurred when flushing data]
with root cause
java.io.IOException: Stream closed

I have tried to add and remove the out.flush(); and out.close(); as well as added flush="true" to the jsp:include tag.

I running tomcat 8.0.24; Netbeans with spring MVC.



via Chebli Mohamed

I am doing a project in Java with Android jni C++. I have a function in C++ with the following parameters:

C++ function: void rectify (vector <Point2f> & corners, Mat & img) {...}

In JAVA, call would be:

Mat image = Highgui.imread("img.png");
List <MatOfPoint> cornners =  new ArrayList<MatOfPoint>();;
Point b = new Point (real_x2, real_y2);
MatOfPoint ma = new MatOfPoint (b);
cornners.add(ma);
rectfy(image.getNativeObjAddr(), cornners)

public native void rectfy(long mat, "??" matofpoint);

With that, I wonder how will the function C++ jni:

JNIEXPORT void JNICALL Java_ImageProcessingActivity_rectfy (JNIEnv * jobject, ?? cornners, inputMatAddress jlong)



via Chebli Mohamed

null pointer exception when sending ISO8583 request

I am trying to send an ISO8583 request to a terminal using the following code:

try {
        XMLParser packager = new XMLParser(this.xmlFile);


        final ISOMsg isoMsg = new ISOMsg();
        isoMsg.setPackager(packager);
        isoMsg.setMTI("0800");
        isoMsg.set(3, "xxxxxx");
        isoMsg.set(7, "xxxxxxxxxx");    //MMDDhhmmss
        isoMsg.set(11, "xxxxxx");
        isoMsg.set(12, "084500");       //Time of the message HHmmss
        isoMsg.set(13, "0621");         //Date MMDD
        isoMsg.set(41, "xxxxxxxx");
        isoMsg.set(62,"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        isoMsg.set(63,"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        BaseChannel channel = new BaseChannel() {};
        channel.setLogger(logger, "server-request-channel");
        channel.setHeader(isoMsg.pack());
        channel.setHost("xx.xx.xx.xx", xxxxx);
        ISOMUX isoMux = new ISOMUX(channel) {
            @Override
            protected String getKey(ISOMsg m) throws ISOException {
                return super.getKey(m);
            }
        };

        isoMux.setLogger(logger, "server-request-mux");
        new Thread(isoMux).start();
        ISORequest req = new ISORequest(isoMsg);
        isoMux.queue(req);
        req.setLogger(logger, "server-request-logger");
        ISOMsg response = req.getResponse(50 * 1000);

        if (response != null) {
                System.out.println("Req ["+ new String(isoMsg.pack()) + "]");
                System.out.println("Res ["+ new String(response.pack()) + "]");
            }else{
                System.out.println("Timeout");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

After executing the code, I get the following error:

<log realm="server-request-mux" at="Fri Aug 14 00:26:43 WAT 2015.995">
    <muxreceiver>
        <exception name="null">
            java.lang.NullPointerException
            at org.jpos.iso.BaseChannel.createISOMsg(BaseChannel.java:561)
            at org.jpos.iso.BaseChannel.createMsg(BaseChannel.java:558)
            at org.jpos.iso.BaseChannel.receive(BaseChannel.java:585)
            at org.jpos.iso.ISOMUX$Receiver.run(ISOMUX.java:263)
            at java.lang.Thread.run(Thread.java:856)
        </exception>
    </muxreceiver>
</log>

I added break point so as to find out the line causing the exception and discovered that the exception occurs whenever it encounters the statement:

ISORequest req = new ISORequest(isoMsg);

I am relatively new to ISO8583 jpos financial programming and I want to building an app on android platform.

How do I get over this exception?



via Chebli Mohamed

Timestamp based sorting for a nested Map

I have a nested Map being returned by the Guava Library's Table structure that is templated as follows:

Map<ComplexID1, Map<ComplexID2, MyObject>>

where ComplexID1 is my row key, ComplexID2 is my column key and MyObject holds my metadata. One of the attributes of my metadata is a JODA timestamp.

I need to sort this whole structure chronologically (or reverse chronologically) for display, newest objects created at the top, going backwards.

I was unable to find any information to sort this data structure. Could someone please provide some pointers?

Further, I tried to have the MyObject class extend Comparable and override CompareTo on the JODA datetime object because I was trying to use Collections.Sort(). Unfortunately, that approach does not seem to work for me.



via Chebli Mohamed

which is the best for GUI C++ Qt or C# or JAVA 2015

hi i want to ask you a question i had learn c++ and something about the framework Qt but the problem that now day the Qt is not used in the world of apps smartphone like C# or JAVA !! so do u leave c++ and Qt and start with C# or JAVA ?? please i need your Advice Thank you



via Chebli Mohamed

Counting all elements in map of string to list

Is there a better way to calculate size of all lists in map? So firstList.size() + secondList().size? I have done this, but creating a list just for counting doesn't feel right approach ..

public static void main(String[] args) {
    List<String> firstList = new ArrayList<>();
    firstList.add("first");
    List<String> secondList = new ArrayList<>();
    secondList.add("second");

    Map<String, List<String>> myMap = new HashMap<>();
    myMap.put("one", firstList);
    myMap.put("two", secondList);

    int size = myMap.entrySet().stream().map(entry -> entry.getValue()).flatMap(list -> list.stream()).collect(Collectors.toList()).size();
    System.out.println("Size of all elements in map is:" + size);

}



via Chebli Mohamed

Internal working of Comparator [on hold]

Can you please explain how sorting is performed here using Comparator? Can you make a simple step by step explanation for Collections.sort(al, Student.StuNameComparator);?

Student class:

public class Student {
    private String name;
    private int rollno;

    public Student(int rollno, String name) {
        this.rollno = rollno;
        this.name = name;
    }

    public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
        public int compare(Student s1, Student s2) {
            return s1.name.compareTo(s2.name);
        }
    };

    public String toString() {
        return "Roll No: " + rollno + " Name: " + name;
    }
}

main method:

public static void main(String args[]) {
   ArrayList<Student> al = new ArrayList<Student>();
   al.add(new Student(983, "AAA" ));
   al.add(new Student(981, "KKK" ));
   al.add(new Student(999, "BBB"));

   System.out.println("Student Name Sorting:");
   Collections.sort(al, Student.StuNameComparator);

   for(Student str: al) {
        System.out.println(str);
   }
}



via Chebli Mohamed

Add an element from a listView to another listView

I want to create an add to favorites action bar button on the news and to add it to a new list adaptor in the favorites tab, can you help me please implementing the button an how to create the new list?

here is my code: (displaying the clicked news)

    public class ListItemClicked extends ActionBarActivity {

    static Bundle extras;

    SectionsPagerAdapter mSectionsPagerAdapter;
    static ImageLoader imageLoader;
    static DisplayImageOptions options;




    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item_clicked);


        mSectionsPagerAdapter = new  SectionsPagerAdapter(getSupportFragmentManager());

        extras = getIntent().getExtras();

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        //Setup the ImageLoader, we'll use this to display our images
        ImageLoaderConfiguration config = new  ImageLoaderConfiguration.Builder(this).build();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);

        //Setup options for ImageLoader so it will handle caching for us.
        options = new DisplayImageOptions.Builder()
                .cacheInMemory()
                .cacheOnDisc()
                .build();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        return id == R.id.action_settings || super.onOptionsItemSelected(item);

    }



    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section4).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section5).toUpperCase(l);
            }
            return null;
        }
    }


    public static class PlaceholderFragment extends Fragment {


        private static final String ARG_SECTION_NUMBER = "section_number";


        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState)
        {

            View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);


            TextView pDate = (TextView) rootView.findViewById(R.id.textView);
            pDate.setText( extras.getString("pdate") );


            TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
            ptitle.setText(extras.getString("pname"));


            TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
            pnText.setText( extras.getString("pText"));




            //Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
            ImageLoadingListener listener = new ImageLoadingListener(){



                @Override
                public void onLoadingStarted(String arg0, View arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLoadingCancelled(String arg0, View arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                    // i/ndicator.setVisibility(View.INVISIBLE);
                    // iconImg.setVisibility(View.VISIBLE);
                }
                @Override
                public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                    // TODO Auto-generated method stub

                }

            };

            //Load the image and use our options so caching is handled.
            final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
            imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);



            return rootView;
        }
    }

}

the first list adaptor with news news from list adaptor clicked the favorites tab



via Chebli Mohamed

Java XML serialization of lists without wrapping each element in list name and giving each object its root name

Using Jackson XML I have the following code :

public static class Person{}

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@JacksonXmlRootElement(localName = "StudentElement")
public static class Student extends Person{
    private String firstName;
}

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@JacksonXmlRootElement(localName = "TeacherElement")
public static class Teacher extends Person{
    private String firstName;
}


@Getter
@Setter
@AllArgsConstructor
public static class School{
    @JacksonXmlElementWrapper(useWrapping = false)
    Person[] people;
}

public static void main(String[] args) throws Exception {
    XmlMapper xmlMapper = new XmlMapper();

    final School school = new School(new Person[]{
            new Student("John"),
            new Teacher("MR. Jackson")
    });

    String asString = xmlMapper.writeValueAsString(school);

    prettyPrintXml(asString);
}

With output :

<?xml version="1.0" encoding="UTF-8"?><School xmlns="">
  <people>
    <firstName>John</firstName>
  </people>
  <people>
    <firstName>MR. Jackson</firstName>
  </people>
</School>

I am trying to keep name of elements in the array and avoid wrapping each element in people tag. Such as

<?xml version="1.0" encoding="UTF-8"?>
<School xmlns="">
    <people>
        <StudentElement>
            <firstName>John</firstName>
        </StudentElement>
        <TeacherElement>
            <firstName>MR. Jackson</firstName>
        </TeacherElement>
    </people>
</School>

Ideally I would still use Jackson XML but I am not limited to it. Is there a way to get this done without writing a new serializer.



via Chebli Mohamed

E/AndroidRuntime(274): java.lang.RuntimeException: An error occured while executing doInBackground()

I am trying to program an application for Android but I have an error in my aplication when I click the button

here is the error:

08-13 22:50:56.182: E/AndroidRuntime(276): FATAL EXCEPTION: AsyncTask #1
08-13 22:50:56.182: E/AndroidRuntime(276): java.lang.RuntimeException: An error occured while executing doInBackground()
08-13 22:50:56.182: E/AndroidRuntime(276):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.lang.Thread.run(Thread.java:1096)
08-13 22:50:56.182: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
08-13 22:50:56.182: E/AndroidRuntime(276):  at com.example.massarv4.Login$AttemptLogin.doInBackground(Login.java:78)
08-13 22:50:56.182: E/AndroidRuntime(276):  at com.example.massarv4.Login$AttemptLogin.doInBackground(Login.java:1)
08-13 22:50:56.182: E/AndroidRuntime(276):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

login.java

import java.util.ArrayList;
import java.util.List; 
import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject;

import com.example.massarv4.JSONParser;
import com.example.massarv4.OtherActivity;

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle; 
import android.util.Log;
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText;
import android.widget.Toast; 
public class Login extends Activity implements OnClickListener{ 
    private EditText user, pass; 
    private Button bLogin;
    // Progress Dialog 
    private ProgressDialog pDialog; 
    // JSON parser class 
    JSONParser jsonParser = new JSONParser(); 
    private static final String LOGIN_URL = "http://ift.tt/1TxPFcU"; 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_MESSAGE = "message";
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.login);
        user = (EditText)findViewById(R.id.username); 
        pass = (EditText)findViewById(R.id.password); 
        bLogin = (Button)findViewById(R.id.login);
        bLogin.setOnClickListener(this);
        } 
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub 
        switch (v.getId()) { 
        case R.id.login: new AttemptLogin().execute(); 
        // here we have used, switch case, because on login activity you may
        //also want to show registration button, so if the user is new ! we can go the 
        //registration activity , other than this we could also do this without switch //case. 
        default: break; 
        }
        } 
    class AttemptLogin extends AsyncTask<String, String, String> {
        /** * Before starting background thread Show Progress Dialog * */ 
        boolean failure = false;
        @Override
        protected void onPreExecute() { 
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting for login...");
            pDialog.setIndeterminate(false); 
            pDialog.setCancelable(true); pDialog.show(); 
            } 
        @Override
        protected String doInBackground(String... args) { 
            // TODO Auto-generated method stub // here Check for success tag 
            int success=0; 
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>(); 
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password)); 
                Log.d("request!", "starting"); 
                JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); 
                // checking log for json response 
                Log.d("Login attempt", json.toString());
                // success tag for json 
                success = json.getInt(TAG_SUCCESS); 
                if (success == 1) { Log.d("Successfully Login!", json.toString());
                Intent ii = new Intent(Login.this,OtherActivity.class); finish(); 
                // this finish() method is used to tell android os that we are done with current 
                //activity now! Moving to other activity 
                startActivity(ii);
                return json.getString(TAG_MESSAGE);
                }else{ 
                    return json.getString(TAG_MESSAGE); 
                    } }
            catch (JSONException e) { 
                e.printStackTrace(); 
                } 
            return null; 
            }
        /** * Once the background process is done we need to Dismiss the progress dialog asap * **/ 
        protected void onPostExecute(String message) { pDialog.dismiss()
            ; if (message != null){
                Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show(); 
                }
            }
        }



        }

login.php

<?php mysql_connect("localhost","root",""); 
$db= mysql_select_db("massar"); 
$pas=$_POST["password"];
$usr=$_POST["username"];
if (!empty($_POST)) { 
    if (empty($_POST['username']) || empty($_POST['password'])) { 
    // Create some data that will be the JSON response 
    $response["success"] = 0; $response["message"] = "One or both of the fields are empty ."; 
    //die is used to kill the page, will not let the code below to be executed. It will also //display the parameter, that is the json data which our android application will parse to be 
    //shown to the users 
    die(json_encode($response)); 
    } 
    $query = " SELECT * FROM parent WHERE CIN = $usr and MotDePasse = $pas "; 
    $sql1=mysql_query($query); 
    $row = mysql_fetch_array($sql1); 
        if (!empty($row)) { 
    $response["success"] = 1; 
    $response["message"] = "You have been sucessfully login";
    die(json_encode($response));
    } else{ 
        $response["success"] = 0; 
        $response["message"] = "invalid username or password "; 
        die(json_encode($response)); } } else{ $response["success"] = 0; 
        $response["message"] = " One or both of the fields are empty "; 
        die(json_encode($response));
        } mysql_close(); 
        ?>



via Chebli Mohamed

Java Swing: How To Parse A Phone Number, Format It, And Display It In A JTable

I am trying to format a phone number column in a JTable as (Area) Prefix-Number. I am not sure what I am doing wrong as it compiles without errors and according to the getTableCellRenderer tutorials and other numerous examples I've pored over it should work. But it doesn't... it is still formatted as one string in the JTable.

I first accept user input from one text field for a phone number:

//import necessary API

public class AddPatientDialog extends JDialog {

    private final JPanel contentPanel = new JPanel();
    private JTextField txtFieldPhneNum;

    private PatientDAO patientDAO;

    private PatientSessionTrackerApp patientSessionTrackerApp;

    public AddPatientDialog(PatientSessionTrackerApp thePatientSessionTracker, PatientDAO thePatientDAO) {
        this();
        patientDAO = thePatientDAO;
        patientSessionTrackerApp = thePatientSessionTracker;
    }

    public final class LengthRestrictedDocument extends PlainDocument {

          private final int limit;

          public LengthRestrictedDocument(int limit) {
            this.limit = limit;
          }

          @Override
          public void insertString(int offs, String str, AttributeSet a)
              throws BadLocationException {
            if (str == null)
              return;

            if ((getLength() + str.length()) <= limit) {
              super.insertString(offs, str, a);
            }
          }
        }

    /**
     * Create the dialog.
     */
    public AddPatientDialog() {
        setSize(450, 300);
        setResizable(false);
        setTitle("Add New Patient");
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(null);
        {
            JLabel lblPhneNum = new JLabel("Phone Number");
            lblPhneNum.setBounds(10, 86, 104, 14);
            contentPanel.add(lblPhneNum);
        }

        txtFieldPhneNum = new JTextField();
        txtFieldPhneNum.setBounds(124, 83, 86, 20);
        contentPanel.add(txtFieldPhneNum);
        txtFieldPhneNum.setColumns(10);
        txtFieldPhneNum.setDocument(new LengthRestrictedDocument(10));

        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton okButton = new JButton("Add Patient");
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    savePatient();
                }
            });
            okButton.setActionCommand("OK");
            buttonPane.add(okButton);
            getRootPane().setDefaultButton(okButton);
        }

        JTextArea txtAddPatientWarning = new JTextArea();
        txtAddPatientWarning.setText("WARNING!!! Once a patient is created it is added to the database and cannot be removed from the database via the Patient Session Tracker. If a patient is added in error, please contact Sudo Technologies at (701) 388-3752.");
        txtAddPatientWarning.setBounds(10, 132, 424, 60);
        txtAddPatientWarning.setEditable(false);
        txtAddPatientWarning.setBackground(Color.YELLOW);
        txtAddPatientWarning.setLineWrap(true);
        contentPanel.add(txtAddPatientWarning);

        JLabel lblIe = new JLabel("Enter numbers only (i.e. 1234567890)");
        lblIe.setBounds(220, 86, 214, 14);
        contentPanel.add(lblIe);
    }

    protected void savePatient() {

        // get the patient info from the gui
        String firstName = txtFieldFName.getText();
        String middleName = txtFieldMName.getText();
        String lastName = txtFieldLName.getText();
        String phneNum = txtFieldPhneNum.getText();
        String email = txtFieldEmail.getText();

        Patient tempPatient = new Patient(phneNum);

        if ((firstName.trim().length() != 0) && (lastName.trim().length() != 0)) {  

            try{
                // save to the database
                patientDAO.addPatient(tempPatient);

                // close dialog
                setVisible(false);
                dispose();

                // refresh gui list
                patientSessionTrackerApp.refreshPatientsView();

                // show success message
                JOptionPane.showMessageDialog(patientSessionTrackerApp, "Patient added to the database.", 
                    "Patient Added",
                    JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception exc) {
                JOptionPane.showMessageDialog(patientSessionTrackerApp, 
                        "Error saving patient: " +
                        exc.getMessage(), "Error",
                        JOptionPane.ERROR_MESSAGE);
            } 
        } else 
            JOptionPane.showMessageDialog(patientSessionTrackerApp, "<html>Please fill in all required fields as denoted by the <font color='red'>*</font>.</html>");
    }
}

I then try to pass it into a PhoneNumber class in order to try and parse the string:

public class PhoneNumber {
    public String areaCode;
    public String prefix;
    public String num;

    public PhoneNumber(String areaCode, String prefix, String num) {
        this.areaCode = areaCode;
        this.prefix = prefix;
        this.num = num;
    }

    public PhoneNumber() {}

    public PhoneNumber parsePhoneNumber(String phneNum) {
        String[] phneNumArr = {phneNum.substring(0,3), phneNum.substring(3,6), phneNum.substring(6)};
        areaCode = phneNumArr[0];
        prefix = phneNumArr[1];
        num = phneNumArr[2];
        return new PhoneNumber(areaCode, prefix, num);
    }

    @Override
    public String toString() {
        return "areaCode=" + areaCode + "; prefix=" + prefix + "; num=" + num;
    }
}

From there I try to use the Object parser to format it in a CellRenderer class:

import java.awt.Component;

import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

import com.patientsessiontracker.core.*;

public class PatientSessionTrackerCellRenderer extends DefaultTableCellRenderer {
    private static final long serialVersionUID = 1L;
    public String areaCode;
    public String prefix;
    public String num;
    public String phneNum;

    public Component getTableCellRendererComponent(JTable table, PhoneNumber value, boolean isSelected, 
                                                   boolean hasFocus, int row, int column) {
        //Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        PhoneNumber phneNum = new PhoneNumber();
        value = phneNum;
        String text =  "(" + phneNum.areaCode + ") " + phneNum.prefix + "-" + phneNum.num;
        setHorizontalAlignment(SwingConstants.CENTER);
        setText(text);
        return this;
    }
}

Finally I attempt to implement the new format in the JTable:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.EventQueue;
import java.awt.FlowLayout;

import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JScrollPane;

import java.util.List;

import com.patientsessiontracker.core.*;
import com.patientsessiontracker.dao.*;

public class PatientSessionTrackerApp extends JFrame {

    private JPanel contentPane;
    private JTextField txtFieldSrchFName;
    private JButton btnSearch;
    private JScrollPane scrollPane;
    private static JTable table;

    private static PatientDAO patientDAO;
    private JPanel panelBtn;
    private JButton btnAddPatient;
    private JTextField txtFieldSrchLName;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    PatientSessionTrackerApp frame = new PatientSessionTrackerApp();
                    frame.setVisible(true);
                    PatientSessionTrackerApp.refreshPatientsView();
                    table.getColumnModel().getColumn(3).setCellRenderer(new PatientSessionTrackerCellRenderer());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public PatientSessionTrackerApp() {

        // create the DAO
        try {
            patientDAO = new PatientDAO();
        } catch (Exception exc) {
            JOptionPane.showMessageDialog(this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE); 
        }

        setTitle("Patient Session Tracker");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 300);
        setResizable(false);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel panelSrch = new JPanel();
        panelSrch.setBounds(5, 5, 579, 33);
        contentPane.add(panelSrch);
        panelSrch.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        JLabel lblFirstName = new JLabel("First Name");
        panelSrch.add(lblFirstName);

        txtFieldSrchFName = new JTextField();
        panelSrch.add(txtFieldSrchFName);
        txtFieldSrchFName.setColumns(13);

        btnSearch = new JButton("Search");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {        

                try {
                    String firstName = txtFieldSrchFName.getText();
                    String lastName = txtFieldSrchLName.getText();

                    List<Patient> patients = null;

                    if (((firstName != null) && (firstName.trim().length() > 0)) ||
                        ((lastName != null) && (lastName.trim().length() > 0))) 
                        patients = patientDAO.searchPatients(firstName, lastName);
                    else
                        patients = patientDAO.getAllPatients();

                    // create the model and update the "table"
                    PatientTableModel model = new PatientTableModel(patients);

                    table.setModel(model);
                    table.getColumnModel().getColumn(3).setCellRenderer(new PatientSessionTrackerCellRenderer());

                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(PatientSessionTrackerApp.this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE); 
                }

            }
        });

        JLabel lblLastName = new JLabel("Last Name");
        panelSrch.add(lblLastName);

        txtFieldSrchLName = new JTextField();
        panelSrch.add(txtFieldSrchLName);
        txtFieldSrchLName.setColumns(13);
        panelSrch.add(btnSearch);

        scrollPane = new JScrollPane();
        scrollPane.setBounds(5, 38, 579, 186);
        contentPane.add(scrollPane);

        table = new JTable();
        scrollPane.setViewportView(table);

        panelBtn = new JPanel();
        panelBtn.setBounds(5, 224, 579, 38);
        contentPane.add(panelBtn);

        btnAddPatient = new JButton("Add Patient");
        btnAddPatient.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // create dialog
                AddPatientDialog addPatient = new AddPatientDialog(PatientSessionTrackerApp.this, patientDAO);

                // show dialog
                addPatient.setModal(true);
                addPatient.setVisible(true);
            }
        });
        panelBtn.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        panelBtn.add(btnAddPatient);
    }

    public static void refreshPatientsView() {

        try {
            List<Patient> patients = patientDAO.getAllPatients();
            PatientTableModel model = new PatientTableModel(patients);

            table.setModel(model);
        } catch (Exception exc) {
            JOptionPane.showMessageDialog(null, "Error: " + exc, "Error",
                    JOptionPane.ERROR_MESSAGE);
        }

    }
}

The phone number gets stored and retrieved from a tinytext column in the MySQL database. Feel free to ask for more code if needed, I hacked a lot of parts out to try and shorten the question.


Okay... I am completely lost and admittedly a noob to Java Swing.I tried invoking the class Phone Number into the Custom CellRenderer Class. What I get for a result is (null) null-null. I'm not sure what I am doing wrong, should I try using the MaskFormatter API as shown in the CustomCellRenderer tutorial? Here is the refractored code:

CustomCellRenderer:
public class PatientSessionTrackerCellRenderer extends DefaultTableCellRenderer {
    private static final long serialVersionUID = 1L;

    public PatientSessionTrackerCellRenderer() {
        super();
        setHorizontalAlignment(SwingConstants.CENTER);
    }

    @Override
    public void setValue(Object value) {
        PhoneNumber phneNum = new PhoneNumber();
        value.toString();
        value =  "(" + phneNum.areaCode + ") " + phneNum.prefix + "-" + phneNum.num;

        super.setValue(value);
    }
}

PhoneNumber Class:

public class PhoneNumber {
    public String areaCode;
    public String prefix;
    public String num;

    private PhoneNumber(String areaCode, String prefix, String num) {
        this.areaCode = areaCode;
        this.prefix = prefix;
        this.num = num;
    }

    public PhoneNumber() {}

    public PhoneNumber parsePhoneNumber(String value) {
        String[] phneNumArr = {value.substring(0,3), value.substring(3,6), value.substring(6)};
        areaCode = phneNumArr[0];
        prefix = phneNumArr[1];
        num = phneNumArr[2];
        return new PhoneNumber(areaCode, prefix, num);
    }

    @Override
    public String toString() {
        return "areaCode=" + areaCode + "; prefix=" + prefix + "; num=" + num;
    }
}



via Chebli Mohamed

right clicking on a Jtable to expand results of that entry via a pop up [JAVA]

I'm new to Java and I have a Jtable that loads up a text file with names and addresses. I would like to be able to right click or double click on a row then have it display another text file that is associated with that entry.. Is this even possible? If so, can you point me to any tutorials besides the sun Jtable. Thanks in advanced



via Chebli Mohamed

Check if a position is clicked using HashMap

I'm writing a simple program and want to know if an approximate position is clicked. I've got a hashmap with the position as key value and want to display a currently invisible object if the user clicks close enough to the position of the object - not just right at it. The position class just holds an x and a y value.

    HashMap<Position, Place> places = new HashMap<>(); //Assume this is populated

    @Override
    class WhatIsHere extends MouseAdapter {
        public void mouseClicked(MouseEvent me) {
            Place place = places.get(new Position(me.getX(), me.getY()));
            if (place != null) {
                place.setVisible(true);
            } else {
                System.out.println("Nothing there");
            }
        }
    }

This bit of code finds the place if you click right on it though I don't know how to look for, say, me.getX()+-10 and find objects in that range.

Do I need to set four ints holding x-10 and x+10 etc. and just loop through all the positions inbetween? It seems awfully dumb to do it that way.



via Chebli Mohamed

Efficent updating entity in Hibernate

I guess it may be like a newbie question, but still I'd like to know some answers.

Let's say there are entities: Hospital and Doctor (Many-To-Many). Suppose in my controller class I have to fetch all existing doctors and hospitals, and then hire one doctor in a specific hospital

@Controller
public class HospitalController {
  ...
    @RequestMapping("/hireDoctor")
    public String (HttpServletRequest request, Model model) {
        List<Hospital> hospitals = hospitalService.findAllHospitals();
        List<Doctor> doctors = doctorService.findAllDoctors();

        //some logic, in the end we choose just one doctor and one hospital

        Doctor doctor = doctors.get(0);
        Hospital hospital = hospitals.get(0);

        hospitalService.hireDoctor(hospital, doctor);
    }
  ...

@Service
public class HospitalService {
  ..  
    @Transactional
    public void hireDoctor(Hospital hospital, Doctor doctor) {
        //ideally
        List<Doctor> doctors = hospital.getDoctors();
        doctors.add(doctor);

        this.em.merge(hospital);
    }
  ..
}

It of course doesn't work, because - as I understand - I've fetched all doctors and hospitals in my controller and then in hireDoctor method we're opening trasaction passing regular Java objects, which are not in a session.

I know, that I can just again fetch Hospital with a speicfic ID, and Doctor with a specific ID and then save it

public void hireDoctor(Hospital hospital, Doctor doctor) {
     Hospital h = hospitalRepo.getHospitalById(hospital.getId());
     Doctor d = hospitalRepo.getDoctorById(doctor.getId());
     List<Doctor> doctors = h.getDoctors();
     doctors.add(d);
}

But it just looks rubbish.

So - how should such update look like to be most efficient?



via Chebli Mohamed

Fortify Annotation to suppress Invalid Privacy Violation

I am trying to find API info for Fortify Annotations. It's not anywhere in the Fortify User's Guide and I can't find it with a search on Google. Specifically, I want to see what available annotations there are. Hopefully, there is one that can make Fortify suppress an invalid Privacy Violation. It thinks PII is being written out to a log, when in actuality it's just an error code value.



via Chebli Mohamed

Spring Mongo "elemMatch" - get other fields included in the result along with specified array elements match

I am working on a web application using Spring + Jersey + Mongo. I am using elemMatch from spring mongo for some specific result.

Here is my class that will be mapped with the output of the mongo query.

public class ABC {
    private String id;

    private String dId;

    private String lId;

    private String hId;

    private String pId;

    private List<GeneralData> generalRecords;

    private List<String> fhistory;

    private List<String> mhistory;

    private List<String> specialNotes;
}

public class GeneralData {
    private Object data;

    private HistoryFilter dataType;
}

Now, this is how my data looks like in mongo :

{
    "_id" : ObjectId("55ccda7fe4b03cc159c2ce17"),
    "_class" : "com.dpdocter.collections.HistoryCollection",
    "dId" : "5525ef96e4b077dfc168369b",
    "lId" : "5525ef96e4b077dfc16836a1",
    "hId : "5525ef96e4b077dfc16836a0",
    "pId" : "55ccd9f1e4b03cc159c2ce0b",
    "generalRecords" : [ 
        {
            "data" : "55ccdde7e4b03cc159c2ce18",
            "dataType" : "REPORTS"
        }, 
        {
            "data" : "55ccda63e4b03cc159c2ce14",
            "dataType" : "CLINICAL_NOTES"
        }
    ]
}

I want record based on dId, lId, hId, pId along with elemMatch on generalRecords for a specific dataType (say REPORTS). And, below is my criteria code to do that.

Criteria matchCriteria = Criteria.where("dId").is(dId).and("lId").is(lId).and("hId").is(hId).and("pId").is(pId).and("generalRecords.dataType").is("REPORTS");
Criteria elementMatchCriteria = Criteria.where("generalRecords").elemMatch(Criteria.where("dataType").is("REPORTS"))

BasicQuery query = new BasicQuery(matchCriteria.getCriteriaObject(), elementMatchCriteria.getCriteriaObject());

ABC abc = mongoOperations.findOne(query, ABC.class);

Result of the above

ABC [id=55ccda7fe4b03cc159c2ce17, dId=null, lId=null, hId=null, pId=null, generalRecords=[GeneralData [data=55ccdde7e4b03cc159c2ce18, dataType=REPORTS]], fhistory=null, mhistory=null, specialNotes=null]

generalRecords is just perfect and as desired, but I just want to include dId, lId, hId, pId, fHistory, mHistory, and specialNotes also. I have already tried :

query.fields().include('fieldName')

also, some other weird query combos, but nothing helps. Can anyone suggest something.



via Chebli Mohamed

Calling Java method from web application

Good evening SO. This is a general question, no code that needs to be checked or anything. Anyhow, I am creating a website running on an Apache 2.4 server and wondering how, using PHP, JS, or any other simple to understand language I would be able to call a java method to execute on the server. I am aware of Apache Tomcat's servlet functionality, but I'm not quite sure how to tie that into a "normal" website. If you guys have answers not involving Tomcat, please let me know of those too, I'm open to any and all assistance. Thanks in advance SO!



via Chebli Mohamed

Missing artifact com.oracle:ojdbc7 in eclipse

I have imported a Maven Project in Eclipse (EE Developer) and I have in my pom.xml file the following error, “Missing artifact com.oracle:ojdbc7:jar:12.1.0.2″ in this code:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>

I have done so by downloading the ojdbc7.jar and run this command:

mvn install:install-file -Dfile=/Path-to-jar/ojdbc7.jar
-DgroupId=com.oracle 
-DartifactId=ojdbc7 
-Dversion=12.1.0.2 
-Dpackaging=jar 
-DgeneratePom=true

After that, I got as an output BUILD SUCCESS, and if I go to the .m2 folder I see in the com->oracle->ojdbc7 two files called “ojdbc7-12.1.0.1.jar.lastUpdated” and “ojdbc7-12.1.0.1.pom.lastUpdated” but still Eclipse brings me the code into the pom.xml file as an error?!?!?! Can some one help?



via Chebli Mohamed

How to sort Row RDD that contains mixures of Rows to make multiple dataframes with different schemas?

I created JavaRDD<Row> row with Rows from a single transformation that will form 3 DataFrame, but the Rows in that RDD is mixed together so I cannot do sqlContext.createDataFrame(row, schema) because there are 3 different schema. How would I split up row so that I can form 3 different Dataframes?



via Chebli Mohamed

Autowiring of a java List in Spring

I have the following Bean which I would like to have autowired in another class:

@Scope("job")
@Component
public class PublicCompanyHolder {

private List<File> publicCompanyList;

public List<File> getPublicCompanyList() {
return publicCompanyList;
}

public void setPublicCompanyList(List<File> publicCompanyList) {
this.publicCompanyList = publicCompanyList;
}

}

My Spring config looks like :

 <bean id="publicCompanyHolder" class="com.sample.bean.PublicCompanyHolder" >   
        <property name="publicCompanyList" ref="publicCompanyList" />
     </bean>
      <bean id="publicCompanyList" class="java.util.List" />

Is this the right way to do it.In another class by simply saying:

@Autowired
    private PublicCompanyHolder publicCompanyHolder;

I would like to use the class.Please let me know.



via Chebli Mohamed

Bukkit Bubble Rejection plugin

I'm trying to code a bukkit 1.8.8 plugin that basically allows someone to type a command composing of 2 parts. The first part is the player to be bubbled, the 2nd part is the radius of the bubble. It would look like /bubble . I basically want anyone who walks within that radius to get shot out very far. I really have no idea how to do this. The main part i'm stuck on is setting a radius around the player, and getting players who enter it. Please help me!!

code:

package me.Glowhoo.EpicUtil;

import java.util.Arrays;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
 import org.bukkit.command.Command;
 import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class Bubble implements CommandExecutor {

private Main plugin;

public Bubble(Main plugin)
{
  this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
    if (cmd.getName().equalsIgnoreCase("bubble"))
    {
        if (sender instanceof Player)
        {
            if (args.length > 0 && args.length < 2)
            {
            if (Bukkit.getPlayer(args[0]) != null)
            {
                Player victim = (Bukkit.getPlayer(args[0]));
                Bukkit.broadcastMessage(ChatColor.BOLD.GREEN + victim.getName() + ChatColor.BOLD.DARK_GRAY + " Is now in a bubble!");










            }
            else
            {
                sender.sendMessage(ChatColor.RED + "Player is not online!");

            }

            }
            else
            {
                sender.sendMessage(ChatColor.RED + "Invalid arguments!");
            }


        }
        else
        {
            sender.sendMessage(ChatColor.AQUA + "The console cannot bubble someone!");
        }

    }



    return false;
}






}

This code is just what I have been messing with. Any more efficient methods would be appreciated. THANKS :D



via Chebli Mohamed

How show text in centre of each rectangle using onDraw

I'm trying to create a text view (black colour) containing numbers 1 to 7 (each number on top and in the centre of each grey rectangle - just like the image I've drawn below) but I'm not sure what properties I need to add in order to achieve this. I believe the code needs to go in the loop section but I don't what code. What can be done so that a number appears centralised in each grey rectangle?

desired outcome

enter image description here

current outcome

enter image description here

public class RectangleTextView extends View {
    private final Paint mBackPaint = new Paint();
    private final Paint mRedPaint = new Paint();
    private int mSideRectWidth = 10;

    public RectangleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mBackPaint.setColor(Color.BLACK);
        mRedPaint.setColor(Color.RED);
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (getWidth() == 0)
            return;

        //draw grey boxes
        setBackgroundColor(Color.parseColor("#808080"));
        int boxWidth = getWidth() / 7;

        //draw black lines and/or draw text in centre of each rectangle
        for (int i = 0; i < 7; i++) {
            canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
        canvas.drawText(?);
        }

        //draw text in centre of each rectangle
        ?

        //draw left end rectangle
        canvas.drawRect(0, 0, mSideRectWidth, getHeight(), mRedPaint);

        //draw right end rectangle
        canvas.drawRect(getWidth() - mSideRectWidth, 0, getWidth(), getHeight(), mRedPaint);
    }
}



via Chebli Mohamed

How to enumerate connected USB storage devices Ubuntu Java

I have an application, mostly in Java' that controls an airborne infrared camera via a webpage GUI (served by the Ubuntu machine) which starts running automatically when the computer is powered up and towards the end of the boot. The application runs as a user, not root, even though the user is not logged in.

After a great many images are collected the data need to be archived by using rsync to a folder on the operator's USB drive. I need to have the USB drive mounted and know its name tag. The computer is headless and the operator, who is on the aircraft, cannot be expected to know Linux in any case.

On an Ubuntu I see that logged in and running the xfce4 GUI, and only then, the drives are listed in /media/user-name/drive-tag (I note that /media/username is owned by root but the folder named for the drive is owned by the user.) and are shown in /etc/mtab :

/dev/sdd1 /media/programmer/DATA-02-2TB vfat rw,nosuid,nodev,uid=1001,gid=1001,shortname=mixed,dmask=0077,utf8=1,showexec,flush,uhelper=udisks2 0 0

How can I, through Java or through a combination of Java and bash, detect and mount a USB storage device?

If that's not possible do I need to ask the user, through the GUI, to enter the device tag or name, e.g., 'DATA-02-2TB' and then create the mount point and mount the USB drive via a script using the information above?



via Chebli Mohamed

Storing data in Android - Java

I am currently working on my first app and i have decided to do it on android. I have the main activity layout the way i wish and the Time/Date displaying dynamically.

What I am needing help with is I need the app to save the date and time whenever a button is pressed. This data will need to be available for 1 week (7 Days) and then it may be overwritten the following week to save space on the device.

Ideally there would be two button presses a day, one to clock in/clock out (App to keep track of my hours at work and calculate pay). What is the best way to go about this? Can you guys point me in the right direction to storing this data?

I thought about using Parse but then an online connection would be needed, correct? Is there anyway to do this locally and then maybe I can implement online storage later?



via Chebli Mohamed

Spring configuration multiple projects - @Autowired no working

I have different java projects for data, business and web layer. I initialise spring context in the web layer and have all the spring beans xml file only in the web layer.

@Autowired feature works only for the spring beans in the web layer and does not works for the spring beans (Java classes) from the other 2 projects.

Do I need to define the spring beans xml configuration in the other 2 projects (data & business) as well ?



via Chebli Mohamed

HDFS - load mass amount of files

For testing purposes I'm trying to load a massive amount of small files into HDFS. Actually we talk about 1 Million (1'000'000) files with a size from 1KB to 100KB. I generated those files with an R-Script on a Linux-System in one folder. Every file has a information structure that contains a header with product information and a different number of columns with numeric information.

The problem is when I try to upload those local files into HDFS with the command:

hdfs dfs -copyFromLocal /home/user/Documents/smallData /

Then i get one of the following Java-Heap-Size errors:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

I use the Cloudera CDH5 distribution with a Java-Heap-Size about 5 GB. Is there another way than increasing this Java-Heap-Size even more? Maybe a better way to load this mass amount of data into HDFS?

I'm very thankfully for every helpful comment!



via Chebli Mohamed

how do I update a key field in a existing JSON string

This code is used to get to a JSON string an change the asignee field to the user currently logged in.

This code does not work because the key Full Name is not updating to the parameter Asignee. Can anybody tell me why its not working?

public void UpdateJsonAsign(String JSONstring, String Asignee){
    JSONObject obj = new JSONObject(JSONstring);
    obj.put("Full Name", Asignee);
}



via Chebli Mohamed

Please make my code shorters, how do I make it better?

I made a simple marijuana information program in which I give user a list of strains and give the user information about it (Effects, medical, negatives) and its cannabis type (sativa-Indica).

package Marijuana;

import java.util.Scanner;
//SANCHIT SHARMA

public class First {

public static void main(String[] args) {
    Scanner sc1 = new Scanner(System.in);


    System.out.println("Welcome to Marijuana info ");

    Strains strain = new Strains();


    strain.Type();
    strain.info();
    strain.Effects();


}

}





      package Marijuana;

      import java.util.*;

      public class Strains {

String name;
int ch;
int ch1;
Scanner sc = new Scanner(System.in);

Strains() {

    System.out.println("Select a Strain.");
    System.out.println("1. Blue Dream");
    System.out.println("2. Sour Diesel");
    System.out.println("3. OG Kush");
    System.out.println("4. Girl Scout Cookies");
    System.out.println("5. Green Crack");
    System.out.println("6. Pineapple Express");
    System.out.println("7. GrandDaddy Purple");
    ch = sc.nextInt();

    switch (ch) {
    case 1:
        System.out.println("
        break;
    case 2:
        System.out.println("
        break;
    case 3:
        System.out.println("
        break;
    case 4:
        System.out.println("
        break;
    case 5:
        System.out.println("
        break;
    case 6:
        System.out.println("
        break;
    case 7:
        System.out.println("
        break;
    }
}

public void Type() {
    String type[] = new String[7];
    type[0] = "Sativa Dominant Hybrid.";
    type[1] = "Invigorating Sativa.";
    type[2] = "Remains a Debatable mystery.";
    type[3] = "OG Kush and Durban Poison hybrid. Type remains a mystery";
    type[4] = "75% indica variety of Green Crack is said to have come from an Afghani strain";
    type[5] = "The child of Trainwreck and Hawaiian. Type remains a mystery";
    type[6] = "GrandDaddy Purple is a famous indica cross between Purple Urkle and Big Bud";

    for (int I = 0; I < type.length; i++) {
        if (ch == 7) {
            System.out.println("What type of cannabis? " + type[6]);
            System.out.println();
            break;
        }
        if (I == ch) {
            System.out.println("What type of cannabis? " + type[i - 1]);
            System.out.println();
        }
    }
}

public void info() {
    String type[] = new String[7];
    type[0] = "Blue Dream balances full-body relaxation with gentle cerebral invigoration. Novice and veteran consumers alike enjoy the level effects of \nBlue Dream, which ease you gently into a calm euphoria.";
    type[1] = "This fast-acting strain delivers energizing, dreamy cerebral effects that have pushed Sour Diesel to its legendary status. \nStress, pain, and depression fade away in long-lasting relief that makes Sour Diesel a top choice among medical patients. ";
    type[2] = "It has an earthy pine scent with woody undertones, an aroma that has become the signature of OG Kush varieties and descendants. \nWith OG Kush, patients most commonly cite improvements in migraines, ADD/ADHD, and stress disorders.";
    type[3] = "Girl Scout Cookies launches you to euphoria’s top floor where full-body relaxation meets a time-bending cerebral space. \nA little goes a long way with this hybrid, whose THC heights have won Girl Scout Cookies numerous Cannabis Cup awards.";
    type[4] = "Few strains compare to Green Crack’s sharp energy and focus as it induces an invigorating mental buzz that keeps you going throughout the day. \nWith a tangy, fruity flavor redolent of mango, Green Crack is the perfect daytime medication for patients treating fatigue, stress, and depression.";
    type[5] = "The smell has been likened to fresh apple and mango, with a taste of pineapple, pine and cedar. \nThis hard-hitting sativa provides an energetic high up to 2 hours and has a THC content up to 17% with CBD of 0.17%. ";
    type[6] = "Its potent psychoactive effects are clearly detectable in both mind and body, delivering a fusion of cerebral euphoria and physical relaxation.\nGranddaddy Purple is typically pulled off the shelf to treat pain, stress, insomnia, appetite loss, and muscle spasms. ";

    for (int I = 0; I < type.length; i++) {
        if (ch == 7) {
            System.out.println(type[6]);
            break;
        }
        if (ch == I)
            System.out.println(type[i - 1]);
    }
    System.out.println();
}

public void Effects() {

    String BD = "Happy: 10 " + "Euphoric: 9 " + "Releaxed: 8.5 " + "Uplifted: 8 " + "Creative: 6.5 ";

    String BDM = "Stress: 10 " + "Depression: 7 " + "Pain:  6.75 ";

    String BDN = "Dry Mouth: 10 " + "Dry Eyes: 5 " + "Paranoid: 3.5 ";

    String SD = "Happy: 10 " + "Euphoric: 8.5 " + "Releaxed: 8 " + "Uplifted: 7.5 " + "Creative: 6 ";

    String SDM = "Stress: 10 " + "Depression: 7 " + "Pain:  6 ";

    String SDN = "Dry Mouth: 10 " + "Dry Eyes: 5.5 " + "Paranoid: 3 ";

    String OG = "Happy: 10 " + "Euphoric: 8 " + "Releaxed: 10 " + "Uplifted: 6 " + "Creative: 5 ";

    String OGM = "Stress: 10 " + "Depression: 6.5 " + "Pain:    6.75 ";

    String OGN = "Dry Mouth: 10 " + "Dry Eyes: 7 " + "Paranoid: 3 ";

    String GSC = "Happy: 10 " + "Euphoric: 9 " + "Releaxed: 8.5 " + "Uplifted: 6 " + "Creative: 5 ";

    String GSCM = "Stress: 10 " + "Depression: 7 " + "Pain: 6.75 ";

    String GSCN = "Dry Mouth: 10 " + "Dry Eyes: 5 " + "Paranoid: 2 ";

    String GC = "Happy: 9.5 " + "Euphoric: 7 " + "Energetic: 10 " + "Uplifted: 8.5 " + "Creative: 6 ";

    String GCM = "Stress: 10 " + "Depression: 8 " + "Pain:  6 ";

    String GCN = "Dry Mouth: 10 " + "Dry Eyes: 5 " + "Paranoid: 3.5 ";

    String PE = "Happy: 10 " + "Euphoric: 8 " + "Releaxed: 7" + "Uplifted: 7 " + "Creative: 6.5 ";

    String PEM = "Stress: 10" + "Depression: 7" + "Pain:    6";

    String PEN = "Dry Mouth: 10 " + "Dry Eyes: 5.5 " + "Paranoid: 2.5 ";

    String GDP = "Happy: 7" + "Euphoric: 6.5" + "Releaxed: 10" + "Hungry: 5 " + "Sleepy: 6.5 ";

    String GDPM = "Stress: 10 " + "Depression: 6 " + "Pain: 9 ";

    String GDPN = "Dry Mouth: 10 " + "Dry Eyes: 5.5 " + "Paranoid: 3";

    System.out.println("What Would You like to know");
    System.out.println("1. Effects");
    System.out.println("2. Medical attributes");
    System.out.println("3. Negatives");
    System.out.println("4. Everything altogether");
    ch1 = sc.nextInt();

    switch (ch1) {
    case 1:
        if (ch == 1) {
            System.out.println(BD);
        }
        if (ch == 2) {
            System.out.println(SD);
        }
        if (ch == 3) {
            System.out.println(OG);
        }
        if (ch == 4) {
            System.out.println(GSC);
        }
        if (ch == 5) {
            System.out.println(GC);
        }
        if (ch == 6) {
            System.out.println(PE);
        }
        if (ch == 7) {
            System.out.println(GDP);
        }
        break;

    case 2:
        if (ch == 1) {
            System.out.println(BDM);
        }
        if (ch == 2) {
            System.out.println(SDM);
        }
        if (ch == 3) {
            System.out.println(OGM);
        }
        if (ch == 4) {
            System.out.println(GSCM);
        }
        if (ch == 5) {
            System.out.println(GCM);
        }
        if (ch == 6) {
            System.out.println(PEM);
        }
        if (ch == 7) {
            System.out.println(GDPM);
        }
        break;

    case 3:
        if (ch == 1) {
            System.out.println(BDN);
        }
        if (ch == 2) {
            System.out.println(SDN);
        }
        if (ch == 3) {
            System.out.println(OGN);
        }
        if (ch == 4) {
            System.out.println(GSCN);
        }
        if (ch == 5) {
            System.out.println(GCN);
        }
        if (ch == 6) {
            System.out.println(PEN);
        }
        if (ch == 7) {
            System.out.println(GDPN);
        }
        break;
    case 4:
        if (ch == 1) {
            System.out.println(BD);
            System.out.println(BDM);
            System.out.println(BDN);
        }
        if (ch == 2) {
            System.out.println(SD);
            System.out.println(SDM);
            System.out.println(SDN);
        }
        if (ch == 3) {
            System.out.println(OG);
            System.out.println(OGM);
            System.out.println(OGN);
        }
        if (ch == 4) {
            System.out.println(GSC);
            System.out.println(GSCM);
            System.out.println(GSCN);
        }
        if (ch == 5) {
            System.out.println(GC);
            System.out.println(GCM);
            System.out.println(GCN);
        }
        if (ch == 6) {
            System.out.println(PE);
            System.out.println(PEM);
            System.out.println(PEN);
        }
        if (ch == 7) {
            System.out.println(GDP);
            System.out.println(GDPM);
            System.out.println(GDPN);
            break;
        }
    }

}

}



via Chebli Mohamed

JButton doesn't work at all after i dispose existing frame and sets the new frame(re instantiate another frame)

I made a calculator and to increase its functionality and simplicity i made three frames which support simple , scientific and conversion calculator

calculator works perfect till i use it once but when i change my calculator type from simple to scientific and scientific to conversion and then again to simple calculator , program doesn't do anything at all , jbutton doesn't perform any action even actionPerformed is getting called i checked that by putting println statement in method actionPerformed.

i instantiate my three frames in constructor and i'd made three methods each for calculator type to instantiating and adding buttons and other stuff to JPanels and adding panels to JFrame

//Constructor
public Calculator()
{

    //instantiating buttons
            buttons = new JButton[15];
            optionButtons = new JButton[5];
            scientificOptionButtons = new JButton[20];
            constantButtons = new JButton[5];

            //instantiating calculatorFrames
            simpleCalculatorFrame = new JFrame("Calculator");
            scientificCalculatorFrame = new JFrame("Scientific Calculator");
            convertCalculatorFrame = new JFrame("Conversion Calculator");

    } // end of the constructor

when i choose calculator type from my JMenuItems i dispose the active frame and call other calculatortype methods for creating and adding stuff to panels and setting up frame like

//if statements inside method actionPerformed to check which type of calculator should run
if(event.getSource() == scientificMenuItem)
        {
            if(simpleCalculatorFrame.isActive())
            {
                simpleCalculatorFrame.dispose();
                scientificCalculatorBuilder();
            }
            else if(convertCalculatorFrame.isActive())
            {
                convertCalculatorFrame.dispose();
                scientificCalculatorBuilder();
            }

        }
        else if(event.getSource() == simpleMenuItem)
        {
            if(scientificCalculatorFrame.isActive())
            {
                scientificCalculatorFrame.dispose();
                simpleCalculatorBuilder();
            }
            else if(convertCalculatorFrame.isActive())
            {
                convertCalculatorFrame.dispose();
                simpleCalculatorBuilder();
            }

        }
        else if(event.getSource() == convertMenuItem)
        {
            if(simpleCalculatorFrame.isActive())
            {
                simpleCalculatorFrame.dispose();
                convertCalculatorBuilder();
            }
            else if(scientificCalculatorFrame.isActive())
            {

                scientificCalculatorFrame.dispose();
                convertCalculatorBuilder();
            }

        }
        else if(event.getSource() == exitMenuItem)
        {
            System.exit(0);
        }

everything looks fine just not getting where the problem is

here's code of my methods which instantiates the components

public void simpleCalculatorBuilder()
{


        //instantiating menuBar , fileMenu and menuItems and adding functionality
        menuBar = new JMenuBar();
        fileMenu = new JMenu("File");
        scientificMenuItem = new JMenuItem("Scientific Calculator");
        convertMenuItem = new JMenuItem("Conversion Calculator");
        convertMenuItem.addActionListener(handler);
        scientificMenuItem.addActionListener(handler);
        exitMenuItem = new JMenuItem("Exit");
        exitMenuItem.addActionListener(handler);
        menuBar.add(fileMenu);
        fileMenu.add(scientificMenuItem);
        fileMenu.add(convertMenuItem);
        fileMenu.add(exitMenuItem);

        //instantiating and adding textField appearing at the top of calculator to show ongoing processes and results
        myField = new JTextField();
        myField.setPreferredSize(new Dimension(this.getWidth() , 40));
        myField.setEditable(false);
        simpleCalculatorFrame.add(myField , BorderLayout.NORTH);

        //instantiating panels to hold buttons
        buttonsPanel = new JPanel(new GridLayout(5 , 3 , 3 , 6));
        optionButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));


        //loop to add buttons to panel , adding eventListeners to buttons , setting background color of buttons
        for(int i = 0 ; i<buttons.length ; i++)
        {
            buttons[i] = new JButton(buttonTitles[i]);
            buttons[i].setBackground(Color.BLACK);
            buttons[i].setForeground(Color.WHITE);
            buttons[i].addActionListener(handler);
            buttons[i].addMouseListener(handler);
            buttonsPanel.add(buttons[i]);
            if(i<5)
            {
                optionButtons[i] = new JButton(optionButtonTitles[i]);
                optionButtons[i].setBackground(Color.BLACK);
                optionButtons[i].setForeground(Color.WHITE);
                optionButtons[i].addActionListener(handler);
                optionButtons[i].addMouseListener(handler);
                optionButtonsPanel.add(optionButtons[i]);
            }
        } 

        //setting background color of panels

        buttonsPanel.setBackground(Color.DARK_GRAY);
        optionButtonsPanel.setBackground(Color.DARK_GRAY);

        //adding items and panels to the frame and setting the simpleCalculatorFrame
        simpleCalculatorFrame.setJMenuBar(menuBar);
        simpleCalculatorFrame.add(buttonsPanel , BorderLayout.CENTER);
        simpleCalculatorFrame.add(optionButtonsPanel , BorderLayout.EAST);
        simpleCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        simpleCalculatorFrame.setSize(240 , 270);
        simpleCalculatorFrame.setLocationRelativeTo(null);
        simpleCalculatorFrame.setVisible(true);
        simpleCalculatorFrame.setResizable(false);

} // end of simple calculator builder

public void scientificCalculatorBuilder()
{

    //instantiating menuBar , fileMenu and menuItems and adding functionality
    menuBar = new JMenuBar();
    fileMenu = new JMenu("File");
    simpleMenuItem = new JMenuItem("Simple Calculator");
    simpleMenuItem.addActionListener(handler);
    convertMenuItem = new JMenuItem("Conversion Calculator");
    convertMenuItem.addActionListener(handler);
    exitMenuItem = new JMenuItem("Exit");
    exitMenuItem.addActionListener(handler);
    menuBar.add(fileMenu);
    fileMenu.add(simpleMenuItem);
    fileMenu.add(convertMenuItem);
    fileMenu.add(exitMenuItem);

    //instantiating and adding textField appearing at the top of calculator to show ongoing processes and results
    myField = new JTextField();
    myField.setPreferredSize(new Dimension(this.getWidth() , 40));
    myField.setEditable(false);
    scientificCalculatorFrame.add(myField , BorderLayout.NORTH);

    //instantiating panels to hold buttons
    buttonsPanel = new JPanel(new GridLayout(5 , 3 , 3 , 6));
    optionButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
    scientificOptionButtonsPanel = new JPanel(new GridLayout(5 , 4 , 3 , 3));
    constantButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
    scientificPanelManager = new JPanel(new GridLayout(1 , 2));



    //loop to add buttons to panel , adding eventListeners to buttons , setting background color of buttons
    for(int i = 0 ; i<scientificOptionButtons.length ; i++)
    {
        if(i<5)
        {
            optionButtons[i] = new JButton(optionButtonTitles[i]);
            optionButtons[i].setBackground(Color.BLACK);
            optionButtons[i].setForeground(Color.WHITE);
            optionButtons[i].addActionListener(handler);
            optionButtons[i].addMouseListener(handler);
            optionButtonsPanel.add(optionButtons[i]);

            constantButtons[i] = new JButton(constantButtonTitles[i]);
            constantButtons[i].setBackground(Color.BLACK);
            constantButtons[i].setForeground(Color.WHITE);
            constantButtons[i].addActionListener(handler);
            constantButtons[i].addMouseListener(handler);
            constantButtonsPanel.add(constantButtons[i]);
        }
        if(i<15)
        {
            buttons[i] = new JButton(buttonTitles[i]);
            buttons[i].setBackground(Color.BLACK);
            buttons[i].setForeground(Color.WHITE);
            buttons[i].addActionListener(handler);
            buttons[i].addMouseListener(handler);
            buttonsPanel.add(buttons[i]);
        }
            scientificOptionButtons[i] = new JButton(scientificOptionButtonTitles[i]);
            scientificOptionButtons[i].setBackground(Color.BLACK);
            scientificOptionButtons[i].setForeground(Color.WHITE);
            scientificOptionButtons[i].addActionListener(handler);
            scientificOptionButtons[i].addMouseListener(handler);
            scientificOptionButtonsPanel.add(scientificOptionButtons[i]);
    }// end of for loop

    //setting background color of panels
    buttonsPanel.setBackground(Color.DARK_GRAY);
    optionButtonsPanel.setBackground(Color.DARK_GRAY);
    scientificOptionButtonsPanel.setBackground(Color.DARK_GRAY);
    constantButtonsPanel.setBackground(Color.DARK_GRAY);

    scientificPanelManager.add(scientificOptionButtonsPanel);
    scientificPanelManager.add(buttonsPanel);
    scientificCalculatorFrame.setJMenuBar(menuBar);
    scientificCalculatorFrame.add(constantButtonsPanel , BorderLayout.WEST);
    scientificCalculatorFrame.add(optionButtonsPanel , BorderLayout.EAST);
    scientificCalculatorFrame.add(scientificPanelManager , BorderLayout.CENTER);
    scientificCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    scientificCalculatorFrame.setSize(580 , 300);
    scientificCalculatorFrame.setLocationRelativeTo(null);
    scientificCalculatorFrame.setVisible(true);
    scientificCalculatorFrame.setResizable(false);

} // end of scientificCalculatorBuilder


//method which starts convertCalculatorFrame and initializes frame needs
public void convertCalculatorBuilder()
{

    convertCalculatorTopPanel = new JPanel(new GridLayout(2 , 1 , 0 , 4));
    convertCalculatorCenterPanel = new JPanel(new GridLayout(2 , 2 , 5 , 3));
    convertCalculatorEastPanel = new JPanel(new GridLayout(2 , 1 ,1 , 3));
    convertCalculatorSouthPanel = new JPanel(new GridLayout(1 , 2 , 5 , 2));


    //instantiating menuBar , fileMenu and menuItems and adding functionality
            menuBar = new JMenuBar();
            fileMenu = new JMenu("File");
            simpleMenuItem = new JMenuItem("Simple Calculator");
            simpleMenuItem.addActionListener(handler);
            scientificMenuItem = new JMenuItem("Scientific Calculator");
            scientificMenuItem.addActionListener(handler);
            exitMenuItem = new JMenuItem("Exit");
            exitMenuItem.addActionListener(handler);
            menuBar.add(fileMenu);
            fileMenu.add(simpleMenuItem);
            fileMenu.add(scientificMenuItem);
            fileMenu.add(exitMenuItem);

    typeConvertCalculatorComboBox = new JComboBox<String>();
    typeConvertCalculatorComboBox.setBackground(Color.BLACK);
    typeConvertCalculatorComboBox.setForeground(Color.WHITE);
    typeConvertCalculatorComboBox.setMaximumRowCount(3);

    typeConvertCalculatorComboBox.addItem("Choose type of conversion");
    typeConvertCalculatorComboBox.addItem("Distance Conversion");
    typeConvertCalculatorComboBox.addItem("Memory Conversion");
    typeConvertCalculatorComboBox.addItem("Temperature Conversion");
    typeConvertCalculatorComboBox.addItem("Mass Conversion");

    typeConvertCalculatorComboBox.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    if(typeConvertCalculatorComboBox.getSelectedItem() == "Distance Conversion")
                    {
                        fromConvertCalculatorComboBox.setEnabled(true);
                        toConvertCalculatorComboBox.setEnabled(true);

                        fromConvertCalculatorComboBox.removeAllItems();
                        fromConvertCalculatorComboBox.setMaximumRowCount(3);
                        fromConvertCalculatorComboBox.addItem("Centimeter(s)");
                        fromConvertCalculatorComboBox.addItem("Meter(s)");
                        fromConvertCalculatorComboBox.addItem("Kilometer(s)");
                        fromConvertCalculatorComboBox.addItem("Mile(s)");

                        toConvertCalculatorComboBox.removeAllItems();
                        toConvertCalculatorComboBox.setMaximumRowCount(2);
                        toConvertCalculatorComboBox.addItem("Centimeter(s)");
                        toConvertCalculatorComboBox.addItem("Meter(s)");
                        toConvertCalculatorComboBox.addItem("Kilometer(s)");
                        toConvertCalculatorComboBox.addItem("Mile(s)");

                    }
                    else if(typeConvertCalculatorComboBox.getSelectedItem() == "Memory Conversion")
                    {
                        fromConvertCalculatorComboBox.setEnabled(true);
                        toConvertCalculatorComboBox.setEnabled(true);

                        fromConvertCalculatorComboBox.removeAllItems();
                        fromConvertCalculatorComboBox.setMaximumRowCount(3);
                        fromConvertCalculatorComboBox.addItem("Kilobyte(s)");
                        fromConvertCalculatorComboBox.addItem("Megabyte(s)");
                        fromConvertCalculatorComboBox.addItem("Gigabyte(s)");
                        fromConvertCalculatorComboBox.addItem("Terabyte(s)");

                        toConvertCalculatorComboBox.removeAllItems();
                        toConvertCalculatorComboBox.setMaximumRowCount(2);
                        toConvertCalculatorComboBox.addItem("Kilobyte(s)");
                        toConvertCalculatorComboBox.addItem("Megabyte(s)");
                        toConvertCalculatorComboBox.addItem("Gigabyte(s)");
                        toConvertCalculatorComboBox.addItem("Terabyte(s)");
                    }
                    else if(typeConvertCalculatorComboBox.getSelectedItem() == "Temperature Conversion")
                    {
                        fromConvertCalculatorComboBox.setEnabled(true);
                        toConvertCalculatorComboBox.setEnabled(true);

                        fromConvertCalculatorComboBox.removeAllItems();
                        fromConvertCalculatorComboBox.addItem("Centigrade");
                        fromConvertCalculatorComboBox.addItem("Fahrenheit");
                        fromConvertCalculatorComboBox.addItem("Kelvin");

                        toConvertCalculatorComboBox.removeAllItems();
                        toConvertCalculatorComboBox.setMaximumRowCount(2);
                        toConvertCalculatorComboBox.addItem("Centigrade");
                        toConvertCalculatorComboBox.addItem("Fahrenheit");
                        toConvertCalculatorComboBox.addItem("Kelvin");
                    }
                    else if(typeConvertCalculatorComboBox.getSelectedItem() == "Mass Conversion")
                    {
                        fromConvertCalculatorComboBox.setEnabled(true);
                        toConvertCalculatorComboBox.setEnabled(true);

                        fromConvertCalculatorComboBox.removeAllItems();
                        fromConvertCalculatorComboBox.setMaximumRowCount(3);
                        fromConvertCalculatorComboBox.addItem("Milligram(s)");
                        fromConvertCalculatorComboBox.addItem("Pound(s) (lbs)");
                        fromConvertCalculatorComboBox.addItem("Kilogram(s)");

                        toConvertCalculatorComboBox.removeAllItems();
                        toConvertCalculatorComboBox.setMaximumRowCount(2);
                        toConvertCalculatorComboBox.addItem("Milligram(s)");
                        toConvertCalculatorComboBox.addItem("Pound(s) (lbs)");
                        toConvertCalculatorComboBox.addItem("Kilogram(s)");

                    }
                }
            }
            );

    fromConvertCalculatorComboBox = new JComboBox<String>();
    fromConvertCalculatorComboBox.setMaximumRowCount(3);
    fromConvertCalculatorComboBox.setBackground(Color.BLACK);
    fromConvertCalculatorComboBox.setForeground(Color.WHITE);
    fromConvertCalculatorComboBox.setEnabled(false);

    toConvertCalculatorComboBox = new JComboBox<String>();
    toConvertCalculatorComboBox.setMaximumRowCount(2);
    toConvertCalculatorComboBox.setBackground(Color.BLACK);
    toConvertCalculatorComboBox.setForeground(Color.WHITE);
    toConvertCalculatorComboBox.setEnabled(false);


        topConvertCalculatorLabel = new JLabel("What type of conversion you want ?");
        topConvertCalculatorLabel.setForeground(Color.WHITE);
        fromConvertCalculatorLabel = new JLabel("From");
        fromConvertCalculatorLabel.setForeground(Color.WHITE);
        toConvertCalculatorLabel = new JLabel("To");
        toConvertCalculatorLabel.setForeground(Color.WHITE);

        fromConvertCalculatorField = new JTextField();
        fromConvertCalculatorField.setPreferredSize(new Dimension(120 , 2));
        fromConvertCalculatorField.addActionListener(convertHandler);
        ansConvertCalculatorField = new JTextField();
        ansConvertCalculatorField.setEditable(false);

        convertButton = new JButton("Convert");
        convertButton.setBackground(Color.BLACK);
        convertButton.setForeground(Color.WHITE);
        convertButton.addMouseListener(handler);

        convertButton.addActionListener(convertHandler);



        convertCalculatorFrame.setJMenuBar(menuBar);

    //adding components to panel and adding panels to frame
    {
        convertCalculatorTopPanel.add(topConvertCalculatorLabel);
        convertCalculatorTopPanel.add(typeConvertCalculatorComboBox);
        convertCalculatorTopPanel.setBackground(Color.DARK_GRAY);
        convertCalculatorFrame.add(convertCalculatorTopPanel , BorderLayout.NORTH);

        convertCalculatorCenterPanel.add(fromConvertCalculatorLabel);
        convertCalculatorCenterPanel.add(fromConvertCalculatorComboBox);
        convertCalculatorCenterPanel.add(toConvertCalculatorLabel);
        convertCalculatorCenterPanel.add(toConvertCalculatorComboBox);
        convertCalculatorCenterPanel.setBackground(Color.DARK_GRAY);
        convertCalculatorFrame.add(convertCalculatorCenterPanel , BorderLayout.CENTER);

        convertCalculatorEastPanel.add(fromConvertCalculatorField);
        convertCalculatorEastPanel.setBackground(Color.DARK_GRAY);
        convertCalculatorFrame.add(convertCalculatorEastPanel , BorderLayout.EAST);

        convertCalculatorSouthPanel.add(convertButton);
        convertCalculatorSouthPanel.add(ansConvertCalculatorField);
        convertCalculatorSouthPanel.setBackground(Color.DARK_GRAY);
        convertCalculatorFrame.add(convertCalculatorSouthPanel , BorderLayout.SOUTH);

        convertCalculatorFrame.getContentPane().validate();
        convertCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        convertCalculatorFrame.setSize(390 , 200);
        convertCalculatorFrame.setLocationRelativeTo(null);
        convertCalculatorFrame.setVisible(true);
        convertCalculatorFrame.setResizable(false);
    }
}//end of convertCalculatorBuilder

i dont have much experience in programming hope you people won't mind helping

here's an MCVE

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test { 
public static void main(String[] args) {
        Practice application = new Practice();
        application.forFrame1();
}
}

class Practice extends JPanel
{
Handler handler = new Handler();

private JButton[] buttons;
private JButton[] moreButtons;

private JMenuBar menuBar;
private JMenu myMenu;
private JMenuItem firstItem;
private JMenuItem secondItem;

private JFrame frame1;
private JFrame frame2;

private JPanel panel1;
private JPanel panel2;

public Practice()
{
    buttons = new JButton[3];
    moreButtons = new JButton[5];

    frame1 = new JFrame();
    frame2 = new JFrame();
}
public void forFrame1()
{
    menuBar = new JMenuBar();
    myMenu = new JMenu("menu");
    secondItem = new JMenuItem("goto 2nd frame");
    secondItem.addActionListener(handler);
    menuBar.add(myMenu);
    myMenu.add(secondItem);

    frame1.setJMenuBar(menuBar);

    panel1 = new JPanel(new GridLayout(3 , 1));

    for(int i = 0 ; i<buttons.length ; i++)
    {
        buttons[i] = new JButton(""+ i);
        buttons[i].addActionListener(handler);
        panel1.add(buttons[i]);
    }
    frame1.add(panel1);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setSize(200 , 200);
    frame1.setVisible(true);
}

public void forFrame2()
{
    menuBar = new JMenuBar();
    myMenu = new JMenu("menu");
    firstItem = new JMenuItem("goto 1st frame");
    firstItem.addActionListener(handler);
    menuBar.add(myMenu);
    myMenu.add(firstItem);
    frame2.setJMenuBar(menuBar);

    panel2 = new JPanel(new GridLayout(1 , 5));
    for(int i = 0 ; i<moreButtons.length ; i++)
    {   
        moreButtons[i] = new JButton(""+ i);
        moreButtons[i].addActionListener(handler);
        panel2.add(moreButtons[i]);
    }
    frame2.add(panel2);
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame2.setSize(200 , 200);
    frame2.setVisible(true);
}

private class Handler implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource() == firstItem)
        {
                frame2.dispose();
                forFrame1();

        }
        else if(event.getSource() == secondItem)
        {
                frame1.dispose();
                forFrame2();    
        }

        for(int i = 0 ; i< moreButtons.length ; i++)
        {
            if(i<buttons.length)
            {
                if(event.getSource() == buttons[i])
        JOptionPane.showMessageDialog(null, "frame1 component working");
            }
            if(event.getSource() == moreButtons[i])
        JOptionPane.showMessageDialog(null, "frame2 components working");
        }
    }
}


}

try using component after changing frame by choosing menuItem



via Chebli Mohamed