vendredi 18 septembre 2015

Java automatic HTTP headers on OutputStream

I have a simple Java TCP Server application that listens for connections and one a client connects it sends a string. If I run the server and make a GET request from a browser the string sent by the server is displayed. This is great, but, How did it work without HTTP Headers? Is the OutputStream class prepending HTTP Headers?

When I write the same code in C#, it doesnt work without Headers, the browsers doesnt display the sent string if there no HTTP headers prepended. The C# behavoir makes sense, so, whats happening with my java code?

Java code

ServerSocket server = new ServerSocket(8080);
            System.out.println("Servidor iniciado.\naguardando a conexao de um cliente...");
            Socket clientSocket = server.accept();
            System.out.println("Um cliente conectou-se ao nosso servidor Socket TCP");



            OutputStream streamSaida = null;
            //Obter a referencia do stream de saida do cliente conectado.
            streamSaida = clientSocket.getOutputStream();

            String bemVindo = "Bem vindo ao nosso primeiro servidor";
            streamSaida.write(bemVindo.getBytes());

            System.out.println("Desligando o servidor");
            clientSocket.close();
            server.close();

C# code

System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 8080);
            server.Start();
            Console.WriteLine("Servidor TCP iniciado");
            Console.WriteLine("Aguardando conexao de um cliente...");
            Socket client = server.AcceptSocket();

            Console.WriteLine("Um cliente conectou-se ao servidor");

            String msg = "Bem-vindo ao nosso servidor TCP C#"; //Mensagem de boas vindas

            NetworkStream streamCliente = new NetworkStream(client);
            System.IO.StreamWriter writer = new System.IO.StreamWriter(streamCliente);
            writer.Write(msg);
            writer.Flush();



from Newest questions tagged java - Stack Overflow http://ift.tt/1MgkImO
via IFTTT

Android: Hashmap concurrent Modification Exception

I keep getting a concurrent modification exception on my code. I'm simply iterating through a hashmap and modifying values. From researching this I found people said to use iterators and iterator.remove, etc. I tried implementing with this and still kept getting the error. I thought maybe multiple threads accessed it? (Although in my code this block is only run in one thread) So I put it in a synchronized block. However, I'm still getting the error.....

 Map map= Collections.synchronizedMap(questionNumberAnswerCache);
        synchronized (map) {
            for (Iterator<Map.Entry<String, Integer>> it = questionNumberAnswerCache.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry<String, Integer> entry = it.next();
                if (entry.getKey() == null || entry.getValue() == null) {
                    continue;
                } else {
                    try {
                        Question me = Question.getQuery().get(entry.getKey());
                        int i = Activity.getQuery()
                                .whereGreaterThan(Constants.kQollegeActivityCreatedAtKey, lastUpdated.get("AnswerNumberCache " + entry.getKey()))
                                .whereEqualTo(Constants.kQollegeActivityTypeKey, Constants.kQollegeActivityTypeAnswer)
                                .whereEqualTo(Constants.kQollegeActivityQuestionKey, me)
                                .find().size();

                        lastUpdated.put("AnswerNumberCache " + entry.getKey(), Calendar.getInstance().getTime());

                        int old_num = entry.getValue();
                        entry.setValue(i + old_num);

                    } catch (ParseException e) {
                        entry.setValue(0);
                    }
                }

            }

        }

Error:

  java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
        at java.util.HashMap$EntryIterator.next(HashMap.java:824)
        at java.util.HashMap$EntryIterator.next(HashMap.java:822)
        at com.juryroom.qollege_android_v1.QollegeCache.refreshQuestionAnswerNumberCache(QollegeCache.java:379)
        at com.juryroom.qollege_android_v1.QollegeCache.refreshQuestionCaches(QollegeCache.java:267)
        at com.juryroom.qollege_android_v1.UpdateCacheService.onHandleIntent(UpdateCacheService.java:28)
        at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.os.HandlerThread.run(HandlerThread.java:61)



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZSHqW
via IFTTT

How can class.this in a callback can be null?

I have a Fragment. In this Fragment I run a http request on an json-rpc. To handle the result I have something like this in my Callback.

FragmentClass.this.getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Do something
    } 
});

The problem is, sometimes i get a NullPointerException on the first line... My first intend was, that the fragment got detached to fast maybe because the user selects an other fragment while the request runs and so the

FragmentClass.this.getActivity();

has no activity and returns null. I enclose the whole thing with an if like this:

// New if:
if (FragmentClass.this.getActivity() != null) {

    FragmentClass.this.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // Do something
        } 
    });

}

But... Nothing... Now I get an NullPointerException on the if statement. it seems that

FragmentClass.this

is null.

How is that possible. I thought an instance will be hold until no code part needs it and the gc collects it...

Thank you for your help!

Artur



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZSGTS
via IFTTT

Android Integration with Zebra zq520 Printer

We are trying to integrate android device with zebra printer zq520 for printing. Though we are able to pair with the printer but not able to get the print for the same.

On the other hand we are able to successfully integrate android device with the zebra printer ez320 in order to get print in desired way.

For integration with android device we are using basic java api rather than any specific api. We are not sure if there is any different mechanism or implementations for these two printers. (ez320 and zq520).

It would be great if we get any support or guidelines in order to resolve this issue.



from Newest questions tagged java - Stack Overflow http://ift.tt/1W7jChG
via IFTTT

Hibernate get all transaction of current year

Suppose I have a class TransactionDetails. This table holds transaction of last 10 year. Now How can i get all TransactionDetails of current year

I am using criteria as following

Criteria criteria = session.getCurrentSession().createCriteria(TransactionDetails.class);
criteria.add(Restrictions.eq("entryDate", thisYear));
return (List<TransactionDetails>) criteria.list();

I know I can achieve this by detecting beginning of year and end of year and the do a query with between operator. But I am looking for a way do this in one line. e.g. like in sql we use CURDATE()

How can this be done??



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuQbVb
via IFTTT

libcurl CURLE_SSL_CACERT_BADFILE error on android

So I'm trying to use libcurl with JNI but it returns CURLE_SSL_CACERT_BADFILE error. This is my code.

JNI side:

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}


//jList is an array containing the certificate.

 Java_packageName_MainActivity_Test(JNIEnv *env, jobject thiz, jobject jList)
    {

        vector<string> certificatesPinning;

        // Convert jobject to jobjectArray
        // retrieve the java.util.List interface class
        jclass cList = env->FindClass("java/util/List");
        // retrieve the toArray method and invoke it
        jmethodID mToArray = env->GetMethodID(cList, "toArray", "()[Ljava/lang/Object;");
        jobjectArray stringArray = (jobjectArray)env->CallObjectMethod(jList, mToArray);

        // Add each certificate to the list
        int stringCount = (env)->GetArrayLength(stringArray);
        for (int i=0; i < stringCount; i++)
        {
            jstring certificateString = (jstring)(env)-> GetObjectArrayElement(stringArray, i);
            const char *cert = (env)->GetStringUTFChars(certificateString, 0);
            const jsize len = env->GetStringUTFLength(certificateString);

            string certificatePinningObj(cert,len);

            certificatesPinning.push_back(certificatePinningObj);
            (env)->ReleaseStringUTFChars( certificateString, cert);
        }

        string readBuffer;
        CURL *curl = curl_easy_init();
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_easy_setopt(curl, CURLOPT_URL, "https://theapi.com");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);// Fill the response in the readBuffer
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 120); // 120 s connect timeout
        curl_easy_setopt(curl, CURLOPT_ENCODING, GZIP);
        curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"der");

        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER , 1);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST , 2L);
        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
        curl_easy_setopt(curl, CURLOPT_CAINFO,certificatesPinning[0].c_str());//buf


        CURLcode res;
        res = curl_easy_perform(curl);
        if(!readBuffer.empty())
        {
           printf("success \n");
        }
        else
        {
            printf("error \n");
        int a = (int)res;// this is 77 = CURLE_SSL_CACERT_BADFILE

        }
    }

