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