Categories
discuss

Upload maven pom.xml to Git repository?

I want to publish my Java project on GitHub. I’m not sure if I should upload my pom.xml from Maven in my repository.

I’m using Eclipse without eGit.

On the one hand:

  • the pom.xml is necessary to know which libraries I used.

On the other hand:

  • it’s a configuration file which maybe shouldn’t made public.
  • it destroys the look of a clean repo, because it’s outside of the normal source files.

What should I do best?

Answer

  • it’s a configuration file which maybe shouldn’t made public.

This is wrong. The POM is indeed a configuration file but it is intended for this file to be public. Actually, quoting Maven guide to uploading artifacts to the Central Repository:

Some folks have asked why do we require all this information in the POM for deployed artifacts so here’s a small explanation. The POM being deployed with the artifact is part of the process to make transitive dependencies a reality in Maven. The logic for getting transitive dependencies working is really not that hard, the problem is getting the data. The other applications that are made possible by having all the POMs available for artifacts are vast, so by placing them into the repository as part of the process we open up the doors to new ideas that involve unified access to project POMs.

As you see, this file is actually required so that the artifact can be uploaded to Maven Central.

What should not be public is your settings, i.e. the settings.xml file. It is in this file that you should store any sensitive information, like passwords. Again, quoting the Settings Reference (emphasis mine):

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information.

If you currently store any sensitive information in your POM, you should consider refactoring it to extract this info and put it inside your settings instead.


  • it destroys the look of a clean repo, because it’s outside of the normal source files.

It is a source file in the sense that Maven only requirement is exactly the presence of this file. It describes how to build your application and declares all of its dependencies. To say it differently: this file is a Maven source file, and as such, should be commited along with the project main source files. Without it, no-one can build your application and no-one can also package it.

Categories
discuss

Retrofit 2 appending post to requestbody in intercept

I have this:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.httpUrl().newBuilder()
                     .addQueryParameter("platform", "android")
                     .addQueryParameter("app_version", com.package.BuildConfig.VERSION_NAME)
                     .build();
        Request newRequest = chain.request().newBuilder().url(url).build();
        return chain.proceed(newRequest);
    }
});

but would also like to append an additional post key-value to the request body containing the userkey. This would look something like

    RequestBody newBody = RequestBody.create(request.body().contentType(),request.body().content+ request.addPost("sUserKey","3254345kdskf");
...
...
 Request newRequest = chain.request()
.newBuilder()
.url(url)
.post(newBody)
.build();

Answer

You can do it without creating additional class.

client.interceptors().add(new Interceptor() {
    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String parameter = "&" + name + "=" + value;
        Request newRequest = interceptRequest(request, parameter)
        return chain.proceed(newRequest);
    }
});

This is simple method that create new request.

 public static Request interceptRequest(@NotNull Request request, @NotNull String parameter)
            throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Sink sink = Okio.sink(baos);
        BufferedSink bufferedSink = Okio.buffer(sink);

        /**
         * Write old params
         * */
        request.body().writeTo(bufferedSink);

        /**
         * write to buffer additional params
         * */
        bufferedSink.writeString(parameter, Charset.defaultCharset());

        RequestBody newRequestBody = RequestBody.create(
                request.body().contentType(),
                bufferedSink.buffer().readUtf8()
        );

        return request.newBuilder().post(newRequestBody).build();
    }

Also you can get it from Gist

Categories
discuss

Where is the Auth class — Google Play Services 8.3.0

I’m going through the new documentation for implementing Google Play Services 8.3.0 on Android and it seems that I need to import com.google.android.gms.auth.api.Auth; but don’t know which dependency to add to my build.gradle file. Any ideas?

Answer

You’ll want to add

com.google.android.gms:play-services-auth:8.3.0

to your build.gradle as per the setup guide

Categories
discuss

How to send a POST request using volley with string body?

I’m developing an Android app that communicate with a RESTful web service I wrote. Using Volley for GET methods is awesome and easy, but I can’t put my finger on the POST methods.

I want to send a POST request with a String in the body of the request, and retrieve the raw response of the web service (like 200 ok, 500 server error).

All I could find is the StringRequest which doesn’t allow to send with data (body), and also it bounds me to receive a parsed String response. I also came across JsonObjectRequest which accepts data (body) but retrieve a parsed JSONObject response.

I decided to write my own implementation, but I cannot find a way to receive the raw response from the web service. How can I do it?

Answer

You can refer to the following code (of course you can customize to get more details of the network response):

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("Title", "Android Volley Demo");
    jsonBody.put("Author", "BNK");
    final String requestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
                // can get more details such as response.headers
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}
Categories
discuss

Block/Disable Statusbar in android Tablet/Mobile

I have seen Kioware and SureLock applications. They simply block every control in tablet. I’m aware about overriding back button and handling the home and recent task options as well. But I’m not sure how they managed to control the setting option on system bar. Settings appear for a fraction of seconds and then disappear. In the same way Statusbar of mobile which appear on swipe down need to be block.

If anyone have idea about it please share it. Any guidance/help is appreciated.

See the attached image selected portion which I need to block/disable

Answer

Finally I found the solution of the above problem. onWindowFocus change I just closed the system generated Dialogs and my problem was solved. below is the sample code.

@Override
     public void onWindowFocusChanged(boolean hasFocus) {
         super.onWindowFocusChanged(hasFocus);

      if(!hasFocus)
      {// Close every kind of system dialog 
          Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 
          sendBroadcast(closeDialog); 

      }

     }

Update:

In Mobile to block the status bar which appear on swipe down on the screen use below way.

private Handler collapseNotificationHandler;
            @Override
            public void onWindowFocusChanged(boolean hasFocus) {
                boolean currentFocus = hasFocus;
                if (!hasFocus) {
                    collapseNow(true,currentFocus);

                }

            }


    public void collapseNow(final boolean shouldCollapse, final boolean currentFocus ) {

                // Initialize 'collapseNotificationHandler'
                if (collapseNotificationHandler == null) {
                    collapseNotificationHandler = new Handler();
                }

                // If window focus has been lost && activity is not in a paused state
                // Its a valid check because showing of notification panel
                // steals the focus from current activity's window, but does not 
                // 'pause' the activity
                if (!currentFocus && !isPaused) {

                    // Post a Runnable with some delay - currently set to 50 ms
                    collapseNotificationHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {

                            // Use reflection to trigger a method from 'StatusBarManager'                

                            Object statusBarService = getSystemService("statusbar");
                            Class<?> statusBarManager = null;

                            try {
                                statusBarManager = Class.forName("android.app.StatusBarManager");
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }

                            Method collapseStatusBar = null;

                            try {

                                // Prior to API 17, the method to call is 'collapse()'
                                // API 17 onwards, the method to call is `collapsePanels()`

                                if (Build.VERSION.SDK_INT > 16) {
                                    collapseStatusBar = statusBarManager.getMethod("collapsePanels");
                                } else {
                                    collapseStatusBar = statusBarManager.getMethod("collapse");
                                }
                            } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                            }

                            collapseStatusBar.setAccessible(shouldCollapse);

                            try {
                                collapseStatusBar.invoke(statusBarService);
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }

                            // Check if the window focus has been returned
                            // If it hasn't been returned, post this Runnable again
                            // Currently, the delay is 50 ms. You can change this
                            // value to suit your needs.
                            if (!currentFocus && !isPaused) {
                                collapseNotificationHandler.postDelayed(this, 50);
                            }

                        }
                    }, 0);
                }   
            }

“isPaused” boolean which set true when app is in Pause state.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..