JAVA side:

// Define the function
native void Test(ArrayList<String> certificates);

// Prepare the certificate
ArrayList<String> certificatesPinning = new ArrayList<String>();
certificatesPinning.add(saveCertPemFile());

// Call the function
Test(certificatesPinning);


 // Helpers
    private String saveCertPemFile()
    {
        Context context=getApplicationContext();
        String assetFileName="certificateName.der";

        if(context==null || !FileExistInAssets(assetFileName,context))
        {
            Log.i("TestActivity", "Context is null or asset file doesnt exist");
            return null;
        }
        //destination path is data/data/packagename
        String destPath=getApplicationContext().getApplicationInfo().dataDir;
        String CertFilePath =destPath + "/" +assetFileName;
        File file = new File(CertFilePath);
        if(file.exists())
        {
            //delete file
            file.delete();
        }
        //copy to internal storage
        if(CopyAssets(context,assetFileName,CertFilePath)==1) return CertFilePath;

        return CertFilePath=null;

    }

    private int CopyAssets(Context context,String assetFileName, String toPath)
    {
        AssetManager assetManager = context.getAssets();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(assetFileName);
            new File(toPath).createNewFile();
            out = new FileOutputStream(toPath);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
            return 1;
        } catch(Exception e) {
            Log.e("tag", "CopyAssets"+e.getMessage());

        }
        return 0;

    }

    private boolean FileExistInAssets(String fileName,Context context)
    {
        try {
            return Arrays.asList(context.getResources().getAssets().list("")).contains(fileName);
        } catch (IOException e) {
            // TODO Auto-generated catch block

            Log.e("tag", "FileExistInAssets"+e.getMessage());

        }
        return false;
    }

"certificateName.der" is the certificate stored in the assets folder.

And this is the certificate path being sent to the jni:

/data/data/packageName/certificateName.der

Reference



from Newest questions tagged java - Stack Overflow http://ift.tt/1W7jBdy
via IFTTT

Spark: After CollectAsMap() or Collect(), every entry has same value

I need to read a text file and change this file to Map. When I make JavaPairRDD, it works well.
However, when I change JavaPairRDD to Map, every entry has same value, more specifically the last data in text file.

Input Text File:

A: ABCDE
B: BCDEF
C: CDEFG

When I read a text file, I used Hadoop custom input format.
Using this format, Key is offset and Value is custom class.

JavaPairRDD:

[0, (A,ABCDE)]
[1, (B,BCDEF)]
[2, (C,CDEFG)]

However, when I do new HashMap<>(JavaPairRDD.collectAsMap()):

[0, (C,CDEFG)]
[1, (C,CDEFG)]
[2, (C,CDEFG)]

I don't know why it happens..
Please help me....



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZuAmX
via IFTTT

web service java wsimport 403

i'm trying to publish a web service with java, once i created the service and compiled via Eclipse running on the browser at http://localhost:4444/WS/Rubica?wsdl i get the xml. But trying to import via command line with wsimport -s . http://localhost:4321/WS/Rubica?wsdl (yesterday with an example it wordked well)

C:\Documents and Settings\gcappella\workspace\codenameporc\src>wsimport -s . htt
p://localhost:4321/WS/Rubica?wsdl
analisi di WSDL in corso...


[ERROR] Server returned HTTP response code: 403 for URL: http://localhost:4321/W
S/Rubica?wsdl

Lettura del documento WSDL: http://localhost:4321/WS/Rubica?wsdl non riuscita pe
rché 1) non è stato possibile trovare il documento; 2) non è stato possibile leg
gere il documento; 3) l'elemento radice del documento non è <wsdl:definitions>.


[ERROR] failed.noservice=Impossibile trovare wsdl:service nei WSDL forniti:

 È necessario fornire almeno un WSDL con almeno una definizione di servizio.


        Analisi di WSDL non riuscita.

C:\Documents and Settings\gcappella\workspace\codenameporc\src>wsimport -s . htt
p://localhost:4444/WS/Rubica?wsdl
analisi di WSDL in corso...


[ERROR] Server returned HTTP response code: 403 for URL: http://localhost:4444/W
S/Rubica?wsdl

Lettura del documento WSDL: http://localhost:4444/WS/Rubica?wsdl non riuscita pe
rché 1) non è stato possibile trovare il documento; 2) non è stato possibile leg
gere il documento; 3) l'elemento radice del documento non è <wsdl:definitions>.


[ERROR] failed.noservice=Impossibile trovare wsdl:service nei WSDL forniti:

 È necessario fornire almeno un WSDL con almeno una definizione di servizio.


        Analisi di WSDL non riuscita.

C:\Documents and Settings\gcappella\workspace\codenameporc\src>

Thank you



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZuCeH
via IFTTT

Wrong Grocery Items when I add Items to the cart

This is for my class assignment. I keep getting the wrong groceryitem in the output. How should I go about getting the right item when the code is ran?

Here is the output i am currently getting:

Shopper Name: Gary


ice cream:5 units at $4.25 per unit = $21.25

ice cream:5 units at $4.25 per unit = $21.25

----> Subtotal = $42.5

----> 7% tax = $2.975

---->Total = $45.475

Shopper Name: Sally


ice cream:2 units at $4.25 per unit = $8.5

ice cream:2 units at $4.25 per unit = $8.5

----> Subtotal = $17.0

----> 7% tax = $1.1900000000000002

---->Total = $18.19


Cart Class:

public class Cart
{
public String Name;
public int ItemNum;
public double tax;




public Cart(String ShopperName){
    Name = ShopperName;
}
public String getShopperName(){
    return Name;
}
public int getItemNumber(){
    return ItemNum;
}
public void addItem1(GroceryItem GroceryItem, int NumberItem){
    GroceryItem = GroceryItem;
    ItemNum = NumberItem;
}
public void addItem2(GroceryItem GroceryItem, int NumberItem){
    GroceryItem = GroceryItem;
    ItemNum = NumberItem;
}
public double getItemTotal(){
    double item_total = (double) (GroceryItem.getCost()*getItemNumber());
    return item_total;
}
public double getSubtotal(){
    double subtotal = (double) (getItemTotal() + getItemTotal());
    return subtotal;
}
public double getTaxTotal(){
    double tax = .07;
    double taxtotal = (double) (getSubtotal()*tax);
    return taxtotal;
}
public double getTotal(){
    double Total = (double) (getTaxTotal()+getSubtotal());
    return Total;
}
public void printReceipt(){
    System.out.println("Shopper Name: " + getShopperName());
    System.out.println("----------------------");
    System.out.println(GroceryItem.getName()+":"+ getItemNumber()+ " units at $" + GroceryItem.getCost()+" per unit"+ " = $"+ getItemTotal());
    System.out.println(GroceryItem.getName()+":"+ getItemNumber()+ " units at $" + GroceryItem.getCost()+" per unit"+ " = $"+ getItemTotal());
    System.out.println("----> Subtotal = $" + getSubtotal());
    System.out.println("----> 7% tax = $" + getTaxTotal() );
    System.out.println("---->Total = $" + getTotal());
    System.out.println("");
    System.out.println("");
    System.out.println("");
}
}

Driver Class:

/**
 * Driver for Cart and GroceryItem.
 */
public class Driver
{
public static void main(String[] args)
{
    // create grocery items
    GroceryItem item1 = new GroceryItem("milk", 3.39);
    GroceryItem item2 = new GroceryItem("eggs", 1.75);
    GroceryItem item3 = new GroceryItem("ice cream", 4.25);

    // create new carts
    Cart shopper1 = new Cart("Gary");
    Cart shopper2 = new Cart("Sally");


    // add items to first cart 
    shopper1.addItem1(item2, 1);        //1 "eggs" is being added
    shopper1.addItem2(item1, 5);        //5 "milk" are being added

    // add items to second cart
    shopper2.addItem1(item3, 2);        //2 "ice cream" are being added
    shopper2.addItem2(item2, 2);        //2 "eggs" are being added

    // print cart's receipt
    shopper1.printReceipt();
    shopper2.printReceipt(); 

}
}



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuQcZa
via IFTTT

Turn on location services automatically in Android 3.1 and above

I know that from android 3.1 and above you can't turn on location services manually. But in Google maps it simply shows an dialog which prompts me to switch it on. This directly switches it on (In android 5.1 - Lollipop). So how does google do it? Is it some Google location services API I can use or should I direct the user to the location services settings screen? Thanks.



from Newest questions tagged java - Stack Overflow http://ift.tt/1im88Iq
via IFTTT

Introduction References Good Learning for Java ee7( video) [on hold]

Introduction References Good Learning for JavaEE 7(video+pdf)

I'm a beginner. I'm interested professional.

help me



from Newest questions tagged java - Stack Overflow http://ift.tt/1Qm8ppL
via IFTTT

Display TimePicker when textField is focused

I am just getting into android apps and now trying to work with an interface that allows the user to enter time into a text box. The time picker dialog will display when a text box is focused. But now when I click the text box, the date picker dialog does not display.

WorkDetails.java

public void onFocusChange(View v, boolean hasFocus) {
        EditText txtTime = (EditText) findViewById(R.id.editText6);
        txtTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                {
                    TimePick time = new TimePick(v);
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    time.show(ft, "TimePicker");

                }
            }
        });
    }

TimePick.java

@SuppressLint("ValidFragment")
public class TimePick extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    private TextView time;

    public TimePick(View view)
    {
        time=(EditText)view;
    }


    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        final Calendar c= Calendar.getInstance();
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minute=c.get(Calendar.MINUTE);

        //Toast.makeText(getActivity(),this,"Date: "+year+"-",+month+"-"+day,Toast.LENGTH_SHORT).show();
        return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view,int hourofDay, int minute)
    {

        time.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));



    }


}



from Newest questions tagged java - Stack Overflow http://ift.tt/1im877n
via IFTTT

Data read through socket on a remote server is empty

We have a client-server software made in java.

Client part sends a string:

dataOutputStream.writeUTF("User");

Server reads this string:

String login = dataInputStream.readUTF();
System.out.println("User accepted: " + login);

The server part is launched on amazon ec2. We have 2 offices and from 1 office everything works fine: server accepts the socket and read the data correctly, but from another office the server accepts the socket, however reads empty strings.

All the ports are opened for our IPs in the EC2 control panel.

I have installed WireShark and checked if correct data goes to the server and yes, it is correct.

Both offices are running the same client part. The only difference i know is that office 1 have Win 7 and 8 (works on both, tried different machines) and office 2 have Win 10 (doesn't work, tried different machines)

What could be the reason of such behavior? What we could check / try to resolve it?



from Newest questions tagged java - Stack Overflow http://ift.tt/1Qm8ppJ
via IFTTT

How to wait for intent service to finish - When the intent service is started from AsyncTask

Here is my scenario:

I have a login form which has a member key field, once the user enters this key I communicate with server to authenticate. There are two more fields namely key and type I add up these in a JSON object and send that across to the server.

Now due to a request I also have to send across the GCM token along with this login information in one call. On submit button click I start the following async task

My do in Background method looks like this:

  @Override
        protected String doInBackground(Void... params) {

            if (checkPlayServices()) {
                   Intent intent = new Intent(LoginActivity.this, GcmRegistrationIntentService.class);
                   startService(intent);
            }
/***// I want to wait here and fetch the GCM token value//***/

            try {
                JSONObject jObj;
                jObj = new JSONObject();

                jObj.put("aes_key", UtilityClass.getencryptkey());
                jObj.put("client_id", key);
                jObj.put("type", "Android");
                // jObj.put("device_token", ); <--- Need to wait for this value


                System.out.println(jObj);
                String authenticateResp = authenticate(jObj);
                System.out.println("Response is: " + authenticateResp);

                JSONObject jResp = new JSONObject(authenticateResp);
                String success = jResp.getString("success");


                if (success.equalsIgnoreCase("True")) {

                    sessionManager.createLoginSession(key);
                    return "granted";

                } else {
                    return jResp.getString("msg");

                }
            } catch (Exception e) {
                e.printStackTrace();
                return "Something went wrong, we are working to fix this, please try again after sometime";
            }
        }

        public String authenticate(JSONObject jObject) {
            return UniversalNetworkConnection.postJSONObject(getResources().getString(R.string.authentication_url), jObject);
        }

So first I start with starting the intent service - which has a registered local broadcast determining that the service has finished, I get the handler to this in onCreate of the particular activity.

 mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("Login Act", "GCM done");
            }
        };

I want to wait in the middle of the doInBackground till I receive the local broadcast from my intent service. So that I can add up the value to my JSON object. It is necessary for me to do this in an Async task because I have to update the UI with relevant messages of authentication success or false. Otherwise I could have migrated all my logic to the intent service - which would be a lot couples and which is not a good design.



from Newest questions tagged java - Stack Overflow http://ift.tt/1KvAqeu
via IFTTT

Send data over USB to Android app

I have a Java application sending bytes over USB to an Android Device, the issue is it doesn't appear to read any bytes on the Android side

Here's how the information is sent

private static void writeAndRead() throws LibUsbException {
    String question = "Hello Android I'll be your host today, how are you?";

    byte[] questionBuffer = question.getBytes();
    ByteBuffer questionData = BufferUtils.allocateByteBuffer(questionBuffer.length);
    IntBuffer transferred = IntBuffer.allocate(1);

    int result = 0;
    System.out.println("Sending question: " + question);
    System.out.println("Length of buffer: " + questionBuffer.length);
    result = LibUsb.bulkTransfer(handle, END_POINT_OUT_ACC, questionData, transferred, 5000);

    if(result < 0) {
        throw new LibUsbException("Bulk write error!", result);
    }
}

This method seems to complete without throwing an exception and it reports it's sent a buffer length of 51.

On the Android side I have the following

public class MainActivity extends AppCompatActivity  {

    private static final String TAG = "MainActivity";

    private UsbManager manager;
    private UsbAccessory accessory;
    private ParcelFileDescriptor accessoryFileDescriptor;
    private FileInputStream accessoryInput;
    private FileOutputStream accessoryOutput;

    private String question = "";
    private TextView questionTV;

    Runnable updateUI = new Runnable() {
        @Override
        public void run() {
            questionTV.append(question);
        }
    };

    Runnable readQuestionTask = new Runnable() {
        @Override
        public void run() {

            byte[] buffer = new byte[51];
            int ret;

            try {
                ret = accessoryInput.read(buffer);
                Log.d(TAG, "Read: " +ret);
                if (ret == 51) {
                    String msg = new String(buffer);
                    question += " Question: " + msg;
                } else {
                    question += " Read error";
                }
                Log.d(TAG, question);

            } catch (IOException e) {
                Log.e(TAG, "Read error ", e);
                question += " Read error";
            }

            questionTV.post(updateUI);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    };


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

        questionTV = (TextView) findViewById(R.id.hello_world);
        questionTV.setMovementMethod(new ScrollingMovementMethod());

        Intent intent = getIntent();
        manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
        if(accessory == null) {
            questionTV.append("Not started by the accessory itself"
                    + System.getProperty("line.separator"));
            return;
        }

        Log.d(TAG, accessory.toString());
        accessoryFileDescriptor = manager.openAccessory(accessory);
        Log.d(TAG, "File Descriptor " +accessoryFileDescriptor.toString());
        if (accessoryFileDescriptor != null) {
            FileDescriptor fd = accessoryFileDescriptor.getFileDescriptor();
            accessoryInput = new FileInputStream(fd);
            accessoryOutput = new FileOutputStream(fd);
        }
        new Thread(readQuestionTask).start();

    }


    @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, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

The following section of code

        try {
            ret = accessoryInput.read(buffer);
            Log.d(TAG, "Read: " +ret);
            if (ret == 51) {
                String msg = new String(buffer);
                question += " Question: " + msg;
            } else {
                question += " Read error";
            }
            Log.d(TAG, question);

        } catch (IOException e) {
            Log.e(TAG, "Read error ", e);
            question += " Read error";
        }

Reports in the console the contents of the question String as being

09-18 09:58:30.084  26198-26221/com.example.paulstatham.testusb D/MainActivity﹕ Read: 51
09-18 09:58:30.084  26198-26221/com.example.paulstatham.testusb D/MainActivity﹕ Question: ������������������������������������������������������������������������������������������������������

The activity itself just shows it as "Question: "

I'm assuming these strange characters are just the default byte value when byte array was first assigned byte[] buffer = new byte[51];

Unfortunately the nature of the app makes it very difficult to debug.

Any suggestions as to why ret = accessoryInput.read(buffer); doesn't appear to read anything?



from Newest questions tagged java - Stack Overflow http://ift.tt/1im8779
via IFTTT

Tool for mocking Java Sockets

I am looking for a tool which can be used to mock java sockets for testing my client applications when the server is unavailable. All the tools I found (e.g. WireMock) are used only for http / https interactions. Any tools for mocking TCP based interactions? The features that I am looking for are to record my interactions when my TCP server is available and to playback those interactions when the server is unavailable.



from Newest questions tagged java - Stack Overflow http://ift.tt/1F659yz
via IFTTT

Map two related enums?

I have two enums which are related:

Enum1:

public enum HttpStatusCode {

    ACCEPTED(202),
    OK(200),
    CREATED(201),
    BAD_REQUEST(400),
    NOT_FOUND(404),
    METHOD_NOT_ALLOWED(405),
    REQUEST_TIMEOUT (408),
    FORBIDDEN(403),
    CONFLICT(409),
    INTERNAL_SERVER_ERROR(500),
    NOT_IMPLEMENTED(501);

    private int httpStatusCode;

    private HttpStatusCode(int name) {
        this.httpStatusCode = name;
    }

    public int getHttpStatusCode() {
        return httpStatusCode;
    }
}

Enum2:

public enum ProtocolStatusCode {

    ACCEPTED(1000),
    OK(2000),
    CREATED(2001),
    BAD_REQUEST(4000),
    NOT_FOUND(4004),
    OPERATION_NOT_ALLOWED(4005),
    REQUEST_TIMEOUT(4008),
    SUBSCRIPTION_CREATOR_HAS_NO_PRIVILEGE(4101),

private int protocolStatusCode;

    private ProtocolStatusCode(int protocolStatusCode) {
        this.protocolStatusCode = protocolStatusCode;
    }

    public int getStatusCode() {
        return protocolStatusCode;
    }
}

These two enums values are related in a mapping, for example

Protocol status code 2000 (OK) has mapping with 200 (OK).

So in my code I will get the ProtocolStatusCode (2000) and corresponding to that I will need HttpStatusCode (200).

I was thinking of maintaing the ProtocolStatusCode enum as

ACCEPTED(1000, 202),
    OK(2000, 200)

So like this when I get 2000, I will reverse lookup the enum to get OK and then call a getter to get the second value (200) related to 2000.

Any better approach ??



from Newest questions tagged java - Stack Overflow http://ift.tt/1Qm8oly
via IFTTT

Check either mail.domain.com is POP or IMAP

How to check whether server uses POP or IMAP protocol? It is not mentioned in mail.domain.com, but it is accessible. I would like to check which protocol mailserver uses without downloading any data from it, when I know both username and password for that mail server.



from Newest questions tagged java - Stack Overflow http://ift.tt/1KvAo6p
via IFTTT

Using second level cache in a DB view based application

I'm trying to set up a second level cache for my application, which uses Hibernate 3.6.10. I have been reading Hibernate documentation and it seems quite straight forward to configure a second level cache over it, just adding a third party provider (in my case it's EhCache).

However, I'm currently using some DB views to avoid having to step through Hibernate entities looking for some properties. As an example, I've got my Person entity, which belongs to an Organization:

<class name="com.mycompany.model.Person" table="tperson">
    <id name="id" column="id" type="integer">
        <generator class="native" />
    </id>
    <property name="name" column="name" />
    <property name="surname1" column="surname1" />
    <property name="emailAddress" column="email" />
    <many-to-one name="organization" 
        class="com.mycompany.model.Organization">
        <column name="id_organization" />
    </many-to-one>
</class>

In order to avoid having to load the Organization property for each Person, specially while I'm loading lists of people, I use a DB view which makes the SQL join and loads the most common fields related to a person. That's how I map it:

<class name="com.mycompany.model.VPerson" table="vperson" mutable="false">
    <id name="id" column="id" type="integer" />
    <property name="name" column="name" />
    <property name="surname1" column="surname1" />
    <property name="emailAddress" column="email" />
    <property name="organizationName" column="organization_name" />
    <property name="clientName" column="client_name" />
</class>

So in most of the cases when I only want to display data I load the view entity, which also avoids having to load collections, and so on. However, when I want to edit a concrete person, I load the Person entity, because I need it to be mutable.

So, if I use a second level cache related to the view, how to notify Hibernate to invalidate it when I update a concrete Person? Cause a second level cache data is related to a concrete entity, AFAIK.



from Newest questions tagged java - Stack Overflow http://ift.tt/1Qm8mu2
via IFTTT

C++: Create an anonymous class for event handlers

Disclaimer: This description contains a lot of Qt specifics. They are not necessary to answer the question, I just wanted to give you the background.

I need to react on the focusInEvent of a QTextEdit. Unfortunately this is not available as a signal, that's why I need to subclass QTextEdit. Since this is the only change I need, I would like to use an anonymous subclass

Like this:

myTextEdit =new QTextEdit(){
            void focusInEvent(){
     //code here
     }
};

This is the code I would write in Java, it doesn't compile in c++. All following code is within the constructor of a custom QWidget. The QTextEdit is contained in this widget and should be initialized in its constructor.

Strangely this code compiles:

class MyTextEdit:protected QTextEdit{
    void focusInEvent();
};
auto myTextEdit=new MyTextEdit();

but is useless, since I can't assign an instance of myTextEdit* to a pointer to QTextEdit. Somehow polymorphism fails. This code doesn't compile:

class MyTextEdit:protected QTextEdit{
        void focusInEvent();
    };
QTextEdit* myTextEdit=new MyTextEdit();

The compiler error is:

/home/lars/ProgrammierPraktikum/moleculator/implementation/Moleculator/gui_elements/editor.cpp:40: error: 'QTextEdit' is an inaccessible base of 'Editor::Editor(std::shared_ptr)::MyTextEdit' QTextEdit* myTextEdit=new MyTextEdit();

Actual question:

How do I create an anonymous subclass that is compatible to pointers of its superclass ?



from Newest questions tagged java - Stack Overflow http://ift.tt/1F659i7
via IFTTT

Selenium tests running twice using Serenity

I'm running some tests using Maven clean/verify. My reporting is in Serenity. However my tests appear to run twice before the build is successful Serenity only shows one test (which is good) can someone check over the code and see what's causing it because I've tried a few things like taking out post-integration-tests etc yet it still runs the same test twice.

POM File

    `<project xmlns="http://ift.tt/IH78KX"` xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
  <modelVersion>4.0.0</modelVersion>
  <groupId>website.SurveyManager</groupId>
  <artifactId>GeneralTests</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>GeneralTests</name>
  <description>General Tests for Survey Manager</description>

  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>4.12</junit.version>

  </properties>


    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.47.1</version>
        </dependency>


<dependency>
    <groupId>net.serenity-bdd</groupId>
    <artifactId>serenity-core</artifactId>
    <version>1.1.12</version>
</dependency>


        <dependency>
            <groupId>net.serenity-bdd</groupId>     
            <artifactId>serenity-junit</artifactId>
            <version>1.1.12</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.18.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                <includes>
                    <include>**/*Test.java</include>
                    <include>**/*When*.java</include>
                </includes>
                </configuration>
            </plugin>

            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>       
                <artifactId>serenity-maven-plugin</artifactId>
                <version>1.1.12</version>

                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>             
                        <goals>
                            <goal>aggregate</goal>                       
                        </goals>
                    </execution>

                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
          <configuration>
                <fork>true</fork>
                <executable>C:\Program Files\Java\jdk1.8.0_60\bin\javac.exe</executable>  

          </configuration>
        </plugin>
        </plugins>
    </build>

</project>

Test FIle:

    package website.SurveyManager.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;

import website.SurveyManager.test.steps.SurveyManagerSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.Steps;

@RunWith (SerenityRunner.class)
public class SurveyManagerTest {

    @Managed
    WebDriver driver;

    @Steps
    SurveyManagerSteps steps;

    @Test
    public void testSurveyManagerVersion(){
        steps.gotoSurveyManager();
        steps.checkVersion();
        steps.VersionValidation("1.0.0.9");


    }

}

Steps FIle:

package website.SurveyManager.test.steps;

import org.openqa.selenium.By;

import net.thucydides.core.annotations.Step;
import net.thucydides.core.steps.ScenarioSteps;
import static org.junit.Assert.*;

public class SurveyManagerSteps extends ScenarioSteps {

    @Step
    public void gotoSurveyManager(){
        getDriver().get("http://ift.tt/1Qm8mdA");
    }

    @Step ()
    public void checkVersion(){
        getDriver().findElement(By.className("popupLink")).click();

    }

    @Step ()
    public void VersionValidation(String s){
        String actualValue = getDriver().findElement(By.xpath(".//*[@id='aboutSM']/div[1]/div[2]/table/tbody/tr[2]/td[2]")).getText();
        assertEquals(s, actualValue);

    }
}



from Newest questions tagged java - Stack Overflow http://ift.tt/1Qm8o57
via IFTTT

Can you force an SQL database to consider opoerations over a period of time to be in one transaction that you can roll back?

I am writing some integration tests for some software that relies heavily on information in its database. A majority of the logic behind our system runs via transactional SQL scripts and DDL/DML triggers against a large database.

When writing the unit tests we couldn't guarantee what order the unit tests would run in, so we had a baseline database state that each test would expect to be run from, with some data setup for each test which is a known constant. At the end of each test all of the changes it makes are rolled back. Because this was written in Java it was as simple as using the JUnit annotations:

@Test
@Transactional 
@Rollback(true)

Now that we are running integration tests we don't have access to the JUnit annotations. We are running the tests by starting up our software and then making API calls to it and verifying certain states in the database are what we expect them to be.

We still cannot guarantee what order the tests will be executed in, so we need each test to be run from a baseline state, and then have all of its changes reverted after we make our verifications. This we have constant knowledge about what state the database at the start for each test.

Is there some way to put the database we are testing in such a state that everything it considers from that point on as part of one big transaction that we can then roll back? I know we could just take a snapshot and restore from that, but depending on the size of the database and the amount of changes that each test may make it would be far far quicker to just be able to rollback.



from Newest questions tagged java - Stack Overflow http://ift.tt/1Qm8o55
via IFTTT

Java right shift integer by 32

I am trying to right shift an integer by 32 but I the result is the same number. (e.g. 5 >> 32 is 5.)

If I try to do same operation on Byte and Short it works. For example, "(byte)5 >> 8" is 0.

What is wrong with Integer?



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZrNdJ
via IFTTT

I can not include javaScript and css to my JSP page

I can not include javaScript and css fiels to my JSP page. I tried this and this but not helped.

My JSP:

  <html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <script src="../resources/js/my.js"></script>
        <link rel="stylesheet" href="../resources/css/menu.css" />
...

and mapping:

<beans xmlns="http://ift.tt/GArMu6"
       xmlns:xsi="http://ift.tt/ra1lAU"
       xmlns:context="http://ift.tt/GArMu7"
       xmlns:mvc="http://ift.tt/1bHqwjR"
       xsi:schemaLocation="http://ift.tt/GArMu6
        http://ift.tt/1jdM0fG
        http://ift.tt/GArMu7 http://ift.tt/1jdLYo7 http://ift.tt/1bHqwjR http://ift.tt/1fmimld">

    <context:component-scan base-package="com.springapp.mvc"/>
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="resources" cache-period="31556926"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

and ctructure:

WEB-INF
 -pages
   -my.jsp
 -resources
   -js
     -my.js
   -css
     -menu.css
 -mvc-dispatcher-servlet.xml
 -web.xml



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMoY1
via IFTTT

String lexer with ANTLR4

I define some String tokens like this in ANTLR4, with some exceptions surely properly handled in Java:

STRINGLIT: '"'('\\'[bfrnt\\"]|~[\n"EOF])*'"';

ILLEGAL_ESC: '"'(('\\'[bfrnt\\"]|~[\n\\"EOF]))*('\\'(~[bfrnt\\"]|EOF))
    {if (true) throw new bkool.parser.IllegalEscape(getText());};

UNCLOSED_STRING: '"'('\\'[bfrnt\\"]|[\n\\"EOF])*
    {if (true) throw new bkool.parser.UncloseString(getText());};

Then I tested with some cases, with:

"This is a string"
"String with legal escape \\"
"Legal \\n"
"Illegal \"
"Illegal \n"

No exceptions are thrown. Then with some other cases:

"This is a string
"String with legal escape \\"
"Legal \\n"
"Illegal \"
"Illegal \n"

Then it ends up with:

Unclosed string: "

The exceptions are handled by printing the respective improper string with the name of exception

I have been struggling with them for a day and now I'm stuck with it. What is still not okay with my ANTLR definitions?



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMyP4
via IFTTT

NullPointerException while adding "addinline" function in mimemessage

500 error - nested exception is org.springframework.mail.MailPreparationException: Could not prepare mail; nested exception is java.lang.NullPointerException

I am trying to generate emails using smtp server.I am able to generate emails without adding inlne image whereas when I add "addinline" function I am getting nullpointer error in the output screen and not able to generate emails,images are not been fetched from the system.I am getting same error when I am trying to send attachments.Thnaks in advance.

in dao implementation

@Autowired
private JavaMailSender mailSender;


mailSender.send(new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException {
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    message.setFrom(from);
    message.setTo(recipientAddress);
    message.setSubject("Subject");
        message.setText("<html><body><img src=\"cid:identifier1234\"/></body></html>", true);
        FileSystemResource res = new FileSystemResource(new File("D:\images\photo.svg.png"));
            message.addInline("identifier1234", res);
     }
    });

Bean class in xml

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.com" />
    <property name="port" value="25" />

     <property name="username" value="Sender.email@abc.com" /> 
    <property name="password" value="password@123" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

error in output window

SEVERE: Servlet.service() for servlet [welcome] in context with path [/registrationForm] threw exception [Request processing failed; nested exception is org.springframework.mail.MailPreparationException: Could not prepare mail; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:226)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:299)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1375)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1354)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1354)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:411)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:355)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:344)
at com.registrationForm.dao.DocumentDaoImpl.generateEmail(DocumentDaoImpl.java:182)
at com.registrationForm.service.DocumentServiceImpl.generateEmail(DocumentServiceImpl.java:45)
at com.registrationForm.controller.DocumentController.saveForm(DocumentController.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMyOW
via IFTTT

MQ Queue transaction not rolled back in a 2 phase transaction

I have an EJB timer (EJB 2.1) which has bean managed transaction.

The timer code calls a business method which deals with 2 resources in a single transaction. One is database and other one is MQ queue server.

Application server used is Websphere Application Server 7 (WAS). In order to ensure consistency across 2 resources (database and queue manager), we have enabled the option to support 2 phase commit in WAS. This is to ensure that in case of any exception during database operation, message posted in queue is rolled back along with database rollback and vice versa.

Below is the flow explained:

When timeout occurs in Timer code, startProcess() in DirectProcessor is called which is our business method. This method has a try block within which there is a method call to createPostXMLMessage() in the same class. This in turn has a call to another method postMessage() in class PostMsg.

The issue is when we encounter any database exception in createPostXMLMessage() method, the message posted earlier does not roll back although database part is successfully rolled back. Please help.

In ejb-jar.xml

<session id="Transmit">
    <ejb-name>Transmit</ejb-name>
    <home>com.TransmitHome</home>
    <remote>com.Transmit</remote>
    <ejb-class>com.TransmitBean</ejb-class>
    <session-type>Stateless</session-type>
    <transaction-type>Bean</transaction-type>       
</session>

public class TransmitBean implements javax.ejb.SessionBean, javax.ejb.TimedObject {
    public void ejbTimeout(Timer arg0) {
         ....

         new DIRECTProcessor().startProcess(mySessionCtx);

    }
}

public class DIRECTProcessor {

    public String startProcess(javax.ejb.SessionContext mySessionCtx) {

        ....

        UserTransaction ut= null;
        ut = mySessionCtx.getUserTransaction();

        try {
            ut.begin();
            createPostXMLMessage(interfaceObj, btch_id, dpId, errInd);
            ut.commit();
        } 

        catch (Exception e) {                      
             ut.rollback();
             ut=null;        
        }
    }

    public void createPostXMLMessage(ArrayList<InstrInterface> arr_instrObj, String batchId, String dpId,int errInd) throws Exception {
      ...

      PostMsg pm = new PostMsg();
      try {
            pm.postMessage( q_name, final_msg.toString());

           // database update operations using jdbc

      }

      catch (Exception e) {
        throw e;      
      }

    }
}

public class PostMsg {

    public String postMessage(String qName, String message) throws Exception {
        QueueConnectionFactory qcf = null;
        Queue que = null;
        QueueSession qSess = null;
        QueueConnection qConn = null;
        QueueSender qSender = null;
        que = ServiceLocator.getInstance().getQ(qName);

        try {
            qConn = (QueueConnection) qcf.createQueueConnection(
                    Constants.QCONN_USER, Constants.QCONN_PSWD);
            qSess = qConn.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
            qSender = qSess.createSender(que);

            TextMessage txt = qSess.createTextMessage();
            txt.setJMSDestination(que);
            txt.setText(message);
            qSender.send(txt);

        } catch (Exception e) {

            retval = Constants.ERROR;
            e.printStackTrace();
            throw e;

        } finally {

            closeQSender(qSender);
            closeQSession(qSess);
            closeQConn(qConn);
        }

        return retval;

    }

}



from Newest questions tagged java - Stack Overflow http://ift.tt/1UZrKys
via IFTTT

Transaction handling with a container managed EntityManager

A collection needs to be fetched lazily. If I then try to access its components, I get the following Exception :

failed to lazily initialize a collection of role:
 mapp3.model.ProductDefinition, could not initialize proxy - no Session

So I retrieved the session from the entityManager this way:

Session session = entityManager.unwrap(Session.class);

but this causes the following exception :

Error executing command: Transaction management is not available for container managed EntityManagers.

I am using Hibernate inside a Karaf container. How else could I proceed to either be able to browse the lazily fetched collection, either to start a Session with a container managed EntityMananger ?



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMyyE
via IFTTT

Is there a standard way in Spring to pass a body with a DELETE request to a REST endpoint?

I am implementing a Spring client for an existing REST API and I need to invoke a DELETE while, at the same time, passing an access token in the request body, like this:

{ 
    "access_token": "..."
}

The problem is that, using the method that works for POST, the transmitted body is empty (I have intercepted the request body and made sure) and I cannot be authorised without this access token. This is what I am doing:

 RestTemplate restTemplate = new RestTemplate();
 UserRequest ur = new UserRequest(access_token);
 HttpEntity<UserRequest> entity = new HttpEntity<>(ur);                                               
 restTemplate.delete(url, entity);

I have no control over the API itself, so I don't have the option of passing the token as url parameter.

Is there a way to do this in Spring, or do I have to build my own HttpUrlConnection like described for instance in this SO answer?



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMyyx
via IFTTT

Best approach to compare rows of table(Java/Oracle)

I have a HISTORY table with million rows and having 300 columns. For one unique ID there could be max of 5000 rows which I want to compare like

Row1 with Row2, Row2 with Row3, Row3 with Row4, . . . Row4999 with Row5000

and find out the data differences in the columns and the output should be something like:

What are the implications of processing the rows on Java side? or is it better to process on the DB side and push the output to Java?



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMyyr
via IFTTT

Java addition with power of a number program wrong result

In my program Logic is like:--

Input      Addition with      Output(result)
2            3                   5
3            3+4                10
4            3+4+4              15
5            3+4+4+4            20
6            3+4+4+4+4          25

So, I have made:--

import java.util.Scanner;

public class Addition {

           public static void main( String[] args) {
              @SuppressWarnings("resource")

            Scanner s = new Scanner(System.in);

              int result=0;

              System.out.print("Enter a number: ");

              int inputNumber = s.nextInt();

              if(inputNumber==2){
                  result = inputNumber+3; 

              }

              else{
                  Addition c=new Addition();


                      int j = inputNumber-2;

                      int power=c.pow(4,j);



                      result = inputNumber+3+power;


              }
              System.out.print(result);  

           }
          int pow(int c, int d)
             {       
                      int n=1;
                      for(int i=0;i<d;i++)
                      {
                               n=c*n;
                      }

                    return n;
             } 
}

In this program I am getting result:--

 Input               Output(result)
    2                        5
    3                       10
    4                       23
    5                       72

why? What Am I doing wrong??



from Newest questions tagged java - Stack Overflow http://ift.tt/1MuMvD0
via IFTTT

Get the class object of an instance variable in java [on hold]

I have a class Route which have a instance variable of type stop(different class type). Now I have a function with return type stop. How can I get the route object associated with this stop object



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S9bX
via IFTTT

will redirect to play store when i another project click back button in jsp page

i have two java web projects , one project have index.jsp with proceed button and another project have index.jsp with back button .

when click proceed button go to another project index.jsp page. this page have back button. user click on the back button it go to previous page to redirect to play store?



from Newest questions tagged java - Stack Overflow http://ift.tt/1KV6b2G
via IFTTT

groovy.lang.MissingPropertyException: in groovy

Am new to groovy code. I have a map like this

response = {"data":{"--class":"java.util.HashMap","Enabled":false,"Adult":"[recursive reference removed]","TVMA":"[recursive reference removed]","Locks":[false,false,false,false,false,false],"PINEnabled":false,"AdvisoryLocks":[false,false,false,false,false,false,false,false,false,false,false,false],"safeSearch":"[recursive reference removed]","RatingLocks":[false,false,false,false,false,false]},"success":true}

Using groovy code i want to check the presents of following keys

Enabled, Adult, TVMA, Locks, PINEnabled, AdvisoryLocks, safeSearch, RatingLocks,

I using following code

 for ( data in response.data ) {
            println("-----------------------------------------")       

            assertNotNull(data.Enabled)
            assertNotNull(data.Adult)
            ;;;;;;
            .......
            }
        Am getting groovy.lang.MissingPropertyException: No such property: Enabled

How can i check the presence of above keys from response map using groovy



from Newest questions tagged java - Stack Overflow http://ift.tt/1KV6b2A
via IFTTT

How to solve this infinite recursion (StackoverflowError) when I use writeValueAsString() method of Jackson ObjectMapper() class?

I am absolutly new in JSON and how Java handle convert into this format.

So I have the following problem into a Spring MVC application I have this controller method that correctly handle AJAX request toward the /provinceDiUnaRegione.json resource:

@RequestMapping(value = "/provinceDiUnaRegione.json")
@ResponseBody
public String getProvince(String codiceRegione) {

    System.out.println("INTO getProvince()");

    List<Twb1013Provincia> provinceDiUnaRegioneList =  geograficaService.getListaProvinceDiUnaRegione(codiceRegione);

    try {
        String listaProvince = new ObjectMapper().writeValueAsString(provinceDiUnaRegioneList);
        return listaProvince;
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    return "";

}

As you can see this method retrieve a list of Twb1013Provincia objects and then use this line to convert the retrieved list into a JSON String (correct me if it is wrong)

String listaProvince = new ObjectMapper().writeValueAsString(provinceDiUnaRegioneList);

The problem is that when this line is performed I obtain this exception:

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafiche.Twb1012Regione["tpg1029Provnuoists"]->org.hibernate.collection.internal.PersistentBag[0]->it.myCompany.myProject.anagrafiche.Tpg1029Provnuoist["twb1012Regione"]->it.myCompany.myProject.anagrafic...

So doing some analysis it seems to me that the problem is that I am trying to convert a list of Twb1013Provincia objects that are something like this:

@Entity
@Table(name="anagrafiche.TWB1013_PROVINCIA")
@NamedQuery(name="Twb1013Provincia.findAll", query="SELECT t FROM Twb1013Provincia t")
public class Twb1013Provincia implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="COD_PRV")
    private String codPrv;

    //bi-directional many-to-one association to Twb1012Regione
    @ManyToOne
    @JoinColumn(name="COD_REG")
    private Twb1012Regione twb1012Regione;

    .................................................
    .................................................
    OTHER FIELDS
    .................................................
    .................................................
}

The problems seems that, as you can see, this class contain a Twb1012Regione twb1012Regione; field and that this Twb1012Regione class contain in turn a reference to the original Twb1013Provincia (the object to convert), something like this:

@Entity
@Table(name="anagrafiche.TWB1012_REGIONE")
@NamedQuery(name="Twb1012Regione.findAll", query="SELECT t FROM Twb1012Regione t")
public class Twb1012Regione implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="COD_REG")
    private String codReg;

    //bi-directional many-to-one association to Twb1013Provincia
    @OneToMany(mappedBy="twb1012Regione")
    private List<Twb1013Provincia> twb1013Provincias;

    .................................................
    .................................................
    OTHER FIELDS
    .................................................
    .................................................
}

So the problems seems to be that when I try to convert a Twb1013Provincia object it find inside it a Twb1012Regione field that itself contain an Twb1013Provincia...so enter in an infinite loop and the conversion is impossible.

So how can I solve this issue? Exist a way to exclude the Twb1012Regione field from the Twb1013Provincia object conversion?

Or better can I specify the list of the Twb1013Provincia class fields that have to be converted in JSON format? (I need to convert only 2 fields of this class)

Tnx



from Newest questions tagged java - Stack Overflow http://ift.tt/1KV6cUg
via IFTTT

Can't open ressource file in Arquillian test

I want to read a test CSV file (xxx.csv) in my integration test using arquillian. I am packing my archive as follows:

@Deployment
public static WebArchive createDeployment() {
    WebArchive archive = ShrinkWrap.create(WebArchive.class);
    archive.addClasses(FileReader.class, FileWriteService.class, MockDataFactory.class, CSVFileReader.class, ExcelFileReader.class);
    archive.addAsResource("config.properties").addAsResource("xxx.csv");
    System.out.println(archive.toString(true));
    return archive;
}

Where the print shows me:

> 7fadc596-9353-4cac-aacc-cf5ec5d94c16.war: /WEB-INF/
> /WEB-INF/classes/ /WEB-INF/classes/config.properties
> /WEB-INF/classes/com/ /WEB-INF/classes/com/goodgamestudios/
> /WEB-INF/classes/com/goodgamestudios/icosphere/
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/CSVFileReader.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/ExcelFileReader$SheetHandler.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/ExcelFileReader.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/ExcelFileReader$xssfDataType.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/ExcelFileReader$1.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileReader/FileReader.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileWriter/
> /WEB-INF/classes/com/goodgamestudios/icosphere/service/fileWriter/FileWriteService.class
> /WEB-INF/classes/com/goodgamestudios/icosphere/datamodel/
> /WEB-INF/classes/com/goodgamestudios/icosphere/datamodel/MockData/
> /WEB-INF/classes/com/goodgamestudios/icosphere/datamodel/MockData/MockDataFactory.class
> /WEB-INF/classes/xxx.csv

As you can see, the file is clearly in the archive (last row).

Now I am trying to open it. I have tried:

private File getFile(String filename) throws IOException {
    return convertInputStreamToFileHelper(getClass().getResourceAsStream(filename), filename);
}


new File(this.getClass().getResource("/xxx.csv").getFile()


new File("/xxx.csv")


new File("xxx.csv")


but none would work.



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S5Jj
via IFTTT

How can implement Triggers in Hibernate?

Two Tables Country And State Both have name and id status columns when insert state table update country column status 'YES' On Hibernate

Like SQL Triggers on Hibernate

How can implement Triggers in Hibernate ????



from Newest questions tagged java - Stack Overflow http://ift.tt/1KV6cDQ
via IFTTT

Sustained connection for game development

I would like to develop a simple game in which two players will be interacting. Say like tennis. We are thinking of maintaining our game state on centralized server and then players will send their data to server and whenever one person sends us the data, server will push that data to both the persons.

Problem: We need to maintain a sustained connection between user and server as in table tennis both persons will be exchanging their states on a high speed.

My way of thinking: I am currently thinking to use socket connections but I feel that socket connections will take lot more effort. Anything else I can use for these type of problem?

I will be developing on c# game engine my client side code, can I use java or any other language for developing server side code.



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S5sJ
via IFTTT

How to know whether command executed using Runtime.exec() is giving some output or is only waiting and not giving any output?

I am trying to run an accurev command using Java Runtime exec (as described in code below). Since I have a network problem so when the login command is executed the command keeps on waiting for the response and doesn't time out. So how should I be able handle this error.

private static void accurevLogin() throws IOException {
    Runtime runTime = Runtime.getRuntime();
    String userName = prop.getProperty("UserName");
    String password = prop.getProperty("Password");
    String command = (new StringBuilder("accurev login ")).append(userName).append(" ").append(password).toString();
    Process ps = null;
    try {
        ps = runTime.exec(command);
    } catch (IOException e) {
        System.out.println("Command Execution Error!");
    }
    /* Error handling Code */
    System.out.println("ACCUREV LOGGED IN");
}

When I use

BufferedReader input = new BufferedReader(new InputStreamReader(ps.getInputStream()));

input.readline in the loop will keep on running and I am not able to check the output.



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S2No
via IFTTT

How to add WebServices Server to SpringMVC?

I have a Spring MVC WebApp and it is working perfectly, now i want it to have a soap WebService server.

I tried adding a new class of type Web Service (runtime apache axis2). this is the content:

public class Emails {

    public String Hello (String name){

        return "Hello Email: " + name;

    }

}

It successfully generates the wsdl! i can access it and all but when i try to get a response out of it, it gives me the following error: HTTP Status 405 - Request method 'POST' not supported

I am suposing this is a problem on my configurations maybe. When i create a project from scratch and its a dynamic web project instead of a spring mvc it works fine.

Any advice?



from Newest questions tagged java - Stack Overflow http://ift.tt/1KV6cDE
via IFTTT

Java - complex data structure with multiple values and acess data structure with filers

I have complex data Object like Stock and it has attributes like region, name, price, volume, high, low... and i need to maintain this millions of object in data structure such that input will contain query like All stock in this X region and price between A-B and Volumne between P-Q... So how can i maintain such data ? to get faster response



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S5c3
via IFTTT

Mockito with Spring

For one of my use case, I have to mock an autowired dependency only a single test case, while I want other tests to use the original one.

<Code>
public class A {

    @Autowired
    private B b;
}

Class TestA {

    @Autowired
    private A a;

    void test1() {
    //using B without mock.
    }

    void test2() {
    // mock B b in A here
    }
}
</Code>

I want to mock the private class variable 'b' here in some particular tests. I know if I have to mock B in entire class I can use @Mock, @InjectMocks and MockitoAnnotations.initMocks(), but that will mock 'b' for the other test cases as well where I want original behavior.



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S4VH
via IFTTT

MainActivity.this like thing for Fragments

I want mAdapter = new MembersAdapter(_______, membersList); to use in fragment class named HomeFragment If this was to be used for Activity then it might be written as mAdapter = new MembersAdapter(MainActivity.this, membersList);

But now, I want this line of code to be executed in Fragment and and and for the Fragment so what should I pass. Something like mAdapter = new MembersAdapter(HomeFragment.this, membersList);



from Newest questions tagged java - Stack Overflow http://ift.tt/1F62SDv
via IFTTT

OkHttp RequestBody returning wrong content length

I have this app where I use OkHttp RequestBody to perform network requests with body, but the content length being returned is plain wrong. As an example of the problem, there is this case:

    public static RequestBody createNewTokenBody(final String redirectUri, final String
        code,
                                             final String clientId, final String
                                                     clientSecret) {

    final byte[] requestBody = "bunchofcharsthatshouldgointhebody".getBytes(Charset.forName("UTF-8"));

    final RequestBody ret = RequestBody.create(MediaType.parse(MEDIA_TYPE), requestBody, 0,
            requestBody.length);

    try {
        Log.d("debug", "Request body length to return: " + ret.contentLength());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ret;
}

So this will print "Request body length to return : 33". However, when the request this body is attached to is captured by the interceptor below:

    client.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(final Chain chain) throws IOException {
            final Request request = chain.request();

            final RequestBody body = request.body();
            if (body != null) {
                Log.d("debug", "REQUEST BODY LENGTH: " + body.contentLength());
            }

            return chain.proceed(request);
        }
    });

"REQUEST BODY LENGTH: 2" is logged instead, regardless of the content that I specified. Needless to mention that this completely screws up the request as the body is not fully read. Does anybody know the reason behind this behavior?



from Newest questions tagged java - Stack Overflow http://ift.tt/1FRgQUD
via IFTTT

AWS S3 Java SDK download speed is slower than REST

I am working on an app in which I need fast file transfers from S3 storage. I have performed several tests and I have found out that downloading a file using AWS S3 Java SDK is 25% slower than downloading a file using basic REST request and reading the data from HTTP stream. I have expected the opposite would be true, yet I can't find a reason for this.

My REST download looks something like this. I download public files from url like http://ift.tt/1P6S2gr

    InputStream inputStream = httpsURLConnection.getInputStream();
    int length = Integer.parseInt(httpsURLConnection.getHeaderField("Content-Length"));
    byte[] data = new byte[length];
    for (int i = 0; i < length; i++) {
        data[i] = (byte)inputStream.read();
    }

My AWS S3 SDK download looks something like this

        S3Object s3Object = amazonS3Client.getObject(awsBucket, objectName);
        long length = s3Object.getObjectMetadata().getContentLength();
        byte[] data = new byte[(int)length];
        S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent();
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) s3ObjectInputStream.read();
        }

Does anyone have / had the same issue? For any ideas which may be the reason for this I am grateful. I saw some posts which mentioned the opposite, that the upload is slow on AWS forums yet none came to any conclusion.



from Newest questions tagged java - Stack Overflow http://ift.tt/1KV6avG
via IFTTT

Rename Realm table

I have a Gift table in my realm scheme. Now I need to rename Gift.class to UserBonus.class and add some new params(not a prob). What is the correct way to do this?

I know that realm.getTable() can return me the table, the problem is that old Giftexists in the schema but on fact I dont have Gift.class(now it is UserBonus and getTable() will return me new created table) so I cant get old gift table values and move them to new Bonus table.

Thanks for any advice,
Yakiv



from Newest questions tagged java - Stack Overflow http://ift.tt/1F62SDm
via IFTTT

JTable Checkbox listener doesnt work properly

I have a JTable which have Checkboxes. This table implements the listener tableChanged, which fires an event selectionChanged with true or false if the Checkbox is selected or not.

In the selectionChanged, there is a counter to know how many checkboxes are checked. But this doesnt work properly. If i click anywhere on the checkbox it also increases the counter.

This is how it looks like:

@Override
    public void tableChanged(TableModelEvent P_evt)
    {
    .....
    listener.selectionChanged(F_newValue);

@Override
    public void selectionChanged(boolean P_selected)
    {
        if (P_selected)
        {
            nextButton.setEnabled(true);
            selectedBundles++;
            System.out.println("Selected Bundles: " + selectedBundles);
        }
        if(!P_selected)
        {
            nextButton.setEnabled(false);
            selectedBundles--;
            System.out.println("Selected Bundles: " + selectedBundles);
        }
        if (selectedBundles > 0)
        {
            nextButton.setEnabled(true);
        }
        else
        {
            nextButton.setEnabled(false);
        }



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S4F0
via IFTTT

pom.xml works, but proxy setting not working?

I have a pom.xml that works on AWS, but behind the proxy at work it does not. I have tried everything in this post Maven proxy settings not working but nothing worked.

Here is the error using mvn help:effective-settings

...
[WARNING] Failed to retrieve plugin descriptor for org.eclipse.m2e:lifecycle-mapping:1.0.0: Plugin org.eclipse.m2e:lifecycle-mapping:1.0.0 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.eclipse.m2e:lifecycle-mapping:jar:1.0.0
Downloading:http://ift.tt/1P6S1Jx
Downloading:http://ift.tt/1ELXXEX
[WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xml from/to central (http://ift.tt/1pDkooA): repo.maven.apache.org
[WARNING] Could not transfer metadata http://ift.tt/1P6S4ot central (http://ift.tt/1pDkooA): repo.maven.apache.org
[WARNING] Failure to transfer org.apache.maven.plugins/maven-metadata.xmlfrom http://ift.tt/1pDkooA was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer metadata org.apache.maven.plugins/maven-metadata.xml from/to central (http://ift.tt/1pDkooA): repo.maven.apache.org
[WARNING] Failure to transfer http://ift.tt/19RVGuV fromhttps://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updatesare forced. Original error: Could not transfer metadata http://ift.tt/19RVGuV from/to central (http://ift.tt/1pDkooA): repo.maven.apache.org
...
[ERROR] No plugin found for prefix 'help' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\David.Wynter\.m2\repository),central(http://ift.tt/1pDkooA)] -> [Help 1]

Here is the relevant part of my settings.xml

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>10.***.0.60</host>
      <port>8080</port>
      <username>dmgp\david.blow</username>
      <password>*******</password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>
</proxies>

The settings for the host etc. come from a pac file that works for the browsers. Any ideas?

I also tried adding this

    <extensions>
        <extension>
            <!-- this extension is required by wagon in order to pass the proxy -->
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-http-lightweight</artifactId>
            <version>2.2</version>
        </extension>
    </extensions>

To my pom.xml and added that jar to my maven install lib directory, but got this

[ERROR]     Unresolveable build extension: Plugin org.apache.maven.wagon:wagon-http-lightweight:2.2 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.wagon:wagon-http-lightweight:jar:2.2: Could not transfer artifact org.apache.maven.wagon:wagon-http-lightweight:pom:2.2 from/to central (http://ift.tt/1pDkooA): repo.maven.apache.org: Unknown host repo.maven.apache.org -> [Help 2]



from Newest questions tagged java - Stack Overflow http://ift.tt/1P6S4oA
via IFTTT